I have array of shape (height, width, 4), i.e., RGBA format, and I want to convert this to grayscale. The original array has RGB values as 0 and the picture is rendered completely based on the alpha values over a white background, hence the traditional ways of turning this into grayscale fail (e.g., cv2.cvtColor(img,cv2.COLOR_RGBA2GRAY)).
Source image:
解决方案
Assumptions:
Your image is always black-n-white;
White is defined as a transparency;
If these things are true, then you can use the Alpha channel directly:
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('image.png', cv2.IMREAD_UNCHANGED)
img_gray = 255 - img[:, :, 3]
plt.imshow(img_gray, cmap='gray', vmin=0, vmax=255)
plt.show()
If you could also have colored images, then I would ask you to provide one.