【问题标题】:Automate cropping with Pillow and python?使用 Pillow 和 python 自动裁剪?
【发布时间】:2020-03-28 02:16:07
【问题描述】:

所以我有一个文件夹,其中包含 500 多张需要裁剪的图像。我已经搜索并设法创建了这个剪切和粘贴脚本。但是,由于某种原因,它没有保存新图像!?终端是静止的,没有错误,什么都没有。

from PIL import Image # import the Python Image processing Library
import os # To read the folder

directory_in_str = "/Users/hora/Downloads/Etik"
directory = os.fsencode(directory_in_str)

for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".png"):
        image = os.path.join(directory_in_str, filename)
        imageObject  = Image.open(image) # Create an Image object from an Image
        cropped     = imageObject.crop((1025,85,2340,2040)) # Crop the iceberg portion (top left x, top left y, bottom right x, bottom right y)
        cropped.save("{}".format(filename+"_cropped"), 'png') # Save the cropped portion
        continue
     else:
        continue

我在特定文件夹中搜索,裁剪后的图像应使用filename_cropped.png 保存。但没必要,如果有什么事情发生了,我有备份。

预期结果:

  • 循环浏览文件夹
  • 裁剪所有以.png 结尾的图像
  • 并使用以前的文件名但带有扩展名保存裁剪图像 FILNAME_cropped.png
  • 完成

【问题讨论】:

  • 您实际上不需要为此编写任何 Python,如果可以的话,您可以使用 ImageMagick 单线非常简单地做到这一点?

标签: python-3.x python-imaging-library


【解决方案1】:

关于这条线的两个问题:

cropped.save("{}".format(filename+"_cropped"), 'png')
  1. 您的filename 仍包含文件扩展名。
  2. 您不会自己添加(新)文件扩展名。

这两个问题都会为您的新文件生成一些字符串 xxx.png_cropped

我对修改代码的建议:

for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".png"):
        image = os.path.join(directory_in_str, filename)
        filename, file_extension = os.path.splitext(filename)       # <-- After reading, filename can be overwritten
        imageObject = Image.open(image)
        cropped = imageObject.crop((1025,85,2340,2040))
        cropped.save("{}".format(filename+"_cropped.png"), 'png')   # <-- Explicitly add .png to your filename 
        continue
     else:
        continue

希望有帮助!

【讨论】:

    【解决方案2】:

    在保存文件时添加目录路径。

    directory_in_str = "/Users/hora/Downloads/Etik/"
    cropped.save("{}".format(directory_in_str+filename+"_cropped"),'png') 
    

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 2023-03-23
      • 2012-12-22
      • 2016-10-15
      相关资源
      最近更新 更多