OpenCV Examples Part 1

Nov 4, 2008 | Tags: OpenCV | del.icio.us del.icio.us | digg Digg

2. Load an Image

Loading images probably the most frequently operation we do with OpenCV. The complete listing is shown in Listing 1 below. It loads an image and display it in a nice window.

Listing 1: loadimg.c

  1. #include <stdio.h>
  2. #include "cv.h"
  3. #include "highgui.h"
  4.  
  5. int main( int argc, char** argv )
  6. {
  7.     /* data structure for the image */
  8.     IplImage *img = 0;
  9.    
  10.     /* check for supplied argument */
  11.     if( argc < 2 ) {
  12.         fprintf( stderr, "Usage: loadimg <filename>\n" );
  13.         return 1;
  14.     }
  15.    
  16.     /* load the image,
  17.        use CV_LOAD_IMAGE_GRAYSCALE to load the image in grayscale */
  18.     img = cvLoadImage( argv[1], CV_LOAD_IMAGE_COLOR );
  19.    
  20.     /* always check */
  21.     if( img == 0 ) {
  22.         fprintf( stderr, "Cannot load file %s!\n", argv[1] );
  23.         return 1;
  24.     }
  25.    
  26.     /* create a window */
  27.     cvNamedWindow( "image", CV_WINDOW_AUTOSIZE );
  28.    
  29.     /* display the image */
  30.     cvShowImage( "image", img );
  31.    
  32.     /* wait until user press a key */
  33.     cvWaitKey(0);
  34.    
  35.     /* free memory */
  36.     cvDestroyWindow( "image" );
  37.     cvReleaseImage( &img );
  38.    
  39.     return 0;
  40. }

Remember to always include cv.h in your OpenCV programs. The listing above also included highgui.h to use OpenCV GUI functions for displaying the image.

To compile the code, type the lines below from your command line:

gcc loadimg.c -o loadimg
     -I"C:\OpenCV\cv\include"
     -I"C:\OpenCV\cxcore\include"
     -I"C:\OpenCV\otherlibs\highgui"
     -L"C:\OpenCV\lib" -lcxcore -lcv -lhighgui

Replace C:\OpenCV with your OpenCV base directory. To simplify the compilation, setup your text editor for the commands above or use Makefile. Run the program with:

loadimg rahma_sarita.jpg

It will load rahma_sarita.jpg and display it in a nice window shown below.

The displayed image
Fig 1. The displayed image