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:
- OpenCV 3.4
- Python 3.6+
- Numpy
- Image, Webcam, Video input
- Documentation Source: OpenCV Official Documentation
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:
Latest posts by Life2Coding (see all)
- How to Create a RGB Color Picker for Images using OpenCV Python - 22 April, 2022
- Combine Several Images Vertically with Padding using OpenCV Python - 21 April, 2022
- Combine Several Images Horizontally with Padding using OpenCV Python - 21 April, 2022