Page 34 -
P. 34
8 Chapter 1 ■ Practical Aspects of a Vision System
First, add the needed include files, declare an image, and read it from a
file.
// Threshold a color image.
#include “stdafx.h“
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
int main (int argc, char* argv[])
{
IplImage *image = 0;
int i,j,k;
int mean=0, count=0;
char c;
image = cvLoadImage(“C:/AIPCV/marchA062.jpg“);
At this point, there should be image data pointed to by image.If so (if the
image is not null), display it in a window, as before.
if( image )
{
printf (“Height %d X with %d\n“, image->height, image->width);
cvNamedWindow( “mainWin“, CV_WINDOW_AUTOSIZE);
cvShowImage( “mainWin“, image );
printf (“Display of image is done.\n“);
cvWaitKey(0); // wait for a key
Now perform the thresholding operation. But this is a color image, so
convert it to grey first using the average of the three color components.
for (i=0; i<image->height; i++)
for (j=0; j<image->width; j++)
{
k=( (image->imageData+i*image->widthStep)[j*image->nChannels+0]
+(image->imageData+i*image->widthStep)[j*image->nChannels+1]
+(image->imageData+i*image->widthStep)[j*image->nChannels+2])/3;
(image->imageData+i*image->widthStep)[j*image->nChannels+0]
= (UCHAR) k;
(image->imageData+i*image->widthStep)[j*image->nChannels+1]
= (UCHAR) k;
(image->imageData+i*image->widthStep)[j*image->nChannels+2]
= (UCHAR) k;