关闭

基于直方图的匹配_视频流

325人阅读 评论(0) 收藏 举报
分类:


#include <opencv2/core/core.hpp>      
#include <opencv2/highgui/highgui.hpp>     
#include <opencv2\opencv.hpp>    
#include<opencv2\imgproc\imgproc.hpp>  
#include <iostream>    
#include<string>    
#include <sstream>    
using namespace cv;    
using namespace std;  
MatND getHistogram(Mat &img)//得到直方图    
{    
	int channels[]={0,1,2};//考察通道    
	int HistSize[3]={16,16,16};//直方图中元素数    
  
	float r_hranges[] = {0, 255};  
    float g_hranges[] = {0, 255};  
    float b_hranges[] = {0, 255};  
    const float *pRange[]={r_hranges, g_hranges, b_hranges}; 
	//计算直方图,直方图结果放在hist.at<float>(i)    
	MatND hist;    
	calcHist(&img,1,channels,Mat(),hist,3,HistSize,pRange);    
	return hist;    
}    

//void getHistogramImage(Mat &image )//画直方图    
//{    
//	MatND hist=getHistogram(image);    
//	double max_val,min_val;    
//	int HistSize[]={256};    
//	minMaxLoc(hist,&min_val,&max_val,0,0);    
//	Mat histImg(cvSize(256*2,300),CV_8U,Scalar(0));    
//	for(int i=0;i<HistSize[0];i++)    
//	{    
//		int val=int(hist.at<float>(i)/max_val*300);    
//		line(histImg,cvPoint(i*2,300),cvPoint(i*2,300-val),cvScalar(255,255,255),1);    
//	}    
//	namedWindow("直方图");    
//	imshow("直方图",histImg);    
//}  
int main()  
{  
	///调用摄像头
	VideoCapture cap(0);  
	if(!cap.isOpened())  
	{  
		return -1;  
	}  
	Mat src;  
	Mat templ;  
	Mat result;
	int match_method=CV_TM_SQDIFF;
	templ=imread("img.jpg",1);
	//getHistogramImage(templ);//输出模板直方图 
	MatND sourceHist=getHistogram(templ); 
	double maxDistance; 
	int best_i,best_j;
	int h_distance=7000;//阈值
	bool stop = false;  

	///循环处理图像
	while(!stop)  
	{  
		maxDistance=0; 
		cap>>src;  

		int T_cols =  src.cols - templ.cols ;
		int T_rows = src.rows - templ.rows;

		for(int i=0;i<T_cols;i=i+5)  
		{
			for(int j=0;j<T_rows;j=j+5)  
			{    

				result=src(Rect(i,j,templ.cols,templ.rows));   

				MatND dstHist=getHistogram(result);//计算各个直方图    
				double distance=compareHist(sourceHist,dstHist,CV_COMP_INTERSECT);//比较直方图    
				// cout<<distance<<endl;    
				if(distance>maxDistance)    
				{    
					best_i=i;
					best_j=j;
					maxDistance=distance;    
				}    
			}   
		}
		if(maxDistance>h_distance)
		{
		Mat best=src(Rect(best_i,best_j,templ.cols,templ.rows))  ;
		//getHistogramImage(best);//输出最优图片直方图    
	    cout<<maxDistance<<endl;
		imshow("BestImage",best);   
		/// 最终结果
		rectangle( src, Point(best_i,best_j), Point( best_i+templ.cols,best_j+templ.rows), Scalar::all(0), 2, 8, 0 );	
		cout<<"目标的中心坐标 ( "<<best_i + templ.cols/2<<" , ("<<best_j+ templ.rows<<" )"<<endl;
		}
		else
		{
			cout<<"未找到目标"<<endl; 
		}
		imshow("当前视频",src);  
		//imshow("result",result);
		
		if(waitKey(300) >=0)  
			stop = true;  
	}  
	waitKey();  
	return 0;  
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:262456次
    • 积分:4914
    • 等级:
    • 排名:第6185名
    • 原创:219篇
    • 转载:89篇
    • 译文:0篇
    • 评论:118条
    最新评论