我有一个python脚本,它列出了目录中照片的元数据。它起作用了,但是它还没有完全发挥作用。当它运行时,我可以从大约250个文件中获取数据,然后得到一个错误。
这是一个错误:
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份文件,所以我希望所有的数据被打印。
下面是完整的脚本:
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')谢谢
发布于 2022-07-15 19:33:08
您可以使用try和except,只需重用您的代码:
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')https://stackoverflow.com/questions/72998757
复制相似问题