Home > Mobile >  Setting the alpha channel of an image, based on the pixel values in another image
Setting the alpha channel of an image, based on the pixel values in another image

Time:05-23

I have two images. In one image all non-alpha channel pixels are equal to 0, and I'd like the alpha channel values to equal 255 where in the other image which is of equal size, the pixels are anything but 0. In this attempt, I'm attempting to create a 4 channel np array based off of the original image, and then use np.argwhere to find where the pixel valeus are non-zero, and then in the new np array, set the alpha channel value based on that.

For example, for each pixel in my input image with values [255, 255, 255], I'd like the corresponding pixel in my new image to be [0, 0, 0, 255]. For each pixel in my input image with values [0, 0, 0], I'd like the corresponding pixel in my new image to be [0, 0, 0, 0].

mask_file = cv.imread(r'PlateMask_0001.png', cv.IMREAD_UNCHANGED)

scale_factor = 0.125
w = int(mask_file.shape[1] * scale_factor)
h = int(mask_file.shape[0] * scale_factor)
scaled = cv.resize(mask_file, (w, h))

coords = np.argwhere(scaled > 0)
new_object = np.zeros((120, 160, 4))
new_object[coords, :] = 255
cv.imshow('Mask', mask)
cv.imshow('Scaled', new_object)
cv.waitKey(0)
cv.destroyAllWindows()

This is my first question on Stack so please feel free to suggest improvements on question formatting, etc. Thank you.

CodePudding user response:

Consider img1 to be your original image and img2 to be the image where alpha channel needs to be modified.

In the following, the alpha channel of img2 contains value 255 in the coordinate where img1 has (255, 255, 255):

img2[:,:,3][img1 == (255, 255, 255)]  = 255

Likewise for value 0:

img2[:,:,3][img1 == (0, 0, 0)]  = 0
  • Related