Reputation: 1
I have this Image with a transparent background. I want to convert the transparent background to solid black. I do not want to change the color of any pixels in the logo.
I use the following code for this:
image = Image.open(IMG_PATH)
new_image = Image.new("RGBA", image.size, "BLACK") # Create a white rgba background
new_image.paste(image, (0, 0), image) # Paste the image on the background.
new_image.convert('RGB').save(SAVE_PATH, "PNG") # Save as PNG
But the result looks like This image. Though I got black background instead of transparent, If you notice, the logo colors are a bit dull now. Why is this happening? How to prevent this? I want my Image to be in the same color as in the original one, but the background should be Black. I am open to use any other libraries like Opencv also.
UPDATE:
Result generated by Photoshop : Image
Result generated by above code : Image
There is a visible difference in both Images above.
Upvotes: 0
Views: 1632
Reputation: 2362
Fill transparent area with color using OpenCV:
import sys
import cv2
import numpy as np
dir = sys.path[0]
im = cv2.imread(dir+'/im.png', -1)
im[np.where(im[:, :, 3] == 0)] = (0, 0, 0, 255)
cv2.imwrite(dir+'/im_.png', im)
Testcase for sure:
Fill anywhere not fully transparent:
im[np.where(im[:, :, 3] != 0)] = (0, 0, 0, 255)
Fill in anywhere that is transparent or has alpha:
im[np.where(im[:, :, 3] != 0|255)] = (0, 0, 0, 255)
Fill anywhere without alpha channel:
im[np.where(im[:, :, 3] == 0|255)] = (0, 0, 0, 255)
Upvotes: 1