python获取图片的地理位置信息

使用Python的PIL库获取图片的经纬度、高度等 EXIF 数据

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS


def get_exif_data(image_path):
    """
    获取 JPEG 图像的 EXIF 数据
    """
    exif_data = {}
    with Image.open(image_path) as img:
        if hasattr(img, '_getexif'):
            # 获取所有 EXIF 标签
            for tag, value in img._getexif().items():
                if tag in TAGS:
                    exif_data[TAGS[tag]] = value
            # 获取 GPSInfo 标签
            if 'GPSInfo' in exif_data:
                # 解析 GPSInfo 标签中的子标签
                gps_data = {}
                for gps_tag in exif_data['GPSInfo'].keys():
                    tag_name = GPSTAGS.get(gps_tag, gps_tag)
                    gps_data[tag_name] = exif_data['GPSInfo'][gps_tag]
                exif_data['GPSInfo'] = gps_data
    return exif_data


def get_gps_info(exif_data):
    """
    从 EXIF 数据中提取经纬度信息
    """
    gps_info = {}
    if 'GPSInfo' in exif_data:
        # 获取纬度
        lat = exif_data['GPSInfo']['GPSLatitude']
        lat_ref = exif_data['GPSInfo']['GPSLatitudeRef']
        # lat_degrees = lat[0][0] / float(lat[0][1])
        lat_degrees = lat[0].numerator / float(lat[0].denominator)
        # lat_minutes = lat[1][0] / float(lat[1][1])
        lat_minutes = lat[1].numerator / float(lat[1].denominator)
        # lat_seconds = lat[2][0] / float(lat[2][1])
        lat_seconds = lat[2].numerator / float(lat[2].denominator)
        lat_direction = lat_ref
        gps_info['latitude'] = (lat_degrees + (lat_minutes / 60.0) + (lat_seconds / 3600.0)) * (
            -1 if lat_direction == 'S' else 1)

        # 获取经度
        lon = exif_data['GPSInfo']['GPSLongitude']
        lon_ref = exif_data['GPSInfo']['GPSLongitudeRef']
        # lon_degrees = lon[0][0] / float(lon[0][1])
        lon_degrees = lon[0].numerator / float(lon[0].denominator)
        # lon_minutes = lon[1][0] / float(lon[1][1])
        lon_minutes = lon[1].numerator / float(lon[1].denominator)
        # lon_seconds = lon[2][0] / float(lon[2][1])
        lon_seconds = lon[2].numerator / float(lon[2].denominator)
        lon_direction = lon_ref
        gps_info['longitude'] = (lon_degrees + (lon_minutes / 60.0) + (lon_seconds / 3600.0)) * (
            -1 if lon_direction == 'W' else 1)
    return gps_info


# 测试代码
if __name__ == '__main__':
    image_path = r'E:\\TestData\Testjpg\IMG_20230808_140247.jpg'
    #image_path = r'E:\\TestData\Testjpg\test.jpg'
    # 修改为你自己的 JPEG 图像路径
    exif_data = get_exif_data(image_path)
    gps_info = get_gps_info(exif_data)
    print('经度:', gps_info['longitude'])
    print('纬度:', gps_info['latitude'])

你可能感兴趣的:(python,图像处理,pycharm)