python 从jpg文件读取gps数据

 

 

 

 

# 读取单张图片的gps数据
def get_gps(path):
    with open(path, 'rb') as f:
        exif_dict = exifread.process_file(f)
        # print(exif_dict)
        # 经度 [108, 45, 19451/400]
        lon_ref = exif_dict["GPS GPSLongitudeRef"].printable
        lon = exif_dict["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
        # print(lon)
        lon = float(lon[0]) + float(lon[1]) / 60 + float(lon[2]) / float(lon[3]) / 3600
        if lon_ref != "E":
            lon = lon * (-1)

        # 纬度 [34, 1, 27739/500]
        lat_ref = exif_dict["GPS GPSLatitudeRef"].printable
        lat = exif_dict["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
        # print(lat)
        lat = float(lat[0]) + float(lat[1]) / 60 + float(lat[2]) / float(lat[3]) / 3600
        if lat_ref != "N":
            lat = lat * (-1)
        

        # 海拔 101077/250
        # alt_ref = exif_dict["GPS GPSAltitudeRef"].printable
        alt = exif_dict["GPS GPSAltitude"].printable.split("/")
        # print(alt)
        alt = float(alt[0]) / float(alt[1])

        # print('照片的经纬度:', (lat, lon, alt))

        return (lat, lon, alt)

# 读取所有图片的gps数据并保存
def get_all_gps(path):
    img_path_root = path + 'image_gps/'
    gps_path = path + '/gps.txt'
    img_list = os.listdir(img_path_root)
    img_list.sort(key=lambda x:int(x[:-4]))
    print(img_list)
    f = open(gps_path,'w')
    for img_name in img_list:
        img_path = os.path.join(img_path_root, img_name)
        img_name_ = img_name.split('.')[0]
        print(img_name_)
        print(img_path)
    
        lat, lon, alt = get_gps(img_path)
        print('照片的经纬度:', (lat, lon, alt))
        line = img_name_ + ' ' + str(lat) + ' ' + str(lon) + ' ' + str(alt) +'\n'
        f.write(line)
        # break
    f.close()

 

posted @ 2021-12-03 11:05  小小灰迪  阅读(24)  评论(0编辑  收藏  举报