本文共 2082 字,大约阅读时间需要 6 分钟。
#include#include #include #include using namespace std;using namespace cv;char *output_title = "直方图绘制";Mat src, dst;int main() { src = imread("E:\\vs2015\\opencvstudy\\1.jpg", 1); if (src.empty()) { cout << "could not load the src image!" << endl; return -1; } imshow("输入图像", src); // 分通道显示 vector bgr_planes; split(src, bgr_planes); /*显示单通道图像 imshow("单通道示例", bgr_planes[0]); imshow("单通道示例", bgr_planes[1]); imshow("单通道示例", bgr_planes[2]); */ // 计算直方图 int histSize = 256; float range[] = { 0, 256 }; const float *histRanges = ⦥ Mat b_hist, g_hist, r_hist; calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, histRanges, true, false); calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, histRanges, true, false); calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, histRanges, true, false); // 绘制直方图 int hist_h = 400; int hist_w = 512; int bin_w = hist_w / histSize; Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(0, 0, 0)); normalize(b_hist, b_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); normalize(g_hist, g_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); normalize(r_hist, r_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); // 绘制直方图图像 for (int i = 1; i < histSize; i++) { line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(b_hist.at (i - 1))), Point(i*bin_w, hist_h - cvRound(b_hist.at (i))), Scalar(255, 0, 0), 2, LINE_AA); line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(g_hist.at (i - 1))), Point(i*bin_w, hist_h - cvRound(g_hist.at (i))), Scalar(0, 255, 0), 2, LINE_AA); line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(r_hist.at (i - 1))), Point(i*bin_w, hist_h - cvRound(r_hist.at (i))), Scalar(0, 0, 255), 2, LINE_AA); } imshow(output_title, histImage); waitKey(0); return 0;}
这个代码片段展示了如何使用OpenCV库来读取图像、分离图像的通道并计算直方图,然后绘制直方图图像。主要步骤包括:
代码中使用了OpenCV的高级功能calcHist和normalize来处理直方图计算和归一化,并通过imshow函数展示结果图像。
转载地址:http://jmsfk.baihongyu.com/