使用均值漂移算法查找物体,源代码

2024-02-20 20:18

本文主要是介绍使用均值漂移算法查找物体,源代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


本文转自:http://blog.csdn.net/williamfan21c/article/details/24333785
[cpp] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #if !defined OFINDER  
  2. #define OFINDER  
  3.   
  4. #include <opencv2\core\core.hpp>  
  5. #include <opencv2\imgproc\imgproc.hpp>  
  6.   
  7. class ContentFinder {  
  8.   
  9. private:  
  10.   
  11.     float hranges[2];  
  12.     const float* ranges[3];  
  13.     int channels[3];  
  14.   
  15.     float threshold;  
  16.     cv::MatND histogram;  
  17.     cv::SparseMat shistogram;  
  18.     bool isSparse;  
  19.   
  20.   public:  
  21.   
  22.     ContentFinder() : threshold(0.1f), isSparse(false) {  
  23.   
  24.         ranges[0]= hranges; // all channels have the same range   
  25.         ranges[1]= hranges;   
  26.         ranges[2]= hranges;   
  27.     }  
  28.      
  29.     // Sets the threshold on histogram values [0,1]  
  30.     void setThreshold(float t) {  
  31.   
  32.         threshold= t;  
  33.     }  
  34.   
  35.     // Gets the threshold  
  36.     float getThreshold() {  
  37.   
  38.         return threshold;  
  39.     }  
  40.   
  41.     // Sets the reference histogram  
  42.     void setHistogram(const cv::MatND& h) {  
  43.   
  44.         isSparse= false;  
  45.         histogram= h;  
  46.         cv::normalize(histogram,histogram,1.0);  
  47.     }  
  48.   
  49.     // Sets the reference histogram  
  50.     void setHistogram(const cv::SparseMat& h) {  
  51.   
  52.         isSparse= true;  
  53.         shistogram= h;  
  54.         cv::normalize(shistogram,shistogram,1.0,cv::NORM_L2);  
  55.     }  
  56.   
  57. cv::Mat find(const cv::Mat& image) {  
  58.   
  59.         cv::Mat result;  
  60.   
  61.         hranges[0]= 0.0;    // range [0,255]  
  62.         hranges[1]= 255.0;  
  63.         channels[0]= 0;     // the three channels   
  64.         channels[1]= 1;   
  65.         channels[2]= 2;   
  66.   
  67.         if (isSparse) { // call the right function based on histogram type  
  68.   
  69.            cv::calcBackProject(&image,  
  70.                       1,            // one image  
  71.                       channels,     // vector specifying what histogram dimensions belong to what image channels  
  72.                       shistogram,   // the histogram we are using  
  73.                       result,       // the resulting back projection image  
  74.                       ranges,       // the range of values, for each dimension  
  75.                       255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255  
  76.            );  
  77.   
  78.         } else {  
  79.   
  80.            cv::calcBackProject(&image,  
  81.                       1,            // one image  
  82.                       channels,     // vector specifying what histogram dimensions belong to what image channels  
  83.                       histogram,    // the histogram we are using  
  84.                       result,       // the resulting back projection image  
  85.                       ranges,       // the range of values, for each dimension  
  86.                       255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255  
  87.            );  
  88.         }  
  89.   
  90.   
  91.         // Threshold back projection to obtain a binary image  
  92.         if (threshold>0.0)  
  93.             cv::threshold(result, result, 255*threshold, 255, cv::THRESH_BINARY);  
  94.   
  95.         return result;  
  96.     }  
  97.   
  98. cv::Mat find(const cv::Mat& image, float minValue, float maxValue, int *channels, int dim) {  
  99.   
  100.         cv::Mat result;  
  101.   
  102.         hranges[0]= minValue;  
  103.         hranges[1]= maxValue;  
  104.   
  105.         for (int i=0; i<dim; i++)  
  106.             this->channels[i]= channels[i];  
  107.   
  108.         if (isSparse) { // call the right function based on histogram type  
  109.   
  110.            cv::calcBackProject(&image,  
  111.                       1,            // we only use one image at a time  
  112.                       channels,     // vector specifying what histogram dimensions belong to what image channels  
  113.                       shistogram,   // the histogram we are using  
  114.                       result,       // the resulting back projection image  
  115.                       ranges,       // the range of values, for each dimension  
  116.                       255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255  
  117.            );  
  118.   
  119.         } else {  
  120.   
  121.            cv::calcBackProject(&image,  
  122.                       1,            // we only use one image at a time  
  123.                       channels,     // vector specifying what histogram dimensions belong to what image channels  
  124.                       histogram,    // the histogram we are using  
  125.                       result,       // the resulting back projection image  
  126.                       ranges,       // the range of values, for each dimension  
  127.                       255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255  
  128.            );  
  129.         }  
  130.   
  131.         // Threshold back projection to obtain a binary image  
  132.         if (threshold>0.0)  
  133.             cv::threshold(result, result, 255*threshold, 255, cv::THRESH_BINARY);  
  134.   
  135.         return result;  
  136.     }  
  137.   
  138. };  
  139.   
  140.   
  141. #endif  
  142.   
  143. #if !defined COLHISTOGRAM  
  144. #define COLHISTOGRAM  
  145.   
  146. #include <opencv2\core\core.hpp>  
  147. #include <opencv2\imgproc\imgproc.hpp>  
  148. #include<opencv2/highgui/highgui.hpp>  
  149. class ColorHistogram {  
  150.   
  151.   private:  
  152.   
  153.     int histSize[3];  
  154.     float hranges[2];  
  155.     const float* ranges[3];  
  156.     int channels[3];  
  157.   
  158.   public:  
  159.   
  160.     ColorHistogram() {  
  161.   
  162.         // Prepare arguments for a color histogram  
  163.         histSize[0]= histSize[1]= histSize[2]= 256;  
  164.         hranges[0]= 0.0;    // BRG range  
  165.         hranges[1]= 255.0;  
  166.         ranges[0]= hranges; // all channels have the same range   
  167.         ranges[1]= hranges;   
  168.         ranges[2]= hranges;   
  169.         channels[0]= 0;     // the three channels   
  170.         channels[1]= 1;   
  171.         channels[2]= 2;   
  172.     }  
  173.   
  174.     // Computes the histogram.  
  175.     cv::MatND getHistogram(const cv::Mat &image) {  
  176.   
  177.         cv::MatND hist;  
  178.   
  179.         // BGR color histogram  
  180.         hranges[0]= 0.0;    // BRG range  
  181.         hranges[1]= 255.0;  
  182.         channels[0]= 0;     // the three channels   
  183.         channels[1]= 1;   
  184.         channels[2]= 2;   
  185.   
  186.         // Compute histogram  
  187.         cv::calcHist(&image,   
  188.             1,          // histogram of 1 image only  
  189.             channels,   // the channel used  
  190.             cv::Mat(),  // no mask is used  
  191.             hist,       // the resulting histogram  
  192.             3,          // it is a 3D histogram  
  193.             histSize,   // number of bins  
  194.             ranges      // pixel value range  
  195.         );  
  196.   
  197.         return hist;  
  198.     }  
  199.   
  200.     // Computes the 1D Hue histogram with a mask.  
  201.     // BGR source image is converted to HSV  
  202.     cv::MatND getHueHistogram(const cv::Mat &image) {  
  203.   
  204.         cv::MatND hist;  
  205.   
  206.         // Convert to Lab color space  
  207.         cv::Mat hue;  
  208.         cv::cvtColor(image, hue, CV_BGR2HSV);  
  209.   
  210.         // Prepare arguments for a 1D hue histogram  
  211.         hranges[0]= 0.0;  
  212.         hranges[1]= 180.0;  
  213.         channels[0]= 0; // the hue channel   
  214.   
  215.         // Compute histogram  
  216.         cv::calcHist(&hue,   
  217.             1,          // histogram of 1 image only  
  218.             channels,   // the channel used  
  219.             cv::Mat(),  // no mask is used  
  220.             hist,       // the resulting histogram  
  221.             1,          // it is a 1D histogram  
  222.             histSize,   // number of bins  
  223.             ranges      // pixel value range  
  224.         );  
  225.   
  226.         return hist;  
  227.     }  
  228.   
  229.       
  230. cv::MatND getHueHistogram(const cv::Mat &image,int minSaturation)  
  231.     {  
  232.         cv::MatND hist;  
  233.         cv::Mat hsv;  
  234.         cv::cvtColor(image,hsv,CV_BGR2HSV);  
  235.         cv::Mat mask;  
  236.         if(minSaturation>0)  
  237.         {  
  238.             std::vector<cv::Mat>v;  
  239.             cv::split(hsv,v);  
  240.             cv::threshold(v[1],mask,minSaturation,255,cv::THRESH_BINARY);  
  241.         }  
  242.         hranges[0]=0.0;  
  243.         hranges[1]=180.0;  
  244.         channels[0]=0;  
  245.         calcHist(&hsv,1,channels,mask,hist,1,histSize,ranges);  
  246.         return hist;  
  247.     }  
  248.   
  249. };  
  250.   
  251.   
  252. #endif  
  253.   
  254. #include<opencv2/core/core.hpp>  
  255. #include<opencv2/highgui/highgui.hpp>  
  256. #include<opencv2/imgproc/imgproc.hpp>  
  257. #include<opencv2/video/video.hpp>  
  258. #include<iostream>  
  259. #include"colorhistogram.h"  
  260. #include"ContentFinder.h"  
  261.   
  262. using namespace std;  
  263. using namespace cv;  
  264.    
  265.   
  266. int main()  
  267. {  
  268.     Mat image=imread("d:/test/opencv/baboon1.jpg");  
  269.     Mat imageROI=image(Rect(110,260,35,40));  
  270.     int minSat=65;  
  271.     ColorHistogram hc;  
  272.     MatND colorhist=hc.getHueHistogram(imageROI,minSat);  
  273.   
  274.     namedWindow("image 1");  
  275.     imshow("image 1",image);  
  276.   
  277.     ContentFinder finder;  
  278.     finder.setHistogram(colorhist);  
  279.     Mat hsv;  
  280.     image=imread("d:/test/opencv/baboon3.jpg");  
  281.     namedWindow("image 2");  
  282.     imshow("image 2",image);  
  283.     cvtColor(image,hsv,CV_BGR2HSV);  
  284.     vector<Mat>v;  
  285.     split(hsv,v);  
  286.     threshold(v[1],v[1],minSat,255,THRESH_BINARY);  
  287.     cv::namedWindow("Saturation");  
  288.     cv::imshow("Saturation",v[1]);  
  289.     int channel[1]={0};  
  290.     Mat result=finder.find(hsv,0.0f,180.0f,channel,1);  
  291.   
  292.   
  293.     cv::namedWindow("Result Hue");  
  294.     cv::imshow("Result Hue",result);  
  295.   
  296.     cv::bitwise_and(result,v[1],result);  
  297.     cv::namedWindow("Result Hue and");  
  298.     cv::imshow("Result Hue and",result);  
  299.   
  300.   
  301.     finder.setThreshold(-1.0f);//  
  302.     result= finder.find(hsv,0.0f,180.0f,channel,1);  
  303.     cv::bitwise_and(result,v[1],result);  
  304.     cv::namedWindow("Result Hue and raw");  
  305.     cv::imshow("Result Hue and raw",result);  
  306.   
  307.     cv::Rect rect(110,260,35,40);  
  308.     cv::rectangle(image, rect, cv::Scalar(0,0,255));  
  309.   
  310.     cv::TermCriteria criteria(cv::TermCriteria::MAX_ITER,10,0.01);  
  311.     cout << "meanshift= " << cv::meanShift(result,rect,criteria) << endl;//  
  312.   
  313.     cv::rectangle(image, rect, cv::Scalar(0,255,0));//  
  314.   
  315.     // Display image  
  316.     cv::namedWindow("Image 2 result");  
  317.     cv::imshow("Image 2 result",image);  
  318.   
  319.     cv::waitKey();  
  320.     return 0;  
  321.   
  322. }  
