CV2 中的 RGB 到灰度转换

问题描述

我正在尝试将图像从 RGB 转换为灰度。阅读后我的图像看起来像这样

img = cv2.imread('sample.png')
plt.imshow(img)

enter image description here

我尝试使用 cv2 函数将其转换为灰度,转换后图像如下所示:

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
plt.imshow(gray)

enter image description here

如您所见,图像未正确转换为灰度。可能是什么原因?我在这里遗漏了什么吗?

解决方法

plt.imshow 中 cmap 的默认选项是 viridis。对灰度图像使用 plt.imshow(gray,cmap='gray')。如果您使用 cv2.imwrite 保存图像,您可以看到图像已转换为灰度。