c++ - 在opencv中从HSV中查找颜色

标签 c++ opencv histogram image-recognition hsv

我需要使用 OpenCV 找到图像中最常出现的颜色。我提到了https://docs.opencv.org/2.4/modules/imgproc/doc/histograms.html?highlight=calchist当我运行该代码时,我得到的 H-S 直方图如下图所示。我如何从该直方图中分辨出最当前的颜色?有人可以告诉我如何使用 HSV 直方图获得图像中最当前的颜色吗? (我正在使用 C++)

this

最佳答案

据我所知(opencv 网站上的一个非常模糊的描述)这里我们在第一轴上有色相,在第二轴上有饱和度,颜色强度作为点亮度。 色调从 0(红色)到 180(从紫色到红色)不等。饱和度从 0 到 255(黑-灰-白)。色调从 180 量化到 30。饱和度从 255 量化到 32(根据您到 opencv 站点的链接)。直方图上的正方形区域越亮,图像上的某些色调和饱和度组合就越亮。 我在我的电脑上复制了 OpenCV 样本。我添加了源图像和 HS 直方图。在 HS 直方图上,我们可以看到一个明亮的矩形对应于中等饱和度的蓝色 enter image description here 我还添加了针对 OpenCV 3.4.0 修改的源代码

#include <Windows.h>
#include <Vfw.h>


#include "opencv2\core\core.hpp"
#include "opencv2\imgproc\imgproc.hpp"
#include "opencv2\imgcodecs\imgcodecs.hpp"
#include "opencv2\highgui\highgui.hpp"

using namespace cv;

int _tmain(int argc, _TCHAR* argv[])
{
    Mat src, hsv;

    src=imread("blue_circle.jpg");
    cvtColor(src, hsv, CV_BGR2HSV);

    // Quantize the hue to 30 levels
    // and the saturation to 32 levels
    int hbins = 30, sbins = 32;
    int histSize[] = {hbins, sbins};
    // hue varies from 0 to 179, see cvtColor
    float hranges[] = { 0, 180 };
    // saturation varies from 0 (black-gray-white) to
    // 255 (pure spectrum color)
    float sranges[] = { 0, 256 };
    const float* ranges[] = { hranges, sranges };
    MatND hist;
    // we compute the histogram from the 0-th and 1-st channels
    int channels[] = {0, 1};

    calcHist( &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);

    int scale = 10;
    Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);

    for( int h = 0; h < hbins; h++ )
        for( int s = 0; s < sbins; s++ )
        {
            float binVal = hist.at<float>(h, s);
            int intensity = cvRound(binVal*255/maxVal);
            rectangle( histImg, Point(h*scale, s*scale),
            Point( (h+1)*scale - 1, (s+1)*scale - 1),
            Scalar::all(intensity),
            CV_FILLED );
        }

        namedWindow( "Source", CV_WINDOW_FREERATIO );
        imshow( "Source", src );

        namedWindow( "H-S Histogram", CV_WINDOW_FREERATIO );
        imshow( "H-S Histogram", histImg );
        waitKey(0);
    return 0;
}

关于c++ - 在opencv中从HSV中查找颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283663/

相关文章:

c++ - C++ 中的 Unicode 处理

Opencv 矩阵值显示

python - Matplotlib 中的 bin 大小(直方图)

python - Matplotlib 直方图不显示分布细节

c++ - 如何在 C/C++ 中从运行时卸载内存偏移量计算?

c++ - 在 OpenMP 中每个线程执行一次代码,无需默认构造函数

c++ - 在 Mac OS X Lion 上使用 OpenMP 编译失败(memcpy 和 SSE 内在函数)

python - 如何使用 Python OpenCV 查找图像中的极端外部点

java - opencv库支持哪些android API?

python - 如何使用数据框中的特定行和列在 Panda Python 中创建直方图