惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
Security Latest
Security Latest
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cybersecurity and Infrastructure Security Agency CISA
Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
大猫的无限游戏
大猫的无限游戏
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
C
Cisco Blogs
V
Vulnerabilities – Threatpost
S
Security Archives - TechRepublic
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
J
Java Code Geeks
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Know Your Adversary
Know Your Adversary
博客园 - 叶小钗
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
P
Palo Alto Networks Blog
博客园_首页
V
V2EX
WordPress大学
WordPress大学
Schneier on Security
Schneier on Security
月光博客
月光博客
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
The Cloudflare Blog
罗磊的独立博客
美团技术团队
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Last Week in AI
Last Week in AI
K
Kaspersky official blog
Google Online Security Blog
Google Online Security Blog
S
SegmentFault 最新的问题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python __getattr__ 懒加载 Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录 2025 Python 版本性能测试 Flutter Hello World Flutter 安装环境配置 Ubuntu VMware 硬盘扩容后 SMBus Host controller not enabled 报错问题解决 Python NetworkX 教程 Docker GPU 报错 - Failed to initialize NVML Unknown Error 解决方案 Python matplotlib 图表绘制 cuda-toolkit 安装替代 Cuda 与 Cudnn Jinja2 Python 利用 docxtpl 和 Jinja2 生成基于模板的 Word 文档 Docker 实现 CPU 核心隔离 LoFTR 基于 Transformer 的特征提取匹配算法 OmniGlue 特征匹配 SuperGlue 使用图神经网络学习特征匹配 Ubuntu 下将 xlsx 文件按照 sheet 转换为 图片 Python 使用 SQLAlchemy Python FastAPI 教程 openwrt 软路由配置安装 Nav2 地图文件(PGM/YAML)规范标准 3D OBJ 模型转换为 glb 瓦片格式 Python 源码 Redis 数据库介绍 Ubuntu 22.04 内核自动升级导致 MongoDB 7.0.12 错误记录 ubuntu 20.04 安装 ROS Noetic ubuntu 18.04 安装 ROS Melodic VMware Workstation Pro 个人免费版下载、安装、使用指南 Hybrid A-star 路径规划 Reeds-Shepp 曲线 Dubins 曲线 Linux kvm 虚拟机网络不通的问题解决方法 Ubuntu 自动内存清理 BiliBili 缓存视频转 mp4 Python 求解线性规划 3D Gaussian Splatting 官方源码实践记录 ImageMagick 教程 Ubuntu 22.04 安装 Colmap 对数几率 odds Ubuntu nmcli 网络管理工具使用指南 SuperPoint 自监督深度学习特征点提取 SyncTV Music Tag Web 在线音乐信息整理工具 ncm 格式转 mp3 MusicBrainz 音乐元数据百科数据库 Ubuntu 网络流量监控工具 私人云音乐平台 Navidrome 入门 手眼标定 四元数(Quaternions) OHTTPS 实现免费自动 https 证书申请、更新、部署 ubuntu 22.04 安装 CloudCompare 单机 KVM 虚拟机冷迁移 Ubuntu 22.04 使用 mdadm 实现软 raid 小鱼 一键安装 ROS-humble Fluid -46- 基于 Simpletex API 构建公式识别页面 公式识别 API 简介 -- Simpletex 使用 Python web 部署库 waitress 3D Gaussian Splatting for Real-Time Radiance Field Rendering Ubuntu Swap 简介与空间扩展 Ubuntu 24.04 安装 forticlient Clash Verge 使用 MongoDB 7.0.17 集群 Docker 构建源码 Error code - 2013. Lost connection to MySQL server during query 问题解决 Python 日志记录库 loguru 使用指北 Python 实现 Web 日志查看服务 MySQL LOAD DATA LOCAL INFILE 极速数据加载 Image size exceeds limit of 89478485 pixels 解决方案 Docker 使用 NVIDIA GPU 驱动错误解决 阿里云 docker 镜像仓库 Ubuntu中没有wired connected的解决方案 MinIO 简介 subconverter 代理订阅格式转换 修复 node –openssl-legacy-provider is not allowed in NODE_OPTIONS 错误
Python 读写图像 GPS 信息
Yiwei Zhang · 2024-05-11 · via 又见苍岚

JPG 图像中经常会保存相机记录的图像拍摄位置的 GPS 信息,本文记录 Python 获取、保存图像拍摄位置信息的方法。

简介

