This blogs post introduces a computer vision skill. Let us know how to count objects in image using opencv computer vision library.

How to count objects in image using opencv

The above image is color image. It has 11 objects of different shapes. RGB ( red, green ,blue) is a mix color model to represent a single color. RGB color model refers to a system for representing the colors to be used on a computer display.

  • To find objects or shape in above image we will use contours.
  • Contours are a curve joining all the continuous point having same color. The contours feature in an image is used for shape analysis, object detection and recognition.
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

Mat src; Mat src_gray;
int thresh = 10;
int max_thresh = 170;

// Function header
void thresh_callback(int, void* );

int main( int, char** argv )
  /// Load source image and convert it to gray
  src = imread( argv[1], IMREAD_COLOR );

  /// Convert image to gray and blur it
  cvtColor( src, src_gray, COLOR_BGR2GRAY );
  blur( src_gray, src_gray, Size(3,3) );
  /// Create Window
  const char* source_window = "Source";
  namedWindow( source_window, WINDOW_AUTOSIZE );
  imshow( source_window, src );

  createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
  thresh_callback( 0, 0 );


void thresh_callback(int, void* )
  Mat canny_output;
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;

  /// Detect edges using canny
  Canny( src_gray, canny_output, thresh, thresh*2,3);
  /// Find contours
  findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(3, 3) );

  namedWindow( "Contours", WINDOW_AUTOSIZE );
  imshow( "Contours", canny_output );

  /// Calculate the area with the moments 00 and compare with the result of the OpenCV function
  printf("number of objects in image are \n");

compile using following command

g++ sample.cpp -o sample `pkg-config --cflags --libs opencv`


$ ./sample /imagepath


The output gives us 22 objects however image has only 11 shapes/objects. It is because of canny edge detector. canny edge detectors detects the edges but it is not continuous. look at the output each detected objects has two edges. so total objects count is 22.

I am working on it to optimize so that it will give exact objects count.


Related Contents to follow