我正在尝试编写一个脚本来协助我的行业项目,但我在使用此代码时遇到了问题。它应该做的是获取目录中的所有图像裁剪它们,每个图像的裁剪是相同的,然后导出裁剪的图像。
import sys
import os
from PIL import Image
filepath = "C:\Users\Ellis\Desktop\bunny_test"
os.listdir = filepath
# Loop through all provided arguments
for i in range(1, len(filepath)):
try:
# Attempt to open an image file
#filepath = sys.argv[i]
image = Image.open(filepath)
except IOError, e:
# Report error, and then skip to the next argument
print "Problem opening", filepath, ":", e
continue
# Perform operations on the image here
image = image.crop(261, 435, 153, 343)
# Split our origional filename into name and extension
(name, extension) = os.path.splittext(filepath)
# Save the image as "(origional_name)_thumb.jpg
image.save("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg')
答案 0 :(得分:0)
您的源代码中存在一些错误。
os.listdir()
image.crop
需要一个元组,而你提供了4个参数os.path.join
连接路径和文件名(image.save不带两个参数)splitext
,而不是splittext
这是应该有用的东西:
import sys
import os
from PIL import Image
filepath = "C:\Users\Ellis\Desktop\bunny_test"
# Loop through all provided arguments
for filename in os.listdir(filepath):
if "." not in filename:
continue
ending = filename.split(".")[1]
if ending not in ["jpg", "gif", "png"]:
continue
try:
# Attempt to open an image file
image = Image.open(os.path.join(filepath, filename))
except IOError, e:
# Report error, and then skip to the next argument
print "Problem opening", filepath, ":", e
continue
# Perform operations on the image here
image = image.crop((261, 435, 153, 343))
# Split our origional filename into name and extension
name, extension = os.path.splitext(filename)
# Save the image as "(origional_name)_thumb.jpg
print(name + '_cropped.jpg')
image.save(os.path.join("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg'))