首页
学习
活动
专区
圈层
工具
发布

:'dpi‘
EN

Stack Overflow用户
提问于 2022-07-15 19:23:05
回答 1查看 111关注 0票数 -1

我有一个python脚本,它列出了目录中照片的元数据。它起作用了,但是它还没有完全发挥作用。当它运行时,我可以从大约250个文件中获取数据,然后得到一个错误。

这是一个错误:

代码语言:javascript
复制
  File "c:\Users\edward\OneDrive - ISC Industries\Summer Intern 2022\Scripts\metadata.py", line 22, in <module>
"Image DPI": image.info['dpi'],
KeyError: 'dpi'

我不知道这是为什么,因为它工作的一些文件,但有超过17000份文件,所以我希望所有的数据被打印。

下面是完整的脚本:

代码语言:javascript
复制
import json
from PIL import Image
from PIL.ExifTags import TAGS
import os
import os.path
import PIL
from pandas import json_normalize

PIL.Image.MAX_IMAGE_PIXELS = 384000000
rootdir = r"C:\Users\edward\OneDrive\Pics"

newfile = newfile = open('meta.txt', 'w')
newfile.write("Filename                                     |  Image DPI                    | Image Height                  |   Image Width                 |   Image Format                |   Image Mode                  |   Image Frames                |\n")
for file in os.listdir(rootdir):
    # read the image data using PIL
    image = Image.open(os.path.join(rootdir, file))

# extract other basic metadata
info_dict = {
    "Filename": image.filename,
    "Image DPI": image.info['dpi'],
    "Image Height": image.height,
    "Image Width": image.width,
    "Image Format": image.format,
    "Image Mode": image.mode,
    "Frames in Image": getattr(image, "n_frames", 1)
}

line = ""
for label, value in info_dict.items():
    line += f"|{str(value):<30} "  
line += " |"  
newfile.write(line + '\n')

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-15 19:33:08

您可以使用tryexcept,只需重用您的代码:

代码语言:javascript
复制
for file in os.listdir(rootdir):
try:
    # read the image data using PIL
    image = Image.open(os.path.join(rootdir,file))

    # extract other basic metadata
    info_dict = {
        "Filename": os.path.basename(image.filename),
        "Image DPI": image.info['dpi'],
        "Image Height": image.height,
        "Image Width": image.width,
        "Image Format": image.format,
        "Image Mode": image.mode,
        "Frames in Image": getattr(image, "n_frames", 1)
    }

    line = ""
    for label, value in info_dict.items():
        line += f"|{str(value):<30} "  
    line += " |"  
    newfile.write(line + '\n')
except:
    # read the image data using PIL
    image = Image.open(os.path.join(rootdir,file))

    # extract other basic metadata
    info_dict = {
        "Filename": os.path.basename(image.filename),
        "Image Height": image.height,
        "Image Width": image.width,
        "Image Format": image.format,
        "Image Mode": image.mode,
        "Frames in Image": getattr(image, "n_frames", 1)
    }

    line = ""
    for label, value in info_dict.items():
        line += f"|{str(value):<30} "  
    line += " |"  
    newfile.write(line + '\n')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72998757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档