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


  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 threshold
	float getThreshold() {

		return threshold;
	}

	// Sets the reference histogram
	void setHistogram(const cv::MatND& h) {

		isSparse= false;
		histogram= h;
		cv::normalize(histogram,histogram,1.0);
	}

	// Sets the reference histogram
	void 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 type

		   cv::calcBackProject(&image,
                      1,            // one image
                      channels,     // vector specifying what histogram dimensions belong to what image channels
                      shistogram,   // the histogram we are using
                      result,       // the resulting back projection image
                      ranges,       // the range of values, for each dimension
                      255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255
		   );

		} else {

		   cv::calcBackProject(&image,
                      1,            // one image
                      channels,     // vector specifying what histogram dimensions belong to what image channels
                      histogram,    // the histogram we are using
                      result,       // the resulting back projection image
                      ranges,       // the range of values, for each dimension
                      255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255
		   );
		}


        // Threshold back projection to obtain a binary image
		if (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 type

		   cv::calcBackProject(&image,
                      1,            // we only use one image at a time
                      channels,     // vector specifying what histogram dimensions belong to what image channels
                      shistogram,   // the histogram we are using
                      result,       // the resulting back projection image
                      ranges,       // the range of values, for each dimension
                      255.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 time
                      channels,     // vector specifying what histogram dimensions belong to what image channels
                      histogram,    // the histogram we are using
                      result,       // the resulting back projection image
                      ranges,       // the range of values, for each dimension
                      255.0         // the scaling factor is chosen such that a histogram value of 1 maps to 255
		   );
		}

        // Threshold back projection to obtain a binary image
		if (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 histogram
		histSize[0]= histSize[1]= histSize[2]= 256;
		hranges[0]= 0.0;    // BRG range
		hranges[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 histogram
		hranges[0]= 0.0;    // BRG range
		hranges[1]= 255.0;
		channels[0]= 0;		// the three channels 
		channels[1]= 1; 
		channels[2]= 2; 

		// Compute histogram
		cv::calcHist(&image, 
			1,			// histogram of 1 image only
			channels,	// the channel used
			cv::Mat(),	// no mask is used
			hist,		// the resulting histogram
			3,			// it is a 3D histogram
			histSize,	// number of bins
			ranges		// pixel value range
		);

		return hist;
	}

	// Computes the 1D Hue histogram with a mask.
	// BGR source image is converted to HSV
	cv::MatND getHueHistogram(const cv::Mat &image) {

		cv::MatND hist;

		// Convert to Lab color space
		cv::Mat hue;
		cv::cvtColor(image, hue, CV_BGR2HSV);

		// Prepare arguments for a 1D hue histogram
		hranges[0]= 0.0;
		hranges[1]= 180.0;
		channels[0]= 0; // the hue channel 

		// Compute histogram
		cv::calcHist(&hue, 
			1,			// histogram of 1 image only
			channels,	// the channel used
			cv::Mat(),	// no mask is used
			hist,		// the resulting histogram
			1,			// it is a 1D histogram
			histSize,	// number of bins
			ranges		// 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 image
	cv::namedWindow("Image 2 result");
	cv::imshow("Image 2 result",image);

	cv::waitKey();
	return 0;

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值