#include <stdio.h>
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat src, dst;
src = imread("lena.jpg");
if (src.empty())
{
cout << "No Data!----------the error of reading image." << endl;
return -1;
}
// 将源图像分割成3个单通道的图像
vector<Mat> rgb_planes;
split(src, rgb_planes);
int histSize = 255; // 特征空间子区段bin的数目
float range[] = {0, 255}; // 特征空间的取值范围
const float* histRange = {range};
bool uniform = true;
bool accumulate = false;
// 计算直方图
Mat r_hist, g_hist, b_hist;
calcHist(&rgb_planes[0], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate);
calcHist(&rgb_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist(&rgb_planes[2], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate);
// 创建直方图画布
int hist_w = 400;
int hist_h = 400;
int bin_w = cvRound((double)hist_w / histSize);
Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(0, 0, 0));
// 将直方图归一化到[0, histImage.rows]
normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());
normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());
normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());
// 画直方图
for (int i = 1; i < histSize; i++)
{
line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(r_hist.at<float>(i-1))),
Point2f(bin_w * (i), hist_h - cvRound(r_hist.at<float>(i))),
Scalar( 0, 0, 255), 2, 8, 0 );
line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(g_hist.at<float>(i-1))),
Point2f(bin_w * (i), hist_h - cvRound(g_hist.at<float>(i))),
Scalar( 0, 255, 0), 2, 8, 0 );
line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(b_hist.at<float>(i-1))),
Point2f(bin_w * (i), hist_h - cvRound(b_hist.at<float>(i))),
Scalar( 255, 0, 0), 2, 8, 0 );
}
/// 显示直方图
namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );
waitKey(0);
return 0;
}
直方图
最新推荐文章于 2024-01-14 18:37:13 发布