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

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

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.