从HSV直方图获得主色值

时间:2013-12-13 13:24:49

标签: c++ image opencv histogram hsv

我正在从下面的图片中创建一个hsv直方图。

- (void)processImageWithHsv:(Mat&)image;
{
    Mat image_hsv;

    cvtColor(image, image_hsv, CV_BGR2HSV);

    int hbins = 50, sbins = 60;
    int histSize[] = {hbins, sbins};

    float hranges[] = { 0, 360 };
    float sranges[] = { 0, 256 };

    const float* ranges[] = { hranges, sranges };
    MatND hist;

    int channels[] = {0, 1};

    calcHist( &image_hsv, 1, channels, Mat(), // do not use mask
             hist, 2, histSize, ranges,
             true, // the histogram is uniform
             false );

    double maxVal = 0;
    minMaxLoc(hist, 0, &maxVal, 0, 0);

    // ???: HOW Convert this information to colour value

}

但我不知道从hist获得最主要的颜色值? 我应该使用maxVal吗?

2 个答案:

答案 0 :(得分:1)

你犯了一些错误:

  1. 您正在寻找支配颜色value但您告诉calcHist使用色调和饱和度。你应该改变频道。
  2. 你的hranges错了:它应该是180。
  3. dims应为1(不是2),因为您只需要value直方图。
  4. 在这些更正后maxVal应包含最常见的value值。

答案 1 :(得分:0)

- (void)processImageWithHsv:(Mat&)image;
{
    Mat image_hsv;

    cvtColor(image, image_hsv, CV_BGR2HSV);

    // Quanta Ratio
    int scale = 10;

    int hbins = 36, sbins = 25, vbins = 25;
    int histSize[] = {hbins, sbins, vbins};

    float hranges[] = { 0, 180 };
    float sranges[] = { 0, 256 };
    float vranges[] = { 0, 256 };

    const float* ranges[] = { hranges, sranges, vranges };
    MatND hist;

    int channels[] = {0, 1, 2};

    calcHist( &image_hsv, 1, channels, Mat(), // do not use mask
             hist, 3, histSize, ranges,
             true, // the histogram is uniform
             false );

    int maxVal = 0;

    int hue = 0; 
    int saturation = 0; 
    int value = 0; 

    for( int h = 0; h < hbins; h++ )
        for( int s = 0; s < sbins; s++ )
             for( int v = 0; v < vbins; v++ )
                {
                      int binVal = hist.at<int>(h, s, v);
                      if(binVal > maxVal)
                      {
                          maxVal = binVal;

                          hue = h;
                          saturation = s;
                          value = v;
                      }
                }

    hue = hue * scale; // angle 0 - 360
    saturation = saturation * scale; // 0 - 255
    value = value * scale; // 0 - 255
}