Opencv显示错误的图像宽度和高度

时间:2019-04-11 15:39:07

标签: python-3.x opencv

问题在标题本身中。

我有一张尺寸为612x408(宽x高)的图像。

当我使用opencv cv2.imread(/path/to/img)打开它时,显示(408,612,3)

这不是问题

cv2.imshow()可以正常显示宽度大于高度的图像,如正常的水平矩形

我添加了mouseCallback来获取像素位置,因此,即使我单击鼠标,将鼠标更靠近图像的右侧,也会出现错误IndexError: index 560 is out of bounds for axis 0 with size 408

我搜索了SO,但找不到类似的问题

import cv2
def capture_pos(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        mouseX = x
        mouseY = y
        print('mouse clicked at x={},y={}'.format(mouseX,mouseY))
        h,s,v = img[mouseX,mouseY]
        print('h:{} s:{} v:{}'.format(h,s,v))
img = cv2.imread('./messi color.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
cv2.namedWindow('get pixel color by clicking on image')
cv2.setMouseCallback('get pixel color by clicking on image',capture_pos)
cv2.imshow('get pixel color by clicking on image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:3)

您得到的尺寸似乎正确。您可以使用

检查图像的尺寸
print(img.shape)

您将获得的图像为(height, width),但这可能有点令人困惑,因为我们通常以宽x高的形式指定图像。这是因为图像在OpenCV中存储为Numpy数组。因此,要索引图像,只需使用img[Y:X],因为 height 是形状中的第一项,宽度是 second

由于它是Numpy数组,所以我们得到(rows,cols),它等效于(height,width)

相关问题