Get the size of a window in OpenCV

Viewed 8604

I have searched online and wasn't able to find an answer to this so I figured I could ask the experts here. Is there anyway to get the current window resolution in OpenCV? I've tried the cvGetWindowProperty passing in the named instance of the window, but I can't find a flag to use.

Any help would be greatly appreciated.

2 Answers

You can get the width and height of the contents of the window by using shape[1] and shape[0] respectively. I think when you use Open CV, the image from the camera is stored as a Numpy array, with the shape being [rows, cols, bgr_channels] like [480,640,3]

code e.g.

import cv2 as cv2

cv2.namedWindow("myWindow")

cap = cv2.VideoCapture(0) #open camera
ret,frame = cap.read() #start streaming

windowWidth=frame.shape[1]
windowHeight=frame.shape[0]
print(windowWidth)
print(windowHeight)

cv2.waitKey(0) #wait for a key
cap.release() # Destroys the capture object
cv2.destroyAllWindows() # Destroys all the windows


console output:
640
480

You could also call getWindowImageRect() which gets a whole rectangle: x,y,w,h

e.g.

import cv2 as cv2

cv2.namedWindow("myWindow")

cap = cv2.VideoCapture(0) #open camera
ret,frame = cap.read() #start streaming

windowWidth=cv2.getWindowImageRect("myWindow")[2]
windowHeight=cv2.getWindowImageRect("myWindow")[3]

print(windowWidth)
print(windowHeight)

cv2.waitKey(0) #wait for a key
cap.release() # Destroys the capture object
cv2.destroyAllWindows() # Destroys all the windows

-which very curiously printed 800 500 (the actual widescreen format from the camera)
Related