how to detect contours for two or more than two specific colors ?
Hello, I want to detect contours for two colors simultaneously, here in code there is one contour for one color is detected but i want the same for second color. Please guide me.
int main ()
{
//cvNamedWindow( "RGB", 1 );
cvNamedWindow( "HSV", 1 );
//cvNamedWindow( "Binary", 1 );
cvNamedWindow( "LargestContour", 1 );
cvNamedWindow( "Final", 1 );
Mat img,hsv,binary;
img = imread("C:\\Users\\ankit\\Downloads\\wallpaper\\p.png"); //change this path according to your image file path
// imshow("RGB",img);
//convert RGB image into HSV image
cvtColor(img, hsv, CV_BGR2HSV);
imshow("HSV",hsv);
//get binary image
inRange(hsv, Scalar(0, 255, 255), Scalar(179, 255, 255), binary);
// imshow("Binary",binary);
//find contours from binary image
int i;
vector< vector<Point> > contours;
findContours(binary, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); //find contours
vector<double> areas(contours.size());
//find largest contour area
for(i = 0; i < contours.size(); i++)
{
areas[i] = contourArea(Mat(contours[i]));
}
//get index of largest contour
double max;
Point maxPosition;
minMaxLoc(Mat(areas),0,&max,0,&maxPosition);
//draw largest contour.
drawContours(binary, contours, maxPosition.y, Scalar(255), CV_FILLED);
imshow("LargestContour",binary);
//draw bounding rectangle around largest contour
Point center;
Rect r;
if (contours.size() >= 1)
{
r = boundingRect(contours[maxPosition.y]);
rectangle(img, r.tl(),r.br(), CV_RGB(255, 0, 0), 3, 8, 0); //draw rectangle
}
//get centroid
center.x = r.x + (r.width/2);
center.y= r.y + (r.height/2);
//print x and y co-ordinates on image
char x[15],y[6];
itoa(center.x,x,10);
itoa(center.y,y,10);
strcat(x,",");
putText(img, strcat(x,y), center, FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(255,0,0), 1, CV_AA);
imshow("Final",img);
//wait for key press
cvWaitKey();
return 0;
}
Thank you very much in advance.
just use the inRange() function again with the second color...
Thank you very much for comment. I have already tried with it, but its not working fine. its give error Native' has exited with code 0 (0x0).
can you write the inRange() command that you tried and gave this error.
inRange(hsv, Scalar(115, 0, 0), Scalar(156, 256, 256), binary); inRange(hsv, Scalar(171, 0, 0), Scalar(256, 256, 256), binary); imshow("Binary",binary);
like this i tried to give command. it not working as its show me only one color detection.
@Akki you cannot have
256
value the maximum value you can use is255
thank you for comment. I change it 256 to 255, but still its take only first inRange() function and show contour only for it. not for both.
it work fine with adding two frame for different color and then draw contour for that frame. :)