用到calcHist函数,返回hist,用minMaxloc来找到hist中数目最大的灰度级,表明其背景大概在这个区域,并以此作为阈值,进行分割。
其代码如下:
// opencv_6.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<opencv245.h> using namespace std; using namespace cv; class Histogram1D { private: int histSize[1]; float hranges[2]; const float* ranges[1]; int channels[1]; public: Histogram1D() { histSize[0] = 256; hranges[0] = 0.0; hranges[1] = 255.0; ranges[0] = hranges; channels[0] = 0; } Mat getHistogram(const Mat& image) { Mat hist; calcHist(&image, 1, channels, Mat(), hist, 1, histSize, ranges); return hist; } double lookMaxpixel(Mat & hist) { double MaxVal = 0.0; /*double MinVal = 0.0;*/ minMaxLoc(hist, NULL, &MaxVal); return MaxVal; } }; int _tmain(int argc, _TCHAR* argv[]) { Histogram1D h; Mat image = imread("C:\\Users\\sony\\Desktop\\cloud.jpg", 0); Mat dst1 , dst2; double thresholds = 0.0; dst1 = h.getHistogram(image); normalize( dst1, dst1, 1.0); thresholds = h.lookMaxpixel(dst1); threshold(image, dst2, thresholds*255, 255, THRESH_BINARY); imshow("dst",dst2); waitKey(0); return 0; }