Ask Your Question
1

Detect a pixel with a specific color (OpenCV/C++)

asked 2015-03-08 12:53:37 -0600

jefferson-sep gravatar image

Hi, I'm trying to detect and map all pixels of a certain color. Then leave the pixels of that color. I have this image: image description

And I need to find the pixels orange (255,127,39). Then leave only the pixels of orange, like this: image description

I know the OpenCV has this function:

cv::findNonZero(src, vector_white_pixels);

but do not know if there is a similar function to specify color with pixels

Thanks for any help.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
4

answered 2015-03-08 14:03:46 -0600

theodore gravatar image

updated 2015-03-08 14:06:37 -0600

the function that you are looking for is the inRange(), for example:

Mat mask;
// specify the range of colours that you want to include, you can play with the borders here
cv::Scalar lowerb = cv::Scalar(255,127,39);
cv::Scalar upperb = cv::Scalar(255,127,39); 

cv::inRange(frame, lowerb, upperb, mask); // if the frame has any orange pixel, this will be painted in the mask as white

imshow("mask", mask); // show where orange pixels are located, then use this mask for further processing pass it for example to findNonZero() function in order to obtain the location of the pixels, etc...
edit flag offensive delete link more

Comments

Thanks again Theodore! I'm using the follow code with image in example, but the output is just a black image. There's something wrong?

  Mat source = imread("chessOrange.png",1);
imshow("source", source);
Mat mask;
cv::Scalar lowerb = cv::Scalar(250, 125, 38);
cv::Scalar upperb = cv::Scalar(255, 129, 42);
cv::inRange(source, lowerb, upperb, mask);

imshow("mask", mask);
jefferson-sep gravatar imagejefferson-sep ( 2015-03-08 18:00:00 -0600 )edit

yes your Scalar values are not correct. In opencv the formation is BGR and not RGB. So, your lower and upper limits should be Scalar(38, 125, 250) and Scalar(42, 129, 255) respectively.

theodore gravatar imagetheodore ( 2015-03-08 18:11:03 -0600 )edit

Oh, that explains why I could only detect white or black -- ' Thanks

jefferson-sep gravatar imagejefferson-sep ( 2015-03-08 18:34:34 -0600 )edit
1

Let me comment that using inrange values on BGR image color channels is highly dependant on the avaible lighting conditions. It will miserably from the moment some sunlight or other lightsource comes into play :)

StevenPuttemans gravatar imageStevenPuttemans ( 2015-03-09 07:41:57 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2015-03-08 12:53:37 -0600

Seen: 20,859 times

Last updated: Mar 08 '15