View an Image in Python with OpenCV

OVERVIEW


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.

CODE


Place the following in a Python script and call it from the command line.  

import cv

# Load the image from designated filepath
img = cv.LoadImageM( "/home/mhughes/PortraitDoubleArches.jpg" )

# Create a window with given title (also used as unique identifier of this window)
#   and insert the loaded image into this window
cv.ShowImage( "My Photo Window",img )

# Call graphics manager to update display 
#  and keep displaying until user closes the window (which triggers buttonID = -1 )
buttonID = cv.WaitKey(-1)
while (buttonID >= 0):
  buttonID = cv.WaitKey(-1)
  print buttonID

Be sure to change the file path to the desired image.

RESULT

You should see something like this screenshot on your desktop (though of course your actual image will be different).


DETAILS


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.
  • if n >= 0
    • WaitKey pauses execution for n milliseconds (or until the first button is pressed), and then returns control to the calling script/function.
  • if n < 0
    • WaitKey pauses until a keypress or GUI buttom pressed and then returns control to the calling script/function
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.

RESOURCES


Comments