EXIF(Exchangeable Image File Format)是一种用于存储图像拍摄相关信息的标准,这些信息包括相机设置、拍摄时间、地点等。EXIF信息通常嵌入在JPEG、TIFF和RAW图像文件中,以便于软件和设备(如数字相机、手机、扫描仪)能够读取和使用这些信息。

在EXIF信息中,GPS信息是一个重要的组成部分,它可以提供关于图像拍摄位置的详细数据。以下是GPS信息可能包含的内容:

  1. GPS版本信息:表示EXIF中GPS信息的版本号。
  2. GPS国界:标识图像拍摄位置所在的国家或地区。
  3. GPS定位日期和时间:记录图像拍摄时的日期和时间。
  4. GPS卫星信息:显示在图像拍摄时,哪些卫星参与了GPS定位。
  5. GPS经度:表示图像拍摄位置的经度,通常以度、分、秒的形式表示。
  6. GPS纬度:表示图像拍摄位置的纬度,同样以度、分、秒的形式表示。
  7. GPS高度:以米为单位,表示图像拍摄位置相对于海平面的高度。
  8. GPS速度:表示图像拍摄时的移动速度,通常以千米/小时为单位。

通过这些GPS信息,我们可以了解到图像的拍摄位置、时间和拍摄时的运动状态。这些信息对于图片的归档、分享和地理信息系统(GIS)分析等方面非常有用。

Python 获取路线

可以在 Python 中很容易地获取到图像的 exif 信息,并从中提取 gps 信息,本质上都是从文件中读取 exif 信息字段,将其解析成我们可读的 gps 信息。

这里介绍三种实现方法:

  1. Pillow 路线
  2. piexif
  3. exifread

经度、纬度概念

  • 经度 Longitude , 本初子午线 位置 为 0 度经线 , 相当于水平 x 轴 的坐标 , 经度的取值范围 -180 度 ~ +180 度 ;

  • 纬度 Latitude , 相当于 垂直 y 轴 的坐标 , 纬度的取值范围 -90 度 ~ + 90 度 ;

  • 西经 和 南纬 是负数 ;

Pillow

安装

1
pip install Pillow

使用

上源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from PIL import Image, ExifTags

def pillow_get_exif_data(image_path):
image = Image.open(image_path)
# 获取图片的exif信息
exif_data = image._getexif()
if exif_data is not None:
# 使用自定义的函数转换exif标签
exif_data = {
ExifTags.TAGS[k]: v
for k, v in exif_data.items()
if k in ExifTags.TAGS
}
return exif_data

if __name__ == '__main__':
image_path = 'demo.jpg'
exif_data = pillow_get_exif_data(image_path)
print(exif_data['GPSInfo'])

输出:

1
{0: b'\x02\x03\x00\x00', 1: 'N', 2: (31.0, 5.0, 37.6518), 3: 'E', 4: (121.0, 14.0, 54.4151), 5: b'\x00', 6: 93.606, 7: (2.0, 32.0, 54.0), 9: 'A', 18: 'WGS-84\x00', 29: '2024:05:04'}

含义:

  • 1 —— 南北
  • 2 —— 纬度(度分秒)
  • 3 —— 东西
  • 4 —— 经度(度分秒)
  • 6 —— 高度(米)

piexif

安装

1
pip install piexif

使用

上源码:

1
2
3
4
5
6
7
8
9
10
import piexif

def piexif_get_exif_data(image_path):
exif_dict = piexif.load(image_path)
return exif_dict

if __name__ == '__main__':
image_path = 'demo.jpg'
exif_data = piexif_get_exif_data(image_path)
print(exif_data['GPS'])

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
0:
(2, 3, 0, 0)
1:
b'N'
2:
((31, 1), (5, 1), (376518, 10000))
3:
b'E'
4:
((121, 1), (14, 1), (544151, 10000))
5:
0
6:
(93606, 1000)
7:
((2, 1), (32, 1), (54, 1))
9:
b'A'
18:
b'WGS-84\x00'

含义:

其中的 tuple 需要第一个数除以第二个数

  • 1 —— 南北
  • 2 —— 纬度(度分秒)
  • 3 —— 东西
  • 4 —— 经度(度分秒)
  • 6 —— 高度(米)

exifread

安装

1
pip install exifread

使用

上源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
import exifread

def exifread_get_exif_data(image_path):
f = open(image_path,'rb')
contents = exifread.process_file(f)
f.close()
return contents

