import re, os, json
try: import requests
except ImportError:
os.system("pip install requests")
import requests
try: import exifread
except ImportError:
os.system("pip install exifread")
import exifread
def latitude_and_longitude_convert_to_decimal_system(*arg):
"""
經緯度轉為小數, param arg:
:return: 十進制小數
"""
return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
def unpack_pic(pic_path):
with open(pic_path, 'rb') as f:
tags = exifread.process_file(f)
return tags
def find_pic_GPS(tags):
GPS = {}
date = ''
for tag, value in tags.items():
# latitude
if re.match('GPS GPSLatitudeRef', tag):
GPS['GPSLatitudeRef'] = str(value)
# longtitude
elif re.match('GPS GPSLongitudeRef', tag):
GPS['GPSLongitudeRef'] = str(value)
# altitude
elif re.match('GPS GPSAltitudeRef', tag):
GPS['GPSAltitudeRef'] = str(value)
elif re.match('GPS GPSLatitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSLongitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSAltitude', tag):
GPS['GPSAltitude'] = str(value)
elif re.match('.*Date.*', tag):
date = str(value)
return {'GPS_information': GPS, 'date_information': date}
def GPS2Address(GPS_info):
lat, lng = GPS_info['GPS_information']['GPSLatitude'], GPS_info['GPS_information']['GPSLongitude']
ak = 'https://lbsyun.baidu.com/apiconsole/key#/home'#注冊查詢
baidu_map_api = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak={}&output=json&coordtype=wgs84ll&location={},{}&extensions_poi=1'.format(ak,lat,lng)
r = requests.get(baidu_map_api)
content = r.text
baidu_map_address = json.loads(content)
# print(json.dumps(baidu_map_address, ensure_ascii=False, indent=2))
address = {}
address["formatted_address"] = baidu_map_address["result"]["formatted_address"]
address["location"] = {}
address["location"]["country"] = baidu_map_address["result"]["addressComponent"]["country"]
address["location"]["province"] = baidu_map_address["result"]["addressComponent"]["province"]
address["location"]["city"] = baidu_map_address["result"]["addressComponent"]["city"]
address["location"]["district"] = baidu_map_address["result"]["addressComponent"]["district"]
address["location"]["street"] = baidu_map_address["result"]["addressComponent"]["street"]
address["sematic_description"] = baidu_map_address["result"]["sematic_description"]
return address
def main():
pic_path = r'C:\test.jpg'
tags = unpack_pic(pic_path)
GPS_info = find_pic_GPS(tags)
address = GPS2Address(GPS_info)
print(json.dumps(GPS_info, ensure_ascii=False, indent=2))
print(json.dumps(address, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 測試時請使用含有經緯度資訊的圖檔。右鍵圖檔->屬性->詳細資訊就可以看到。如果沒有合适的圖檔,可以用手機拍照,拍照前從設定裡打開地理位置。發送到電腦時需發送原圖。
- 這裡使用的是百度地圖API,調用需注冊申請AK。
- 該API是百度地圖全球逆地理編碼V3版本,附文檔連結:百度地圖API文檔——逆地理編碼
- 本文參考部落格女友半夜加班發自拍 python男友用30行代碼發現驚天秘密。這篇部落格用的是V2版本的API