1. 程式人生 > >python解析照片拍攝時間和地點資訊

python解析照片拍攝時間和地點資訊

一、概述

  1. 通常通過手機或相機拍攝的圖片中影藏了照片的屬性資訊和拍攝資料,主要通過EXIF(Exchangeable image file format: 可交換影象檔案格式) 進行儲存這部分資訊
  2. 該部分資訊可以被修改,另外也可通過影象資訊影藏方式,往影象中寫入特定的資訊,可用於資訊加密等

二、解析圖片拍照時間

  • 環境中需要先安裝exifread,採用下面命令進行:pip install exifread
import os
import exifread

def getExif(path, filename):
    old_full_file_name =
os.path.join(imgpath, filename) FIELD = 'EXIF DateTimeOriginal' fd = open(old_full_file_name, 'rb') tags = exifread.process_file(fd) fd.close() #顯示圖片所有的exif資訊 # print("showing res of getExif: \n") # print(tags) # print("\n\n\n\n"); if FIELD in tags: print
("\nstr(tags[FIELD]): %s" %(str(tags[FIELD]))) # 獲取到的結果格式類似為:2018:12:07 03:10:34 print("\nstr(tags[FIELD]).replace(':', '').replace(' ', '_'): %s" %(str(tags[FIELD]).replace(':', '').replace(' ', '_'))) # 獲取結果格式類似為:20181207_031034 print("\nos.path.splitext(filename)[1]: %s" %(os.path.splitext(
filename)[1])) # 獲取了圖片的格式,結果類似為:.jpg new_name = str(tags[FIELD]).replace(':', '').replace(' ', '_') + os.path.splitext(filename)[1] print("\nnew_name: %s" %(new_name)) # 20181207_031034.jpg time = new_name.split(".")[0][:13] new_name2 = new_name.split(".")[0][:8] + '_' +filename print("\nfilename: %s" %filename) print("\n%s的拍攝時間是: %s年%s月%s日%s時%s分" %(filename,time[0:4],time[4:6],time[6:8],time[9:11],time[11:13])) # 可對圖片進行重新命名 new_full_file_name = os.path.join(imgpath, new_name2) #print(old_full_file_name," ---> ", new_full_file_name) # os.rename(old_full_file_name, new_full_file_name) else: print('No {} found'.format(FIELD),' in: ', old_full_file_name) imgpath = "/home/yph001/python_photo/photo/" for filename in os.listdir(imgpath): # os.path.join用於路徑拼接,將imgpath和filename連在一起得到完整的路徑,後面的引數可有多個,從第一個以”/”開頭的引數開始拼接 full_file_name = os.path.join(imgpath, filename) # os.path.isfile用於判斷路徑指向的是否為檔案,相類似的os.path.isdir用於判斷是否為資料夾 if os.path.isfile(full_file_name): getExif(imgpath, filename) print(full_file_name)
  • 其中,主要通過tags = exifread.process_file(fd) 這個函式讀取了圖片的exif資訊,其中讀取的圖片資訊大致包含以下內容:
{'Image ImageWidth': (0x0100) Short=4032 @ 18, 
'Image Model': (0x0110) ASCII=****@ 158, 
'Image ImageLength': (0x0101) Short=3024 @ 42,
 'Image Orientation': (0x0112) Short=Horizontal (normal) @ 54, 
'Image DateTime': (0x0132) ASCII=2018:12:07 03:10:34 @ 166, 
'Image YCbCrPositioning': (0x0213) Short=Centered @ 78, 
'Image ExifOffset': (0x8769) Long=209 @ 90, 
'Image ResolutionUnit': (0x0128) Short=Pixels/Inch @ 102, 
'Image GPSInfo': (0x8825) Long=792 @ 114, 
'Image XResolution': (0x011A) Ratio=72 @ 186, 
'Image YResolution': (0x011B) Ratio=72 @ 194, 
'Image Make': (0x010F) ASCII=Xiaomi @ 202, 
'Thumbnail JPEGInterchangeFormat': (0x0201) Long=928 @ 808, 
'Thumbnail Orientation': (0x0112) Short=Horizontal (normal) @ 820, 
'Thumbnail JPEGInterchangeFormatLength': (0x0202) Long=8039 @ 832, 
'Thumbnail Compression': (0x0103) Short=JPEG (old-style) @ 844, 
'Thumbnail ResolutionUnit': (0x0128) Short=Pixels/Inch @ 856, 
'Thumbnail XResolution': (0x011A) Ratio=72 @ 912, 
'Thumbnail YResolution': (0x011B) Ratio=72 @ 920, 
'Thumbnail ExifImageLength': (0xA003) Long=240 @ 892, 
'Thumbnail ExifImageWidth': (0xA002) Long=320 @ 904, 
'EXIF ISOSpeedRatings': (0x8827) Long=372 @ 219, 
'EXIF ExposureProgram': (0x8822) Short=Program Normal @ 231, 
'EXIF FNumber': (0x829D) Ratio=19/10 @ 599, 'EXIF ExposureTime': (0x829A) Ratio=1/50 @ 607, 
'EXIF Tag 0x9999': (0x9999) ASCII={"sensor_type":"rear","mirror":false} @ 615, 
'EXIF SensingMethod': (0xA217) Short=Not defined @ 279, 
'EXIF SubSecTimeDigitized': (0x9292) ASCII=183622 @ 653, 
'EXIF SubSecTimeOriginal': (0x9291) ASCII=183622 @ 660, 
'EXIF SubSecTime': (0x9290) ASCII=183622 @ 667, 
'EXIF FocalLength': (0x920A) Ratio=197/50 @ 674, 
'EXIF Flash': (0x9209) Short=Flash did not fire, compulsory flash mode @ 339, 
'EXIF LightSource': (0x9208) Short=Unknown @ 351, 
'EXIF MeteringMode': (0x9207) Short=CenterWeightedAverage @ 363,
 'EXIF SceneCaptureType': (0xA406) Short=Standard @ 375, 
'Interoperability InteroperabilityIndex': (0x0001) ASCII=R98 @ 772, 
'Interoperability InteroperabilityVersion': (0x0002) Undefined=[48, 49, 48, 48] @ 784, 
'EXIF InteroperabilityOffset': (0xA005) Long=762 @ 387, 
'EXIF FocalLengthIn35mmFilm': (0xA405) Short=20 @ 399,
 'EXIF MaxApertureValue': (0x9205) Ratio=37/20 @ 682, 
'EXIF DateTimeDigitized': (0x9004) ASCII=2018:12:07 03:10:34 @ 690,
 'EXIF ExposureBiasValue': (0x9204) Signed Ratio=0 @ 710, 
'EXIF ExifImageLength': (0xA003) Long=3024 @ 447, 
'EXIF WhiteBalance': (0xA403) Short=Auto @ 459,
 'EXIF DateTimeOriginal': (0x9003) ASCII=2018:12:07 03:10:34 @ 718,
 'EXIF BrightnessValue': (0x9203) Signed Ratio=-79/50 @ 738, 
'EXIF ExifImageWidth': (0xA002) Long=4032 @ 495, 
'EXIF ExposureMode': (0xA402) Short=Auto Exposure @ 507, 
'EXIF ApertureValue': (0x9202) Ratio=37/20 @ 746, 
'EXIF ComponentsConfiguration': (0x9101) Undefined=YCbCr @ 531, 
'EXIF ColorSpace': (0xA001) Short=sRGB @ 543, 
'EXIF SceneType': (0xA301) Byte=Directly Photographed @ 555, 
'EXIF ShutterSpeedValue': (0x9201) Signed Ratio=5643/1000 @ 754, 
'EXIF ExifVersion': (0x9000) Undefined=0220 @ 579, 'EXIF FlashPixVersion': (0xA000) Undefined=0100 @ 591, 
'JPEGThumbnail': b'\xff\xd8\xf
  • exif資訊中則包含拍照時間資訊,通過讀取EXIF DateTimeOriginal的值則可獲取其資訊,並進行解析和處理則可獲得拍照時間
  • 上述程式碼為了便於理解,多處增加了print輸出變數的值,執行結果如下:
[email protected]:~python_photo$ python parase_pic.py 

str(tags[FIELD]): 2018:12:07 03:10:34

str(tags[FIELD]).replace(':', '').replace(' ', '_'): 20181207_031034

os.path.splitext(filename)[1]: .jpg

new_name: 20181207_031034.jpg

filename: 1.jpg

1.jpg的拍攝時間是: 201812070310

三、解析拍照地點

  • 一般手機拍照的時候預設會開啟保留地理資訊開關,但通常只有在室外拍的圖片有GPS資訊,因室內GPS資訊不太好。
  • 突變經過壓縮之後,通常會將GPS資訊壓縮掉,則不能看到GPS資訊。
  • 解析拍照地點的程式碼如下:
import exifread
import re
import json
import requests

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)

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}

def find_address_from_GPS(GPS):
    """
    使用Geocoding API把經緯度座標轉換為結構化地址。
    :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]
    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"]
    return formatted_address,province,city,district

GPS_info = find_GPS_image(pic_path='photo/09.jpg')
address = find_address_from_GPS(GPS=GPS_info)
print(address)

  • 其中將經緯度轉換為結構化地址需要類似呼叫百度地圖api獲取,上述程式碼中api呼叫的api和key則可直接來使用

四、參考資料