if __name__ == '__main__':
image_path = 'demo.jpg'

contents = exifread_get_exif_data(image_path)
print(contents["GPS GPSLongitude"], contents['GPS GPSLongitudeRef'], contents["GPS GPSLatitude"], contents['GPS GPSLatitudeRef'], contents["GPS GPSAltitude"])

输出:

1
[121, 14, 544151/10000] E [31, 5, 188259/5000] N 46803/500

pyexiv2

安装

1
pip install pyexiv2

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from pyexiv2 import Image as xmpImage
from pyexiv2 import ImageData

def phase_all_exif_info(image_path):
img = xmpImage(image_path)
total_info = dict()

xmp_data = img.read_xmp()
total_info.update(xmp_data)

exif_info = img.read_exif()
total_info.update(exif_info)

return total_info

性能评估

连续运行一千次,统计时间:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from PIL import Image, ExifTags
import mtutils as mt
import numpy as np
import piexif
import exifread
import time

def piexif_get_exif_data(image_path):
exif_dict = piexif.load(image_path)
return exif_dict

def pillow_get_exif_data(image_path):
image = Image.open(image_path)
# 获取图片的exif信息
exif_data = image._getexif()
if exif_data is not None:
# 使用自定义的函数转换exif标签
exif_data = {
ExifTags.TAGS[k]: v
for k, v in exif_data.items()
if k in ExifTags.TAGS
}
return exif_data

def exifread_get_exif_data(image_path):
f = open(image_path,'rb')
contents = exifread.process_file(f)
f.close()
return contents

if __name__ == '__main__':
image_path = 'demo.JPG'

times = 1000

start = time.time()
for _ in range(times):
exif_data = pillow_get_exif_data(image_path)
end = time.time()
print(f'pillow_get_exif_data: {end - start}')

start = time.time()
for _ in range(times):
exif_data2 = piexif_get_exif_data(image_path)
end = time.time()
print(f'piexif_get_exif_data: {end - start}')

start = time.time()
for _ in range(times):
exifread_get_exif_data(image_path)
end = time.time()
print(f'exifread_get_exif_data: {end - start}')

pass

输出:

1
2
3
pillow_get_exif_data: 0.94569993019104
piexif_get_exif_data: 0.17222881317138672
exifread_get_exif_data: 0.8518986701965332

结论piexif 又快又好用。

写入exif信息

pyexiv2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from pyexiv2 import Image as xmpImage
from pyexiv2 import ImageData

def modify_xmp_and_exif(image_path, xmp_changes=None, exif_changes=None):
"""
只修改 XMP 元数据,不操作像素数据
"""
try:
# 1. 打开图片读取元数据(仅加载元数据,不加载完整像素)
with xmpImage(image_path) as img:
# 如果提供了 EXIF 修改,应用它
if exif_changes:
img.modify_exif(exif_changes)

# 如果提供了 XMP 修改,应用它
if xmp_changes:
img.modify_xmp(xmp_changes)

# 3. 获取修改后的完整元数据(包括 EXIF、XMP)
exif = img.read_exif()
xmp = img.read_xmp()

# 4. 用原始图片创建 ImageData 对象(承载像素和原始元数据)
with open(image_path, 'rb') as f:
img_data = ImageData(f.read())

# 5. 将修改后的元数据写入 ImageData(仅更新元数据区)
img_data.modify_exif(exif)
img_data.modify_xmp(xmp)

except FileNotFoundError:
print(f"错误:找不到文件 '{image_path}'")
except Exception as e:
print(f"处理图片时发生错误: {e}")

Pillow

当需要用Python 保存图像并附带 exif 信息时,可以用到 Pillow 库了,exif信息这里两种方式:

  1. pillow 自带信息

    1
    2
    3
    4
    5
    from PIL import Image
    image_path = 'demo.jpg'

    pil_img = Image.open(image_path)
    pil_img.save('target.jpg', exif=pil_img.info['exif'])

  2. piexif 信息压缩成字符串送入 pil 写图像中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from PIL import Image
    import piexif

    image_path = 'demo.jpg'
    pil_img = Image.open(image_path)

    exif_dict = piexif.load(img.info['exif'])
    exif_bytes = piexif.dump(exif_dict)

    pil_img.save('target.jpg', exif=exif_bytes)

参考资料

文章链接:
https://www.zywvvd.com/notes/coding/python/get-jpg-img-gps-info/get-jpg-img-gps-info/