Question

How do I detect one color without using Trackbar (identify one color range)? I'm trying to get all colored object within that range and I'm using Qt and openCV.

I've attached this code using trackbar:

  CvSeq* find_contour = NULL;
  bool isStop = false;
  img = cvLoadImage(QFileDialog::getOpenFileName(this, "Ouvrir un fichier", "/../../Fichiers Image", "Image (*.jpg *.bmp *.jpeg)").toStdString().c_str(),3);
  if(img == NULL)
  {
    printf("capture device not found!!");

  }


  Allocate_imgs();

  // creat windows
  cvNamedWindow("Capture", CV_WINDOW_AUTOSIZE);
  cvNamedWindow("Result", CV_WINDOW_AUTOSIZE);


  // To in_rang_filter() MIN , MAX RGB value set
  cvCreateTrackbar( "minR","Result",&mR_val, 256,set_RGB);
  cvCreateTrackbar( "minG","Result",&mG_val, 256,set_RGB);
  cvCreateTrackbar( "minB","Result",&mB_val, 256,set_RGB);

  cvCreateTrackbar( "maxR","Result",&MAR_val, 256,set_RGB);
  cvCreateTrackbar( "maxG","Result",&MAG_val, 256,set_RGB);
  cvCreateTrackbar( "maxB","Result",&MAB_val, 256,set_RGB);
  //


  cvCvtColor( img, imgHsv, CV_BGR2HSV);//convert the color space
  in_rang_filter();


  cvShowImage("Capture", img);
  cvShowImage("Result", test);
  cvWaitKey(0);
  cvReleaseImage(&imgResult);
  cvReleaseImage(&imgHsv);
  cvDestroyAllWindows();

}


void in_rang_filter()
{
  IplImage* test=cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);
  CvScalar min_color = CV_RGB(mR_val,mG_val,mB_val);
  CvScalar max_color = CV_RGB(MAR_val,MAG_val,MAB_val);
  cvInRangeS(imgHsv, min_color,max_color, imgResult);//search for the color in image

  cvCvtColor( imgResult, test,CV_GRAY2RGB);
  cvShowImage("Result", test);
  cvReleaseImage(&test);
}

void Allocate_imgs()
{
  const int w = img->width;
  const int h = img->height;
  imgResult = cvCreateImage(cvSize(w, h), IPL_DEPTH_8U,1);
  imgHsv=cvCreateImage(cvSize(w, h), IPL_DEPTH_8U, 3);
Was it helpful?

Solution

1) convert image to HSV color space using cvCvtColor function.

2) Split HSV plane to seperate H,S,V planes.

3) Next you need H,S,V values for your color, i mean, a range of values in that color range.

4) Now use cvInrangeS function to extract that color only. It will become white and all other colors become black.

Now if you want code for detecting yellow color only, try this tutorial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top