Detecting the Toy Car with OpenCV

OpenCV is a wonderful library with a lot of options on image processing. The simplest way to detect an object is by color. Color range can be in RGB/HSV/YUV. Algorithms for filtering work well with HSV.


  1. Find lower and upper ranges of HSV values
  2. Filter using color and find mask-color
  3. Optional: Filter using backgroundSubtractorMog2-> mask object movement AND both the masks
  4. Use erode, dilate and threshold to remove any noise
  5. Find contours. Assume that whatever contour we have are part of moving car, combine all points
  6. Find Centre of mass using moments
 Here is the sample code for finding the HSV Ranges from an image

void readPixels(final Mat imageHSV) {
        for (int i = 0; i < imageHSV.rows(); i++)
            for (int j = 0; j < imageHSV.cols(); j++) {
                double pixel[] = imageHSV.get(i, j);

                for (int k = 0; k < pixel.length; k++)
                    System.out.print(pixel[k] + "\t");
                System.out.println();
            }
    }

I have used GIMP to extract the car
This is converted to HSV and output from readPixels were copied to OpenOffice Calc (excel) to get the value ranges

final Scalar carColorThresholdHSVLow = new Scalar(90, 20, 180);
final Scalar carColorThresholdHSVHigh = new Scalar(102, 115, 255);


The output from Detection.

Source can be found here.