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 post, I am going to show you the simplest way to read an image in Python.
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:
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 library. We get our image into matrix data and store it in our variable. As you can see that we print the image matrix data. So, after you run it, you will able to see the matrix data on the console.
You can notice that we are using IMREAD_GRAYSCALE enumerator which convert 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)
Below are the images with both color and gray version:
Now you 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)
In the above code, the imshow() shows the image in a window. But it will close the window instantly. So here I have used the waitKey(0) which display 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 parameter here in milliseconds.
At the end we put the below line of code:
Using destroyAllWindows() method close the window and de-allocate any associated memory usage.
Complete final code to read an image in Python
Below is the code 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.