3

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?

Danaro
  • 61
  • 1
  • 2
  • 11
  • can you see your source image properly? or a black window? – K.M. Shihab Uddin Jun 28 '16 at 16:54
  • Thank you for replying, I see the source image properly. – Danaro Jun 28 '16 at 17:20
  • you forgot to convert to hsv the `src` image ;D Also, in OpenCV uses BGR, not RGB, so you are thresholding the blue channel. So, in BGR your thresholds should be something like: `inRange(src, Scalar(0, 0, 0), Scalar(50, 50, 255), threshold);` Better use HSV color space, see the duplicate – Miki Jun 28 '16 at 17:44
  • Possible duplicate of [OpenCV better detection of red color?](http://stackoverflow.com/questions/32522989/opencv-better-detection-of-red-color) – Miki Jun 28 '16 at 17:44
  • Thank you for replying, I tried using the suggestion in the liked you supplied, but, it also filters and shows many other captured objects which are originally not red, is there any way to make the filtering more accurate? btw, why can't I use: inRange(src, Scalar(0, 0, 0), Scalar(0, 0, 255), threshold);? – Danaro Jun 29 '16 at 08:18
  • @Miki opencv c++ Scalar are in HSV or in BGR format? – user924 Mar 16 '18 at 08:31
  • @user scalars are just numbers – Miki Mar 16 '18 at 08:43

1 Answers1

2

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.

Ayad B.S
  • 61
  • 2
  • 7