ODM_pro/preprocess/gps_extractor.py

56 lines
2.1 KiB
Python
Raw Normal View History

2024-12-17 22:09:47 +08:00
import os
from PIL import Image
import piexif
import logging
class GPSExtractor:
"""从图像文件提取GPS坐标"""
def __init__(self, image_dir):
self.image_dir = image_dir
self.logger = logging.getLogger('UAV_Preprocess.GPSExtractor')
@staticmethod
def _dms_to_decimal(dms):
"""将DMS格式转换为十进制度"""
return dms[0][0] / dms[0][1] + (dms[1][0] / dms[1][1]) / 60 + (dms[2][0] / dms[2][1]) / 3600
def get_gps(self, image_path):
"""提取单张图片的GPS坐标"""
try:
image = Image.open(image_path)
exif_data = piexif.load(image.info['exif'])
gps_info = exif_data.get("GPS", {})
if gps_info:
lat = self._dms_to_decimal(gps_info.get(2, []))
lon = self._dms_to_decimal(gps_info.get(4, []))
self.logger.debug(f"成功提取图片GPS坐标: {image_path} - 纬度: {lat}, 经度: {lon}")
return lat, lon
else:
self.logger.warning(f"图片无GPS信息: {image_path}")
return None, None
except Exception as e:
self.logger.error(f"提取GPS坐标时发生错误: {image_path} - {str(e)}")
return None, None
def extract_all_gps(self):
"""提取所有图片的GPS坐标"""
self.logger.info(f"开始从目录提取GPS坐标: {self.image_dir}")
gps_points = []
total_images = 0
successful_extractions = 0
for image_file in os.listdir(self.image_dir):
if image_file.lower().endswith('.jpg'):
total_images += 1
image_path = os.path.join(self.image_dir, image_file)
lat, lon = self.get_gps(image_path)
if lat and lon:
successful_extractions += 1
gps_points.append(
{'file': image_file, 'lat': lat, 'lon': lon})
self.logger.info(f"GPS坐标提取完成 - 总图片数: {total_images}, 成功提取: {successful_extractions}, 失败: {total_images - successful_extractions}")
return gps_points