A few months ago, I was teaching an online seminar on the basics of computer vision.
And do you know what the most common question I got asked was?
How do I use OpenCV to load an image and display it on my screen?
It’s a pretty basic concept, but I think many instructors (myself included) quickly jump over this question and immediately dive into more advanced techniques such as blurring, edge detection, and thresholding.
Displaying an image to your screen is a simple way to debug a computer vision program, so let’s take a couple minutes and answer the this question.
Looking for the source code to this post?
Jump Right To The Downloads SectionHow-To: OpenCV Load an Image
The objective of this post is to show you how to read an image off of disk using OpenCV, display it on your screen, and then wait for a key press to close the window and terminate the script.
While simply displaying an image on your screen isn’t practical by itself, it’s an important technique that you will use a lot when you’re developing (and more importantly, debugging) your own computer vision applications.
You see, displaying an image on your screen is much like a print
statement when you’re debugging a tricky program.
When it comes to debugging, nothing beats a few well placed print
statements to figure out where the problem is coming from.
The same is true in computer vision.
A few well placed calls to cv2.imshow
will quickly help you resolve the problem.
So let’s go ahead and jump into some code:
import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("image", image) cv2.waitKey(0)
Lines 1-2 handle importing the packages that we’ll need — argparse
to parse command line arguments and cv2
for our OpenCV bindings.
Then, on Lines 4-6 we parse our command line arguments. We only need a single switch, --image
, which is the path to where our image resides on disk.
Loading the image using OpenCV is taken care on Line 8 by making a call to the cv2.imread
function. This function takes a single parameter — the path to where the image resides on disk, which is supplied as a command line argument.
Finally, we can display our image to our screen on Lines 10-11.
Displaying the image to our screen is handled by the cv2.imshow
function. The first argument to cv2.imshow
is a string containing the name of our window. This text will appear in the titlebar of the window. The second argument is the image that we loaded off of disk on Line 8.
After we have made a call to the cv2.imshow
function, we then need to wait for a key press using the cv2.waitKey
function on Line 11.
It’s very important that we make a call to this function, otherwise our window will close automatically!
See, the cv2.waitKey
function pauses execution of our Python script and waits for a key press. If we removed Line 11, then the window containing our image would close automatically. By making a call to cv2.waitKey
, we are able to pause the execution of our script, thus displaying our image on our screen, until we press any key on our keyboard.
The only argument cv2.waitKey
takes is an integer, which is a delay in milliseconds. If this value is positive, then after the specified number of milliseconds elapses the window will close automatically. If the number of milliseconds is zero, then the function will wait infinitely until a key is pressed.
The return value of cv2.waitKey
is either the code of the pressed key, or -1
, indicating that no key was pressed prior to the supplied amount of milliseconds elapsing.
We can execute our script by issuing the following command:
$ python load_image.py --image doge.jpg
You should then see an image on your screen:
Clearly a wild Doge has appeared! And I’m all out of Pokeballs…
Pressing any key on your keyboard will un-pause the script and close the window.
What's next? We recommend PyImageSearch University.
86 total classes • 115+ hours of on-demand code walkthrough videos • Last updated: October 2024
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 86 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 86 Certificates of Completion
- ✓ 115+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this blog post I answered one of the most common questions I get asked: “How do I use OpenCV to load an image and display it on my screen?”
In order to load an image off of disk and display it using OpenCV, you first need to call the cv2.imread
function, passing in the path to your image as the sole argument.
Then, a call to cv2.imshow
will display your image on your screen.
But be sure to then use cv2.waitKey
to wait for a key press, otherwise the window created by cv2.imshow
will close automatically.
Learn the Basics of Computer Vision in a Single Weekend
If you’re interested in learning the basics of computer vision, but don’t know where to start, you should definitely check out my new eBook, Practical Python and OpenCV.
In this book I cover the basics of computer vision and image processing…and I can teach you in a single weekend!
I know, it sounds too good to be true.
But I promise you, this book is your guaranteed quick-start guide to learning the fundamentals of computer vision. After reading this book you will be well on your way to becoming an OpenCV guru!
So if you’re looking to learn the basics of OpenCV, definitely check out my book. You won’t be disappointed.
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Sebastian
Hi Adrian, i’m trying to make the code work, but i can’t.
Can you give me an example of how to put the path directory for a Raspberry Pi 2 on this line:
Adrian Rosebrock
Please see the example at the bottom of this post:
$ python load_image.py --image doge.jpg
The path to the image is passed via command line at execution, you do not need to modify the original code.
Sadecutz
Hello sir. Can you please give me an example of a path u used in –image in this line of code:
ap.add_argument(“-i”, “–image”, required = True, help = “Path to the image”)
Adrian Rosebrock
You do not need to modify the argument parsing code. It just indicates that the
args["image"]
variable will be supplied via command line argument. You can see an example running the Python script via command line this post:$ python load_image.py --image doge.jpg
Notice how the
--image
switch points to the path to thedoge.jpg
image.If you’re unfamiliar with command line arguments, I suggest giving this tutorial a read.
Mathys
Hi there
For the life of me I cant get a image to load with argparse.
I have tried running it from the command line etc etc
Im using windows if that makes a difference.
I dont know where to put my path to the image?
Thanks
Adrian Rosebrock
You specify the path to the image via command line argument. It’s been a long time since I’ve used Windows, but I believe it uses the “\” path separator instead of “/”, so your command should look something like:
$ python load_image.py --image path\to\your\image.jpg
sarvin
Hi Adrian,
Im using Windows also. where do i write this command ?
‘ python load_image.py –image path\to\your\image.jpg’ ?
Adrian Rosebrock
You would open up your command line, change directory to where your
load_image.py
script lives and execute the command.Mickey
Hi Adrian,
Love you blog. Are there any minor changes I can make to this code that would allow me to upload multiple images? Thank you!
Adrian Rosebrock
What do you mean “upload” images? Do you mean load images from disk? Or upload to a server?
Mickey
Hi Adrian,
I meant to ask if there was a way to upload an entire folder of images for processing, without having to write in each image.
mukesh
hi
did u get the answer ?
plz responde…i m facing same problem
Adrian Rosebrock
I’m still not sure I understand what the question is.
Vivaan
You can press enter to get to the next img
Dave
Hi, imread keeps returning “none”, even when I hardcode the file location as the argument for cv2.imread
Adrian Rosebrock
If you’re getting a
NoneType
fromcv2.imread
, then one of two things are happening: (1) The path tocv2.imread
is (still) incorrect or (2) OpenCV cannot read the type of image you’re supplying to it.alex
I am having the same problem, Adrian! I download your code and try to running by CMD on Windows, and nothing happens. Can it be a bug on windows args?
Adrian Rosebrock
Keep in mind that the Windows operating system uses the
\
path separator while Unix uses the/
path separator. You likely need to update the path to your input image using the\
separator.Coach
Adrian,
Love your blog. I just started you tutorails today, I seem to be opening an image just fine, but it appears I missed how to display images when I’m ssh’d into my Pi.
I get the following error: (image:30709) Gtk-WARNING **: cannot open display:
Please point me to instructions on how to open a display via ssh.
Thanks!
Adrian Rosebrock
If you’re using SSH to access your Pi, make sure you enable X11 forwarding so that the frames can be displayed:
$ ssh -X pi@your_ip_address
Francisco
Hi Adrian!
Thank you so much for your effort and help!
I’m stuck with load_display_save.py, and it looks like work, but I see nothing on the screen. When I execute the program, the raspi gets nothing, just an empty line in the command prompt screen (like thinking), then returns to the normal prompt.
I tried the $ ssh -X pi@your_ip_address
But then it gets again freezes, until I press Ctrl+C.
I made other tests in OpenCV, and I can see the picture or video the camera captured via SSH or VNC.
It happens both via direct SSH with PuTTy, and with VNC.
Do you know what can be happening?
Thanks!
Adrian Rosebrock
That is certainly odd, Francisco! Unfortunately without having direct access to your Pi I’m not sure why that may be happening. I’m sorry I couldn’t be of more help here.
Melissa
Hi Adrian,
thanks for the tutorial 🙂 I am trying it and I get an error saying that the imshow function isn’t implemented. I’ve done a few tutorials trying to get this to work, with no success. Any recomendations? Thanks
Adrian Rosebrock
Hi Melissa — how did you install OpenCV? Via one of the tutorials here on PyImageSearch? Or elsewhere? Normally you receive this error when OpenCV was compiled without “highgui” support which is the module responsible for GUI operations and displaying images to your screen.
Yuv
Hello Adrian, I like your tutorials, I’m using them for a project.
When i run the code, I get the error:
usage: TestOpenImage.py [-h] -i IMAGE
TestOpenImage.py: error: the following arguments are required: -i/–image
>>>
could you help me out please? I’m new to Python programming. Thanks alot!
Adrian Rosebrock
Please read the other comments before posting. I have addressed this question in my reply to “Sadecutz” above.
Yiyou
Hi Adrian, I’ve been a loyal reader of your blog posts and books since the day I found your blog! I have a problem of loading .png image with transparency channel – I could do it with PIL sometimes using .convert(“RGBA”), but sometimes even PIL fails. Do you have any idea how can I cope with that? Thanks!!
Adrian Rosebrock
Hi Yiyou — for PNG’s with transparent channels, please check out the information at the bottom of this blog post.
Karel Jansseune
Hello Adrian,
Really love your blog and the clear explanation about OpenCV.
I do run into some problems with the above example. When I run this code, the console runs fine, the arguments get loaded, but then it all ends. No image is shown.
I guess I’m missing a very basic point here, but so far i couldn’t fine a way to solve it. (As a matter of fact, this post is the first one to explain how to load arguments into a script 🙂 )
Adrian Rosebrock
Hey Karel — I would check the output of
cv2.imread
. Is it “None”? If so, then an invalid image path was supplied to the script. If you’re new to command line arguments, read this tutorial first. Otherwise, it would be helpful to know the system you are executing the script on, OpenCV version, and how you installed OpenCV.Finally, I would recommend reading through Practical Python and OpenCV. My book is has helped thousands of developers new to OpenCV and Python jumpstart their education. Be sure to take a look!
Aziz
Hello Adrian , Thank you a lot for your lovely blogs,
I tried the code but got the error, i’m using python 3.6
>python load_image.py –image penny.jpg
Traceback (most recent call last):
File “readimage.py”, line 8, in
image = cv2.imread(args[“image”])
NameError: name ‘args’ is not defined
thank you
Aziz
Thank you so much Adrian, I found the error it was my spelling mistake of args
😉
Adrian Rosebrock
Congrats on resolving the error, Aziz!
Tahir
Hello Adrian,
Thank you for amazing blogs. I have tried your code and it is working fine, but now I need to use multiple images in the program and I can’t seem to find way to .add_argument multiple images. Do you think you can help me?
Adrian Rosebrock
I would instead suggest putting all your images in an input directory, then passing the path to the input directory to your script. Your script can then loop over all images in the directory and access them one-by-one. This tutorial provides an example of this as does Practical Python and OpenCV.
ali
Hi Adrian,
i write code in the Idle , how to run this?
Adrian Rosebrock
You can use IDLE if you want, but you’ll need to copy and paste line-by-line. I would instead recommend you use the command line to execute the script.
İlyas Kaan Kalkan
usage: 1.py [-h] -i IMAGE
1.py: error: the following arguments are required: -i/–image
Adrian Rosebrock
1. Make sure you use the “Downloads” section of this blog post to download the code + images before you try to execute them.
2. Your error is due to not specifying the
--image
command line argument when executing the script. Make sure you read up on command line arguments before continuing.Ridho
hi adrian
i have error in: arguments -i/–image is required
Adrian Rosebrock
Please see my reply to “Sebastian” on October 1, 2015 (the very first comment on this post).
andrey
hi, i load images in directory, how i print the filename ?
Adrian Rosebrock
Hi Andrey, to list the images in a directory you should try using
imutils.paths
and use the function,list_images
. See the implementation here. From there you could print the list of filenames in your terminal.John
Hi Adrian,
I am getting an invalid syntax error,
load_image py –image doge.jpg
I am using spyder editor through anaconda.
Any help will be greatly appreciated.
John
*load_image.py –image doge.jpg
the syntax error is at the e of doge
Adrian Rosebrock
Hey John — can you try to execute the code via your command line argument instead of Spyder and see if you still have the same issue?
vibha
Hi Adrian.,
I hope you are doing well.,i have encountered with an error while working on detect-faces.py
Error is
usage: __main__.py [-h] -i IMAGE -p PROTOTXT -m MODEL [-c CONFIDENCE]
__main__.py: error: the following arguments are required: -i/–image, -p/–prototxt, -m/–model.
Please help me out.Thanks a lot 🙂
Adrian Rosebrock
Reading this blog post on command line arguments will help you solve the error.
Aleem
Hi, how could I run this in the pycharm itself. How to give the path here,
ap.add_argument(“-i”, ‘diagram.png’, required=True, help=”path to the input image”)
Adrian Rosebrock
Hey Aleem, make sure you read this tutorial on command line arguments. It will help you better understand argparse and even demonstrates how to set an argument via PyCharm.
FJ
Hello. I just want to know how to load the latest image in a folder using python and opencv
Adrian Rosebrock
I would suggest sorting your image paths via timestamp, grabbing the latest image path, and then loading it.
aa
how i pass video name as an argument
Adrian Rosebrock
Refer to this tutorial on how to use command line arguments.
aln
Hi Adrian
thanks a lot for your blog, i use PyCharm IDE ,so when first see your code, i even did not know what it’s mean, after see these issue, i can show the image after load model, but i still have a problem ,how to use camera frame when i want to get the real-time result ,thank you !
Jacob
Hello Adrian,
I’m getting the following error on my Jetson nano:
error: (-215) size.width>0 && size.height>0 in function imshow
Do you know what might be wrong?
Thanks!
Adrian Rosebrock
Yes. Your path to the input image is incorrect and OpenCV is returning “None”. Double-check your input paths. Additionally, read this tutorial on NoneType errors and how to resolve them.
Luzuko
So i went through your other blogs. i get that the image maybe in the wrong path. my question: is this t-rex image a default image in our laptops? by that i mean, i dont remember loading a file with that image. if it is a default, what other path it maybe under?….these questions sound stupid, but am a novice in this space.
Adrian Rosebrock
No, it’s not a default image. It’s included in the “.zip” download which can be found in the “Downloads” section of this post.
Luzuko
Great…let me go and download it…thanks…
Luzuko
works…thanks…
Adrian Rosebrock
Awesome, glad to hear it!
RajaRam
Hello, Adrian your each and every post is very useful for students like me,Great work.
I have a small ques, can we get two images of same object into one plane??
For example,
If a sticker is attached at the edge of a wall or any edge.we cannot take the image of the sticker at once because some part sticker may be in another plane.Now my problem is to get the 2 images into same plane so that it looks like our normal images captured .
Adrian Rosebrock
Do you have an example image of what you are trying to achieve? That would better help me provide a suggestion to you.
Yu
This really helped me, thanks so much! If I wanted to create a for loop, such that for each image I have, the script runs, how would I do that? Could I use the command line in a for loop in a different .py script?
Adrian Rosebrock
I would recommend you use the “imutils.list_images” function which can be used to loop over all image paths in a directory.
David
Hi Adrian,
I just want to say that your blog is amazing. Your posts are so valuable and quite well explained, they are really helping me out in getting started to this world of artificial vision.
Thanks.
Adrian Rosebrock
Thanks David, I really appreciate the kind words 🙂