前言
这篇文章主要讲述如何手动计算并且绘制图像的灰度直方图
一、代码
//第二题 直方图
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
float chance[256];
int main()
{
cv::Mat srcMat = imread("C://Users//john//Desktop//1.jpg");
float height = srcMat.rows;
float width = srcMat.cols;
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
uchar average = (srcMat.at<Vec3b>(j, i)[0] + srcMat.at<Vec3b>(j, i)[1] + srcMat.at<Vec3b>(j, i)[2]) / 3;
srcMat.at<Vec3b>(j, i)[0] = average;
srcMat.at<Vec3b>(j, i)[1] = average;
srcMat.at<Vec3b>(j, i)[2] = average;
chance[average] = chance[average] + 1;
}
}
int i;
for (i = 0; i <= 255; i++)
{
chance[i] = chance[i] / (height*width);
}
cv::Mat displayMat = cv::Mat::zeros(500, 500, CV_8UC3);
cv::Point pt1;
cv::Point pt2;
for (i = 0; i <= 255; i++)
{
pt1.x = i;
pt2.x = i;
pt1.y = 500;
pt2.y = 500-chance[i]*500;
line(displayMat, pt1, pt2, CV_RGB(255, 0, 0), 1, 8, 0);
}
imshow("dis", displayMat);
waitKey(0);
}
总结
代码运行成功,就可以在当前界面显示灰度直方图了。