单反相机照片用python 脚本添加gps位置信息

现在的单反相机基本都不带gps,如果要给照片添加gps信息,需要一直开着官方的app,非常耗电,出去拍照,可能忘记打开app,或者手机电量不够都可能导致照片没有位置信息。

个人整理照片的时候,喜欢在手机的相册里通过位置找照片:

 所以我就想把单反没有gps信息的照片手工补上gps信息。

在网上找了很多方法,大部分都很老,或者补上的gps 信息会位置偏移,就自己研究了一下:

--------------------------------------------------------------------------------------------------------------

思路这样:把没有位置信息的照片单独放一个文件夹(拷贝的副本,保持备份的习惯),

然后到地图拾取经纬度,然后填到照片的源数据。

1.准备一张照片

(建议先备份一下),我随便找了张壁纸

右键可以看到没有任何的位置信息

2.拾取坐标

到这个地址去直接拾取国际WGS84坐标
GPS工具箱管理https://web.gpstool.com/index

 点击一个点,把这个点的经纬度记下来,

30.648850,104.045879

3.用python程序添加gps信息

然后用以下python代码

或者直接使用我打包好的exe程序。

 

阿里云盘分享https://www.aliyundrive.com/s/vxENXi63yDE提取码 35ob

# ecoding:utf-8
import os
from PIL import Image
import piexif
import win32con
import win32ui
import ctypes

"""
安装第三方包
pip install piexif
pip install pywin32
pip install Pillow
pip install pyinstaller
打包命令:pyinstaller -F -i .\gps.ico .\gps.py
"""

# DIP缩放设置
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
success = ctypes.windll.user32.SetProcessDPIAware()


def main():
    image_path = browse(True)[1]
    gps_str = input('请输入经纬度:')
    arr = gps_str.split(',')
    lng = float(arr[1])
    lat = float(arr[0])

    # 将经纬度与相对航高转为exif可用的经纬度与行高
    # exif需要的航高输入为(20000,2)格式,表示高度为20000/100米
    # exif需要的经度与维度为((12, 1), (20,1), (41000, 1000))格式表示12度20分41秒
    lng_exif = format_latlng(lng)
    lat_exif = format_latlng(lat)
    _dict = {"lng": lng_exif, "lat": lat_exif, "lng_ref": 'E', "lat_ref": 'N'}
    print("写入文件:", image_path)
    # 判断图片是否有exif
    read_check_exif(image_path)
    # 修改图片的exif
    read_modify_exif(image_path, _dict)


def browse(mode: bool,
           default_name: str = "",
           title: str = "选择您的文件",
           file_type: str = "图片文件(*.jpg)|*.jpg|",
           path: str = "desktop"):
    """弹出窗口返回保存或者选择的路径
    :param mode: False"为 "保存/另存为", "True"为 "打开"
    :param default_name:默认输入文件名
    :param title:窗口提示
    :param file_type:可选的文件类型,所有文件(*.*)|*.*|图片文件(*.jpg)|*.jpg|
    :param path:
    :return:[存储类型、文件路径、文件类型]
    """
    api_flag = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
    dlg = win32ui.CreateFileDialog(mode, None, default_name, api_flag, file_type)
    dlg.SetOFNTitle(title)
    dlg.SetOFNInitialDir(os.path.abspath(path))
    dlg.DoModal()
    filename = dlg.GetPathName()
    fileExt = dlg.GetFileExt()
    if os.path.exists(filename):
        if_pass = True
    elif not mode:
        if os.path.split(filename)[0] == '':
            if_pass = False
        else:
            if_pass = True
    else:
        if_pass = False
    return [if_pass, filename, fileExt]


def format_latlng(latlng):
    """经纬度十进制转为分秒"""
    degree = int(latlng)
    res_degree = latlng - degree
    minute = int(res_degree * 60)
    res_minute = res_degree * 60 - minute
    seconds = round(res_minute * 60.0, 3)

    return ((degree, 1), (minute, 1), (int(seconds * 1000), 1000))


def read_check_exif(image_path):
    """
    判断图片是否有'exif'信息,没有就写入初始'exif'信息
    :param image_path:图片路径
    :return:无
    """
    img = Image.open(image_path)  # 读图
    try:
        exif_dict = piexif.load(img.info['exif'])  # 提取exif信息
    except KeyError:
        # 处理exif不存在的情况
        # 创建一个初始的EXIF字典
        exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "Interop": {}, "1st": {}, "thumbnail": None}
        # 将EXIF字典添加到图像的元数据中
        exif_bytes = piexif.dump(exif_dict)
        img.save(image_path, exif=exif_bytes)


def read_modify_exif(image_path, _dict):
    """ 读取并且修改exif文件"""
    img = Image.open(image_path)  # 读图
    exif_dict = piexif.load(img.info['exif'])  # 提取exif信息

    exif_dict['GPS'][piexif.GPSIFD.GPSLongitude] = _dict['lng']  # 修改经度
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitude] = _dict['lat']  # 修改纬度
    exif_dict['GPS'][piexif.GPSIFD.GPSLongitudeRef] = _dict['lng_ref']  # odm需要读取,一般为’W'
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitudeRef] = _dict['lat_ref']  # 一般为‘N'

    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, image_path)


if __name__ == "__main__":
    main()

把python代码保存到本地py文件

运行前得先安装依赖的第三方包:

pip install piexif
pip install pywin32
pip install Pillow
pip install pyinstaller

 

python第三方包安装后,双击执行py文件会提示选择一个图片文件,我选择之前准备的图片文件。 

然后会提示输入经纬度,则把上面准备的坐标输入回车即可。 

然后图片就有经纬度信息了

可以用这个网站来看看位置信息

在线查看图片Exif信息_定位信息_GPS信息 - StrErr.com查看图片Exif信息https://www.strerr.com/cn/exif.html

 

然后就成功啦

 这种方法有弊端,位置信息全靠记忆,比较麻烦,后期文章更新通过轨迹信息批量给照片添加位置信息的方法。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值