點擊上方“機器學(xué)習(xí)愛好者社區(qū)”
選擇“星標”公眾號,重磅干貨掠剑,第一時間送達
這是一個悲傷的故事
昨天屈芜,我司的python開發(fā)小哥剛準備下班陪女友共進晚餐,滿心期待地盼著女友的回復(fù)朴译,卻接到女友晚上要加班的電話井佑,滿滿的失落感涌上心頭~
還有比這空歡喜更讓人傷心難過的事情嘛!emmm還真有
不一會兒动分,小哥哥的女友發(fā)來了一張自稱在加班并將背景模糊的自拍照毅糟,故事從這兒就開始了:
? 如下 ↓ ↓ ↓
不就是一張自拍照嗎?這事兒又是為何最終讓人難過呢澜公,難道這不是女友在安慰我們的python開發(fā)小哥哥嗎姆另?
老鐵們,你們要是這么想坟乾,接下來文章內(nèi)容一定要細細品味迹辐、好好學(xué)習(xí)、深入研究……
為何女友要背景虛化甚侣?為何要特意發(fā)照片明吩?明明平常工作不加班呀?
面對重重疑惑殷费,我們的python開發(fā)小哥哥心生疑慮印荔,決心運用所學(xué)python知識對女友自拍照編寫了一段代碼進行分析,不遛彎了详羡,結(jié)果卻顯示照片的拍攝地址為「X X酒店」
綠帽從天而降仍律,小哥哥這綠帽子是戴的穩(wěn)穩(wěn)的了,好在及時止損了实柠,不然天天為老板996水泉,最終換來的卻是女友的669??
想知道小哥哥是如何捍衛(wèi)自己男人的尊嚴的,快拿小本本記下來窒盐,快拿小本本記下來草则,快拿小本本記下來!P防臁炕横!?
重要事情說三遍
第一步:編寫python腳本分析照片
通過下載發(fā)來的照片原圖,利用python來編寫全文的腳本文件葡粒,由此讀取照片中拍攝的詳細地址(地址可以詳細到具體的街道和酒店名稱)
第二步:引入exifread模塊
再安裝python中的exifread模塊看锉,用于照片分析
pip install exifread 安裝exfriead模塊姿锭。
PS C:\WINDOWS\system32> pip install exifread
Collecting exifread
Downloading ExifRead-2.3.2-py3-none-any.whl (38 kB)
Installing collected packages: exifread
Successfully installed exifread-2.3.2
PS C:\WINDOWS\system32> pip install json
第三步:讀取GPS定位的經(jīng)緯度信息
通過Python的exifread模塊,可以讀取照片中隱藏的經(jīng)緯度信息(其實我們?nèi)粘5恼掌型[藏著很多的秘密伯铣,包括拍攝時間以及經(jīng)緯度等)
#讀取照片的GPS經(jīng)緯度信息
def find_GPS_image(pic_path):
GPS = {}
date = ''
with open(pic_path, 'rb') as f:
tags = exifread.process_file(f)
for tag, value in tags.items():
#緯度
if re.match('GPS GPSLatitudeRef', tag):
GPS['GPSLatitudeRef'] = str(value)
#經(jīng)度
elif re.match('GPS GPSLongitudeRef', tag):
GPS['GPSLongitudeRef'] = str(value)
#海拔
elif re.match('GPS GPSAltitudeRef', tag):
GPS['GPSAltitudeRef'] = str(value)
elif re.match('GPS GPSLatitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSLongitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSAltitude', tag):
GPS['GPSAltitude'] = str(value)
elif re.match('.*Date.*', tag):
date = str(value)
return {'GPS_information': GPS, 'date_information': date}
第四步:利用百度API將GPS轉(zhuǎn)地址
最后我們再通過調(diào)用百度的API接口呻此,將獲得的GPS經(jīng)緯度信息轉(zhuǎn)換為可定位讀取的具體地址信息
def find_address_from_GPS(GPS):
secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
if not GPS['GPS_information']:
return '該照片無GPS信息'
#經(jīng)緯度信息
lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
secret_key, lat, lng)
response = requests.get(baidu_map_api)
#百度API轉(zhuǎn)換成具體的地址
content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
print(content)
baidu_map_address = json.loads(content)
#將返回的json信息解析整理出來
formatted_address = baidu_map_address["result"]["formatted_address"]
province = baidu_map_address["result"]["addressComponent"]["province"]
city = baidu_map_address["result"]["addressComponent"]["city"]
district = baidu_map_address["result"]["addressComponent"]["district"]
location = baidu_map_address["result"]["sematic_description"]
return formatted_address,province,city,district,location
if __name__ == '__main__':
GPS_info = find_GPS_image(pic_path='C:/女友自拍.jpg')
address = find_address_from_GPS(GPS=GPS_info)
print("拍攝時間:" + GPS_info.get("date_information"))
print('照片拍攝地址:' + str(address))
接下來就靜待開獎……
{"status":0,"result":{"location":{"lng":103.41424699999998,"lat":24.410461020097278},
"formatted_address":"云南省紅河哈尼族彝族自治州彌勒縣",
"business":"",
"addressComponent":{"country":"中國",
"country_code":0,
"country_code_iso":"CHN",
"country_code_iso2":"CN",
"province":"云南省",
"city":"紅河哈尼族彝族自治州",
"city_level":2,"district":"彌勒縣",
"town":"","town_code":"","adcode":"532526",
"street_number":"",
"direction":"","distance":""},
"sematic_description":"湖泉酒店-A座東南128米",
"cityCode":107}}
拍攝時間:2021:5:03 20:05:32
照片拍攝地址:('云南省紅河哈尼族彝族自治州彌勒縣', '云南省', '紅河哈尼族彝族自治州', '彌勒縣', '湖泉酒店-A座東南128米')
完整代碼如下
import exifread
import re
import json
import requests
import os
#轉(zhuǎn)換經(jīng)緯度格式
def latitude_and_longitude_convert_to_decimal_system(*arg):
"""
經(jīng)緯度轉(zhuǎn)為小數(shù), param arg:
:return: 十進制小數(shù)
"""
return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
#讀取照片的GPS經(jīng)緯度信息
def find_GPS_image(pic_path):
GPS = {}
date = ''
with open(pic_path, 'rb') as f:
tags = exifread.process_file(f)
for tag, value in tags.items():
#緯度
if re.match('GPS GPSLatitudeRef', tag):
GPS['GPSLatitudeRef'] = str(value)
#經(jīng)度
elif re.match('GPS GPSLongitudeRef', tag):
GPS['GPSLongitudeRef'] = str(value)
#海拔
elif re.match('GPS GPSAltitudeRef', tag):
GPS['GPSAltitudeRef'] = str(value)
elif re.match('GPS GPSLatitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLatitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSLongitude', tag):
try:
match_result = re.match('\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
GPS['GPSLongitude'] = int(match_result[0]), int(match_result[1]), int(match_result[2])
except:
deg, min, sec = [x.replace(' ', '') for x in str(value)[1:-1].split(',')]
GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
elif re.match('GPS GPSAltitude', tag):
GPS['GPSAltitude'] = str(value)
elif re.match('.*Date.*', tag):
date = str(value)
return {'GPS_information': GPS, 'date_information': date}
#通過baidu Map的API將GPS信息轉(zhuǎn)換成地址。
def find_address_from_GPS(GPS):
"""
使用Geocoding API把經(jīng)緯度坐標轉(zhuǎn)換為結(jié)構(gòu)化地址腔寡。
:param GPS:
:return:
"""
secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
if not GPS['GPS_information']:
return '該照片無GPS信息'
lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
secret_key, lat, lng)
response = requests.get(baidu_map_api)
content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
print(content)
baidu_map_address = json.loads(content)
formatted_address = baidu_map_address["result"]["formatted_address"]
province = baidu_map_address["result"]["addressComponent"]["province"]
city = baidu_map_address["result"]["addressComponent"]["city"]
district = baidu_map_address["result"]["addressComponent"]["district"]
location = baidu_map_address["result"]["sematic_description"]
return formatted_address,province,city,district,location
if __name__ == '__main__':
GPS_info = find_GPS_image(pic_path='C:/Users/pacer/desktop/img/5.jpg')
address = find_address_from_GPS(GPS=GPS_info)
print("拍攝時間:" + GPS_info.get("date_information"))
print('照片拍攝地址:' + str(address))
?·合作焚鲜、交流請關(guān)注:公眾號「機器學(xué)習(xí)愛好者社區(qū)」(ML_shequ)
?·轉(zhuǎn)載請?zhí)砑游⑿牛簓imudeguo