#if !defined OFINDER
#define OFINDER#include <opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>class ContentFinder {private:float hranges[2];const float* ranges[3];int channels[3];float threshold;cv::MatND histogram;cv::SparseMat shistogram;bool isSparse;public:ContentFinder() : threshold(0.1f), isSparse(false) {ranges[0]= hranges; // all channels have the same range ranges[1]= hranges; ranges[2]= hranges; }// Sets the threshold on histogram values [0,1]void setThreshold(float t) {threshold= t;}// Gets the thresholdfloat getThreshold() {return threshold;}// Sets the reference histogramvoid setHistogram(const cv::MatND& h) {isSparse= false;histogram= h;cv::normalize(histogram,histogram,1.0);}// Sets the reference histogramvoid setHistogram(const cv::SparseMat& h) {isSparse= true;shistogram= h;cv::normalize(shistogram,shistogram,1.0,cv::NORM_L2);}cv::Mat find(const cv::Mat& image) {cv::Mat result;hranges[0]= 0.0;	// range [0,255]hranges[1]= 255.0;channels[0]= 0;		// the three channels channels[1]= 1; channels[2]= 2; if (isSparse) { // call the right function based on histogram typecv::calcBackProject(&image,1,            // one imagechannels,     // vector specifying what histogram dimensions belong to what image channelsshistogram,   // the histogram we are usingresult,       // the resulting back projection imageranges,       // the range of values, for each dimension255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255);} else {cv::calcBackProject(&image,1,            // one imagechannels,     // vector specifying what histogram dimensions belong to what image channelshistogram,    // the histogram we are usingresult,       // the resulting back projection imageranges,       // the range of values, for each dimension255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255);}// Threshold back projection to obtain a binary imageif (threshold>0.0)cv::threshold(result, result, 255*threshold, 255, cv::THRESH_BINARY);return result;}cv::Mat find(const cv::Mat& image, float minValue, float maxValue, int *channels, int dim) {cv::Mat result;hranges[0]= minValue;hranges[1]= maxValue;for (int i=0; i<dim; i++)this->channels[i]= channels[i];if (isSparse) { // call the right function based on histogram typecv::calcBackProject(&image,1,            // we only use one image at a timechannels,     // vector specifying what histogram dimensions belong to what image channelsshistogram,   // the histogram we are usingresult,       // the resulting back projection imageranges,       // the range of values, for each dimension255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255);} else {cv::calcBackProject(&image,1,            // we only use one image at a timechannels,     // vector specifying what histogram dimensions belong to what image channelshistogram,    // the histogram we are usingresult,       // the resulting back projection imageranges,       // the range of values, for each dimension255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255);}// Threshold back projection to obtain a binary imageif (threshold>0.0)cv::threshold(result, result, 255*threshold, 255, cv::THRESH_BINARY);return result;}};#endif#if !defined COLHISTOGRAM
#define COLHISTOGRAM#include <opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
class ColorHistogram {private:int histSize[3];float hranges[2];const float* ranges[3];int channels[3];public:ColorHistogram() {// Prepare arguments for a color histogramhistSize[0]= histSize[1]= histSize[2]= 256;hranges[0]= 0.0;    // BRG rangehranges[1]= 255.0;ranges[0]= hranges; // all channels have the same range ranges[1]= hranges; ranges[2]= hranges; channels[0]= 0;		// the three channels channels[1]= 1; channels[2]= 2; }// Computes the histogram.cv::MatND getHistogram(const cv::Mat &image) {cv::MatND hist;// BGR color histogramhranges[0]= 0.0;    // BRG rangehranges[1]= 255.0;channels[0]= 0;		// the three channels channels[1]= 1; channels[2]= 2; // Compute histogramcv::calcHist(&image, 1,			// histogram of 1 image onlychannels,	// the channel usedcv::Mat(),	// no mask is usedhist,		// the resulting histogram3,			// it is a 3D histogramhistSize,	// number of binsranges		// pixel value range);return hist;}// Computes the 1D Hue histogram with a mask.// BGR source image is converted to HSVcv::MatND getHueHistogram(const cv::Mat &image) {cv::MatND hist;// Convert to Lab color spacecv::Mat hue;cv::cvtColor(image, hue, CV_BGR2HSV);// Prepare arguments for a 1D hue histogramhranges[0]= 0.0;hranges[1]= 180.0;channels[0]= 0; // the hue channel // Compute histogramcv::calcHist(&hue, 1,			// histogram of 1 image onlychannels,	// the channel usedcv::Mat(),	// no mask is usedhist,		// the resulting histogram1,			// it is a 1D histogramhistSize,	// number of binsranges		// pixel value range);return hist;}cv::MatND getHueHistogram(const cv::Mat &image,int minSaturation){cv::MatND hist;cv::Mat hsv;cv::cvtColor(image,hsv,CV_BGR2HSV);cv::Mat mask;if(minSaturation>0){std::vector<cv::Mat>v;cv::split(hsv,v);cv::threshold(v[1],mask,minSaturation,255,cv::THRESH_BINARY);}hranges[0]=0.0;hranges[1]=180.0;channels[0]=0;calcHist(&hsv,1,channels,mask,hist,1,histSize,ranges);return hist;}};#endif#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/video/video.hpp>
#include<iostream>
#include"colorhistogram.h"
#include"ContentFinder.h"using namespace std;
using namespace cv;int main()
{Mat image=imread("d:/test/opencv/baboon1.jpg");Mat imageROI=image(Rect(110,260,35,40));int minSat=65;ColorHistogram hc;MatND colorhist=hc.getHueHistogram(imageROI,minSat);namedWindow("image 1");imshow("image 1",image);ContentFinder finder;finder.setHistogram(colorhist);Mat hsv;image=imread("d:/test/opencv/baboon3.jpg");namedWindow("image 2");imshow("image 2",image);cvtColor(image,hsv,CV_BGR2HSV);vector<Mat>v;split(hsv,v);threshold(v[1],v[1],minSat,255,THRESH_BINARY);cv::namedWindow("Saturation");cv::imshow("Saturation",v[1]);int channel[1]={0};Mat result=finder.find(hsv,0.0f,180.0f,channel,1);cv::namedWindow("Result Hue");cv::imshow("Result Hue",result);cv::bitwise_and(result,v[1],result);cv::namedWindow("Result Hue and");cv::imshow("Result Hue and",result);finder.setThreshold(-1.0f);//result= finder.find(hsv,0.0f,180.0f,channel,1);cv::bitwise_and(result,v[1],result);cv::namedWindow("Result Hue and raw");cv::imshow("Result Hue and raw",result);cv::Rect rect(110,260,35,40);cv::rectangle(image, rect, cv::Scalar(0,0,255));cv::TermCriteria criteria(cv::TermCriteria::MAX_ITER,10,0.01);cout << "meanshift= " << cv::meanShift(result,rect,criteria) << endl;//cv::rectangle(image, rect, cv::Scalar(0,255,0));//// Display imagecv::namedWindow("Image 2 result");cv::imshow("Image 2 result",image);cv::waitKey();return 0;}


 

这篇关于使用均值漂移算法查找物体,源代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/729420

相关文章

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件