Python 中的值错误,数组中的索引数不匹配

ValueError in Python, Number of Indices in Array not Matching

我应该编写一种方法,通过使用“平均法”将 RGB 图像转换为灰度图像,其中我取 3 种颜色的平均值(不是加权法或光度法)。然后我必须显示原始的 RGB 图像和灰度图像彼此相邻(连接)。我写的语言是 Python。这就是我的代码目前的样子。

import numpy as np
import cv2

def average_method(img):
    grayValue = (img[:,:,2] + img[:,:,1] + img[:,:,0])/3
    gray_img = grayValue.astype(np.uint8)
    return gray_img

def main():
    img1 = cv2.imread('html/images/sunflowers.jpg')
    img1 = cv2.resize(img1, (0, 0), None, .25, .25)
    img2 = average_method(img1)
    numpy_concat = np.concatenate((img1, img2), 1)
    cv2.imshow('Numpy Concat', numpy_concat)
    cv2.waitKey(0)
    cv2.destroyAllWindows

if __name__ =="__main__":
    main()

当我尝试 运行 时,它显示了这个错误:

    Traceback (most recent call last):
  File "test.py", line 23, in <module>
    main()
  File "test.py", line 16, in main
    numpy_concat = np.concatenate((img1, img2), 1)
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 3 dimension(s) and the array at index 1 has 2 dimension(s)

谁能帮我解决这个问题,这样我就可以使用“平均法”成功地并排处理 RGB 和灰度?不确定我是否正确设置了平均方法并导致了这个问题,或者它是否来自我尝试连接图片的方式。谢谢

错误消息几乎可以告诉您发生了什么。您的 img2 现在是灰度 (single-channel) 图像,而 img1 显然仍然是彩色 (three-channel)。

我不是 numpy 向导,所以可能有更好的解决方案,但我认为您可以使用

将 img2 扩展到三个通道
img2 = np.stack(3 * [img2], axis=2)

编辑:可能更有效(也更难理解):

img2 = np.repeat(A[..., np.newaxis], 3, axis=2)