opencv 直方图 CV::calcHist使用

2023-11-01



本文转自:http://www.xuebuyuan.com/1014703.html

特别提醒读者:注意实例中数据成员很多都定义成数据,这是由于calcHist函数形参要求的。


直方图在图形处理中很常用,直方图可以统计图像的像素特征分布,用于修改图像显示,修改图像内容,通过比较不同图片的直方图可以识别和跟踪特殊纹理的物体和图像,下面先学习怎么计算图像的直方图。

      opencv2提供calchist函数可以方便的计算直方图。

      calchist函数头文件 #include <opencv2/imgproc/imgproc.hpp>

      calchist函数定义:

//! computes the joint dense histogram for a set of images.
CV_EXPORTS void calcHist( const Mat* images, int nimages,
                          const int* channels, InputArray mask,
                          OutputArray hist, int dims, const int* histSize,
                          const float** ranges, bool uniform=true, bool accumulate=false );

//! computes the joint sparse histogram for a set of images.
CV_EXPORTS void calcHist( const Mat* images, int nimages,
                          const int* channels, InputArray mask,
                          SparseMat& hist, int dims,
                          const int* histSize, const float** ranges,
                          bool uniform=true, bool accumulate=false );

CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
                            const vector<int>& channels,
                            InputArray mask, OutputArray hist,
                            const vector<int>& histSize,
                            const vector<float>& ranges,
                            bool accumulate=false );

      举例说明函数应用:

Histogram1D::Histogram1D(){
	histSize[0] = 256; 
	hranges[0] = 0.0;
	hranges[1] = 255.0;
	ranges[0] = hranges;
	channels[0] = 0;
}

cv::MatND Histogram1D::getHistogram(const cv::Mat &image){
	cv::MatND hist;
	cv::calcHist(&image,   //source image
		     1,        //histogram from 1 image only
		     channels, //the channel used
		     cv::Mat(),//no mask is uesd
		     hist,     //the resulting histogram
		     1,        //it is a 1D histogram
		     histSize, //number of bins
		     ranges    //pixel value range
				);//直方图函数
	return hist;
}

       函数参数介绍:

const Mat* images      //源图像组

int nimages       (Number of source arrays)   //源图像组图像个数

const int* channels   (List of the dims channels used to compute the histogram.)   //图像信道

InputArray mask   ( Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as arrays[i].  The non-zero mask elements mark the array elements counted in the histogram.)
                          //可选的掩码,如果不为空,则必须是8-bit数组,而且大小和原图像相同,非零位置为要计算的直方  图区域

OutputArray hist   (Output histogram, which is a dense or sparse dims -dimensional array.)
                       //输出直方图数组,稠密或者稀疏,dims维的数组

int dims    ( Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS)
                        //处理直方图的维数正数,最大32维,CV_MAX_DIMS是32.

const int* histSize   ( Array of histogram sizes in each dimension.)
                      //每一维的直方图的尺寸大小

const float** ranges    (Array of the dims arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( uniform =true),   then for each dimension i it is enough to specify the  lower (inclusive) boundary
of the 0-th histogram bin and the upper(exclusive)  boundary for  the last histogram bin histSize[i]-1. That is, in case of a uniform histogram each of ranges[i] is  an array of 2 elements.   When the histogram is not uniform ( uniform=false ), then each of
 ranges[i] contains histSize[i]+1 elements:.  The array elements, that are not between  and,are not counted in the histogram.)
                                  //直方图每一维的数据大小范围

 下面是计算1维图像的直方图:

cv::Mat Histogram1D::getHistogramImage(const cv::Mat &image){
	//compute histogram first
	cv::MatND hist = getHistogram(image);
	//get min and max bin values
	double maxVal = 0;
	double minVal = 0;
	cv::minMaxLoc(hist,&minVal,&maxVal,0,0);
	//Image on which to display histogram
	cv::Mat histImg(histSize[0],histSize[0],CV_8U,cv::Scalar(255));
	//set highest point at 90% of nbins 
	int hpt = static_cast<int>(0.9*histSize[0]);
	//Draw a vertical line for each bin 
	for (int h =0;h<histSize[0];h++)
	{
		float binVal = hist.at<float>(h);
		int intensity = static_cast<int>(binVal*hpt/maxVal);
		cv::line(histImg,cv::Point(h,histSize[0]),cv::Point(h,histSize[0]-intensity),cv::Scalar::all(0));
	}
	return histImg;
}

             源图像:

                    histogram:

 计算H-S直方图分布:

