How to Load and Display Images in Python using the OpenCV Module



Python


In this article, we show how to load and display images in Python using the OpenCV module.

The OpenCV module is a powerful module in Python that is used a lot for computer vision.

Computer Vision is used for all types of things, including for object detection and facial recognition. It is used extensively for driverless cars because self-driving rely on object detection, such as identifying cars, traffic signs, stop lights, pedestrians, sidewalks, buildings, etc.

There are many advanced things we can do with images such as detect objects within images with OpenCV. However, we start with the basics in this article.

As a note, in order for this project to work, you must have installed OpenCV, which you can do with the line, pip install opencv-contrib-python

In this article, we show how to load an image and also display it with the OpenCV module.

We can load an image into the imread() function and we show an image using the inshow() function.

This is shown in the code below where we load and display a file named 'moon.jpg'.



So let's now go over this code.

So the first thing we have do is to import the OpenCV module, which we do with the line, import cv2

Next, we must load the image in. If the image is in the current working directory that you are using, then you simply just have to specify the file name. If it isn't, then you have to specify the full path on your computer to the image. In the example, the image is in the same folder as the current working directory, so we simply specify the file name, 'moon.jpg'.

So we now have the image loaded into the variable, image.

Next, to display the image, we use the imshow() function, which takes in 2 parameters. The first parameter is the name of the window in which the image will appear. This will appear in the title bar of the window. The 2nd parameter is the image that you want to appear. We simply pass in the image variable, which is the variable which contains the image we loaded in.

After running this code, you should see the image you loaded in.

Now, depending on the operating system you're using, you may have to add another line of code if you don't see the image appear. This is because some operating systems will have the image show and then closed within a fraction of a second. To combat this, if it occurs, you add in the line, cv2.waitKey(0). What this does is it will have the image appear and will only have it closed if the user presses a key.

So if the image is not appearing the full line of code should be as follows.



And this is how we can load and display images in Python using the OpenCV module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...