毕业设计过程记录六,单目单点测距

平面测距做不出来了,无奈只好用单目单点测距顶上!感谢mbees大神提供的设备和技术上的支持,有时间大家给大神的博客点个关注吧,谢谢。老规矩,直接贴代码!

#include "stdafx.h"
#include 
#include "highgui.h"
#include 
#include  
using namespace cv;
using namespace std;
Mat src;   //原图像存储变量
Mat src_gray;   //存灰度图变量
int thresh = 180;   //阈值设定
int max_thresh = 255;//最大阈值
int main( int argc, char** argv ) {
	VideoCapture cam(1);//获取摄像头0
	if (!cam.isOpened()) exit(0);//判断是否存在,不存在退出
	bool stop = false;//循环使能
	while(!stop)
	{
		cam >> src;//获取摄像头
	    cvtColor( src, src_gray, CV_BGR2GRAY );//灰度化      
		GaussianBlur( src, src, Size(3,3), 0.1, 0, BORDER_DEFAULT ); //线性滤波
		blur( src_gray, src_gray, Size(3,3) ); //滤波       
		namedWindow( "原图像", 0 );   //创建一个窗体    
		imshow( "原图像", src );       //显示原图
		
		//定义Canny边缘检测图像       
		Mat canny_output;  //定义边缘检测存储变量   
		vector hierarchy;    
		Canny( src_gray, canny_output, thresh, thresh*3, 3 ); //利用canny算法检测边缘      
		namedWindow( "边缘轮廓", 0 );       
		imshow( "边缘轮廓", canny_output );      
		     
	   vector > contours;  
		findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); //查找轮廓       
		//计算轮廓矩       
		vector mu(contours.size() );       
		for( int i = 0; i < contours.size(); i++ )     
		{   
			mu[i] = moments( contours[i], false );   
		}     
		//计算轮廓的质心     
		vector mc( contours.size() );      
		for( int i = 0; i < contours.size(); i++ )     
		{   
			mc[i] = Point2d( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );   
		}     
		//画轮廓及其质心并显示      
		Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );         
		for( int i = 0; i< contours.size(); i++ )      
		{         
			if (mc[i].y>260||mc[i].y<200)
			{
				continue;
			}
			Scalar color = Scalar( 255, 0, 0);        
			drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );         
			circle( drawing, mc[i], 5, Scalar( 0, 0, 255), -1, 8, 0 );                
			rectangle(drawing, boundingRect(contours.at(i)), cvScalar(0,255,0));  
			double    gain = 0.001644074345 ;
            double    offset =0.001607879449 ;//Offset是弧度误差
			unsigned int pixels_from_center =320 - mc[i].x;
            // 算出距离并打印出来
			if(pixels_from_center>140)
			{
				gain = 0.001513280086  ;
				offset =0.017372721230  ;
			}else if(pixels_from_center>104)
			{
				gain = 0.001635044755  ;
				offset =0.003201011964  ;
			}else
			{
				gain = 0.001644074345 ;
				offset =0.001607879449 ;
			}
			const double    h_cm = 7.00;              // 摄像头和激光头距离cm
            double          range;
            range = h_cm / tan(pixels_from_center * gain + offset);
			char tam[100];   
			sprintf(tam, "(%0.0f,%0.0f,%d,%0.3fcm)",mc[i].x,mc[i].y,pixels_from_center,range);   
			cout<<"距离="<

声明:此段代码归mbees大神所有!
我宣布我的毕设博客到此结束!希望大家都能够完成毕设。

你可能感兴趣的:(毕业设计)