利用Python解析照片中的具體位置

想不想知道和你正在聊天的人現在在哪裏,比如我正在微信聊天,對方給我發了幾張照片

大家猜猜我這三張照片都是在哪照的?

我們用代碼執行一下:

這張就不放具體位置了……

答案揭曉,第一張是在重慶朝天門碼頭,第二張在長沙橘子洲

如何通過代碼解析到照片中的具體位置呢?如果人人都可以通過照片解析他人的位置,豈不是亂了套了!別急,想通過代碼解析微信發送的照片地理位置,需要滿足以下幾點要求:

  1. 他人通過選擇原圖的方式,發送照片

  2. 相機拍照時,默認設置了GPS定位

  3. 非iphone手機(iphone的地理位置,不會保存在照片中)

現在的手機在拍照時,默認都是打開GPS地位的。那麼你只需要確認對方手機不是iphone的,然後讓他給你發送原圖就OK了。
照片屬性中保存了經緯度,可我們如何能通過經緯度逆推地理位置呢?此時我們需要使用到百度地圖的逆地理編碼工具(也可以使用高德的):

                                                                                     百度地圖逆地理編碼

接口很簡單,我們簡單註冊後,創建一個針對地理位置解析的應用即可:

源代碼

說了這麼多,最終的逆天代碼發佈出來,讓大家圓個福爾摩斯的夢吧!

# -*- coding: utf-8 -*-
# @Author   : 姜昊
# @Date     : 2020/02/22 13:59

import requests
import exifread


class GetPhotoInfo:
    def __init__(self, photo):
        self.photo = photo
        # 百度地圖ak
        self.ak = '3iVKI77ap5Tb2M2FIGS1gvEtcSzD3yWZ'
        self.location = self.get_photo_info()

    def get_photo_info(self, ):
        with open(self.photo, 'rb') as f:
            tags = exifread.process_file(f)
        try:
            # 打印照片其中一些信息
            print('拍攝時間:', tags['EXIF DateTimeOriginal'])
            print('照相機製造商:', tags['Image Make'])
            print('照相機型號:', tags['Image Model'])
            print('照片尺寸:', tags['EXIF ExifImageWidth'], tags['EXIF ExifImageLength'])
            # 拿到的是度分秒的經緯度,需要轉化爲十進制的經緯度
            # 轉換公式爲    度 + 分 / 60 + 秒 / 3600
            # 緯度
            lat_ref = tags["GPS GPSLatitudeRef"].printable
            lat = tags["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
            lat = float(lat[0]) + float(lat[1]) / 60 + float(lat[2]) / float(lat[3]) / 3600
            if lat_ref != "N":
                lat = lat * (-1)
            # 經度
            lon_ref = tags["GPS GPSLongitudeRef"].printable
            lon = tags["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
            lon = float(lon[0]) + float(lon[1]) / 60 + float(lon[2]) / float(lon[3]) / 3600
            if lon_ref != "E":
                lon = lon * (-1)
        except KeyError:
            return "ERROR:請確保照片包含經緯度等EXIF信息。"
        else:
            print("經緯度:", lat, lon)
            return lat, lon

    def get_location(self):
        url = 'http://api.map.baidu.com/reverse_geocoding/v3/?ak={}&output=json' \
              '&coordtype=wgs84ll&location={},{}'.format(self.ak, *self.location)
        response = requests.get(url).json()
        status = response['status']
        if status == 0:
            address = response['result']['formatted_address']
            print('詳細地址:', address)
        else:
            print('baidu_map error')


if __name__ == '__main__':
    Main = GetPhotoInfo('微信圖片_20200222140752.jpg')
    Main.get_location()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章