I am trying to learn to detect the color red in opencv in c++. and i am struggling with the code a bit can someone help me? the code is below: #include
#include “opencv2/objdetect.hpp”
#include “opencv2/highgui.hpp”
#include “opencv2/imgproc.hpp”
#include “opencv2/videoio.hpp”
#include <opencv2/imgcodecs.hpp>
#include
#include
#include <opencv2/core.hpp>
using namespace cv;
using namespace std;
char s = ‘s’;
int min_blue = (110,50,50);
int max_blue= (130,255,255);
int min_red = (0,150,127);
int max_red = (178,255,255);
Mat img;
int main(){
String path = samples::findFile(“/home/d22/opencv_contrib-4.x/samples/data/redtest1.jpg”); // img to read
img = imread(path,IMREAD_COLOR); // reading img
if(img.empty())
{
cout << "Could not read the image: " << img << endl;
return 1;
}
Mat background;
Mat mask, imghsv;
cvtColor(img,imghsv,COLOR_BGR2HSV);
inRange(imghsv,Scalar(min_red),Scalar(max_red),mask);
vector < vector < Point>> contours;
vector redbox(contours.size());
Mat canny_out;
Canny(img,canny_out,100,100);
findContours(mask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
// Draw contours and labels
for (size_t i = 0; i < contours.size(); i++) {
if (contourArea(contours[i]) > 500) {
redbox[i] = boundingRect(contours[i]);
rectangle(img, redbox[i].tl(), redbox[i].br(),Scalar(0, 0, 255), 2);
// putText(img, "Red", redbox.tl(), cv::FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2);
cout << "Red_contours values " << contours.size() << endl;
}
}
imshow(“mask”,img);
waitKey(0);
destroyAllWindows();
}