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

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

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1