设为首页收藏本站 |天气与日历| 2025-04-20 星期日 06:12:00 乙巳(蛇)年 三月廿三 卯时 谷雨
     
切换到窄版

私人站点

 找回密码
 立即注册
搜索
查看: 148|回复: 0

直方图计算

[复制链接]

954

主题

954

帖子

3875

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3875
发表于 2022-3-9 08:24:48 | 显示全部楼层 |阅读模式
1.png 2.png 3.png

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





[C++] 纯文本查看 复制代码
/*
注意:
直方图的计算
*/
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
	Mat src, dst;
	src = imread("D:/IDE/opencv-3.1.0/demo.jpg");
	if (!src.data) {
		printf("加载图片异常\n");
		return -1;
	}
	namedWindow("input", CV_WINDOW_AUTOSIZE);
	imshow("input", src);
	//分通道显示
	vector<Mat> bgr_planes;
	//把多通道图像分为多个单通道图像
	split(src, bgr_planes);
	
	//计算直方图
	int histSize = 256;
	float range[] = { 0,256 };
	const float* thisRanges = { range };
	Mat b_hist, g_hist, r_hist;
	calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize,&thisRanges, true, false);
	calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &thisRanges, true, false);
	calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &thisRanges, true, false);
	//归一化
	int hist_h = 400;
	int hist_w = 512;
	int bin_w = hist_w / histSize;
	Mat histImge(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, b_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
	normalize(r_hist, b_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
	//绘制直方图
	for (int i = 1; i < histSize; i++)
	{
		line(
			histImge,
			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(
			histImge,
			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(
			histImge,
			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("直方图效果", histImge);
	}
	
	waitKey(0);
	return 0;
}


aa.jpg

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|编程站点 ( 冀ICP备2023028127号-2 )|友链申请|

GMT+8, 2025-4-20 06:12 , Processed in 0.094357 second(s), 25 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表