首页 > 解决方案 > 转换用透明度保存的 TIFF 图像无法在 Python 中转换为 JPEG 图像

问题描述

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

标签: pythonopencvimage-processingpython-imaging-librarytiff

解决方案


感谢@cgohlke,找到了解决方案!使用图像编解码器的解决方案如下。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.

推荐阅读