Python中的ValueError,数组中的索引数不匹配

结尾

我应该写一种方法,通过使用“平均方法”将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现在是灰度(单通道)图像,而img1显然仍然是彩色(三通道)。

我不是numpy向导,所以可能会有更好的解决方案,但是我认为您可以使用以下方法将img2扩展为三个通道

img2 = np.stack(3 * [img2], axis=2)

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章