Single color detection using OpenCV

After a few days of learning OpenCV, I started to write my first OpenCV program, the requirement is to detect single color and find three largest color objects, it’s a very basic program, but you can know a lot about computer vision if you understand the code. OpenCV provide so many functions, you have to know what you want and what the function does.

This program still run on the Raspberry Pi, frame per second is about 8.5, if you want to find more or less than 3 biggest objects, you can change N. Here is code(You also can get it in my Github) sg_color.c:

#include <stdio.h>
#include <time.h>

#include "cv.h"
#include "highgui.h"

#define N 3  

IplImage* Threshold(IplImage* imgThresh,IplImage* imgHSV)
{         
       cvInRangeS(imgHSV, cvScalar(160,175,75,0), cvScalar(180,255,255,0), imgThresh); 
       cvDilate(imgThresh,imgThresh,NULL,1);
       cvErode(imgThresh,imgThresh,NULL,1);   
       return imgThresh;
} 
 
int main()
{    
	  time_t start,end;
	 ////// Variables /////////////////////////////////////////////////////
	  CvMemStorage *storage = cvCreateMemStorage(0);    
      CvSeq *contours[N], *tmp_cont, *contour;
      IplImage *frame, *imgHSV, *imgThresh;  
      CvCapture *capture; 
      int area, tmp_area, i, j, k,m;
    ///////////////////////////////////////////////////////////////////////                     
        
      cvNamedWindow("Original",1);   
      cvNamedWindow("Result",1);
      
      imgHSV = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U,3);     
      imgThresh = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U,1); 
       
      capture = cvCaptureFromCAM(0);        
      cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH,320);
	  cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT,240);

      if(!capture){
            printf("Capture failure\n");
            return -1;
      }
      
      time(&start);
      int counter=0;
          
      while(1){     
		      
            frame = cvQueryFrame(capture);         
            if(!frame) break;  
                            
            cvCvtColor(frame, imgHSV, CV_BGR2HSV);  
            
            imgThresh = Threshold(imgThresh,imgHSV);
            
            cvShowImage("Result", imgThresh);   
                         
            cvFindContours(imgThresh, storage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0)); 
             
            int cnt = 0; 
            int maxArea[N]={0}; 
            
            for(;contour != 0;contour = contour->h_next)   
            {    
              
              area = fabs(cvContourArea(contour, CV_WHOLE_SEQ,1 ));
              
              if(area<100 || area>50000)
              {
				  cvSeqRemove(contour,0);
				  continue;
			  }          
             
              cnt++;
              
              for(i = N-1; i >= 0; --i)
              {
                if(area > maxArea[i])
                {
                  maxArea[i] = area;
                  contours[i] = contour;
                  for(m = (i-1); m >= 0; --m)
                   {
                     if(maxArea[m] < maxArea[m+1])
                      {
                        tmp_area = maxArea[m+1];
                        tmp_cont = contours[m+1];
                        maxArea[m+1] = maxArea[m];
                        contours[m+1] = contours[m];
                        maxArea[m] = tmp_area;
                        contours[m] = tmp_cont;
                      }
                    }
                  break;
                }
              }          
            }                                          
    
            if(cnt != 0)
            {	
		        CvRect rect = ((CvContour*)contours[0])->rect;
		        cvRectangle(frame, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height),CV_RGB(0, 255, 0), 2, 8, 0);
		        printf("(%d , %d) (%d , %d)\n", rect.x,rect.y,rect.x + rect.width,rect.y + rect.height);
	        }	      
                                         
            time(&end);
            ++counter;
            double sec=difftime(end,start);
            double fps=counter/sec;
            printf("FPS = %.2f\n\n",fps);                          
            
            cvShowImage("Original", frame);
            
            if ( (cvWaitKey(10) & 255) == 27 ) break; 
      }
      
      cvReleaseImage(&imgHSV);
      cvReleaseImage(&imgThresh); 
      cvReleaseMemStorage(&storage); 
      cvDestroyAllWindows() ;
      cvReleaseCapture(&capture);     

      return 0;
}

Here is makefile:

LIBS= `pkg-config --libs opencv`
CFLAGS= `pkg-config --cflags opencv`
objects= sg_color.o

sg_color: $(objects) 
	gcc $(LIBS)$(CFLAGS) -o sg_color $(objects)

.PHONY: clean
clean:
	rm sg_color $(objects)

Here is processed frame and threshold image:
frame

Threshold

3 thoughts on “Single color detection using OpenCV

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s