首页 > 解决方案 > numpy.AxisError:轴 2 超出维度 0 数组的范围

问题描述

我正在创建一个程序,它需要一个黑白图像和两个数组,分别包含黑白像素的 X 和 Y 坐标。我有一个程序,它利用 OpenCV 和二进制阈值来创建黑白图像(代码源)。听到的是我到目前为止的完整代码。

#Load image
im = cv2.imread('image.png')

#create grey image
grayImage = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

#create full black and white image
(thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)

#Define black and white
black = [0,0,0]
white = [255,255,255]

#Get X and Y coordinates of both black and white
Xb,Yb = np.where(np.all(blackAndWhiteImage==black,axis=2))
Xw,Yw = np.where(np.all(blackAndWhiteImage==white,axis=2))

#combine x and y
Bzipped = np.column_stack((Xb,Yb))
Wzipped = np.column_stack((Xw,Yw))

#show
print(Bzipped,Wzipped)

我遇到的问题出现在这些行

Xb,Yb = np.where(np.all(blackAndWhiteImage==black,axis=2))
Xw,Yw = np.where(np.all(blackAndWhiteImage==white,axis=2))

当程序运行时,错误numpy.AxisError: axis 2 is out of bounds for array of dimension 0显示。

这个错误是什么意思,我该如何修复程序?

标签: pythonimagenumpyopencvimage-processing

解决方案


将这两行代码替换为以下行:

#Black
(Xb, Yb) = np.where(blackAndWhiteImage==0)
#white
(Xw, Yw) = np.where(blackAndWhiteImage==255)

这里发生的blackAndWhiteImage是二进制图像。因此,它只包含一个通道。因此,axis=2对于单通道图像无效,并且您将图像值与之进行比较[0, 0, 0] or [255, 255, 255]是不可能的,因为图像包含的值0 or 255仅等于。


推荐阅读