Reputation: 15
I have got a script to spot a pothole in an image and draw an ellipse around it. I have two images. one the original image and then a separate numpy array which is white with a red ellipse on it. I have converted the ellipse image RGBA image with the intention of overlaying it onto the original image, using the code below. However the output image ( new_img ) is showing a blend with the ellipse image background still showing at half opacity (because the transparency is set in blend() however I would like the white background to be completely clear and the ellipse to be half transparent) . In other words the for loop is not creating a RGBA image with alpha of 0. Attached are the input, ellipse image and output.
from PIL import Image
import cv2
# Make True pixels red
RGB[test_ellipse==255] = [255,0,0]
# Make False pixels blue
RGB[test_ellipse==1] = [255,255,255]
image = cv2.imread(file_path , cv2.IMREAD_GRAYSCALE)
test = Image.fromarray(RGB)
over = test.convert('RGBA')
datas = over.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
over.putdata(newData)
background = Image.fromarray(image)
background = background.convert('RGBA')
new_img = Image.blend(background, over, 0.5)
new_img.show()
Upvotes: 0
Views: 763
Reputation: 207465
Hopefully this will give you an idea of adding an alpha channel. I just mocked up a dummy alpha channel with a painting program, making it mid-grey with one black and one white circle:
#!/usr/bin/env python3
import cv2
import numpy as np
# Load image and alpha
im = cv2.imread('pothole.png', cv2.IMREAD_GRAYSCALE)
alpha = cv2.imread('alpha.png', cv2.IMREAD_GRAYSCALE)
# Make grey pothole picture 3 channel grey and add alpha layer
res = np.dstack((im,im,im,alpha))
cv2.imwrite('result.png', res)
You can maybe see the effect more clearly if I undertile with a chessboard like Photoshop does:
Upvotes: 1