
本教程详细阐述了如何使用python从图片exif数据中提取gps经纬度信息。文章深入解析了exif中gps数据的存储格式(度分秒),并重点讲解了如何根据经纬度参考(南北半球、东西半球)正确转换并应用符号,以避免常见的坐标错误。教程提供了完整的示例代码,并涵盖了使用`geopy`库进行反向地理编码,以及处理潜在问题和最佳实践。
数码照片通常包含元数据,即EXIF(可交换图像文件格式)数据,其中可能包含拍摄时的GPS坐标信息。这些信息通常存储在GPSInfo字典中,以特定的标签ID表示。
关键的GPS EXIF标签包括:
需要注意的是,GPSLatitude和GPSLongitude存储的是绝对值,其正负号取决于GPSLatitudeRef和GPSLongitudeRef。例如,南半球的纬度应为负值,西半球的经度也应为负值。
EXIF中的GPS数据通常以DMS格式存储,而大多数地理信息系统和API(如geopy)需要十进制格式。DMS到十进制的转换公式如下:
立即学习“Python免费学习笔记(深入)”;
十进制经纬度 = 度 + (分钟 / 60) + (秒 / 3600)
例如,如果纬度是 (33, 51, 52.4),则其十进制值为 33 + (51 / 60) + (52.4 / 3600)。
在转换过程中,必须结合GPSLatitudeRef和GPSLongitudeRef来确定最终的符号:
这是解决纬度或经度符号错误的关键。例如,原始问题中用户在澳大利亚(南半球)拍照,但计算出的纬度为正值,导致被错误识别为日本。通过检查GPSLatitudeRef是否为'S'并应用负号,即可纠正此问题。
以下是一个完整的Python代码示例,演示如何从图片中提取EXIF GPS数据,将其转换为正确的十进制格式,并使用geopy库进行反向地理编码。
import PIL.Image
import PIL.ExifTags
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut, GeocoderServiceError
def get_exif_data(image_path):
"""
从指定路径的图片中提取EXIF数据。
返回一个字典,其中键为EXIF标签名,值为对应的EXIF数据。
"""
try:
img = PIL.Image.open(image_path)
exif_data = img._getexif()
if exif_data is None:
return {}
# 将EXIF标签ID映射到可读的标签名
exif = {
PIL.ExifTags.TAGS.get(k, k): v
for k, v in exif_data.items()
}
return exif
except Exception as e:
print(f"读取EXIF数据时发生错误: {e}")
return {}
def convert_dms_to_decimal(dms_tuple, ref):
"""
将度、分、秒(DMS)元组转换为十进制经纬度。
并根据参考('N', 'S', 'E', 'W')应用正确的符号。
"""
if not isinstance(dms_tuple, tuple) or len(dms_tuple) != 3:
raise ValueError("DMS元组格式不正确,应为 (degrees, minutes, seconds)")
# PIL库中的DMS值通常是分数形式 (numerator, denominator)
# 需要将其转换为浮点数
degrees = float(dms_tuple[0][0]) / dms_tuple[0][1] if isinstance(dms_tuple[0], tuple) else float(dms_tuple[0])
minutes = float(dms_tuple[1][0]) / dms_tuple[1][1] if isinstance(dms_tuple[1], tuple) else float(dms_tuple[1])
seconds = float(dms_tuple[2][0]) / dms_tuple[2][1] if isinstance(dms_tuple[2], tuple) else float(dms_tuple[2])
decimal_degrees = degrees + (minutes / 60.0) + (seconds / 3600.0)
if ref in ['S', 'W']:
decimal_degrees *= -1
return decimal_degrees
def get_gps_coordinates(exif_data):
"""
从EXIF数据中提取并转换GPS坐标。
返回 (latitude, longitude) 元组,如果无法获取则返回 (None, None)。
"""
gps_info = exif_data.get('GPSInfo')
if not gps_info:
return None, None
# GPSInfo中的标签通常是数字ID,需要映射到GPSTAGS中的名称
# PIL.ExifTags.GPSTAGS 是一个反向映射 (tag_name: tag_id)
# 我们需要 (tag_id: tag_name)
gps_tag_id_to_name = {v: k for k, v in PIL.ExifTags.GPSTAGS.items()}
# 使用映射后的ID来获取数据
latitude_dms = gps_info.get(gps_tag_id_to_name.get('GPSLatitude'))
latitude_ref = gps_info.get(gps_tag_id_to_name.get('GPSLatitudeRef'))
longitude_dms = gps_info.get(gps_tag_id_to_name.get('GPSLongitude'))
longitude_ref = gps_info.get(gps_tag_id_to_name.get('GPSLongitudeRef'))
if all([latitude_dms, latitude_ref, longitude_dms, longitude_ref]):
try:
lat = convert_dms_to_decimal(latitude_dms, latitude_ref)
lon = convert_dms_to_decimal(longitude_dms, longitude_ref)
return lat, lon
except ValueError as e:
print(f"DMS转换错误: {e}")
return None, None
return None, None
# --- 主程序执行 ---
# 请替换为你的图片文件路径
image_path = r"C:\Users\RGCRA\Pictures\Camera Roll\WIN_20240102_11_46_09_Pro.jpg"
print(f"正在处理图片: {image_path}")
exif = get_exif_data(image_path)
if not exif:
print("未找到EXIF数据或读取图片时发生错误。")
else:
latitude, longitude = get_gps_coordinates(exif)
if latitude is not None and longitude is not None:
print(f"提取并校正后的GPS坐标: 纬度={latitude}, 经度={longitude}")
# 使用Nominatim进行反向地理编码
try:
# 必须提供一个唯一的user_agent,以遵守Nominatim的使用政策
geoLoc = Nominatim(user_agent='EXIF_GPS_Tutorial_App')
# 增加超时设置,避免网络请求无限等待
locname = geoLoc.reverse(f"{latitude}, {longitude}", timeout=10)
if locname:
print(f"反向地理编码地址: {locname.address}")
else:
print("无法对坐标进行反向地理编码。")
except GeocoderTimedOut:
print("地理编码服务超时。请稍后重试。")
except GeocoderServiceError as e:
print(f"地理编码服务错误: {e}")
except Exception as e:
print(f"反向地理编码过程中发生意外错误: {e}")
else:
print("图片EXIF数据中未找到有效的GPS坐标。")
通过本教程,我们学习了如何利用Python的PIL库提取图片EXIF中的GPS数据,并解决了将度分秒格式转换为十进制经纬度时,因半球参考(南北、东西)导致的正负号问题。正确处理GPSLatitudeRef和GPSLongitudeRef是确保坐标准确性的关键。结合geopy库进行反向地理编码,可以进一步验证提取出的位置信息,为图片处理和地理位置分析提供了强大的工具。在实际应用中,务必注意数据完整性、错误处理和用户隐私。
以上就是从图片EXIF数据中提取并校正GPS坐标的Python教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号