Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To count number of colors you could find peaks in the histogram of HUE channel.

Because you have few colors, @strann has right solution: you could can simply check the histogram where the number of pixel count is non zero.

int CountColors(const Mat &img)
{
  Mat hsv,hue,hist;
  vector<Mat> hsv_planes;
  uchar rangeMin = 0;
  uchar rangeMax = 255;
  if (img.type() == CV_8UC1) hue = img;
  else if (img.type() == CV_8UC3)
  {
    cvtColor(img, hsv, CV_BGR2HSV);
    rangeMax = 360/2; //hue range is 0..180
    split(hsv, hsv_planes);
    hue= hsv_planes[0];
  }

    // Set the range for histogram
    float range[] = { 0, rangeMax};
    int histSize = rangeMax+1;
    const float* histRange = { range };
    bool uniform = true;
    bool accumulate = false;
    cv::calcHist(&hue, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, uniform, accumulate);
    int numOfColors = countNonZero(hist);
    return numOfColors ;
}