Yusuf
Yusuf

Reputation: 449

Opencv showing wrong width and height of image

I have an image with dimension 612x408 (widthxheight).

When I open it using opencv cv2.imread(/path/to/img) it shows me (408,612,3).

This is not the problem

When I cv2.imshow() it shows the image correctly with width larger than height like a normal horizontal rectangle

I added mouseCallback to get the pixel position so when I put my mouse nearer to the right edge of image I get error IndexError: index 560 is out of bounds for axis 0 with size 408 although I have clicked on the image.

I searched on SO but could not find similar question

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()

Upvotes: 1

Views: 5427

Answers (1)

nathancy
nathancy

Reputation: 46600

The dimensions you're getting seems correct. You can check the dimensions of the image with

print(img.shape)

You will get the image as (height, width) but this may be a bit confusing since we usually specify images in terms of width x height. This is because images are stored as a Numpy array in OpenCV. Therefore, to index the image, you can simply use img[Y:X] as height is the first entry in the shape and the width is the second.

Since it is Numpy array we get (rows,cols) which is equivalent to (height,width).

Upvotes: 5

Related Questions