Load and Display Image With OpenCV 2.4

In this python exercise we do a very basic chore, retrive an image from a folder and display it in a window.

 Load and display an image using OpenCV2

 This module needs two arguments: imageName, imageFormat

 imageName must also include the path to the image file if the
 image file is not in the same directory as imgDisplay.py

 imageFormat is either 1 or 0 or -1
 1 for loading as RGB image (strips alfa component of RGBA file)
 0 for loading as grayscale image
 -1 for loading as is (includes alfa component of RGBA file)

 Supported file formats include bmp, png, tiff, jpeg, jpg and
 a bunch more. See "imread" in "OpenCV2 Reference Manual" for
 more info on supported files.

 Command line use:
 python imgDisplay.py /pathToFile/mypicture.jpg -1

 Author: Sameer Khan (samkhan13.wordpress.com)
 July 25th 2012
 No copyrights, warranty or guaranties are associated with this file.

## use cv2 package
import cv2

## define a function for loading and displaying an image
def imageDisplay(imageName, imageFormat):
 imageMatrix = cv2.imread(imageName, imageFormat)

 cv2.namedWindow('Display Window')
 cv2.imshow('Display Window',imageMatrix)

 cv2.waitKey(0) # wait indefinitely for a key press
 cv2.destroyWindow('Display Window') # any key press closes window

## for using imgDisplay.py from the command line
if __name__ == '__main__':
 import sys

 ## all arguments at the command line are a list of strings in sys.argv
 ## sys.argv[0] is the name of the file in use
 ## so there must be three values in sys.argv
 if len(sys.argv)!=3:
  print __doc__
  print "\nClick on the display window and press any key to close it.\n"

 imageName = sys.argv[1]
 imageFormat = int(sys.argv[2])

 imageDisplay(imageName, imageFormat)

## end of imgDisplay.py

One thought on “Load and Display Image With OpenCV 2.4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s