Thursday, May 7, 2009

OpenCV#5: Copy a portion from an image

1. set an ROI in the source image

cvSetImageROI( img_src, cvRect roi );

2. create a new image with the same size as the ROI

IplImage* img_dst = cvCreateImage( cvSize( roi.width, roi.height ), IPL_DEPTH_8U, 1 );

3. copy the portion from the source image to destination image

cvCopy( img_src, img_dst );

Wednesday, May 6, 2009

OpenCV#4: Remove small blobs from binary image


// Function to remove small blobs from the binary image
IplImage* remove_small_objects( IplImage* img_in, int size )
{
IplImage* img_out = cvCloneImage( img_in ); // return image
CvMemStorage* storage = cvCreateMemStorage( 0 ); // container of retrieved contours
CvSeq* contours = NULL;
CvScalar black = CV_RGB( 0, 0, 0 ); // black color
CvScalar white = CV_RGB( 255, 255, 255 ); // white color
double area;

// find contours in binary image
cvFindContours( img_in, storage, &contours, sizeof( CvContour ), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE );

while( contours ) // loop over all the contours
{
area = cvContourArea( contours, CV_WHOLE_SEQ );
if( fabs( area ) <= size ) // if the area of the contour is less than threshold remove it
{
// draws the contours into a new image
cvDrawContours( img_out, contours, black, black, -1, CV_FILLED, 8 ); // removes white dots
}
/* else
{
cvDrawContours( img_out, contours, white, white, -1, CV_FILLED, 8 ); // fills in holes
}*/
contours = contours->h_next; // jump to the next contour
}

cvReleaseMemStorage( &storage );
return img_out;
}

Tuesday, May 5, 2009

OpenCV #3: Converting an image to gray scale


int M = img_rgb->width;
int N = img_rgb->height;

// convert to gray scale
IplImage* img_gray = cvCreateImage( cvSize(M, N), IPL_DEPTH_8U, 1 );
cvCvtColor( img_rgb, img_gray, CV_BGR2GRAY );

Thursday, April 2, 2009

DIP using OpenCV #2 : Clearing an image


// clear the image

cvSet( IplImage* img, cvScalar(0,0));

// this will set each and every pixel to zero

Another simple method I recently became aware of:

cvZero( IplImage* img );

Wednesday, April 1, 2009

Image processing using OpenCV #1: Invert an image

Code to open an image and invert it using OpenCV:


img = cvLoadImage(argv[1]);

// get the image data
height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
data = (uchar *)img->imageData;

for( i=0;i<height;i++ )
{
for( j=0;j<width;j++ )
{
for( k=0;k<channels;k++ )
data[i*step+j*channels+k] = 255 - data[i*step+j*channels+k];
}
}

Followers