After installing OpenCV, I was looking for a quick way to test out basic functionality in Python. A quick and dirty test to make sure things are working is to just try importing the OpenCV libraries via the command import cv. If this executes without errors, Python is able to access the OpenCV libraries just fine.
However, I wanted to figure out how to display an image using these newly-accessible libraries. I couldn't find clean, well-documented code that explained this seemingly simple task on the web, so I wrote it myself.
Place the following in a Python script and call it from the command line.
Be sure to change the file path to the desired image.
You should see something like this screenshot on your desktop (though of course your actual image will be different).
The key to actually getting an image to display on screen is this mysterious "WaitKey" command.
Any call to WaitKey updates the display instantly. Without this call, nothing appears. This is because the "ShowImage" command only lets OpenCV know that a window *should* be created. By itself, it doesn't have the functionality to tell the operating system to actually create the window. This seems like bizarre functionality to a first-time user, but probably makes more sense when you're writing complex graphics programs and you only want the display updated every so often and not all the time.
Digging further under the hood, we find that WaitKey's primary purpose is to way for a button press and return that button. It takes an integer argument n that specifies how long to wait (in milliseconds) for a button press.
WaitKey returns an integer corresponding to the keyboard key that was pressed. When a button is pressed within the waiting interval, WaitKey returns a unique positive integer corresponding to that button. If some other event terminates its waiting prematurely (like clicking the X to close a window), or its waiting time elapsed without any key pressed, WaitKey returns -1.
Tutorials / How To >