OpenCV RGB Threshold Image

I have a color image that I want to threshold in OpenCV. What I would like if any of the RGB channels in accordance with a certain value to set the value in all channels to zero (i.e. black).

So, I am using the opencv threshold function as:

cv::Mat frame, thresholded // read frame somewhere, it is a BGR image. cv::threshold(frame, thresholded, 5, 255, cv::THRESH_BINARY); 

So, I thought that this would be done if any of the channels is less than 5, I thought he would set them to zero. However, this does not seem to work. For example, I see that for some of these regions only the green channel passes, indicating that not all channels are set to 0.

Is there a way to achieve this using OpenCV in fast mode?

+9
opencv
source share
2 answers

You can cv::inRange color image using the cv::inRange .

 void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst) 

For example, you can only allow values ​​between (0, 125, 0) and (255, 200, 255) or any values ​​for individual channels:

 cv::Mat image = cv::imread("bird.jpg"); if (image.empty()) { std::cout << "> This image is empty" << std::endl; return 1; } 

Original image

 cv::Mat output; cv::inRange(image, cv::Scalar(0, 125, 0), cv::Scalar(255, 200, 255), output); cv::imshow("output", output); 

Output image

+19
source share

In short, you need to draw an image on three images containing three channels, i.e. them separately, and then combine them again.

 Mat frame,thresholded; vector<Mat> splited_frame; //Read your frame split(frame, splited_frame); for (size_t i = 0; i < splited_frame.size(); i++) threshold(splited_frame[i], splited_frame[i], 5, 255, cv::THRESH_BINARY); merge(splited_frame,thresholded); 

This code should do this.

Sorry, I read to fast. Then you should change the code a bit after

 thresholded = splited_frame[0].clone(); for(size_t i = 1; i < splited_frame.size(); i++) thresholded &= splited_frame[i]; frame &= thresholded; 

You create a mask from three generated images, then apply this mask to your input image.

+1
source share

All Articles