python - 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显示。
这个错误是什么意思,我该如何修复程序?
解决方案
将这两行代码替换为以下行:
#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
仅等于。
推荐阅读
- php - 使用 isNull() 清除 ezSQL 中的查询
- javascript - Juicer.io (Soc Media Feed) 仅在 Internet Explorer 11 中不加载
- java - 获取两个图顶点之间的边列表
- javascript - 在从 redux 接收更改的 prop 时设置输入值
- python - 如何使用 keras 在 LSTM 中实现多元回归的输入?
- php - 如何在 woocommerce 帐户页面中删除“我是客户”和“我是供应商”的单选按钮?
- ios - ARKIT:SKVideoNode 在节点不在场景时继续播放,暂停不起作用
- java - 此代码是否支持相互身份验证,如果是,如何触发它?
- pytest - --disable-warnings + "ra" 选项在 pytest.ini 中不能很好地叠加
- python - 使用python通过UART接收数据