Read an image in Python and open it in a Window

Python has very powerful modules to work with image processing. There are several great image processing libraries are used by Python programmers.

In this tutorial, I am going to show you the simplest way to read an image in Python and then open it in a window. Please make sure you have OpenCV installed before following this tutorial. If you don’t have it, please install it first.

Here I am going to use the OpenCV Python module to read the image. Let’s see how you can use this module to read an image.

At the very first, import the OpenCV module:

import cv2

After that use the imread() method to read an image.

my_img = cv2.imread("imgs/pd2.jpg", cv2.IMREAD_GRAYSCALE)
print(my_img)

The imread() method has come from the OpenCV Python library. We get our image into matrix data and store it in our variable my_img. As you can see that we print the image matrix data. So, after you run it, you will be able to see the matrix data of the image in the console.

You can notice that we are using IMREAD_GRAYSCALE enumerator which converts the image to the single channel grayscale image. If we want the colored image, then we have to set it to IMREAD_COLOR just like you can see below:

my_img = cv2.imread("imgs/pd2.jpg", cv2.IMREAD_COLOR)

Now we are ready to show the image on the window. below is the Python code to open your image in a window:

cv2.imshow("My image", my_img)
cv2.waitKey(0)

In the above code, the imshow() uses shows the image in a window. But it will close the window instantly. So here I have used the waitKey(0) that displays the window until we press any key. If we use waitKey(1000), then it will close the window after 1000 milliseconds or after 1 second. We pass the parameter here in milliseconds.

At the end we put the below line of Python code in our program:

cv2.destroyAllWindows()

Using destroyAllWindows() method close the window and de-allocate any associated memory usage.

Also, read:

Complete final code to read an image in Python

Below is the complete code that we have discussed above:

import cv2

my_img = cv2.imread("imgs/pd2.jpg", cv2.IMREAD_COLOR)
print(my_img)

cv2.imshow("My image", my_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

You can run the above code, change the image path with the image from your computer and run it. You will able to see a window open that contains the gray version of the image.

Below are two different pictures with both IMREAD_GRAYSCALE and IMREAD_COLOR enumerator:
Image With IMREAD_GRAYSCALE Enumerations

Image With IMREAD_GRAYSCALE Enumerations

Image With IMREAD_COLOR Enumerations

Image With IMREAD_COLOR Enumerations

Leave a Reply

Your email address will not be published. Required fields are marked *