I need to save a tiff image with 4 channels, specifically R,G,B and A channels.
When I try using Image.save()
to save a tiff with 4 channels, the resulting image is an RGBA image but when examining the tiff in Photoshop the only channels are RGB, without the Alpha. Is there any way to merge 4 channels to a RGBA image, with a 4th channel (a separate alpha channel)?
Below is an example of what I've tried
from PIL import Image
# import image A
inputImageA = Image.open(input_imageA_path)
# import image B
inputImageB = Image.open(input_imageB_path)
# split channels
R, G, B, A = inputImageA.split()
alpha_channel = inputImageA.split()[-1]
# merge 4 channels back into a single image
outputImage = Image.merge("RGBA", [R,G,B,alpha_channel])
# save the new image
outputImage.save(ouput_image_path)
In this example the resulting output image only has 3 channels (RGB).
Please see below image for a visual explanation of what I'm trying to do:
Updated Answer
Ok, I think you mean this now:
#!/usr/bin/env python3
from PIL import Image
# Open background image, ensuring RGB
im = Image.open('start.png').convert('RGB')
# Open alpha channel, ensuring single channel
alpha = Image.open('alpha.png').convert('L')
# Add that alpha channel to background image
im.putalpha(alpha)
# Save as TIFF
im.save('result.tif')
Which makes start.png
:
plus alpha.png
:
into result.tif
:
Original Answer
Here's a simple example of creating and saving a 4 channel, RGBA TIFF:
#!/usr/bin/env python3
from PIL import Image, ImageDraw
# Create RGB image full of yellow
w, h = 640, 480
im =Image.new('RGB',(w,h),color=(255,255,0))
# Create alpha channel of white i.e. opaque
alpha =Image.new('L',(w,h),color=255)
# Get drawing context to draw into alpha channel and draw black (i.e. transparent) rectangle
d = ImageDraw.Draw(alpha)
d.rectangle([10,40,200,250],fill=0)
# Add that alpha channel to yellow image
im.putalpha(alpha)
# Save as TIFF
im.save('result.tif')
I figured out a solution to this issue using the OpenCV2 library instead of PIL. See below how I did it:
import cv2
# read original image
original = cv2.imread(original_image_path, cv2.IMREAD_UNCHANGED)
# get dimensions for resizing mask
height, width, channels = original.shape
# read alpha image
alpha = cv2.imread(alpha_path)
# resize alpha image to match original
alpha_resized = cv2.resize(alpha, (height,width))
# split alpha_resized into individual channels
channels = cv2.split(alpha_resized)
# apply to 4th channel of original
original[:,:,3] = channels[0]
# write new image file with alpha channel
cv2.imwrite(output_path,original)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With