【问题标题】:Converting a TIFF Image saved with a transparency can't be converted to JPEG image in Python转换用透明度保存的 TIFF 图像无法在 Python 中转换为 JPEG 图像
【发布时间】:2020-10-06 05:08:10
【问题描述】:

我正在尝试解决 Python 中需要将 TIFF 图像转换为 JPEG 的问题。我曾尝试使用 Pillow 和 OpenCV 来执行此操作,但是当我尝试转换保存了透明度的 TIFF 图像时不断出错。如果我保存 TIFF 并删除透明度,它将成功保存 JPEG。透明度必须保留在 TIFF 上。有谁知道这个问题的解决方案?如果我能找到一种方法,甚至可以通过 Python 脚本在没有透明度的情况下保存 TIFF,将其另存为 JPEG,然后在没有透明度的情况下删除 TIFF 也可以。在这里的任何帮助将不胜感激。以下是我尝试过的失败代码示例:

import os
from PIL import Image

os.chdir('S:/DAM/Test/Approved/')
# for root, dirs, files in os.walk('S:/DAM/Test/Approved'):
for root, dirs, files in os.walk('.'):
    for name in files:

        if name.endswith('.tif'):

            filename = os.path.join(root, name)
            print('These are the files: ', filename)
            # img = Image.open(filename).convert('RGB')
            img = Image.open(filename)
            print('image is open', filename)
            img = img.convert('RGB')
            print('image should be converted: ', filename)
            imageResize = img.resize((2500, 2500))
            print('image should be resized: ', filename)
            imageResize.save(filename[:-4]+'.jpg', 'JPEG')
            print('image should be saved as a jpeg: ', filename)

这是我在 Python 尝试使用 Pillow 以透明方式打开 TIFF 时遇到的错误:

Exception has occurred: UnidentifiedImageError
cannot identify image file '.\\Beauty Images\\XXX.tif'
  File "U:\Python files\image_conversion2.py", line 22, in <module>
    img = Image.open(filename)

当我使用 OpenCV 运行此代码时,它也会在同一图像上失败:

img = cv2.imread('S:/DAM/Test/Approved/Beauty Images/XXX.tif')
cv2.imwrite('S:/DAM/Test/Approved/Beauty Images/XXX.jpg', img)

这是我使用此代码时遇到的错误:

OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:715: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
  File "U:\Python files\img_convert_new.py", line 19, in <module>
    cv2.imwrite('S:/DAM/Test/Approved/Beauty Images/XXX.tif', img)

【问题讨论】:

  • 尝试使用 ImageMagick 并运行“ide​​ntify -verbose XXX.tif”或分享此图像。见stackoverflow.com/q/22170601/13226440
  • @Alex Alex,ImageMagick 会为这个问题做些什么?
  • ImageMagick 将提供有关图像的信息。特别是关于 Alpha 通道。此问题的进一步解决方案取决于此信息。
  • @Alex Alex,我没有安装 ImageMagick。在没有 ImageMagick 的情况下还有其他方法可以获取这些信息吗?
  • 也许 OpenCV/PIL 无法读取 CMYKA 图像。我不知道全部限制。 ImageMagick 和 Python Wand 可以读取它们,但您必须安装 ImageMagick。如果您在 Linux 上,则它已经安装。 OpenCV/PIL 已阅读它,然后您可以制作副本并删除 alpha 通道,然后从副本中保存,如果您需要将 alpha 通道保留在原始 TIFF 中。在 OpenCV/PIL 中移除 alpha 通道不会改变磁盘文件。它只会更改已读取的内存版本。您可以发布指向您的 TIFF 文件的链接吗?

标签: python opencv image-processing python-imaging-library tiff


【解决方案1】:

这里是如何使用 Python Wand 读取 CMYKA TIFF,删除 alpha 通道,将其保存为 JPG 并将图像转换为 OpenCV 格式。

输入:

from wand.image import Image
from wand.display import display
import numpy as np
import cv2

with Image(filename='guinea_pig.tiff') as img:
    display(img)

    with img.clone() as img_copy:
        # remove alpha channel and save as JPG
        img_copy.alpha_channel='off'
        img_copy.format = 'jpeg'
        img_copy.save(filename='guinea_pig.jpg')
        display(img_copy)

        # convert to opencv/numpy array format and reverse channels from RGB to BGR for opencv
        img_copy.transform_colorspace('srgb')
        img_opencv = np.array(img_copy)
        img_opencv = cv2.cvtColor(img_opencv, cv2.COLOR_RGB2BGR)

        # display result with opencv
        cv2.imshow("img_opencv", img_opencv)
        cv2.waitKey(0)


生成的 JPG:

【讨论】:

  • 谢谢@fmw42!我会试试这个。我确实有一个问题,如果我的图像位于此目录中:S:/DAM/Test/Approved/Beauty Images/BAR076W-FB-SP.tif 我是将整个路径放在文件名变量中还是只放在文件名中? python 脚本从与图像不同的位置运行..
  • tiff 文件的完整路径,如果您从其他目录运行脚本。
  • 如何修改代码以将 jpeg 调整为 2500 x 2500 并使其成为 RGB jpeg?
  • 谢谢@fmw42。我将如何修改代码以使其不显示图像但将 jpeg 保存在与转换它的 TIFF 相同的文件夹中并将其大小调整为 2500 x 2500?
  • 您需要我从 Wand 图像转换而来的 OpenCV 图像吗?如果没有,那么我可以在 Wand 中完成所有这些操作。您是从拥有 TIFF 的同一目录还是从其他位置运行脚本?
【解决方案2】:

感谢@cgohlke 找到了解决方案!使用图像编解码器的解决方案如下。 fullpath 变量是 root + '/' + 源路径的文件。

for root, subdirs, files in os.walk(src):
   for file in files:
      fullpath = (root + '/' + file)
from imagecodecs import imread, imwrite
from PIL import Image

imwrite(fullpath[:-4] + '.jpg', imread(fullpath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
                    # The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
                    # Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
                    # The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
                    img = Image.open(fullpath[:-4] + '.jpg') # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
                    img = img.convert('RGB') # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
                    imageResize = img.resize((2500, 2500)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
                    imageResize.save(fullpath[:-4] + '.jpg') # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多