Search code examples
pythonopencvpngtifftransparent

How to write a .tiff file with transparent background in python and openCV?


I have some .png files with transparent backgrounds, I am doing some channel alterations on the files and converting them into the .tiff format

 def convert_image(input_image_name):
    # Reading the image using imread() function
    file_name = ""
    image = cv2.imread(input_image_name)
    image[:] = (0, 0, 255)
    file_name = "converted.tiff"
    cv2.imwrite(file_name, image, [cv2.IMWRITE_TIFF_COMPRESSION, 5])
    return file_name

but I want to create .tiff files with transparent backgrounds, how do I achieve this in python and openCV?


Solution

  • So the answer was numpy and pillow

    from PIL import Image
    import numpy as np
    
    im = Image.open("3.png")
    im = im.convert('RGBA')
    
    data = np.array(im)   # "data" is a height x width x 4 numpy array
    data[..., :-1]= (255, 0, 0) # Transpose back needed
    im2 = Image.fromarray(data)
    im2.save("mytiff.tiff")