OpenCV inRange() function

Danaro picture Danaro · Jun 28, 2016 · Viewed 21k times · Source

I try to run the following code:

#include<opencv\cv.h>
#include<opencv\highgui.h>

using namespace cv;


int main() {

    VideoCapture cap;
    cap.open(0);


    while (1) {

Mat src;
Mat threshold;

cap.read(src);

inRange(src, Scalar(0, 0, 0), Scalar(255, 0, 0), threshold);
imshow("thr", threshold);
imshow("hsv", src);

        waitKey(33);
    }
    return 0;
}

But it seems like it doesn't filter because there is only a blank window appearing when I run the code.

How to get that code to detect red colors?

Answer

Ayad B.S picture Ayad B.S · Jun 29, 2017

You have to modify inRange function like this:

inRange(src, Scalar(0, 0, 0), Scalar(255, 255, 255), threshold);

If you try to threshold just the first channel (the blue channel), then you have to make other channels free, so set it to 0 in lawerb and its dtype, usually 255 for np.uint8

E.g.

inRange(src, Scalar(0, 50, 0), Scalar(255, 100, 255), threshold);

this line will compare the 2nd channel (the green channel) and ignore others.