opencv024-直方图计算

23 篇文章 0 订阅

直方图计算

直方图概念

假设有图像数据8x8,像素值范围0~1415个灰度等级,、统计得到各个等级出现次数及直方图如右侧所示,每个紫色的长条叫BIN

l上述直方图概念是基于图像像素值,其实对图像梯度、每个像素的角度、等一切图像的属性值,我们都可以建立直方图。这个才是直方图的概念真正意义,不过是基于图像像素灰度直方图是最常见的。

l直方图最常见的几个属性:

 - dims 表示维度,对灰度图像来说只有一个通道值dims=1。

- bins 表示在维度中子区域大小划分,bins=256,划分为256个级别。

 - range 表示值得范围,灰度值范围为[0~255]之间。

API学习

split(// 把多通道图像分为多个单通道图像

const Mat &src, //输入图像

Mat* mvbegin// 输出的通道图像数组

 

calcHist(//计算直方图

 const Mat* images,//输入图像指针

int images,// 图像数目

const int* channels,// 通道数

InputArray mask,// 输入mask,可选,不用

OutputArray hist,//输出的直方图数据

int dims,// 维数

const int* histsize,// 直方图级数

const float* ranges,// 值域范围

bool uniform,// true by default

bool accumulate// false by defaut

)

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

Mat src, dst, map_x,map_y;
const char* input_win = "input";
int index = 0;
const char* out_put = "histogram";
int main(int agrc, char** agrv) {
	src = imread("C:/Users/liyangxian/Desktop/bjl/nm4.jpg");
	if (!src.data) {
		printf("no load..\n");
		return -1;
	}
	namedWindow(input_win, CV_WINDOW_AUTOSIZE);
	namedWindow(out_put, CV_WINDOW_AUTOSIZE);
	imshow(input_win, src);


	//分通道显示
	vector<Mat> bgr_planes;
	split(src, bgr_planes);
	//imshow("a", bgr_planes[0]);
	
	//计算直方图
	int histSize = 256;
	float range[] = { 0,256 };
	const float *histRange = { range };
	Mat b_hist, g_hist, r_hist;
	calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, true, false);
	calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, true, false);
	calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, 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<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(out_put, histImage);
	waitKey(0);
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值