微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python将图像文件夹lat和lon获取到df

如何解决Python将图像文件夹lat和lon获取到df

我试图用python构建代码以遍历文件夹中的所有照片并获取exif信息(仅日期和GPS信息相关)。 我在网上找到了一个代码,但它给了我一个错误代码

def find_images(image_dir,extensions=None):
    default_extensions = ('jpg','jpeg')
    if extensions is None:
        extensions = default_extensions
    elif isinstance(extensions,str):
        extensions = (extensions,)
    for root,dirs,filenames in os.walk(image_dir):
        for filename in filenames:
#             print(filename,filename.split('.',1))
            if filename.split('.',1)[-1].lower() in extensions:
                yield os.path.join(root,filename)
            
def process_exif_data(image):
    decoded_exif = {}
    with Image.open(image) as image_file:
        exif_data = image_file._getexif()
        if exif_data is None:
            return None
        for tag,value in exif_data.items():
            decoded = TAGS.get(tag,tag)
            if decoded == "GPSInfo":
                decoded_exif.update(decode_gps_data(value))
            else:
                decoded_exif[decoded] = value

    # This Could be done with a dict comprehension and a ternary expression too
    return decoded_exif
    

def decode_gps_data(info):
    gps_tags = {GPSTAGS.get(k,k): v for k,v in value.items}

    lat,long = get_coordinates(gps_tags)
    gps_tags['lat'] = lat
    gps_tags['lon'] = lon

    return gps_tags

def get_coordinates(gps_tags):
    coords = {'Latitude': 'N','Longitude': 'E'}
    for coord,nominal_ref in coords.items():
        c = gps_tags.get("GPS%s" % coord,None)
        c_ref = gps_tags.get("GPS%sRef" % coord,None)

        if c and c_ref:
            yield _convert_to_degrees(c,c_ref,nominal_ref)
        else:
            yield None
            
def _convert_to_degrees(value,ref,nominal_ref=None):
    if nominal_ref is None:
        nominal_ref = ('N','E',)
    elif isinstance(nom,str):
        nominal_ref = (nominal_ref,)
    ref = 1 if ref in nominal_ref else -1
    return ref * sum(float(v[0]) / float(v[1]) / 60 ** i for i,v in enumerate(value))
                        
def extract_important_data(image_data,important_datalabels=('lat','lon','DateTimeOriginal')):
    if image_data is None:
        return None
    return {key: image_data.get(key,None) for key in important_datalabels}
                        
def extract_info(images,'DateTimeOriginal')):
    for image_path in images:
        print(image_path)
        exif_data = process_exif_data(image_path)
        important_data = extract_important_data(exif_data)
        if important_data:
            yield image_path,important_data
                        
def get_photos_info(image_dir,filename=None,'DateTimeOriginal')):
    if image_dir is None:
        image_dir='.'

    images = find_images(image_dir)
    info = extract_info(imgs,important_datalabels=important_datalabels)
    result_df = pd.DataFrame(columns = important_datalabels)
    for image_path,item in info:
        result_df.loc[image_path] = item
    if 'DateTimeOriginal' in important_datalabels:
        date_format = '%Y:%m:%d %H:%M:%s'
        result_df['DateTimeOriginal'] = pd.to_datetime(result_df['DateTimeOriginal'],format=date_format)

    if filename:
        result_df.to_excel(filename)

    return result_df

empty_df = pd.DataFrame
empty_df = get_photos_info(r"C:\Users\dor h\OneDrive\Desktop\study\Final project")

错误

AttributeError                            Traceback (most recent call last)
<ipython-input-32-0aaf3d855413> in <module>
    123 
    124 empty_df = pd.DataFrame
--> 125 empty_df = get_photos_info(r"C:\Users\dor h\OneDrive\Desktop\study\Final project")
    126 # print(empty_df)

<ipython-input-32-0aaf3d855413> in get_photos_info(image_dir,filename,important_datalabels)
    111     info = extract_info(imgs,important_datalabels=important_datalabels)
    112     result_df = pd.DataFrame(columns = important_datalabels)
--> 113     for image_path,item in info:
    114         result_df.loc[image_path] = item
    115     if 'DateTimeOriginal' in important_datalabels:

<ipython-input-32-0aaf3d855413> in extract_info(images,important_datalabels)
     99     for image_path in images:
    100         print(image_path)
--> 101         exif_data = process_exif_data(image_path)
    102         important_data = extract_important_data(exif_data)
    103         if important_data:

<ipython-input-32-0aaf3d855413> in process_exif_data(image)
     48 def process_exif_data(image):
     49     decoded_exif = {}
---> 50     with Image.open(image) as image_file:
     51         exif_data = image_file._getexif()
     52         if exif_data is None:

D:\paython\lib\site-packages\PIL\Image.py in open(fp,mode)
   2816         exclusive_fp = True
   2817 
-> 2818     prefix = fp.read(16)
   2819 
   2820     preinit()

AttributeError: 'JpegImageFile' object has no attribute 'read'

我在某个地方读到问题是我正在尝试打开一个已经打开的jpg文件,但我看不到我在哪里,而且我也不知道该怎么解决

提前

tnx

解决方法

info = extract_info(imgs,important_datalabels=important_datalabels)行中,imgs似乎是一个错字,应该是images

为什么这会为您提供特定的错误模式,具体取决于imgs是什么。变量imgs必须在笔记本的某个位置定义,否则您的代码将引发NameError。 imgs可能是一个列表或迭代器,其中包含Image.open()不需要的某种对象;这会导致它在尝试使用对象的read方法时失败。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。