/*********************************************
             内容:计算H-S 直方图分布      
             时间:2013 5.27
	     作者:恋上蛋炒面      
*********************************************/
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;

void main()
{
	Mat source = imread("baboon.jpg");
	namedWindow("Source");
	imshow("Source",source);
	Mat hsv;
	cvtColor(source,hsv,CV_BGR2HSV);
	//Quantize the hue to 60 levels
	//and the saturation to 64 levels
	int hbins = 60,sbins = 64;
	int histSize[] = {hbins,sbins};
	//hue varies from 0 to 179
	float hranges[] = {0,180};
	//saturation varies from 0 to 255
	float sranges[] = {0,255};
	const float *ranges[] = {hranges,sranges};
	//two channels 0th,1th
	int channels[] = {0,1};
	MatND hist;
	//compute h-s histogram
	calcHist(&hsv,1,channels,Mat(),hist,2,histSize,ranges);
	//get the max value
	double maxVal = .0;
	minMaxLoc(hist,0,&maxVal,0,0);
	int scale = 8;
	//show the histogram on the image
	Mat histImg = Mat::zeros(sbins*scale,hbins*scale,CV_8UC3);
	for (int h = 0;h < hbins;h++)
	{
		for (int s = 0;s<sbins;s++)
		{
			float binVal = hist.at<float>(h,s);
			int intensity = cvRound(binVal*0.9*255/maxVal);
			rectangle(histImg,Point(h*scale,s*scale),Point((h+1)*scale-1,(s+1)*scale-1),Scalar::all(intensity),CV_FILLED);
		}
	}

	namedWindow("H-S Histogram");
	imshow("H-S Histogram",histImg);
	imwrite("hshistogram.jpg",histImg);
	waitKey(0);
}

       源图像:

h-s histogram:

   RGB直方图:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;

void main()
{
	//Mat source = imread("red.jpg");
	Mat source = imread("baboon.jpg");
	//Mat source(300,300,CV_8UC3,Scalar(1,1,244));
	//imwrite("red.jpg",source);
	namedWindow("Source");
	imshow("Source",source);
	int channels_r[1],channels_g[1],channels_b[1],histSize[1];
	float hranges[2];
	const float *ranges[1];
	histSize[0] = 256;
	hranges[0] = 0.0;
	hranges[1] = 255.0;
	ranges[0] = hranges;
	channels_b[0] = 0;
	channels_g[0] = 1;
	channels_r[0] = 2;
	MatND hist_r,hist_g,hist_b;

	double max_val_r,max_val_g,max_val_b;
	Mat histImage(histSize[0],3*histSize[0],CV_8UC3);
	//R
	calcHist(&source,1,channels_r,Mat(),hist_r,1,histSize,ranges);
	minMaxLoc(hist_r,0,&max_val_r,0,0);
	//G
	calcHist(&source,1,channels_g,Mat(),hist_g,1,histSize,ranges);
	minMaxLoc(hist_r,0,&max_val_g,0,0);
	//B
	calcHist(&source,1,channels_b,Mat(),hist_b,1,histSize,ranges);
	minMaxLoc(hist_r,0,&max_val_b,0,0);

	for (int i =0;i<histSize[0];i++)
	{
		float binVal_r = hist_r.at<float>(i);
		float binVal_g = hist_g.at<float>(i);
		float binVal_b = hist_b.at<float>(i);
		int intensity_r = static_cast<int>(0.9*histSize[0]*binVal_r/max_val_r);
		int intensity_g = static_cast<int>(0.9*histSize[0]*binVal_g/max_val_g);
		int intensity_b = static_cast<int>(0.9*histSize[0]*binVal_b/max_val_b);
		line(histImage,Point(i,histImage.rows),Point(i,histImage.rows-intensity_r),Scalar(0,0,255));
		line(histImage,Point(i+histSize[0],histImage.rows),Point(i+histSize[0],histImage.rows-intensity_g),Scalar(0,255,0));
		line(histImage,Point(i+histSize[0]*2,histImage.rows),Point(i+histSize[0]*2,histImage.rows-intensity_b),Scalar(255,0,0));
	}
	namedWindow("RGB Histogram");
	imshow("RGB Histogram",histImage);
	waitKey(0);
}

                     源图像:图上图

                     RGB-Histogram:

