How to convert an RGBA image to Grayscale in python?

落花浮王杯 提交于 2019-12-24 02:21:54

问题


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:


回答1:


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.



来源:https://stackoverflow.com/questions/55677216/how-to-convert-an-rgba-image-to-grayscale-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!