python - 如何在不使用 cv2.cvtColor() 的情况下将 3 channel 图像转换为 1 channel 图像?

标签 python opencv rgb

因此,我被要求使用每个像素的加权平均值将 BGR 图像转换为 GRAYSCALE

img = cv2.imread('..\\Images\\horse.jpg',-1)
height = img.shape[0]
width = img.shape[1]
gray = img.copy()
for x in range(img.shape[1]):
  for y in range(img.shape[0]):
     gray[y][x]= (0.11 * img[y][x][0] + 0.6 * img[y][x][1] + 0.3 * img[y][x][2])



print(gray)
print(gray.shape)
cv2.imshow('gray',gray)
cv2.waitkey(0)

最终图像的形状:

(404, 640, 3)

它应该是单 channel 图像,对吧? 结果显示的图像是灰度图像,但它仍然是 3 channel 图像,有人可以帮助我吗?

最佳答案

原因很简单,发生这种情况是因为你在开头复制了整个 img,它有三个 channel 。您只需复制一个 channel ,如下所示:

gray = img[:, :, 0].copy()

关于python - 如何在不使用 cv2.cvtColor() 的情况下将 3 channel 图像转换为 1 channel 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58587249/

相关文章:

android - 相同的 Tensorflow 模型在 Android 和 Python 上给出不同的结果

python - 在同一个 GPU 上运行多个 tensorflow 进程不安全吗?

ios - 在 iOS 的 UIImageview/位图中检测特定的 RGB 值

c++ - OpenCV 错误 : "LNK1181: cannot open file ' opencv_flann310. 库'”

opengl - 色彩空间、 Gamma 和图像增强

c++ - 使用 ICC 配置文件将 L*a*b* 转换为 RGB

python - Python 解释器欢迎信息可以被抑制吗?

python - keras:如何使用 model.train_on_batch() 的学习率衰减

java - 使用OpenCV打开Android原生Camera

python-3.x - 无法访问内置网络摄像头 Python