【问题标题】:Wand Outputs Too Many Images魔杖输出太多图像
【发布时间】:2020-03-13 20:58:09
【问题描述】:

所以我总体上对 python 比较缺乏经验,并且对 ImageMagick 和 Wand 是全新的,但是,到目前为止,这些工具已经完成了我需要的 95%,这意味着从长远来看,可以为项目节省大量时间我正在努力。

我只是获取一个图像文件夹,将它们从 .tiff 转换为 .png,然后将它们保存到子文件夹中。看起来很简单,对吧?下面的代码正在运行:

# Import os functions for setting path and getting files from directory
import os

# Import Wand functions to get the image and the required colors to convert
from wand.image import Image
from wand.color import Color

# Set the path where the images are being held
sourcePath = '/somePath/'
destinationPath = '/somePath/batch/'

# Set the image extenion we want to process and convert to
sourceExt = 'tiff'
destinationExt = 'png'

# Use os to get all files held in that directory
files = os.listdir(sourcePath)

# Loop through every file
for file in files:

    # Get the current image file's name and extension
    filename, file_extension = os.path.splitext(sourcePath + file)
    print('Filename: ' + filename)
    print('File extension: ' + file_extension)

    updatedFilename = filename.replace(sourcePath, '')

    # Only process for images with the .tiff extension
    if file_extension == ('.' + sourceExt):

        with Image(filename=filename + file_extension) as img:
            img.format = 'png'
            with Color('#FFFFFF') as white:
                img.transparent_color(white, alpha=0.0)
            img.save(filename=destinationPath + updatedFilename + '.' + destinationExt)

总的来说,代码运行良好,输出我的输入文件的 .png 版本,去除了白色背景。

但是,我拍摄了 80 张图像,输出总共 712 张图像。 Wand 是否有什么特别的原因导致了这种情况,还是我在 python 中的循环?

【问题讨论】:

  • 循环中有print(Filename) 语句。那输出什么? 80 个文件名,还是 712 个文件名?
  • 您的代码应该正常工作。我看到的唯一可能是这些 TIFF 文件中的一些或全部实际上是 multi-image TIFF。在这种情况下,您可能需要 seek() 所需的子图像并保存它。您应该能够从文件名本身看到是否是这种情况。
  • 您可能有多页 TIFF。要解决此问题,只需通过将 [0] 附加到文件后缀的末尾来选择第一页。试试with Image(filename=filename + file_extension + "[0]") as img:
  • 顺便说一句,变量和函数名称应该遵循lower_case_with_underscores 样式。
  • 可能值得将您的发现作为答案发布,并接受它。这将有助于未来有类似问题的读者知道问题已得到解决。

标签: python wand


【解决方案1】:

我的 .tiff 文件是秘密的多页文件,我得到了所有页面,而不仅仅是第一个。我意外地解决了这个问题,将我的图像导出为支持更好的 .png 格式(我的转储图像没有背景被剥离的额外好处),但这非常有帮助。

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 2017-12-24
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2015-12-06
    • 1970-01-01
    相关资源
    最近更新 更多