bis*_*uke 2 python image python-imaging-library
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")
Run Code Online (Sandbox Code Playgroud)
你好.因此,上面的代码应该删除文件夹中每个图像的背景.当我处理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'
Run Code Online (Sandbox Code Playgroud)
带有图像的文件夹称为"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
Run Code Online (Sandbox Code Playgroud)
if f != '.DS_Store'name, ext = 'image.jpg'.split(".") if ext in ['jpg', 'png' ... ]