Steph
Steph

Reputation: 639

Detect only RGB blue in image using OpenCV

I am trying to detect the 3 circles of blue color on the image below, using C++ and openCV.

enter image description here

I use this code

int main(){
     Mat original=imread("img.jpg");
     Mat hsv;
     cvtColor(original,hsv,CV_BGR2HSV);
     Mat bw;
     inRange(hsv,Scalar(110,50,50),Scalar(130,255,255),bw);//detects blue
}

This code does detect the 3 blue circles BUT also detect other blue points. I am thinking it has to do with the range I specified. Is there a way to detect only those RGB blue circles because I do not think there are any other points which are RGB blue in the image. How can I detect only this color (255,0,0)??

Upvotes: 1

Views: 12345

Answers (2)

Haris
Haris

Reputation: 14053

For the image you provided above, the below thresholds will work fine.

Scalar hsv_l(110,150,150); 
Scalar hsv_h(130,255,255); 
cvtColor(original,hsv,CV_BGR2HSV);
inRange(hsv,hsv_l,hsv_h,bw) 

And you can easily find the HSV value of any pixel using mouse as described here.

Also the HSV color wheel (below) might be helpful to choose any color and get it's HSV value.

HSV Colour wheel

Upvotes: 3

Chris
Chris

Reputation: 8170

If you want to detect the colour represented by (255,0,0) then this is the value you should specify when using the inRange function. Also, if you are interested in the RGB colour, then you don't need to convert your image to hsv.

Note that the relevant page in the OpenCV docs says that the upper and lower bounds in the inRange function are inclusive - you can use the same value for both.

Some minor modifications:

int main()
{
    // Paint a blue square in image
    cv::Mat img = cv::Mat::zeros(100,100,CV_8UC3);
    cv::Scalar blue(255,0,0);

    img(cv::Rect(20,20,50,50)) = blue;
    cv::imshow("Original Image", img);


    // Detect this blue square
    cv::Mat img2;
    cv::inRange(img, blue, blue, img2);
    cv::imshow("Specific Colour", img2);

    cv::imwrite("Input.png",img);
    cv::imwrite("Output.png",img2);
    cv::waitKey(0);

    return 0;
}

Input.png A blue square drawn in an image

Input.png

Output.png The blue square has been detected in this binary image

Output.png

Upvotes: 2

Related Questions