在 Python 中无法将使用透明胶片保存的 TIFF 图像转换为 JPEG 图像

Converting a TIFF Image saved with a transparency can't be converted to JPEG image in Python

我正在尝试解决 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)

以下是如何使用 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:

感谢@cgohlke 找到了解决方案!使用imagecodecs解决方案如下。 fullpath变量为源码路径的根+'/'+文件

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.