目錄
一.引言
1.读取照片信息,获取坐标
2.通过baidu Map的API将GPS信息转换成地址。
二.源码附上!!!
注意事项
首頁 後端開發 Python教學 怎麼用python取得到照片拍攝時的詳細位置

怎麼用python取得到照片拍攝時的詳細位置

May 19, 2023 pm 01:22 PM
python

    一.引言

    我们的朋友给我们发来一张照片我们如何获取到她的位置呢?

    用手机拍照会带着GPS信息,原来没注意过这个,因此查看下并使用代码获取照片里的GPS信息

    查看图片文件属性

    怎麼用python取得到照片拍攝時的詳細位置

    1.读取照片信息,获取坐标

    ExifRead

    Python library to extract EXIF data from tiff and jpeg files.

    安装

    pip install exifread
    登入後複製

    读取GPS

    import exifread
    import re
    
    def read():
        GPS = {}
        date = ''
        f = open("C:\\Users\\24190\\Desktop\\小朱学长.jpg",'rb')
        contents = exifread.process_file(f)
        for key in contents:
            if key == "GPS GPSLongitude":
                print("经度 =", contents[key],contents['GPS GPSLatitudeRef'])
            elif key =="GPS GPSLatitude":
                print("纬度 =",contents[key],contents['GPS GPSLongitudeRef'])
            #print(contents)
    read()
    登入後複製

    运行

    怎麼用python取得到照片拍攝時的詳細位置

    我们得到了一个简易的gps地址

    如果想要读取全部的拍摄信息:

    # 读取照片的GPS经纬度信息
    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)
                            # 经度
                            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}
    登入後複製

    2.通过baidu Map的API将GPS信息转换成地址。

    众所周知gps和百度的经纬度会有误差,那么我们需要调用百度转换接口,这个百度目前没有开源。

    # 通过baidu Map的API将GPS信息转换成地址。
    def find_address_from_GPS(GPS):
            """
            使用Geocoding API把经纬度坐标转换为结构化地址。
            :param GPS:
            :return:
            """
            secret_k ey = 'XXX'
            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
    登入後複製

    然后在主函数输出:

    怎麼用python取得到照片拍攝時的詳細位置

    二.源码附上!!!

    # coding=utf-8
    import exifread
    import re
    import json
    import requests
    import os
    
    
    # 转换经纬度格式
    def latitude_and_longitude_convert_to_decimal_system(*arg):
            """
            经纬度转为小数, param arg:
            :return: 十进制小数
            """
            return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
    
    
    # 读取照片的GPS经纬度信息
    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)
                            # 经度
                            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信息转换成地址。
    def find_address_from_GPS(GPS):
            """
            使用Geocoding API把经纬度坐标转换为结构化地址。
            :param GPS:
            :return:
            """
            secret_ke y = '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='小朱学长.jpg')
            address = find_address_from_GPS(GPS=GPS_info)
            print("拍摄时间:" + GPS_info.get("date_information"))
            print('照片拍摄地址:' + str(address))
    登入後複製

    注意事项

    1.照片的地址信息等,一般的手机相机默认是打开的。

    2.微信和QQ里面发送原图,信息都会完整的保留下来。

    3.代码里面需要处理在照片我放到了代码的同文件夹下,所以没有写路径,大家可以自己写路径,或者放到于代码相同的路径下即可。

    以上是怎麼用python取得到照片拍攝時的詳細位置的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    AI Hentai Generator

    AI Hentai Generator

    免費產生 AI 無盡。

    熱門文章

    R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳圖形設置
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.如果您聽不到任何人,如何修復音頻
    4 週前 By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25:如何解鎖Myrise中的所有內容
    1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

    熱工具

    記事本++7.3.1

    記事本++7.3.1

    好用且免費的程式碼編輯器

    SublimeText3漢化版

    SublimeText3漢化版

    中文版,非常好用

    禪工作室 13.0.1

    禪工作室 13.0.1

    強大的PHP整合開發環境

    Dreamweaver CS6

    Dreamweaver CS6

    視覺化網頁開發工具

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級程式碼編輯軟體(SublimeText3)

    mysql 是否要付費 mysql 是否要付費 Apr 08, 2025 pm 05:36 PM

    MySQL 有免費的社區版和收費的企業版。社區版可免費使用和修改,但支持有限,適合穩定性要求不高、技術能力強的應用。企業版提供全面商業支持,適合需要穩定可靠、高性能數據庫且願意為支持買單的應用。選擇版本時考慮的因素包括應用關鍵性、預算和技術技能。沒有完美的選項,只有最合適的方案,需根據具體情況謹慎選擇。

    HadiDB:Python 中的輕量級、可水平擴展的數據庫 HadiDB:Python 中的輕量級、可水平擴展的數據庫 Apr 08, 2025 pm 06:12 PM

    HadiDB:輕量級、高水平可擴展的Python數據庫HadiDB(hadidb)是一個用Python編寫的輕量級數據庫,具備高度水平的可擴展性。安裝HadiDB使用pip安裝:pipinstallhadidb用戶管理創建用戶:createuser()方法創建一個新用戶。 authentication()方法驗證用戶身份。 fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

    Navicat查看MongoDB數據庫密碼的方法 Navicat查看MongoDB數據庫密碼的方法 Apr 08, 2025 pm 09:39 PM

    直接通過 Navicat 查看 MongoDB 密碼是不可能的,因為它以哈希值形式存儲。取回丟失密碼的方法:1. 重置密碼;2. 檢查配置文件(可能包含哈希值);3. 檢查代碼(可能硬編碼密碼)。

    如何針對高負載應用程序優化 MySQL 性能? 如何針對高負載應用程序優化 MySQL 性能? Apr 08, 2025 pm 06:03 PM

    MySQL數據庫性能優化指南在資源密集型應用中,MySQL數據庫扮演著至關重要的角色,負責管理海量事務。然而,隨著應用規模的擴大,數據庫性能瓶頸往往成為製約因素。本文將探討一系列行之有效的MySQL性能優化策略,確保您的應用在高負載下依然保持高效響應。我們將結合實際案例,深入講解索引、查詢優化、數據庫設計以及緩存等關鍵技術。 1.數據庫架構設計優化合理的數據庫架構是MySQL性能優化的基石。以下是一些核心原則:選擇合適的數據類型選擇最小的、符合需求的數據類型,既能節省存儲空間,又能提升數據處理速度

    Python:探索其主要應用程序 Python:探索其主要應用程序 Apr 10, 2025 am 09:41 AM

    Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

    如何將 AWS Glue 爬網程序與 Amazon Athena 結合使用 如何將 AWS Glue 爬網程序與 Amazon Athena 結合使用 Apr 09, 2025 pm 03:09 PM

    作為數據專業人員,您需要處理來自各種來源的大量數據。這可能會給數據管理和分析帶來挑戰。幸運的是,兩項 AWS 服務可以提供幫助:AWS Glue 和 Amazon Athena。

    2小時的Python計劃:一種現實的方法 2小時的Python計劃:一種現實的方法 Apr 11, 2025 am 12:04 AM

    2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

    mysql 可以連接到 sql 服務器嗎 mysql 可以連接到 sql 服務器嗎 Apr 08, 2025 pm 05:54 PM

    否,MySQL 無法直接連接到 SQL Server。但可以使用以下方法實現數據交互:使用中間件:將數據從 MySQL 導出到中間格式,然後通過中間件導入到 SQL Server。使用數據庫鏈接器:商業工具可提供更友好的界面和高級功能,本質上仍通過中間件方式實現。

    See all articles