如何用python获取照片的拍摄地

本文介绍了一个Python脚本,用于从照片的EXIF数据中提取GPS信息,并利用Baidu地图API将经纬度转换为详细地址。通过 latitude_and_longitude_convert_to_decimal_system 函数,处理了不同格式的经纬度,最后输出位置信息。
摘要由CSDN通过智能技术生成
import exifread
import re
import json
import requests
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def latitude_and_longitude_convert_to_decimal_system(*arg):
    """
    经纬度转为小数, 作者尝试适用于iphone6、ipad2以上的拍照的照片,
    :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('Image Make', tag):
                print('[*] 品牌信息: ' + str(value))
            if re.match('Image Model', tag):
                print('[*] 具体型号: ' + str(value))
            if re.match('EXIF LensModel', tag):
                print('[*] 摄像头信息: ' + str(value))
            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)
    #print({'GPS_information':GPS, 'date_information': date})
    print('[*] 拍摄时间: '+ date)
    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']
    print('[*] 经度: ' + str(lat) + ', 纬度: ' + str(lng))
    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"]
    return formatted_address


# img_path = sys.argv[1]
img_path = '888.jpg'
if len(img_path) >= 2:
    print('[*] 打开文件: '+ img_path)
    GPS_info = find_GPS_image(pic_path=img_path)
    address = find_address_from_GPS(GPS=GPS_info)
    print('[*] 位置信息: '+address)
else:
    print('python script.py filename')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python的PIL库(Python Imaging Library)来读取照片的Exif信息,其中包含了照片的拍摄日期。然后可以使用shutil库来将照片移动到对应的文件夹中,以实现按拍摄日期整理分类。 以下是一个简单的示例代码: ```python import os import shutil from PIL import Image # 遍历指定目录下的所有照片文件 for filename in os.listdir('path/to/photos'): if filename.endswith('.jpg') or filename.endswith('.jpeg'): filepath = os.path.join('path/to/photos', filename) # 读取照片的Exif信息 with Image.open(filepath) as img: exif = img._getexif() if exif: # 获取拍摄日期 date_str = exif.get(36867) if date_str: # 将日期格式化为yyyy-mm-dd date = '-'.join(date_str.split(' ')[0].split(':')) # 创建目标文件夹并移动照片 target_dir = os.path.join('path/to/sorted_photos', date) os.makedirs(target_dir, exist_ok=True) shutil.move(filepath, os.path.join(target_dir, filename)) ``` 在上述代码中,`path/to/photos`是存放原始照片的目录,`path/to/sorted_photos`是存放按拍摄日期整理分类后的照片的目录。通过遍历原始照片目录下的所有照片文件,并读取其Exif信息,获取照片的拍摄日期,然后将照片移动到以拍摄日期为名称的目录中。如果目标文件夹不存在,则会自动创建。 ### 回答2: 使用Python照片进行按拍摄日期整理分类可通过以下步骤实现: 1. 导入所需的Python模块,如os、shutil等。 2. 使用os模块获取文件夹中的所有文件。 3. 循环遍历每个文件,使用os.path模块获取文件的创建时间或修改时间。 4. 转换时间格式为指定的年月日格式。 5. 创建以年月日为名称的文件夹,通过os模块创建文件夹。 6. 使用shutil模块将文件移动到对应的年月日文件夹中。 7. 完成整理分类后,输出提示信息。 下面是一个简单的示例代码: ```python import os import shutil # 获取文件夹径 folder_path = "照片文件夹径" # 遍历文件夹中的文件 for filename in os.listdir(folder_path): # 获取文件的创建时间 creation_time = os.path.getctime(os.path.join(folder_path, filename)) # 转换时间格式为年月日 date = time.strftime("%Y%m%d", time.localtime(creation_time)) # 创建以年月日为名称的文件夹 new_folder_path = os.path.join(folder_path, date) os.makedirs(new_folder_path, exist_ok=True) # 移动文件到对应的文件夹中 shutil.move(os.path.join(folder_path, filename), os.path.join(new_folder_path, filename)) print("照片已按拍摄日期整理分类完成!") ``` 需要注意的是,以上示例代码的前提是照片文件的元数据中包含了拍摄日期信息,如果照片文件没有拍摄日期信息,可以使用其他方式来获取拍摄日期,例如根据文件名或其他标识信息来判断和分类。 ### 回答3: 使用Python照片按拍摄日期进行整理分类是非常简单的。首先,我们需要安装PIL库来处理图像。 首先,我们需要通过使用PIL库中的`Image.open()`函数打开图片文件。然后,我们可以使用`_getexif()`方法获取图像的元数据,其中包含了拍摄日期等信息。接下来,我们可以使用`DateTimeOriginal`键来提取拍摄日期。 接下来,我们可以使用`os`库的一些函数来创建和移动目录。首先,我们需要将所有图片移动到同一个文件夹中,然后创建一个用于存储分类后的照片的目录。 接下来,我们可以使用`glob`库的函数来获取所有文件夹中的照片文件。然后,我们可以使用之前获得的拍摄日期来将这些照片分类。 最后,我们可以使用`shutil`库的`move()`函数将每张照片移动到相应的目录中。 下面是一个简单的示例代码: ``` import os import glob import shutil from PIL import Image # 创建一个目录来存储分类后的照片 output_directory = '分类后的照片' os.makedirs(output_directory, exist_ok=True) # 获取所有的照片文件 photo_files = glob.glob('*.jpg') for photo_file in photo_files: photo = Image.open(photo_file) exif_data = photo._getexif() # 从元数据中获取拍摄日期 if 36867 in exif_data: capture_date = exif_data[36867] # 将日期格式化为年份和月份 year = capture_date[:4] month = capture_date[5:7] # 创建分类后的目录 output_directory_year = os.path.join(output_directory, year) output_directory_month = os.path.join(output_directory_year, month) os.makedirs(output_directory_year, exist_ok=True) os.makedirs(output_directory_month, exist_ok=True) # 移动照片到分类后的目录中 shutil.move(photo_file, output_directory_month) ``` 以上就是使用Python照片按拍摄日期进行整理分类的简单示例代码。请注意,在使用之前,你需要将示例代码中的`*.jpg`替换为你照片的文件名模式,并确保你已经安装了相关的库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值