Posts tagged ‘pixel’

Threshold an Image using OpenCV

The cvThreshold function allows us to reject pixels above or below a set value while keeping the others. In this example the input image is separated into the RGB channels. Then we preform a threshold on the red channel, with a maximum value of 100. The result of this is that all the light areas of the image are removed.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

int _tmain(int argc, _TCHAR* argv[])
{
	// open and display input image  
    IplImage* input = cvLoadImage("test.jpg");  
    cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);  
    cvShowImage("Input", input); 

	// create the output images
	IplImage* channel_r = cvCreateImage(cvSize(input->width, input->height), input->depth, 1);
	IplImage* channel_g = cvCreateImage(cvSize(input->width, input->height), input->depth, 1);
	IplImage* channel_b = cvCreateImage(cvSize(input->width, input->height), input->depth, 1);

	// split the image
	cvSplit(input, channel_r, channel_g, channel_b, NULL);
	
	// display image
	cvNamedWindow("Channel R", CV_WINDOW_AUTOSIZE);
	cvShowImage("Channel R", channel_r);
	cvSaveImage("channel_r.png", channel_r);

	// threshold red channel
	IplImage* output = cvCreateImage(cvSize(channel_r->width, channel_r->height), channel_r->depth, 1);
	cvThreshold(channel_r, output, 100,100, CV_THRESH_TRUNC);

	// display the output image
	cvNamedWindow("Output", CV_WINDOW_AUTOSIZE);
	cvShowImage("Output", output);
	cvSaveImage("output.png", output);

	// wait for user
	cvWaitKey(0);

	// garbage collection	
	cvReleaseImage(&input);
	cvDestroyWindow("Input");
	cvReleaseImage(&channel_r);
	cvDestroyWindow("Channel R");
	cvReleaseImage(&output);
	cvDestroyWindow("Output");
	return 0;
}

Input Image


The red channel, before threshold

The red channel, after threshold

Flood Fill using OpenCV

To use the flood fill, first a seed point is selected, then all neighbouring pixels of a similar colour are converted to a uniform colour. In this example the seed point is at 200, 200 (shown by a blue circle). The neighbouring pixels are then flood filled with a red colour.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

int _tmain(int argc, _TCHAR* argv[])
{
	// load the input image
	IplImage* img = cvLoadImage("test.jpg");

	// define the seed point
	CvPoint seedPoint = cvPoint(200,200);

	// flood fill with red
	cvFloodFill(img, seedPoint, CV_RGB(255,0,0), CV_RGB(8,90,60), CV_RGB(10,100,70),NULL,4,NULL);
	
	// draw a blue circle at the seed point
	cvCircle(img, seedPoint, 3, CV_RGB(0,0,255), 3, 8);

	// show the output
	cvNamedWindow("Output", CV_WINDOW_AUTOSIZE);  
    cvShowImage("Output", img); 

	// wait for user
	cvWaitKey(0);

	// save image
	cvSaveImage("output.jpg",img);

	// garbage collection		
	cvReleaseImage(&img);
	cvDestroyWindow("Output");
	return 0;
}

Input image

The flood filled output image