Traceback (most recent call last): File "G:\pythonProject4\6.py", line 51, in <module> extract_pos_to_txt(folder_path, output_file) File "G:\pythonProject4\6.py", line 44, in extract_pos_to_txt pos = get_image_pos(file_path) File "G:\pythonProject4\6.py", line 21, in get_image_pos lat_deg = lat[0][0] / lat[0][1] TypeError: 'IFDRational' object is not subscriptable
时间: 2024-02-19 15:03:17 浏览: 59
这个错误的原因与你之前提到的错误相同,是因为你在尝试对 `IFDRational` 类型的对象进行下标操作。 我们需要更改获取纬度和经度的代码,以使用 `IFDRational` 对象的属性和方法来获取其值。以下是更改后的代码:
```python
import os
from PIL import Image
from PIL.ExifTags import TAGS
# 定义函数获取图片位置信息
def get_image_pos(file_path):
with Image.open(file_path) as img:
exif_data = img._getexif()
if exif_data:
exif = {
TAGS[k]: v
for k, v in exif_data.items()
if k in TAGS
}
if 'GPSInfo' in exif:
lat = exif['GPSInfo'][2]
lat_ref = exif['GPSInfo'][1]
lon = exif['GPSInfo'][4]
lon_ref = exif['GPSInfo'][3]
if lat and lat_ref and lon and lon_ref:
lat_deg = lat[0].__truediv__(lat[1])
lat_min = lat[1].__truediv__(lat[2])
lat_sec = lat[2].__truediv__(lat[3])
lat_ref = lat_ref.upper()
lon_deg = lon[0].__truediv__(lon[1])
lon_min = lon[1].__truediv__(lon[2])
lon_sec = lon[2].__truediv__(lon[3])
lon_ref = lon_ref.upper()
lat_decimal = lat_deg + (lat_min / 60.0) + (lat_sec / 3600.0)
lon_decimal = lon_deg + (lon_min / 60.0) + (lon_sec / 3600.0)
if lat_ref == 'S':
lat_decimal = -lat_decimal
if lon_ref == 'W':
lon_decimal = -lon_decimal
return lat_decimal, lon_decimal
return None
# 遍历文件夹中的所有jpg文件,提取位置信息并写入txt文件
def extract_pos_to_txt(folder_path, output_file):
with open(output_file, 'w') as f:
for file_name in os.listdir(folder_path):
if file_name.lower().endswith('.jpg'):
file_path = os.path.join(folder_path, file_name)
pos = get_image_pos(file_path)
if pos:
f.write(f"{file_name}: {pos}\n")
# 测试示例
folder_path = 'path/to/folder'
output_file = 'output.txt'
extract_pos_to_txt(folder_path, output_file)
```
你需要将 `path/to/folder` 替换为你的文件夹路径,然后运行该脚本即可。它将遍历文件夹中的所有jpg文件,提取位置信息,并将其写入名为 `output.txt` 的文本文件中。
阅读全文