cpp
复制代码
#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
cout << "直方图calcHist" << endl;
Mat src = imread("left.png", IMREAD_GRAYSCALE);
if (src.empty())
{
cout << "read image failed." << endl;
return -1;
}
imshow("gray_img", src);
Mat hist;
int histSize = 256;
calcHist(&src, 1, 0, Mat(), hist, 1, &histSize, 0);
double maxVal = 0;
double minVal = 0;
minMaxLoc(hist, &minVal, &maxVal, 0, 0);
int zoom = 2;
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);
}
}
imshow("hist_img", histImg);
cout << "直方图均衡化equalizeHist" << endl;
Mat result;
equalizeHist(src, result);
imshow("equalizeHist", result);
cout << "直方图反向投影calcBackProject" << endl;
Mat imageROI = src(Rect(400,20,150,80));
Mat hist2;
calcHist(&imageROI, 1, 0, Mat(), hist2, 1, &histSize, 0);
normalize(hist2, hist2, 1.0);
Mat backP;
calcBackProject(&src, 1, 0, hist2, backP, 0, 255.0);
Mat mask;
threshold(backP, mask, 30, 255, THRESH_BINARY);
imshow("backProject", mask);
cout << "积分图像" << endl;
Mat integralImg;
integral(src, integralImg, CV_32S);
waitKey();
return 0;
}