python3获取图片拍摄位置和时间

python3获取图片拍摄位置和时间

调试运行的环境

windows10, python3.7

准备工作

安装exifread库,requests库,申请高德地图web服务api,要用到其中的坐标转换和你地理编码功能。安装相关库的方法很简单,这里就不说了。
申请高德Web服务api的key高德开放平台在这里插入图片描述

关键代码

导入要使用的模块

import requests
import exifread
import json

使用exifread获取图片的gps坐标和图片的拍摄时间

def __get_locations_gps(self):
        """通过exifread获取图片的gps位置坐标"""

        # 获取exif属性
        with open(self.img_path, 'rb') as f:
            img_exif = exifread.process_file(f)
            print(f"图片拍摄时间:{img_exif.get('EXIF DateTimeOriginal')}")
        # 经度
        longitude_gps = img_exif['GPS GPSLongitude']
        longitude_gps = eval(str(longitude_gps))
        longitude_gps = longitude_gps[0] + longitude_gps[1] / 60 + \
                        longitude_gps[2] / 3600
        longitude_gps = '{:.6f}'.format(longitude_gps)
        # 纬度
        latitude_gps = img_exif['GPS GPSLatitude']
        latitude_gps = eval(str(latitude_gps))
        latitude_gps = latitude_gps[0] + latitude_gps[1] / 60 + latitude_gps[
            2] / 3600
        latitude_gps = '{:.6f}'.format(latitude_gps)

        locations_gps = longitude_gps + ',' + latitude_gps
        # 返回gps坐标
        return locations_gps

调用高德地图的坐标转换,把gps坐标转成高德的坐标,提高精准度

def __convert_coordsys(self):
        """调用高德API将gps坐标转换成高德地图坐标"""

        url = "https://restapi.amap.com/v3/assistant/coordinate/convert?"
        headers = {
            'User-Agent': self.user_agent
        }
        params = {
            # 在高德地图官网申请Web服务API类型KEY
            'key': self.api_key,
            # 经度和纬度用","分割,经度在前,纬度在后,经纬度小数点后不得超过6位
            'locations': self.__get_locations_gps(),
            # 原坐标系:gps
            'coordsys': 'gps'
        }
        response = requests.get(url, headers=headers, params=params)
        response = eval(response.text)
        locations_gd = response['locations']
        locations_gd = eval(locations_gd)
        locations_gd = '{:.6f},{:.6f}'.format(locations_gd[0], locations_gd[1])

        # 返回高德坐标
        print(f"高德地图经纬度:{locations_gd}")
        return locations_gd

我们已经拿到了高德对应的坐标值,可以返回格式地址信息,或者在浏览器上打开查看地图,按坐标搜索位置地图查看

def __get_addr(self):
        """根据高德地图坐标获取地理位置"""

        url = "https://restapi.amap.com/v3/geocode/regeo?"
        headers = {
            'User-Agent': self.user_agent
        }
        params = {
            # 在高德地图官网申请Web服务API类型KEY
            'key': self.api_key,
            # 经度在前,纬度在后,经纬度间以“,”分割,经纬度小数点后不要超过 6 位
            'location': self.__convert_coordsys(),
        }
        response = requests.get(url, headers=headers, params=params)
        addr_data = json.loads(response.text)
        address = addr_data.get('regeocode').get('formatted_address')

        # 返回详细地址
        return address

完整代码

import requests
import exifread
import json


