Ask Your Question
0

Change color detection from RGB to HSV

asked 2013-05-23 00:56:18 -0500

colol gravatar image

updated 2013-05-23 01:17:16 -0500

Abid Rahman K gravatar image

Hello, I have create a color detection using RGB, but I would like to change it to HSV instead. This is the code:

IplImage *src=cvLoadImage("D:\\Pattern_for_Project\\1.png",1);
IplImage *copy=cvCreateImage( cvGetSize(src), 8, 3 );

// create two scalar variables
CvScalar s,c; 

//In the 2D array of the img..count till the vertical pixel reaches the height of src
for(int i=0;i<(src->height);i++)
{

//In the 2D array of the img..count till horizontal pixel reaches the width of src
for(int j=0;j<(src->width);j++)
{

//Get the RGB values of src's i,j into a scalar s
s=cvGet2D(src,i,j);



// if RGB values (in the order as in code) are satisfying threshold condition ie. RED<50 & GREEN>100 & BLUE<100
if((s.val[2]<50)&&(s.val[1]<100)&&(s.val[0]>100)) // blue

//Remember s.val[2],s.val[1],s.val[0] are RGB correspondingly
{ 

//ie. if the pixel is predominantly Green
// here you color the detection part in the image, red green or blue
c.val[2]=0;//Set R to 0
c.val[1]=0;//Set G to 255
c.val[0]=255;//Set B to 0

//Change the pixel value of copy img to pure green(G=255 R=0 B=0)
cvSet2D(copy,i,j,c); 
}

else if((s.val[2]<50)&&(s.val[1]>100)&&(s.val[0]<100)) //green

//Remember s.val[2],s.val[1],s.val[0] are RGB correspondingly
{ 

//ie. if the pixel is predominantly Green
// here you color the detection part in the image, red green or blue
c.val[2]=0;//Set R to 0
c.val[1]=255;//Set G to 255
c.val[0]=0;//Set B to 0

//Change the pixel value of copy img to pure green(G=255 R=0 B=0)
cvSet2D(copy,i,j,c); 
}

else if((s.val[2]>100)&&(s.val[1]<50)&&(s.val[0]<100)) //red

//Remember s.val[2],s.val[1],s.val[0] are RGB correspondingly
{ 

//ie. if the pixel is predominantly Green
// here you color the detection part in the image, red green or blue
c.val[2]=255;//Set R to 0
c.val[1]=0;//Set G to 255
c.val[0]=0;//Set B to 0

//Change the pixel value of copy img to pure green(G=255 R=0 B=0)
cvSet2D(copy,i,j,c); 
}


//Set all other pixels in copy to white
else 
{
c.val[2]=0; // Red
c.val[1]=0;// Green
c.val[0]=0;// Blue
 // Now set the scalar c(now white) to the pixel in i,j in copy

cvSet2D(copy,i,j,c);
}
}
}

Any idea on how to change this code from rgb to hsb? Please help me.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2013-05-23 01:20:52 -0500

Abid Rahman K gravatar image

You convert BGR image to HSV using cv::cvtColor() function.

Then apply cv::inRange() function to extract the color you want.

You can see how to track yellow color in this link : http://www.aishack.in/2010/07/tracking-colored-objects-in-opencv/

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

Stats

Asked: 2013-05-23 00:56:18 -0500

Seen: 4,678 times

Last updated: May 23 '13