【发布时间】:2019-10-31 15:08:07
【问题描述】:
我正在处理约 50MB(约 19000 像素 x 25500 像素)的图像文件,并将它们裁剪成大小为 4705 像素 x 8375 像素的图像。我写了一个循环遍历一个包含 95 个图像的文件夹。在大多数情况下,裁剪效果很好,但是在随机图像上,当代码裁剪图像时,它的子图像会显示为空白图像。发生这种情况时,12 个图像中的第一个将正常显示(正确裁剪),但其余 11 个图像将显示为空白。当问题没有发生时,所有 12 张图片都会正确裁剪。
我在 MBP 10.14.5 上运行 Spyder 3.3.4 上的代码。 PIL 是版本 1.1.7 和 Python 3.6。我已经检查了我在图像之间的循环是否正确。重新运行失败(裁剪不正确)的图像,当我裁剪它们而不是 for 循环的一部分时工作正常。
stepCounter = 4705
for folder in os.listdir(location):
if folder == "MyFolder":
for file in os.listdir(location+folder):
resetCounter = -8375
for i in range(12):
print("Iteration", i, " on file", file)
if i%4 == 0:
resetCounter += 8375
left = 0
top = 0 + resetCounter
right = 4705
bottom = 8375 + resetCounter
fileLocation = location + folder + "/" + file
newLocation = location + folder + "/" + file[:-4] + str(i+1) + ".jpg"
img = Image.open(fileLocation)
img = img.crop((left, top, right, bottom))
img.save(newLocation)
img.close()
else:
left = left + stepCounter
top = top
right = right + stepCounter
bottom = bottom
fileLocation = location + folder + "/" + file
newLocation = location + folder + "/" + file[:-4] + str(i+1) + ".jpg"
img = Image.open(fileLocation)
img = img.crop((left, top, right, bottom))
img.save(newLocation)
img.close()
else:
print("Skipping", folder)
再次,我希望图像是较大图像的子图像,而不是空白图像。不确定这是内存问题,还是其他与代码无关的问题。
【问题讨论】:
-
location+folder应该是os.path.join(location, folder) -
是不是有些图片不够大?
-
图像大于我裁剪的区域。关于 location+folder 与 os.path.join(location, folder) 我可以尝试,但我不明白为什么它会改变间歇性裁剪问题。谢谢!
-
不太可能,但某些位置可能缺少尾部斜杠?
-
图片文件名都是用同样的方式构造的(使用循环),更奇怪的是当过程正常工作时,所有图像都是正确的,当过程出错时,第一个子图像是正确的,但后面的 11 个将是空白图像。
标签: python python-imaging-library crop