1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <opencv2/opencv.hpp>
cv::Mat src; cv::Mat histimg; cv::MatND hist;
int histSize = 50;
void HIST(int t,void*) { char string[10];
if(histSize==0) { printf("直方图条数不能为零!\n"); } else { int dims = 1; float hranges[2] = {0, 255}; const float *ranges[1] = {hranges}; int channels = 0;
histimg.create(512,256*4,CV_8UC3); histimg.setTo(cv::Scalar(0,0,0));
calcHist(&src, 1, &channels, cv::Mat(), hist, dims, &histSize, ranges);
double maxVal = 0; cv::Point maxLoc; cv::minMaxLoc(hist, NULL, &maxVal, NULL, &maxLoc);
double bin_w =(double) histimg.cols / histSize; double bin_u = (double)histimg.rows/ maxVal;
for(int i=0;i<histSize;i++) { cv::Point p0=cv::Point(i*bin_w,histimg.rows);
float binValue = hist.at<float>(i); cv::Point p1=cv::Point((i+1)*bin_w,histimg.rows-binValue*bin_u);
cv::rectangle(histimg,p0,p1,cv::Scalar(0,255,0),2,8,0); }
for (int i = 0; i < histSize; i++) { cv::line(histimg, cv::Point(bin_w*i+bin_w/2, histimg.rows-hist.at<float>(i)*bin_u), cv::Point(bin_w*(i+1)+bin_w/2, histimg.rows-hist.at<float>(i+1)*bin_u), cv::Scalar(255, 0, 0), 2, 8, 0); }
int kedu=0; for(int i=1;kedu<maxVal;i++) { kedu=i*maxVal/10; sprintf(string,"%d",kedu); cv::putText(histimg, string , cv::Point(0,histimg.rows-kedu*bin_u), cv::FONT_HERSHEY_SIMPLEX,0.5,cv::Scalar(0,255,255),1);
cv::line( histimg,cv::Point(0,histimg.rows-kedu*bin_u),cv::Point(histimg.cols-1,histimg.rows-kedu*bin_u),cv::Scalar(0,0,255)); } kedu=0; for(int i=1;kedu<256;i++) { kedu=i*20; sprintf(string,"%d",kedu); putText(histimg, string , cv::Point(kedu*(histimg.cols / 256),histimg.rows), cv::FONT_HERSHEY_SIMPLEX,0.5,cv::Scalar(0,255,255),2); }
cv::imshow( "Histogram", histimg ); } }
int main( int argc, char** argv ) {
src = cv::imread("../pictures/lena.jpg",0);
cv::namedWindow( "src", 1); cv::imshow( "src", src); cv::namedWindow( "Histogram", 1 );
int maxvalue = 256; cv::createTrackbar( "histSize", "src", &histSize, maxvalue, HIST ); HIST(0,0); cv::waitKey(0);
cv::destroyWindow("src"); cv::destroyWindow("Histogram");
return 0; }
|