// recognition.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <opencv2/opencv.hpp>
#define cvQueryHistValue_1D( hist, idx0 ) \
((float)cvGetReal1D( (hist)->bins, (idx0)))
using namespace cv;
using namespace std;
int main()
{
IplImage* src = cvLoadImage("3.jpg");
IplImage* gray_dst = cvCreateImage(cvGetSize(src), 8, 1);
cvCvtColor(src, gray_dst, CV_BGR2GRAY);
//一维维数
int dims = 1;
//直方图的尺寸
int size = 256;
//直方图的高度
int height = 256;
//灰度图的范围0到255
float range[] = { 0, 256 };
float *ranges[] = { range };
//创建一维直方图
CvHistogram* hist;
hist = cvCreateHist(dims, &size, CV_HIST_ARRAY, ranges, 1);
//计算灰度图的一维直方图
cvCalcHist(&gray_dst, hist, 0, 0);
//归一化直方图
cvNormalizeHist(hist, 1.0);
int scale = 2;
//创建图像,用于显示直方图
IplImage* hist_img = cvCreateImage(cvSize(size* scale, height), 8, 3);
//图像置零
cvZero(hist_img);
//计算直方图的最大方块值,初始化为0
float max_value = 0;
cvGetMinMaxHistValue(hist, 0, &max_value, 0, 0);
//绘制直方图
for (int i = 0; i < size; i++)
{
float bin_val = cvQueryHistValue_1D(hist, i); //像素i的概率
int intensity = cvRound(bin_val* height / max_value); // 绘制的高度
cvRectangle(hist_img,
cvPoint(i* scale, height - 1),
cvPoint((i + 1)* scale - 1, height - intensity),
CV_RGB(255, 255, 255));
}
cvNamedWindow("gray");
cvShowImage("gray", gray_dst);
cvNamedWindow("Histogram");
cvShowImage("Histogram", hist_img);
cvWaitKey(0);
cvReleaseImage(&src);
cvReleaseImage(&gray_dst);
cvReleaseImage(&hist_img);
cvDestroyWindow("gray");
cvDestroyWindow("Histogram");
}
参考:
https://blog.csdn.net/morewindows/article/details/8364690
https://blog.csdn.net/zhangfuliang123/article/details/74170894