How do I replace the alpha channel of any image (png, jpg, rgb, rbga) with specified background color? It must also work with images that do not have an alpha channel.
How do I replace the alpha channel of any image (png, jpg, rgb, rbga) with specified background color? It must also work with images that do not have an alpha channel.
I'd suggest using Image.alpha_composite.
This code can avoid a tuple index out of range error if png has no alpha channel.
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
I also recommend you inspect both results with a image.show().
Credits for this answer goes to shuuji3 and others who helped build a vast answers repertoire in this other question.
I updated Vincius M's code with the user, tutuDajuju, suggestion to make [height, width, 3] matrix (not [height, width, 4]):
from PIL import Image
import numpy as np
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))
alpha_composite = Image.alpha_composite(background, png)
# if you check the matrix dimension, channel, it would be still 4.
h, w, channel = np.asarray(alpha_composite)
alpha_composite_3 = alpha_composite.convert('RGB')
# if you check the matrix dimension, channel, it would be 3.
h, w, channel = np.asarray(alpha_composite_3)