python怎么图片转灰度_如何在python中将RGBA图像转换为灰度?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值