如何使用cv2将图像转换为灰度并保留透明度?

3

目前我的代码可以将彩色图像转换为灰度图像。但问题是它会把透明的像素变成白色或黑色。

以下是我已经完成的部分:

import cv2

img = cv2.imread("watch.png",cv2.IMREAD_GRAYSCALE)
cv2.imwrite("gray_watch.png",img)

这是参考图片: Watch.png

1
谢谢您的评论!我是个新手,所以请原谅我的冗长。我已经将其编辑到了最简单的形式。请告诉我您的想法。再次感谢! - Des
1个回答

2
我发现只使用PIL就可以实现这个功能:
from PIL import Image

image_file = Image.open("convert_image.png") # opens image  
image_file = image_file.convert('LA') # converts to grayscale w/ alpha
image_file.save('output_image.png') # saves image result into new file

这样可以保留图像的透明度。"LA"是一种颜色模式。您可以在此处找到其他模式:https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接