imagetools/get_locality.py

77 lines
2.4 KiB
Python
Raw Permalink Normal View History

import sys
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import requests
API_KEY = "LSoLu_4Ca6jjJPVaBZnNPdObHi701oGYbZmnyukL_4I"
def get_decimal_form_dms(dms, ref):
degrees = dms[0]
minutes = dms[1] / 60.0
seconds = dms[2] / 3600.0
if ref in ['S', 'W']:
degrees = -degrees
minutes = -minutes
seconds = -seconds
return round(degrees + minutes + seconds, 5)
# define function get_geodata which extracts geolocation data from image metadata and converts it to decimal degrees
def get_geodata(exif_data):
latitude = None
latitude_ref = None
longitude = None
longitude_ref = None
for tag, value in exif_data.items():
if TAGS.get(tag) == 'GPSInfo':
for key in value.keys():
if GPSTAGS.get(key) == 'GPSLatitude':
latitude = value[key]
elif GPSTAGS.get(key) == 'GPSLatitudeRef':
latitude_ref = value[key]
elif GPSTAGS.get(key) == 'GPSLongitude':
longitude = value[key]
elif GPSTAGS.get(key) == 'GPSLongitudeRef':
longitude_ref = value[key]
latitude = get_decimal_form_dms(latitude, latitude_ref)
longitude = get_decimal_form_dms(longitude, longitude_ref)
return latitude, longitude
def get_location_info(latitude, longitude):
if not latitude or not longitude:
return None, None
url = f"https://api.mapy.cz/v1/rgeocode?lon={longitude}&lat={latitude}&apikey={API_KEY}&lang=cs"
response = requests.get(url)
if response.status_code == 200:
location_data = response.json()
items = location_data.get('items', [])
if items:
item = items[0]
locality = item['location']
region = item['regionalStructure'][5]['name']
return locality, region
return None, None
# get picture file name from command line argument
def main():
if len(sys.argv) != 3 or sys.argv[1] != '-i':
print("Chybné použití. Použijte: script.py -i vstupni_obrazek")
sys.exit(1)
input_image_path = sys.argv[2]
try:
image = Image.open(input_image_path)
exif_data = image._getexif()
except Exception as e:
print(f"Chyba při čtení metadat obrázku: {str(e)}")
sys.exit(1)
print(f'Lokalita: {get_location_info(*get_geodata(exif_data))}')
if __name__ == "__main__":
main()