Open In App

Python OpenCV – getWindowImageRect() Function

Python OpenCV getWindowImageRect() Function returns the client screen coordinates, along with the width and height of the window containing the picture.

Syntax of cv2.getWindowImageRect()

Syntax: cv2.getWindowImageRect(window_name)



Parameter: 

  • window_name – Name of the window displaying image/video

Return: return a tuple of x, y, w, h(Set of four integers including the coordinates & size of rectangle)with window name. 



Image for Demonstration:

 

Example 1: Get default window size using getWindowImageRect() Python




# Importing OpenCV
import cv2
  
# Path to image
path = 'C:/Users/Amisha Kirti/Downloads/GFG.png'
  
# Reading an image in default mode
image = cv2.imread(path)
  
# Creating window with name "Display1" 
# of default size
cv2.namedWindow("Display1", cv2.WINDOW_AUTOSIZE)
  
# Using getWindowImageRect()
print(cv2.getWindowImageRect("Display1"))
  
# Assigning the returned values to variables
(x, y, windowWidth, windowHeight) = cv2.
getWindowImageRect("Display1")
  
"""
We can also assign values to variables by 
accessing returned value by index
   
x = cv2.getWindowImageRect("Display1")[0]
y = cv2.getWindowImageRect("Display1")[1]
windowWidth=cv2.getWindowImageRect("Display1")[2]
windowHeight=cv2.getWindowImageRect("Display1")[3]
"""
  
print("Origin Coordinates(x,y): ", x, y)
print("Width: ", windowWidth)
print("Height: ", windowHeight)
  
# Displaying the image using imshow
cv2.imshow('Display1', image)
  
# Waiting 0ms for user to press any key
cv2.waitKey(0)
  
# Destroying all windows open on screen
cv2.destroyAllWindows()

Output:

Example-1 Console & Window Output

Example 2: Get fullscreen window size using getWindowImageRect() Python

This function helps us get the exact number of pixels of the window in which the image is displayed.




# Importing OpenCV
import cv2
  
# Path to image [NOTE: Here resized image 
# is used to be able to fit to screen]
path = 'download3.png'
  
# Reading an image in default mode
image = cv2.imread(path)
  
# Creating a full screen window with 
# name "Display2" using WINDOW_FULLSCREEN 
# or WINDOW_NORMAL
cv2.namedWindow("Display2", cv2.WINDOW_NORMAL)
  
# Using getWindowImageRect()
print(cv2.getWindowImageRect("Display2"))
  
# Assigning the returned values to variables
(x, y, windowWidth, windowHeight) = cv2.
        getWindowImageRect("Display2")
  
print("Origin Coordinates(x,y): ", x, y)
print("Width: ", windowWidth)
print("Height: ", windowHeight)
  
# Displaying the image using imshow
cv2.imshow('Display2', image)
  
# Waiting 0ms for user to press any key
cv2.waitKey(0)
  
# Destroying all created windows 
# open on screen
cv2.destroyAllWindows()

Output:

Example-2 Window Output

Example-2 Console Output


Article Tags :