# Trying to detect the color red in opencv c++

**URL:** <https://forum.opencv.org/t/trying-to-detect-the-color-red-in-opencv-c/24299>\
**Category:** C++\
**Tags:** programming\
**Created:** [January 6, 2026, 2:04pm UTC](https://forum.opencv.org/t/trying-to-detect-the-color-red-in-opencv-c/24299 "2026-01-06T14:04:14Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![d22](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/d22/32/13302_2.png) [@d22](https://forum.opencv.org/u/d22)\
**Post date:** [January 6, 2026, 2:04pm UTC](https://forum.opencv.org/t/trying-to-detect-the-color-red-in-opencv-c/24299/1 "2026-01-06T14:04:14Z")

</div>

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();

}
