Life2Coding
Resize the OpenCV Window According to the Screen Resolution

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to resize the input image according to the screen resolution.

Documentation:

Python: cv2.resizeWindow(winname, width, height) → None

Resizes window to the specified size

Parameters: 

  • winname – Window name
  • width – The new window width
  • height – The new window height

Note

  • The specified window size is for the image area. Toolbars are not counted.
  • Only windows created without CV_WINDOW_AUTOSIZE flag i.e with CV_WINDOW_NORMAL flag can be resized.

 Steps:

  • Load Image using cv2.imread()
  • Create window using cv2.namedWindow()
  • Resize the window using cv2.resizeWindow()
  • Display Image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np

def main():
    #load the image
    img = cv2.imread('Hanif.jpg')

    #define the screen resulation
    screen_res = 1280, 720
    scale_width = screen_res[0] / img.shape[1]
    scale_height = screen_res[1] / img.shape[0]
    scale = min(scale_width, scale_height)

    #resized window width and height
    window_width = int(img.shape[1] * scale)
    window_height = int(img.shape[0] * scale)

    #cv2.WINDOW_NORMAL makes the output window resizealbe
    cv2.namedWindow('Resized Window', cv2.WINDOW_NORMAL)

    #resize the window according to the screen resolution
    cv2.resizeWindow('Resized Window', window_width, window_height)

    cv2.imshow('Resized Window', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

Output:

1.-210x250 Resize the OpenCV Window According to the Screen Resolution resize-114x250 Resize the OpenCV Window According to the Screen Resolution

life2coding_icon [] Resize the OpenCV Window According to the Screen Resolution

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.