如何在python中将RGBA图像转换为灰度? [英] How to convert an RGBA image to Grayscale in python?
问题描述
我有一个形状为(height, width, 4)
的数组,即RGBA格式,我想将其转换为灰度.原始数组的RGB值为0,并且图片完全基于白色背景上的alpha值进行渲染,因此,将其转换为灰度的传统方法会失败(例如cv2.cvtColor(img,cv2.COLOR_RGBA2GRAY)
).
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)
).
源图像:
推荐答案
假设:
-
您的图片始终为黑白;
Your image is always black-n-white;
白色被定义为透明;
如果这些都是真的,那么您可以直接使用Alpha频道 :
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.
这篇关于如何在python中将RGBA图像转换为灰度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!