使用Python自动裁剪图像

时间:2017-12-04 15:36:07

标签: python image image-processing crop

我正在尝试编写一个脚本来协助我的行业项目,但我在使用此代码时遇到了问题。它应该做的是获取目录中的所有图像裁剪它们,每个图像的裁剪是相同的,然后导出裁剪的图像。

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')

1 个答案:

答案 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'))