首页 > 解决方案 > 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()

标签: pythonimageopencvimage-processing

解决方案


你得到的尺寸似乎是正确的。您可以检查图像的尺寸

print(img.shape)

你会得到图像,(height, width)但这可能有点令人困惑,因为我们通常根据宽度 x 高度来指定图像。这是因为图像在 OpenCV 中存储为 Numpy 数组。因此,要索引图像,您可以简单地使用img[Y:X]as height是形状中的第一个条目,而 width 是第二个条目。

因为它是 Numpy 数组,所以我们得到(rows,cols)它等价于(height,width).


推荐阅读