<pre class="cpp" name="code"><pre class="cpp" name="code"><pre class="cpp" name="code"><pre class="cpp" name="code"><pre class="cpp" name="code"><pre>
 
 
 
 
 
 
 

                
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

opencv 直方图 CV::calcHist使用 的相关文章

  • 同时从多个流中捕获、最佳方法以及如何减少 CPU 使用率

    我目前正在编写一个应用程序 该应用程序将捕获大量 RTSP 流 在我的例子中为 12 个 并将其显示在 QT 小部件上 当我超过大约 6 7 个流时 问题就会出现 CPU 使用率激增并且出现明显的卡顿 我认为它不是 QT 绘制函数的原因是因
  • Opencv Mat内存管理

    内存管理对于图像类至关重要 在opencv中 图像类是cv Mat 它有一个微妙的内存管理方案 假设我已经有了自己的图像类SelfImage class SelfImage public int width int height unsig
  • 如何使用 opencv.omnidir 模块对鱼眼图像进行去扭曲

    我正在尝试使用全向模块 http docs opencv org trunk db dd2 namespacecv 1 1omnidir html用于对鱼眼图像进行扭曲处理Python 我正在尝试适应这一点C 教程 http docs op
  • “没有名为‘cv2’的模块”,但已安装

    我已经安装了包含 opencv 贡献的 whl 文件 因为我想使用 SIFT 算法 我在 conda 环境中使用 pip 安装了它 所以当我在 conda list 中提示时 它会向我显示 opencv python 3 4 5 contr
  • 在 Visual Studio C++ 2008 中包含 dll

    有没有办法将 dll 包含在项目中 这样我就不必在编译后将这些 dll 与可执行文件放在同一文件夹中 这样我就可以用它们编译我的项目 这是否有可能 如果是 有人可以指导我 我的项目是一个 opencv 项目 有很多 dll 我必须包含在文件
  • 从 NumPy 数组到 Mat 的 C++ 转换 (OpenCV)

    我正在围绕 ArUco 增强现实库 基于 OpenCV 编写一个薄包装器 我试图构建的界面非常简单 Python 将图像传递给 C 代码 C 代码检测标记并将其位置和其他信息作为字典元组返回给 Python 但是 我不知道如何在 Pytho
  • 让网络摄像头在 OpenCV 中工作

    我正在尝试让我的网络摄像头在 Windows 7 64 位中的 OpenCV 版本 2 2 中捕获视频 但是 我遇到了一些困难 OpenCV 附带的示例二进制文件都无法检测到我的网络摄像头 最近我发现这篇文章表明答案在于重新编译一个文件 o
  • opencv中如何去除二值图像噪声?

    将图像转换为二值图像 黑白 后如果有任何噪音怎么办 我消除了那些不需要的噪音 您可以看到下图的黑色区域内有一些白噪声 我该如何去除噪声 使用opencv http img857 imageshack us img857 999 blackn
  • java.lang.UnsatisfiedLinkError:java.library.path中没有opencv_java2411

    我正在尝试将 opencv 添加到我的 Spring Boot Maven 项目中 为了使用 opencv 库 我必须在 java library path 中提供本机库 我已将以下命令添加到 Eclipse VM 参数中 Djava li
  • 我的 Opencv 应用程序处理速度非常慢

    我正在构建一个 OpenCV 应用程序 它从相机捕获视频 并在删除背景后将其覆盖在另一个视频上 我无法达到合理的速度 因为它以大约 1 fps 的速度播放输出 而我的背景去除以 3 fps 的速度工作 有没有办法以正常速度显示背景视频并以
  • OpenCV Python 和 SIFT 功能

    我知道有很多关于Python and OpenCV但我没有找到有关这个特殊主题的帮助 我想提取SIFT关键点来自 python OpenCV 中的图像 我最近安装了 OpenCV 2 3 可以访问 SURF 和 MSER 但不能访问 SIF
  • 针对不同处理器架构的 Gradle android 构建

    我想使用 Gradle 为 4 个不同的 Android CPU 处理器架构 armeabi armeabi v7a x86 mips 构建 4 个单独的 apk 我有为 4 个 CPU 架构构建的本机 OpenCV 库libs folde
  • 车辆分割和跟踪

    我已经从事一个项目一段时间了 目的是在无人机捕获的视频中检测和跟踪 移动 车辆 目前我正在使用 SVM 该 SVM 接受了从车辆和背景图像中提取的局部特征的特征袋表示的训练 然后 我使用滑动窗口检测方法来尝试定位图像中的车辆 然后我想要跟踪
  • 在 virtualenvwrapper 中激活环境

    我安装了virtualenv and virtualenvwrapper用这个命令我创建了一个环境 mkvirtualenv cv 它有效 创建后我就处于新环境中 现在我重新启动了我的电脑 我想activate又是那个环境 但是怎么样 我使
  • 在Spyder(Python 3.6)中导入cv2时出现导入错误

    我已经在Windows操作系统中安装了opencv 3 0 0 我已运行该应用程序并已成功将其安装在C 驱动器并还复制了cv2 pyd文件输入C Python27 Lib site packages正如我在几个教程视频中看到的那样 在我的
  • 从基本矩阵中查找单应矩阵

    我正在尝试计算单应性矩阵H给定一组对应关系和基本矩阵F 根据对极几何原理 我知道这可以通过对极线和对极线的叉积来完成F from 极点几何 http www cs unc edu marc tutorial node44 html e ij
  • 使用 Brew 安装 OpenCV 永远不会完成

    所以我尝试使用 Homebrew 安装 opencv 但它不起作用 我用了brew tap homebrew science进而brew install opencv发生的情况是 gt Installing opencv from home
  • 使用 OpenCV 从轮廓获取掩模

    我想从我通过 cv findContours 计算的轮廓 它只存在 1 个轮廓 获取图像掩模 然而 虽然我的轮廓变量不为空 但我无法使用 cv drawContours 检索图像蒙版 我的目标图像始终为空 这是我的代码 img mosaic
  • OpenCV findContours() 仅返回一个外部轮廓

    我试图隔离验证码中的字母 我设法过滤验证码 结果是这个黑白图像 但是当我尝试使用 OpenCV 的 findContours 方法分离字母时 它只是发现了一个包裹整个图像的外部轮廓 从而产生了该图像 图像外部的黑色轮廓 我将此代码与 Pyt
  • 已过时 - OpenCV 的错误模式

    我正在使用 OpenCV 1 进行一些图像处理 并且对 cvSetErrMode 函数 它是 CxCore 的一部分 感到困惑 OpenCV 具有三种错误模式 叶 调用错误处理程序后 程序终止 Parent 程序没有终止 但错误处理程序被调

