OpenCV中分析绘制直方图并没有直接可用的函数,以下是绘制直方图统计的一种实现。
paint_histogram.h:
#ifndef OPENVCV_H
#define OPENVCV_H
#include <opencv2/opencv.hpp>
class Histogram1D
{
public:
Histogram1D();
~Histogram1D();
cv::Mat GetHistogram(const cv::Mat& image);
cv::Mat GetHistogramImage(const cv::Mat& image, int zoom = 1);
cv::Mat GetImageOfHistogram(const cv::Mat& hist, int zoom);
private:
int histSize[1];
float hranges[2];
const float* ranges[1];
int channels[1];
};
#endif
paint_histogram.cpp如下所示:
#include "paint_histogram.h"
using namespace cv;
using namespace std;
Histogram1D::Histogram1D()
{
histSize[0] = 256;
hranges[0] = 0.0;
hranges[1] = 256.0;
ranges[0] = hranges;
channels[0] = 0;
}
Histogram1D::~Histogram1D()
{
}
Mat
Histogram1D::GetHistogram(const Mat& image)
{
Mat hist;
calcHist(&image, 1, channels, Mat(), hist, 1, histSize, ranges);
return hist;
}
Mat
Histogram1D::GetHistogramImage(const cv::Mat& image, int zoom)
{
Mat hist = GetHistogram(image);
return GetImageOfHistogram(hist, zoom);
}
Mat
Histogram1D::GetImageOfHistogram(const cv::Mat& hist, int zoom)
{
double maxVal = 0;
double minVal = 0;
minMaxLoc(hist, &minVal, &maxVal, 0, 0);
int histSize = hist.rows;
Mat histImg(histSize * zoom, histSize * zoom, CV_8U, Scalar(255));
int hpt = static_cast<int>(0.9 * histSize);
for (int h = 0; h < histSize; ++h) {
float binVal = hist.at<float>(h);
if (binVal > 0) {
int intensity = static_cast<int>(binVal * hpt / maxVal);
line(histImg, Point(h * zoom, histSize * zoom), Point(h * zoom, (histSize - intensity) * zoom), Scalar(0), zoom);
}
}
return histImg;
}
main函数调用如下:
#include "paint_histogram.h"
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("flower.png", IMREAD_GRAYSCALE);
Histogram1D h;
namedWindow("Histogram");
imshow("Histogram", h.GetHistogramImage(src));
waitKey(0);
return 0;
}
执行结果如下:
image.png
内容来自于书籍。
网友评论