Python cv2 imshow() | How to show image in Python
The cv2.imshow() method in Python is used to display an image in a window. The window automatically fits the image size. OpenCV-Python is the library of Python bindings designed to solve computer vision problems, and it provides a cv2 module that helps us to edit or save the image in the particular filesystem.
Let’s install Python OpenCV library in Python.
Install Python OpenCV
To work with OpenCV in Python, we have to install the opencv-python module.
Type the following command.
python3 -m pip install opencv-python # OR pip install opencv-python
To use the opencv-python in our project, we have to import the cv2 module in the file.
Python cv2 imshow()
To display the image, we read with an image with an imread() function, and then we call the imshow() method of the cv2 module. The imshow() function will display the image in a window, and it receives as input the name of the window and the image.
In Computer Vision applications, images are an integral part of the development process. Often there would be a requirement to read images and display them if required.
To read and display image using OpenCV Python, you could use cv2.imread() for reading the image to a variable and cv2.imshow() to display the image in a separate window.
window_name: A string representing the name of a window in which image to be displayed.
image: It is an image that is to be displayed.
The imshow() method doesn’t return anything.
See the following code.
# importing cv2 import cv2 # image path path = './forest.jpg' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'image' # Using cv2.imshow() method # Displaying the image cv2.imshow(window_name, image) # waits for user to press any key # (this is necessary to avoid Python kernel form crashing) cv2.waitKey(0) # closing all open windows cv2.destroyAllWindows()
In this example, first, we are importing the cv2 module.
In the next step, we have defined an image path.
Then read the image using cv2.imread() function.
Then we have defined a window_name that we have set to image.
Then we are using the imshow() function and pass the two parameters to open the image window and can see the image.
To keep the image window, we have used the waitKey() function.
We passed 0 to waitKey() method that means it will remain open forever until we said otherwise.
That is it for the Python cv2.imshow() function.