随机推荐

  • vue3中知识点总结(持续更新)

    1 具名插槽 Vue3 具名插槽 Named Slots 文档地址 具名插槽添加
  • java并发怎么理解_java中并发的理解

    在java中谈到并发 我们一定会想到两种锁 一种synchronized锁 一种ReentrantLock 还有一种轻量级的作用在变量上的volatile 那么他们三个有什么具体区别 和具体怎么用呢 下面针对他们三个分别说一下原理和作用 v
  • ArcGIS 正高转换成椭球体高度

    转载 https resources arcgis com zh cn help main 10 1 index html 009t000001vm000000 一 椭球体高度与正高 具体讲解可见 https resources arcgi
  • Fabric加密算法

    BCCSP Blockchain crypto provider 即区块链加密提供商 用于定义选择使用的密码学实现库 负责摘要生成 非对称密钥的签名与验证 根据证书查找私钥等 该模块提供了一系列的接口 这些接口定义了摘要的生成方法 签名 验
  • 负载均衡之Keepalived

    严格意义来说 Keepalived主要是通过虚拟路由冗余来实现高可用功能 但是其也可以借助IPVS实现负载均衡 所以也简要的学习了一下 简介 起初是设计来监控集群中各个节点的状态 根据TCP IP模型中网络层 ICMP控制消息请求 传输层
  • QFileInfo

    一 描述 QFileInfo 提供有关文件系统中文件的名称和位置 路径 访问权限 文件类型等信息 FileInfo 还可用于获取有关 Qt 资源的信息 这个类是隐式共享的 二 成员函数 2 1 判断函数 1 bool isAbsolute
  • python_sqlalchemy

    SQLAlchemy使用和踩坑记 知乎 2 长时间未请求连接自动断开 现象 长时间服务端没有连接数据库 数据库连接自动断开 原因 1 sqlalchemy在create engine时 使用连接池并没有指定连接池回收时间 则连接池的连接不会
  • 交互设计实用指南系列(1) – 操作入口明确

    链接 http ued taobao org blog 2009 12 the practice guidelines of interaction design clear operational entrance of effectiv
  • 微软 AD 已成过去式,这个身份领域国产化替代方案你了解吗?

    随着全球互联网和数字化浪潮的不断发展 信息安全已成为不可忽视的问题 并随着日益复杂的国内外市场格局 其重要性更加凸显 我国政府也相继印发和实施了 数字中国建设整体布局规划 全国一体化大数据体系建设指南 等一系列政策 将核心技术自主可控 安全
  • CSS学习————css的选择器(2)

    选择器的作用 用来查找要设置html样式的元素 css的选择器分为4大类 1 简单选择器 6种 1 1 通配符选择器 1 2 标签选择器 1 3 id选择器 1 4 属性选择器 1 5 类选择器 1 6 分组选择器
  • Mac OS X下Android系统华为手机无法连接问题之解决方案

    一般的android连接mac 很方便不用安装驱动就可以啦 可是不知道为什么特殊情况下有的android手机 小米2 华为等 就是连接不上 下来就说说特殊情况下如何连接 使用USB连接安卓手机后可以做2件事情 关于本机 gt 更多信息 gt
  • 模板的显示实例化与显示具体化

    显式实例化 C 中模板函数 类 的调用与定义分离时 需要使用显式实例化 否则就会出现链接错误 编译器对各个cpp分别编译的时候 模板函数必须被实例化编译 如果我们把调用与定义写在一个文件 在调用语句处有int a b cmp a b 那么编
  • UVM的phase机制(Ⅰ)

    uvm存在phase机制 每个phase完成对应的功能 将所有的程序分解在不同的phase中执行 保证了验证环境的验证代码的执行顺序 并且每个phase完成对应的功能 使验证环境运行仿真层次化 让各种组件的例化次序正确 环境的执行顺序正确
  • 万字长文分享,如何自学Java(方法+步骤)

    目录 收起 大家存在的问题 为什么我觉得方法很重要 五个步骤学习Java 第一阶段 揽全局 怎么办 你需要的是系统化学习 教程式笔记 我的大学 我准备从思想方法和具体的学习步骤上给大家聊一下我的做法 希望对大家有所帮助 看完本篇文章你会得到
  • C语言-商品销售管理系统

    C语言 商品销售管理系统 全部代码如下 include
  • jsp中的stl标签库

    catch标签 forEach标签 remove标签 param标签 set标签 url标签
  • ZooKeeper安装后无法启动JAVA_HOME is not set and java could not be found in PATH.

    JAVA HOME is not set and java could not be found in PATH 在安装后使用命令 zkServer sh start启动出现JAVA HOME找不到的提示 去查看 etc profile文件
  • Java网络编程相关知识

    网络编程 1 在网络通信协议下 不同 计算机上运行的程序 进行的数据传输 2 应用场景 即时通信 网游对战 金融证券 国际贸易 邮件等等 3 Java中可以使用java net包下的技术开发出常见的网络应用程序 4 常见的软件架构有CS和B
  • UE4_蓝图调试器

    蓝图调试器 在蓝图调式器里可以看到所有的断点和 watch this value 的值 下面这幅图可以取消所有的断点和watch this value 节点注释
  • opencv 直方图 CV::calcHist使用

    本文转自 http www xuebuyuan com 1014703 html 特别提醒读者 注意实例中数据成员很多都定义成数据 这是由于calcHist函数形参要求的 直方图在图形处理中很常用 直方图可以统计图像的像素特征分布 用于修改