第25课 直方图计算

1. 直方图概念

在24课有详细介绍,此就不做赘述。

1.1 直方图常见的几个属性:

  • dims 表示维度,对灰度图像来说只有一个通道值dims=1
  • bins 表示在维度中子区域大小划分,bins=256,划分为256个级别
  • range 表示值得范围,灰度值范围为[0~255]之间

2. 相关API

2.1 split()

  • 把多通道图像分为多个单通道图像
 split(
const Mat &src, //输入图像
Mat* mvbegin)// 输出的通道图像数组

2.2 直方图计算calcHist()

calcHist(
 const Mat* images,//输入单通道图像指针,
int images,// 图像数目,设为1即可
const int* channels,// 通道数,设为0即可
InputArray mask,// 输入mask,计算掩模内的直方图,设为Mat()即可
OutputArray hist,//输出的直方图数据,为一个Mat型变量
int dims,// 维数,需要统计直方图通道的个数
const int* histsize,// 直方图级数,指的是直方图分成多少个区间,就是 bin的个数
const float* ranges,// 值域范围
bool uniform = true,// 是否对得到的直方图数组进行归一化处理
bool accumulate = false// 在多个图像时,是否累计计算像素值得个数
)

3.例程

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

int main(int argc, char** argv) {
	Mat src = imread("D:/resource/images/face.jpg");
	if (!src.data) {
		printf("could not load image...\n");
		return -1;
	}
	char INPUT_T[] = "input image";
	char OUTPUT_T[] = "histogram demo";
	namedWindow(INPUT_T, WINDOW_AUTOSIZE);
	namedWindow(OUTPUT_T, WINDOW_AUTOSIZE);
	imshow(INPUT_T, src);


	// 分通道
	vector<Mat> bgr_planes;
	split(src, bgr_planes);

	// 计算直方图
	int histSize = 256;
	float range[] = { 0, 256 };
	const float *histRanges = { range };
	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());

	// render histogram chart,画直方图
	for (int i = 1; i < histSize; i++) {
		line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(b_hist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 2, LINE_AA);

		line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(g_hist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 2, LINE_AA);

		line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(r_hist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, LINE_AA);
	}
	imshow(OUTPUT_T, histImage);

	waitKey(0);
	return 0;
}

在这里插入图片描述

发布了31 篇原创文章 · 获赞 12 · 访问量 2759

猜你喜欢

转载自blog.csdn.net/weixin_42877426/article/details/104343880