python 解析图片拍摄地址

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()

  1. 测试时请使用含有经纬度信息的图片。右键图片->属性->详细信息就可以看到。如果没有合适的图片,可以用手机拍照,拍照前从设置里打开地理位置。发送到电脑时需发送原图。
  2. 这里使用的是百度地图API,调用需注册申请AK。
  3. 该API是百度地图全球逆地理编码V3版本,附文档链接:百度地图API文档——逆地理编码
  4. 本文参考博客女友半夜加班发自拍 python男友用30行代码发现惊天秘密。这篇博客用的是V2版本的API

你可能感兴趣的:(python)