引言
在数字化时代,图片已经成为我们生活中不可或缺的一部分。然而,如何从图片中提取有用的信息,尤其是地址信息,一直是一个具有挑战性的问题。Python作为一种强大的编程语言,为我们提供了丰富的工具和库来解决这个问题。本文将介绍如何使用Python从图片中提取地址信息,并分享一些实用的技巧和经验。
一、准备工作
ExifRead==3.0.0
requests==2.31.0
ExifRead: 解析出图片的exif信息,手机拍摄的图片额外携带一些信息,可以通过exif解析出来,比如经纬度
requests: 解析出经纬度之后通过百度地图开发者平台的API接口获取地理位置
二、提取出经纬度
import os
from datetime import datetime
import exifreaddef get_latlng(content):"""获取经纬度"""lat_lng_info = {"lat_key": "GPS GPSLatitudeRef","lat_value": "GPS GPSLatitude","lng_key": "GPS GPSLongitudeRef","lng_value": "GPS GPSLongitude"}for key in lat_lng_info.values():if key not in content:return "", ""lat_list = content[lat_lng_info["lat_value"]].valueslat = int(lat_list[0]) + int(lat_list[1]) / 60 + float(lat_list[2]) / 3600lng_list = content[lat_lng_info["lng_value"]].valueslng = int(lng_list[0]) + int(lng_list[1]) / 60 + float(lng_list[2]) / 3600return lat, lngdef get_size(content):"""获取照片的大小"""w_key = "EXIF ExifImageWidth"l_key = "EXIF ExifImageLength"if w_key in content and l_key in content:return int(str(content[l_key])), int(str(content[w_key]))else:return "", ""def get_time(content):"""获取拍摄时间"""key = "EXIF DateTimeOriginal"if key in content:str_time = str(content[key])return datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")else:return ""def exif_analysis(image_path):try:print(f"开始分析图片的exit信息:{os.path.basename(image_path)}")f = open(image_path, "rb")content = exifread.process_file(f)length, width = get_size(content)shooting_time = get_time(content)lat, lng = get_latlng(content)f.close()exif_dict = {"name": os.path.basename(image_path),"shooting_time": shooting_time, "lat": lat, "lng": lng,"length": length, "width": width}print(f"exif分析完成,结果:{exif_dict}")return exif_dictexcept Exception:print("exif解析失败")return {}if __name__ == '__main__':image_file = r"test.jpg"result = exif_analysis(image_file)print(result)
运行后结果中可以获取经纬度
三 通过百度地图开发者平台解析
上一个步骤中已经能获取到经纬度度信息,根据经纬度信息获取详情的地理位置信息可以通过百度地图的开放者平台实现
1 [百度开发者平台](控制台 | 百度地图开放平台 (baidu.com))中创建一个应用
创建一个应用后,记住应用访问的AK
设置应用访问的白名单
import os
import requests
from datetime import datetime
import exifreaddef get_latlng(content):"""获取经纬度"""lat_lng_info = {"lat_key": "GPS GPSLatitudeRef","lat_value": "GPS GPSLatitude","lng_key": "GPS GPSLongitudeRef","lng_value": "GPS GPSLongitude"}for key in lat_lng_info.values():if key not in content:return "", ""lat_list = content[lat_lng_info["lat_value"]].valueslat = int(lat_list[0]) + int(lat_list[1]) / 60 + float(lat_list[2]) / 3600lng_list = content[lat_lng_info["lng_value"]].valueslng = int(lng_list[0]) + int(lng_list[1]) / 60 + float(lng_list[2]) / 3600return lat, lngdef get_size(content):"""获取照片的大小"""w_key = "EXIF ExifImageWidth"l_key = "EXIF ExifImageLength"if w_key in content and l_key in content:return int(str(content[l_key])), int(str(content[w_key]))else:return "", ""def get_time(content):"""获取拍摄时间"""key = "EXIF DateTimeOriginal"if key in content:str_time = str(content[key])return datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")else:return ""def exif_analysis(image_path):try:print(f"开始分析图片的exit信息:{os.path.basename(image_path)}")f = open(image_path, "rb")content = exifread.process_file(f)length, width = get_size(content)shooting_time = get_time(content)lat, lng = get_latlng(content)f.close()exif_dict = {"name": os.path.basename(image_path),"shooting_time": shooting_time, "lat": lat, "lng": lng,"length": length, "width": width}print(f"exif分析完成,结果:{exif_dict}")return exif_dictexcept Exception:print("exif解析失败")return {}def get_address_by_latlng(lat, lng):"""通过经纬度获取地理位置"""try:ak = "百度开发者平台中的AK"url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=wgs84ll&location=%s, %s" % (ak,lat, lng)print(f"接收到经纬度为:{lat},{lng}")response = requests.get(url)content = response.json()["result"]address_dict = {"detail": content.get("formatted_address"),"country": content["addressComponent"].get("country"),"province": content["addressComponent"].get("province"),"city": content["addressComponent"].get("city"),"district": content["addressComponent"].get("district"),"adcode": content["addressComponent"].get("adcode"),"street": content["addressComponent"].get("street", ""),}print(f"通过经纬度分析地址完成,结果:{address_dict}")return address_dictexcept Exception as e:print(f"通过经纬度获取位置异常:{e}")return {}if __name__ == '__main__':# 上一个步骤中获取的经纬度lat = 30.28670277777778lng = 114.4552027777777result = get_address_by_latlng(lat, lng)print(result)
四、完整的代码
import os
import requests
from datetime import datetime
import exifreaddef get_latlng(content):"""获取经纬度"""lat_lng_info = {"lat_key": "GPS GPSLatitudeRef","lat_value": "GPS GPSLatitude","lng_key": "GPS GPSLongitudeRef","lng_value": "GPS GPSLongitude"}for key in lat_lng_info.values():if key not in content:return "", ""lat_list = content[lat_lng_info["lat_value"]].valueslat = int(lat_list[0]) + int(lat_list[1]) / 60 + float(lat_list[2]) / 3600lng_list = content[lat_lng_info["lng_value"]].valueslng = int(lng_list[0]) + int(lng_list[1]) / 60 + float(lng_list[2]) / 3600return lat, lngdef get_size(content):"""获取照片的大小"""w_key = "EXIF ExifImageWidth"l_key = "EXIF ExifImageLength"if w_key in content and l_key in content:return int(str(content[l_key])), int(str(content[w_key]))else:return "", ""def get_time(content):"""获取拍摄时间"""key = "EXIF DateTimeOriginal"if key in content:str_time = str(content[key])return datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")else:return ""def exif_analysis(image_path):try:print(f"开始分析图片的exit信息:{os.path.basename(image_path)}")f = open(image_path, "rb")content = exifread.process_file(f)length, width = get_size(content)shooting_time = get_time(content)lat, lng = get_latlng(content)f.close()exif_dict = {"name": os.path.basename(image_path),"shooting_time": shooting_time, "lat": lat, "lng": lng,"length": length, "width": width}print(f"exif分析完成,结果:{exif_dict}")return exif_dictexcept Exception:print("exif解析失败")return {}def get_address_by_latlng(lat, lng):"""通过经纬度获取地理位置"""try:ak = "百度地图开发者平台中的ak码"url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=wgs84ll&location=%s, %s" % (ak,lat, lng)print(f"接收到经纬度为:{lat},{lng}")response = requests.get(url)content = response.json()["result"]address_dict = {"detail": content.get("formatted_address"),"country": content["addressComponent"].get("country"),"province": content["addressComponent"].get("province"),"city": content["addressComponent"].get("city"),"district": content["addressComponent"].get("district"),"adcode": content["addressComponent"].get("adcode"),"street": content["addressComponent"].get("street", ""),}print(f"通过经纬度分析地址完成,结果:{address_dict}")return address_dictexcept Exception as e:print(f"通过经纬度获取位置异常:{e}")return {}def main(image_file):image_info = exif_analysis(image_file)lat = image_info.get("lat")lng = image_info.get("lng")result = get_address_by_latlng(lat, lng)return resultif __name__ == '__main__':image_file = r"test.png"result = main(image_file)print(result)