class Location:
    """图片地理位置类"""

    def __init__(self, img_path):
        self.img_path = img_path
        self.api_key = '在高德申请的KEY'
        self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'

    def __get_locations_gps(self):
        """通过exifread获取图片的gps位置坐标"""

        # 获取exif属性
        with open(self.img_path, 'rb') as f:
            img_exif = exifread.process_file(f)
            print(f"图片拍摄时间:{img_exif.get('EXIF DateTimeOriginal')}")
        # 经度
        longitude_gps = img_exif['GPS GPSLongitude']
        longitude_gps = eval(str(longitude_gps))
        longitude_gps = longitude_gps[0] + longitude_gps[1] / 60 + \
                        longitude_gps[2] / 3600
        longitude_gps = '{:.6f}'.format(longitude_gps)
        # 纬度
        latitude_gps = img_exif['GPS GPSLatitude']
        latitude_gps = eval(str(latitude_gps))
        latitude_gps = latitude_gps[0] + latitude_gps[1] / 60 + latitude_gps[
            2] / 3600
        latitude_gps = '{:.6f}'.format(latitude_gps)

        locations_gps = longitude_gps + ',' + latitude_gps
        # 返回gps坐标
        return locations_gps

    def __convert_coordsys(self):
        """调用高德API将gps坐标转换成高德地图坐标"""

        url = "https://restapi.amap.com/v3/assistant/coordinate/convert?"
        headers = {
            'User-Agent': self.user_agent
        }
        params = {
            # 在高德地图官网申请Web服务API类型KEY
            'key': self.api_key,
            # 经度和纬度用","分割,经度在前,纬度在后,经纬度小数点后不得超过6位
            'locations': self.__get_locations_gps(),
            # 原坐标系:gps
            'coordsys': 'gps'
        }
        response = requests.get(url, headers=headers, params=params)
        response = eval(response.text)
        locations_gd = response['locations']
        locations_gd = eval(locations_gd)
        locations_gd = '{:.6f},{:.6f}'.format(locations_gd[0], locations_gd[1])

        # 返回高德坐标
        print(f"高德地图经纬度:{locations_gd}")
        return locations_gd

    def __get_addr(self):
        """根据高德地图坐标获取地理位置"""

        url = "https://restapi.amap.com/v3/geocode/regeo?"
        headers = {
            'User-Agent': self.user_agent
        }
        params = {
            # 在高德地图官网申请Web服务API类型KEY
            'key': self.api_key,
            # 经度在前,纬度在后,经纬度间以“,”分割,经纬度小数点后不要超过 6 位
            'location': self.__convert_coordsys(),
        }
        response = requests.get(url, headers=headers, params=params)
        addr_data = json.loads(response.text)
        address = addr_data.get('regeocode').get('formatted_address')

        # 返回详细地址
        return address

    def run(self):
        try:
            address = self.__get_addr()
            print(f"图片拍摄位置:{address}")
        except Exception as ret:
            print(ret)


def main():
    # 原图
    location = Location('test3.jpg')
    # 寻找位置信息
    # 检验坐标值
    # https://lbs.amap.com/console/show/picker
    location.run()
    # 在浏览器中打开指定url
    # import webbrowser
    # webbrowser.open("https://lbs.amap.com/console/show/picker")


if __name__ == '__main__':
    main()

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
获取图片的地理位置,需要使用图片的元数据信息。在Python中,可以使用Pillow库来读取图片的元数据信息。具体步骤如下: 1. 安装Pillow库:在命令行中输入`pip install Pillow`即可安装。 2. 导入Pillow库:在Python代码中导入Pillow库,代码如下: ``` from PIL import Image ``` 3. 打开图片:使用Image.open()方法打开图片,代码如下: ``` img = Image.open('image.jpg') ``` 4. 获取图片的元数据信息:使用img._getexif()方法获取图片的元数据信息,代码如下: ``` exif_data = img._getexif() ``` 5. 解析元数据信息:元数据信息是一个字典类型,其中包含了很多信息,包括图片拍摄时间、相机型号、GPS信息等。要获取GPS信息,需要解析元数据信息中的GPS信息。具体代码如下: ``` # 获取GPS信息 gps_info = {} for key in exif_data[34853].keys(): decode_key = Image.ExifTags.GPSTAGS.get(key, key) gps_info[decode_key] = exif_data[34853][key] # 获取经度和纬度 latitude = gps_info.get('GPSLatitude') longitude = gps_info.get('GPSLongitude') # 转换经度和纬度格式 latitude = float(latitude[0]) + float(latitude[1])/60 + float(latitude[2])/3600 longitude = float(longitude[0]) + float(longitude[1])/60 + float(longitude[2])/3600 # 获取经度和纬度的方向 latitude_ref = gps_info.get('GPSLatitudeRef') longitude_ref = gps_info.get('GPSLongitudeRef') # 根据方向转换经度和纬度的正负 if latitude_ref == 'S': latitude = -latitude if longitude_ref == 'W': longitude = -longitude # 输出经度和纬度 print('Latitude:', latitude) print('Longitude:', longitude) ``` 以上代码可以获取图片的经度和纬度信息。如果需要获取更多的GPS信息,可以参考Pillow库的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值