示例程序:
#include <opencv.hpp> using namespace cv; using namespace std; int main() { Mat src, dst; //load img; src = imread("001.jpg",1); if (!src.data) { printf("error"); return -1; } imshow("1", src); //分成三个通道 vector<Mat> rgb_planes; // 保存在stl容器里 split(src, rgb_planes); // 设置直方图尺寸 int histSize = 255; Mat histImage(400, 400, CV_8UC1, Scalar(0)); int bin_w = cvRound((double)400 / histSize); //设置范围 float range[] = { 0, 255 }; const float * histRange = { range }; bool uniform = true; bool accumulate = false; Mat r_hist, g_hist, b_hist; // 用于保存三个通道的直方图 //计算直方图 calcHist(&rgb_planes[1], 1,0,Mat(),r_hist,1, &histSize, &histRange, uniform, accumulate); normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); // 直方图归一化 for (int i = 1; i < histSize; i++) { line(histImage, Point(bin_w * (i - 1), 400 - cvRound(r_hist.at<float>(i - 1))), Point(bin_w * (i), 400 - cvRound(r_hist.at<float>(i))), Scalar(255), 1, 8, 0); } imshow("dst", histImage); waitKey(0); return 0; }
时间: 2024-10-24 20:12:12