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输出变量的值,运行结果如下:
yph001@ubuntu:~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则可直接来使用

四、参考资料

  • 利用python读取照片拍摄时间来重命名照片,方便组织和查找
  • 使用Python对带有GPS信息的照片进行定位
  • 黑客小攻略 – 使用Python通过带有GPS信息的照片进行监控定位

你可能感兴趣的:(图像处理)