python讀取圖片信息gps位置

直接寫代碼吧

#改進檢測地區
import os
import exifread
import re
import sys
import requests
import json

__author__ = 'DaDaLuLa'


# ************************************************************************
# 代碼功能:                                                               #
#   1.讀取所有圖片文件的exif信息                                            #
#   2.提取圖片中的經緯度,將度、分、秒轉換爲小數形式                           #
#   3.利用百度地圖API接口將經緯度轉換成地址形式                               #
# ************************************************************************


# 遍歷文件夾及子文件夾中的所有圖片,逐個文件讀取exif信息
def get_pic_GPS(pic_dir):
    items = os.listdir(pic_dir)
    for item in items:
        path = os.path.join(pic_dir, item)
        if os.path.isdir(path):
            get_pic_GPS(path)
        else:
            imageread(path)


# 將經緯度轉換爲小數形式
def convert_to_decimal(*gps):
    # 度
    if '/' in gps[0]:
        deg = gps[0].split('/')
        if deg[0] == '0' or deg[1] == '0':
            gps_d = 0
        else:
            gps_d = float(deg[0]) / float(deg[1])
    else:
        gps_d = float(gps[0])
    # 分
    if '/' in gps[1]:
        minu = gps[1].split('/')
        if minu[0] == '0' or minu[1] == '0':
            gps_m = 0
        else:
            gps_m = (float(minu[0]) / float(minu[1])) / 60
    else:
        gps_m = float(gps[1]) / 60
    # 秒
    if '/' in gps[2]:
        sec = gps[2].split('/')
        if sec[0] == '0' or sec[1] == '0':
            gps_s = 0
        else:
            gps_s = (float(sec[0]) / float(sec[1])) / 3600
    else:
        gps_s = float(gps[2]) / 3600

    decimal_gps = gps_d + gps_m + gps_s
    # 如果是南半球或是西半球
    if gps[3] == 'W' or gps[3] == 'S' or gps[3] == "83" or gps[3] == "87":
        return str(decimal_gps * -1)
    else:
        return str(decimal_gps)


# 讀取圖片的經緯度和拍攝時間
def imageread(path):

    f = open(path, 'rb')
    GPS = {}
    Data = ""
    try:
        tags = exifread.process_file(f)
    except:
        return
    print(tags)
    '''
    for tag in tags:               
        print(tag,":",tags[tag])
    '''

    # 南北半球標識
    if 'GPS GPSLatitudeRef' in tags:

        GPS['GPSLatitudeRef'] = str(tags['GPS GPSLatitudeRef'])
        # print(GPS['GPSLatitudeRef'])
    else:
        GPS['GPSLatitudeRef'] = 'N'  # 缺省設置爲北半球

    # 東西半球標識
    if 'GPS GPSLongitudeRef' in tags:
        GPS['GPSLongitudeRef'] = str(tags['GPS GPSLongitudeRef'])
        # print(GPS['GPSLongitudeRef'])
    else:
        GPS['GPSLongitudeRef'] = 'E'  # 缺省設置爲東半球

    # 海拔高度標識
    if 'GPS GPSAltitudeRef' in tags:
        GPS['GPSAltitudeRef'] = str(tags['GPS GPSAltitudeRef'])

    # 獲取緯度
    if 'GPS GPSLatitude' in tags:
        lat = str(tags['GPS GPSLatitude'])
        # 處理無效值
        if lat == '[0, 0, 0]' or lat == '[0/0, 0/0, 0/0]':
            return

        deg, minu, sec = [x.replace(' ', '') for x in lat[1:-1].split(',')]
        # 將緯度轉換爲小數形式
        GPS['GPSLatitude'] = convert_to_decimal(deg, minu, sec, GPS['GPSLatitudeRef'])

    # 獲取經度
    if 'GPS GPSLongitude' in tags:
        lng = str(tags['GPS GPSLongitude'])
        # print(lng)

        # 處理無效值
        if lng == '[0, 0, 0]' or lng == '[0/0, 0/0, 0/0]':
            return

        deg, minu, sec = [x.replace(' ', '') for x in lng[1:-1].split(',')]
        # 將經度轉換爲小數形式
        GPS['GPSLongitude'] = convert_to_decimal(deg, minu, sec, GPS['GPSLongitudeRef'])  # 對特殊的經緯度格式進行處理

    # 獲取海拔高度
    if 'GPS GPSAltitude' in tags:
        GPS['GPSAltitude'] = str(tags["GPS GPSAltitude"])


    # 獲取圖片拍攝時間
    if 'Image DateTime' in tags:
        GPS["DateTime"] = str(tags["Image DateTime"])
        print(GPS["DateTime"])
    elif "EXIF DateTimeOriginal" in tags:
        GPS["DateTime"] = str(tags["EXIF DateTimeOriginal"])
        print(GPS["DateTime"])
    if 'Image Make' in tags:
        print('照相機制造商:', tags['Image Make'])
    if 'Image Model' in tags:
        print('照相機型號:', tags['Image Model'])
    if 'Image ExifImageWidth' in tags:
        print('照片尺寸:', tags['EXIF ExifImageWidth'],tags['EXIF ExifImageLength'])

    if 'GPSLatitude' in GPS:
        # 將經緯度轉換爲地址
        convert_gps_to_address(GPS)


# 利用百度全球逆地理編碼服務(Geocoder)Web API接口服務將經緯轉換爲位置信息
def convert_gps_to_address(GPS):
    secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'  # 百度密鑰
    lat, lng = GPS['GPSLatitude'], GPS['GPSLongitude']
    # 注意coordtype爲wgs84ll(GPS經緯度),否則定位會出現偏差
    baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?coordtype=wgs84ll&location={0},{1}&output=json&pois=0&ak={2}".format(
        lat, lng, secret_key)
    content = requests.get(baidu_map_api).text
    gps_address = json.loads(content)
    # 結構化的地址
    print(gps_address)
    formatted_address = gps_address["result"]["formatted_address"]
    # 國家(若需訪問境外POI,需申請逆地理編碼境外POI服務權限)
    country = gps_address["result"]["addressComponent"]["country"]
    # 省
    province = gps_address["result"]["addressComponent"]["province"]
    # 城市
    city = gps_address["result"]["addressComponent"]["city"]
    # 區
    district = gps_address["result"]["addressComponent"]["district"]
    # 語義化地址描述
    sematic_description = gps_address["result"]["sematic_description"]
    # 將轉換後的信息寫入文件
    with open("gps_address.csv", "a+") as csv:
        csv.write(GPS[
                      "DateTime"] + "|" + formatted_address + "|" + country + "|" + province + "|" + city + "|" + district + "|" + sematic_description + "\n")


if __name__ == "__main__":
    get_pic_GPS("./image")

批量讀取

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