opencv:绘制图像直方图

Posted wbyixx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv:绘制图像直方图相关的知识,希望对你有一定的参考价值。

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    Mat src = imread("f:/images/butterfly.jpg");
    if (src.empty())
    {
        printf("Could not find the image!
");
        return -1;
    }

    namedWindow("input", WINDOW_AUTOSIZE);
    imshow("input", src);
    
    vector<Mat> mv;
    split(src, mv);

    // 计算直方图
    int histSize = 256;
    float range[] = { 0, 255 };
    const float* histRanges = { range };
    Mat b_hist, g_hist, r_hist;
    calcHist(&mv[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRanges, true, false);
    calcHist(&mv[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRanges, true, false);
    calcHist(&mv[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRanges, true, false);

    Mat result = Mat::zeros(Size(600, 400), CV_8UC3);
    int margin = 50;
    int maxValue = result.rows - 2 * margin;
    // 归一化
    normalize(b_hist, b_hist, 0, maxValue, NORM_MINMAX, -1, Mat());
    normalize(g_hist, g_hist, 0, maxValue, NORM_MINMAX, -1, Mat());
    normalize(r_hist, r_hist, 0, maxValue, NORM_MINMAX, -1, Mat());

    float step = 500.0 / 256.0;
    // 绘制直方图
    for (int i = 0; i < 255; i++) {
        float bh1 = b_hist.at<float>(i, 0);
        float gh1 = g_hist.at<float>(i, 0);
        float rh1 = r_hist.at<float>(i, 0);

        float bh2 = b_hist.at<float>(i + 1, 0);
        float gh2 = g_hist.at<float>(i + 1, 0);
        float rh2 = r_hist.at<float>(i + 1, 0);

        line(result, 
            Point(step * i + margin, maxValue + 50 - bh1),
            Point(step * (i + 1) + margin, maxValue + 50 - bh2),
            Scalar(255, 0, 0), 1, 8, 0);
        line(result, 
            Point(step * i + margin, maxValue + 50 - gh1),
            Point(step * (i + 1) + margin, maxValue + 50 - gh2),
            Scalar(0, 255, 0), 1, 8, 0);
        line(result, 
            Point(step * i + margin, maxValue + 50 - rh1),
            Point(step * (i + 1) + margin, maxValue + 50 - rh2),
            Scalar(0, 0, 255), 1, 8, 0);
    }

    imshow("result", result);

    waitKey(0);
    destroyAllWindows();
}

以上是关于opencv:绘制图像直方图的主要内容,如果未能解决你的问题,请参考以下文章

利用OpenCV的函数calcHist()计算出图像的直方图数据后绘制图像的直方图

利用OpenCV的函数calcHist()计算出图像的直方图数据后绘制图像的直方图

OpenCV学习笔记13-图像直方图的介绍及代码实现

opencv —— calcHistminMaxLoc 计算并绘制图像直方图寻找图像全局最大最小值

python opencv实现绘制图像的灰度直方图

如何在OpenCV中绘制图像的3D直方图