目前,我的代码采用彩色图像并将其转换为灰度图像。问题是它使透明像素变白或变黑。
这是我目前所拥有的:
import cv2
img = cv2.imread("watch.png",cv2.IMREAD_GRAYSCALE)
cv2.imwrite("gray_watch.png",img)
图片供引用: Watch.png
请您参考如下方法:
我发现只使用 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
