gpt4 book ai didi

Python:处理包含一百万张图像的文件夹而不会出现错误

转载 作者:行者123 更新时间:2023-11-28 21:41:10 29 4
gpt4 key购买 nike

def preprocess_image(path_to_images):
print("preprocessing images..")
files = os.listdir(path_to_images)
for f in files:
im = Image.open(os.path.join(path_to_images, f))
im = im.convert("RGBA")

datas = im.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
im.putdata(newData)
im.save(os.path.join(path_to_images, f),"PNG")

嗨。所以上面的这段代码应该删除文件夹中每个图像的背景。当我处理包含 10 张 jpg 图像的文件夹时,这项工作工作得很好,但如果我使用包含 12000 张图像的文件夹运行它,我会收到以下错误:

Traceback (most recent call last):
File "test1.py", line 28, in <module>
preprocess_image("train_images" )
File "test1.py", line 9, in preprocess_image
im = Image.open(os.path.join(path_to_images, f))
File "/Library/Python/2.7/site-packages/PIL/Image.py", line 2452, in open
% (filename if filename else fp))
IOError: cannot identify image file 'train_images/.DS_Store'

包含图像的文件夹称为“train_images”,我不知道 .DS_Store 来自哪里。

非常感谢您的帮助。

最佳答案

.DS_Store 是 mac 文件系统创建的文件(当您使用 finder 打开目录时),当您遍历该目录时,您应该忽略它

try:
im = Image.open(os.path.join(path_to_images, f))
except:
print 'fail to read', path_to_images
  • 你可以像上面的例子那样添加一个 try 和 except block
  • if f != '.DS_Store'
  • 拆分以检查文件扩展名是否为图像 name, ext = 'image.jpg'.split(".") if ext in ['jpg', 'png' ... ]

关于Python:处理包含一百万张图像的文件夹而不会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45058539/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com