Pythonで写真の地理情報を取得する方法は何ですか?
PythonのPILライブラリ(Python Imaging Library)やExifReadライブラリを使用すると、写真の地理位置情報を取得できます。
最初に、PILライブラリとExifReadライブラリをインストールするには、次のコマンドを使用することができます:
pip install pillow
pip install exifread
次に、写真の地理位置情報を取得するために、次のコードを使用できます:
PILライブラリの使用:
from PIL import Image
from PIL.ExifTags import TAGS
def get_geolocation(image_path):
image = Image.open(image_path)
exif_data = image._getexif()
if exif_data is not None:
for tag_id, value in exif_data.items():
tag_name = TAGS.get(tag_id, tag_id)
if tag_name == 'GPSInfo':
return value
return None
# 传入照片路径作为参数
geolocation = get_geolocation('path/to/photo.jpg')
if geolocation is not None:
print(geolocation)
else:
print('No geolocation found.')
ExifReadライブラリの使用:
import exifread
def get_geolocation(image_path):
with open(image_path, 'rb') as image_file:
tags = exifread.process_file(image_file)
if 'GPS GPSLatitude' in tags and 'GPS GPSLongitude' in tags:
latitude = tags['GPS GPSLatitude'].values
longitude = tags['GPS GPSLongitude'].values
return (latitude, longitude)
return None
# 传入照片路径作为参数
geolocation = get_geolocation('path/to/photo.jpg')
if geolocation is not None:
print(geolocation)
else:
print('No geolocation found.')
If there is no geolocation information in the photo, the code will output ‘No geolocation found.’