Преобразование изображения TIFF, сохраненного с прозрачностью, невозможно преобразовать в изображение JPEG в формате Python - PullRequest
0 голосов
/ 16 июня 2020

Я пытаюсь решить проблему в Python, где мне нужно преобразовать изображения TIFF в JPEG. Я пробовал использовать Pillow, а также OpenCV для этого, но продолжаю получать ошибки, когда пытаюсь преобразовать изображение TIFF, на котором сохранена прозрачность. Если я сохраню TIFF и удалю прозрачность, он успешно сохранит JPEG. Прозрачность должна оставаться на TIFF. Кто-нибудь знает решение этой проблемы? Если бы я мог найти способ даже сохранить TIFF без прозрачности с помощью сценария Python, сохранить как 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 пытается открыть TIFF с прозрачностью с помощью Pillow:

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)

Ответы [ 2 ]

0 голосов
/ 18 июня 2020

Благодаря @cgohlke решение было найдено! Решение заключается в следующем с использованием кодеков изображений. Переменная полного пути - это 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.
0 голосов
/ 17 июня 2020

Вот как прочитать CMYKA TIFF с помощью Python Wand, удалить альфа-канал, сохранить его в JPG, а также преобразовать изображение в формат OpenCV.

Ввод:

enter image description here

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:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...