直方图的计算在OpenCV中可以使用calcHist()函数,计算完成后可以采用OpenCV中的绘图函数,如绘制矩形的rectangle()函数,绘制线段的line()函数来完成。
所用函数:1.计算直方图:calcHist()
2.找寻最值:minMaxLoc()
以下附上画出图像HSV直方图的代码
#include
#include
#include
using namespace cv;
using namespace std;
int main()
{
Mat srcimage = imread("1.bmp");
imshow("原图", srcimage);
Mat srcimageHSV;
//图像转化HSV颜色空间图像
cvtColor(srcimage, srcimageHSV, COLOR_BGR2HSV);
imshow("HSV空间图像", srcimageHSV);
int channels = 0;
int histsize[] = { 256 };
float midranges[] = { 0,255 };
const float *ranges[] = { midranges };
MatND dsthist;
calcHist(&srcimageHSV, 1, &channels, Mat(), dsthist, 1, histsize, ranges, true, false);
Mat drawImage = Mat::zeros(Size(256 * 3, 256), CV_8UC3);
double g_dhistmaxvalue;
minMaxLoc(dsthist, 0, &g_dhistmaxvalue, 0, 0);
//画出h色调通道
for (int i = 0; i < 256; i++) {
int value = cvRound(256 * 0.9 *(dsthist.at(i) / g_dhistmaxvalue));
line(drawImage, Point(i, drawImage.rows - 1), Point(i, drawImage.rows - 1 - value), Scalar(255, 0, 0));
}
//画出s饱和度通道
channels = 1;
calcHist(&srcimageHSV, 1, &channels, Mat(), dsthist, 1, histsize, ranges, true, false);
for (int i = 0; i < 256; i++) {
int value = cvRound(256 * 0.9 *(dsthist.at(i) / g_dhistmaxvalue));
line(drawImage, Point(i + 256, drawImage.rows - 1), Point(i + 256, drawImage.rows - 1 - value), Scalar(0, 255, 0));
}
//画出v亮度通道
channels = 2;
calcHist(&srcimageHSV, 1, &channels, Mat(), dsthist, 1, histsize, ranges, true, false);
for (int i = 0; i < 256; i++) {
int value = cvRound(256 * 0.9 *(dsthist.at(i) / g_dhistmaxvalue));
line(drawImage, Point(i + 256 * 2, drawImage.rows - 1), Point(i + 256 * 2, drawImage.rows - 1 - value), Scalar(0, 0, 255));
}
imshow("HSV直方图", drawImage);
waitKey(0);
return 0;
}