Exemplo n.º 1
0
void ImagePro::on_btnHoughLines_clicked()
{
    double PI = 3.14159;
    LineFinder finder;
    //    // Set probabilistic Hough parameters
    //finder.setLineLengthAndGap(100,20);
    //finder.setMinVote(40);
    //    // Detect lines and draw them
    cv::Mat tmp1, tmp2;
    cv::cvtColor(_img,tmp1,CV_BGR2GRAY);
    cv::Canny(tmp1,tmp2,40,100);
    //cv::Canny(tmp1,tmp2,40,150);
    //cv::threshold(tmp2,tmp2,128,255,cv::THRESH_BINARY_INV);
    std::vector<cv::Vec4i> lines= finder.findLines(tmp2);
    //finder.drawDetectedLines(_img);
    cv::namedWindow("Detected Lines with HoughP");
    cv::imshow("Detected Lines with HoughP",tmp2);
}
Exemplo n.º 2
0
int main(){
	//Dimensions of Capture window
	int scale = 1;
	int width = 640/scale;
	int height = 480/scale;
	int lineSize;
	unsigned int start_time,stop_time;
	//Open capture device
	int device = 0; //assume we want first device

	bool gui = true;
	bool record = false;

	//create video capture device, set capture area
	VideoCapture capture = VideoCapture(device);
	capture.open(device);
	capture.set(CAP_PROP_FRAME_WIDTH,width);
	capture.set(CAP_PROP_FRAME_HEIGHT,height);


	//create recording object
	VideoWriter *recorder;
	//recorder = new VideoWriter ("test.avi",cv::CV_F FOURCC('D','I','V','X'), 30,Point(width,height));
	if (!recorder->isOpened() && record){
		return 0;
	}


	//Construct GUI object
	DebugGUI myGUI = DebugGUI(gui);

	//create image processing objects
	LineFinder imgproc = LineFinder(myGUI.getHSV(),scale);
	//imgproc.configWebcam("line");
	if(capture.isOpened()){  //check if we succeeded
		Mat raw;
		//main loop
		while(true){
			start_time = GetTimeMs64();

			//Pull a frame from the camera to the raw image
			// capture the current frame

			if (!capture.grab()){
				break;
			}
			capture >> raw;

			if (gui){
				imgproc.setFrame(raw.clone());
			}else{
				imgproc.setFrame(raw);
			}
			imgproc.setHSV(&myGUI);
			/*//imgproc.getGray();
			imgproc.thresholdHSV();
			imgproc.fillHoles();
			//imgproc.findObjects();
			//imgproc.printBiggestObject(raw)
			imgproc.findLines();
			double size =  imgproc.calculateBestGradient();
			LineObject* drawLine = imgproc.calculateErrorLine(height,width);
			if (drawLine != 0){
				lineSize = drawLine->size();
			}else{
				lineSize = 0;
			}
			if (gui){
				imgproc.drawErrorLine(raw,height,width);
				imgproc.printLines(raw);
			}
			//print (1/(time2-time1))

#ifdef time
			stop_time = GetTimeMs64();
			cout << "FPS: "  <<  1000/(stop_time - start_time) << endl;
#else
			cout << "Gradient: " << size << " " << "Offset: " << lineSize  << endl;
#endif
			*/
			if (gui){
				imshow("Raw",raw);
			}
			if (record){
				recorder->write(raw);
			}
			if(waitKey(30) >= 0){
				return 0;
			}
		}
	}
int main()
{
	// Read input image
	cv::Mat image= cv::imread("road.jpg",0);
	if (!image.data)
		return 0; 
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

    // Display the image
	cv::namedWindow("Original Image");
	cv::imshow("Original Image",image);

	// Compute Sobel
	EdgeDetector ed;
	ed.computeSobel(image);

    // Display the Sobel orientation
	cv::namedWindow("Sobel (orientation)");
	cv::imshow("Sobel (orientation)",ed.getSobelOrientationImage());
	cv::imwrite("ori.bmp",ed.getSobelOrientationImage());

    // Display the Sobel low threshold
	cv::namedWindow("Sobel (low threshold)");
	cv::imshow("Sobel (low threshold)",ed.getBinaryMap(125));

    // Display the Sobel high threshold
	cv::namedWindow("Sobel (high threshold)");
	cv::imshow("Sobel (high threshold)",ed.getBinaryMap(350));

	// Apply Canny algorithm
	cv::Mat contours;
	cv::Canny(image,contours,125,350);

    // Display the image of contours
	cv::namedWindow("Canny Contours");
	cv::imshow("Canny Contours",255-contours);

	// Create a test image
	cv::Mat test(200,200,CV_8U,cv::Scalar(0));
	cv::line(test,cv::Point(100,0),cv::Point(200,200),cv::Scalar(255));
	cv::line(test,cv::Point(0,50),cv::Point(200,200),cv::Scalar(255));
	cv::line(test,cv::Point(0,200),cv::Point(200,0),cv::Scalar(255));
	cv::line(test,cv::Point(200,0),cv::Point(0,200),cv::Scalar(255));
	cv::line(test,cv::Point(100,0),cv::Point(100,200),cv::Scalar(255));
	cv::line(test,cv::Point(0,100),cv::Point(200,100),cv::Scalar(255));

    // Display the test image
	cv::namedWindow("Test Image");
	cv::imshow("Test Image",test);
	cv::imwrite("test.bmp",test);

	// Hough tranform for line detection
	std::vector<cv::Vec2f> lines;
	cv::HoughLines(contours,lines,1,PI/180,50);

	// Draw the lines
	cv::Mat result(contours.rows,contours.cols,CV_8U,cv::Scalar(255));
	image.copyTo(result);

	std::cout << "Lines detected: " << lines.size() << std::endl;

	std::vector<cv::Vec2f>::const_iterator it= lines.begin();
	while (it!=lines.end()) {

		float rho= (*it)[0];   // first element is distance rho
		float theta= (*it)[1]; // second element is angle theta
		
		if (theta < PI/4. || theta > 3.*PI/4.) { // ~vertical line
		
			// point of intersection of the line with first row
			cv::Point pt1(rho/cos(theta),0);        
			// point of intersection of the line with last row
			cv::Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
			// draw a white line
			cv::line( result, pt1, pt2, cv::Scalar(255), 1); 

		} else { // ~horizontal line

			// point of intersection of the line with first column
			cv::Point pt1(0,rho/sin(theta));        
			// point of intersection of the line with last column
			cv::Point pt2(result.cols,(rho-result.cols*cos(theta))/sin(theta));
			// draw a white line
			cv::line( result, pt1, pt2, cv::Scalar(255), 1); 
		}

		std::cout << "line: (" << rho << "," << theta << ")\n"; 

		++it;
	}

    // Display the detected line image
	cv::namedWindow("Lines with Hough");
	cv::imshow("Lines with Hough",result);

	// Create LineFinder instance
	LineFinder ld;

	// Set probabilistic Hough parameters
	ld.setLineLengthAndGap(100,20);
	ld.setMinVote(60);

	// Detect lines
	std::vector<cv::Vec4i> li= ld.findLines(contours);
	ld.drawDetectedLines(image);
	cv::namedWindow("Lines with HoughP");
	cv::imshow("Lines with HoughP",image);

	std::vector<cv::Vec4i>::const_iterator it2= li.begin();
	while (it2!=li.end()) {

		std::cout << "(" << (*it2)[0] << ","<< (*it2)[1]<< ")-(" 
			     << (*it2)[2]<< "," << (*it2)[3] << ")" <<std::endl;

		++it2;
	}

	// Display one line
	image= cv::imread("road.jpg",0);
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	int n = 0;
	cv::line(image, cv::Point(li[n][0],li[n][1]),cv::Point(li[n][2],li[n][3]),cv::Scalar(255),5);
	cv::namedWindow("One line of the Image");
	cv::imshow("One line of the Image",image);

	// Extract the contour pixels of the first detected line
	cv::Mat oneline(image.size(),CV_8U,cv::Scalar(0));
	cv::line(oneline, cv::Point(li[n][0],li[n][1]),cv::Point(li[n][2],li[n][3]),cv::Scalar(255),3);
	cv::bitwise_and(contours,oneline,oneline);
	cv::namedWindow("One line");
	cv::imshow("One line",255-oneline);

	std::vector<cv::Point> points;

	// Iterate over the pixels to obtain all point positions
	for( int y = 0; y < oneline.rows; y++ ) {
    
		uchar* rowPtr = oneline.ptr<uchar>(y);
    
		for( int x = 0; x < oneline.cols; x++ ) {

		    // if on a contour
			if (rowPtr[x]) {

				points.push_back(cv::Point(x,y));
			}
		}
    }
	
	// find the best fitting line
	cv::Vec4f line;
	cv::fitLine(points,line,CV_DIST_L2,0,0.01,0.01);

	std::cout << "line: (" << line[0] << "," << line[1] << ")(" << line[2] << "," << line[3] << ")\n"; 

	int x0= line[2]; // a point on the line
	int y0= line[3];
	int x1= x0+100*line[0]; // add a vector of length 100
	int y1= y0+100*line[1];
	image= cv::imread("road.jpg",0);
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	// draw the line
	cv::line(image,cv::Point(x0,y0),cv::Point(x1,y1),0,3);
	cv::namedWindow("Fitted line");
	cv::imshow("Fitted line",image);

	// eliminate inconsistent lines
	ld.removeLinesOfInconsistentOrientations(ed.getOrientation(),0.4,0.1);

   // Display the detected line image
	image= cv::imread("road.jpg",0);
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	ld.drawDetectedLines(image);
	cv::namedWindow("Detected Lines (2)");
	cv::imshow("Detected Lines (2)",image);

	// Create a Hough accumulator
	cv::Mat acc(200,180,CV_8U,cv::Scalar(0));

	// Choose a point
	int x=50, y=30;

	// loop over all angles
	for (int i=0; i<180; i++) {

		double theta= i*PI/180.;

		// find corresponding rho value 
		double rho= x*std::cos(theta)+y*std::sin(theta);
		int j= static_cast<int>(rho+100.5);

		std::cout << i << "," << j << std::endl;

		// increment accumulator
		acc.at<uchar>(j,i)++;
	}

	// draw the axes
	cv::line(acc, cv::Point(0,0), cv::Point(0,acc.rows-1), 255);	
	cv::line(acc, cv::Point(acc.cols-1,acc.rows-1), cv::Point(0,acc.rows-1), 255);	
	
	cv::imwrite("hough1.bmp",255-(acc*100));

	// Choose a second point
	x=30, y=10;

	// loop over all angles
	for (int i=0; i<180; i++) {

		double theta= i*PI/180.;
		double rho= x*cos(theta)+y*sin(theta);
		int j= static_cast<int>(rho+100.5);

		acc.at<uchar>(j,i)++;
	}

	cv::namedWindow("Hough Accumulator");
	cv::imshow("Hough Accumulator",acc*100);
	cv::imwrite("hough2.bmp",255-(acc*100));

	// Detect circles
	image= cv::imread("chariot.jpg",0);
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	cv::GaussianBlur(image, image, cv::Size(5, 5), 1.5);
	std::vector<cv::Vec3f> circles;
	cv::HoughCircles(image, circles, CV_HOUGH_GRADIENT, 
		2,   // accumulator resolution (size of the image / 2) 
		20,  // minimum distance between two circles
		200, // Canny high threshold 
		60, // minimum number of votes 
		15, 50); // min and max radius

	std::cout << "Circles: " << circles.size() << std::endl;
	
	// Draw the circles
	image= cv::imread("chariot.jpg",0);
	// image is resize for book printing
	cv::resize(image, image, cv::Size(), 0.6, 0.6);

	std::vector<cv::Vec3f>::const_iterator itc = circles.begin();
	
	while (itc!=circles.end()) {
		
	  cv::circle(image, 
		  cv::Point((*itc)[0], (*itc)[1]), // circle centre
		  (*itc)[2], // circle radius
		  cv::Scalar(255), // color 
		  2); // thickness
		
	  ++itc;	
	}

	cv::namedWindow("Detected Circles");
	cv::imshow("Detected Circles",image);

	cv::waitKey();
	return 0;
}
Exemplo n.º 4
0
int main() {

    // Set-Up
    int houghVote = 200;
    string arg = "";

    // Set up windows
    bool showOriginal = 1;
    bool showCanny = 1;
    bool showHough = 1;
    bool showHoughP = 1;

    // Capture Input
    string window_name = "Processed Video";
    namedWindow(window_name, CV_WINDOW_KEEPRATIO); //resizable window;
    VideoCapture capture(arg);

    if (!capture.isOpened())  // Caputure Camera
    {capture.open(atoi(arg.c_str()));}

    capture.set(CV_CAP_PROP_POS_MSEC, 100000); //start the video at 100 seconds in

    double dWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
    double dHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

    std::cout << "Frame Size = " << dWidth << "x" << dHeight << std::endl;
    Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));

    // Encode resulting video
    // VideoWriter oVideoWriter ("LaneDetection.avi", CV_FOURCC('P','I','M','1'), 20, frameSize, true);

    // Process Frame
    Mat image;
    double frameItr = 0;
    image = imread(arg);
    int crestCount = 0, frameSkip = 0;
    while (1)
    {
        // capture on intervals to make vid smoother
        capture >> image;
        frameItr += 100;
        capture.set(CV_CAP_PROP_POS_MSEC, frameItr);

        if (image.empty())
            break;

        Mat gray;
        cvtColor(image,gray,CV_RGB2GRAY);
        vector<string> codes;
        Mat corners;
        findDataMatrix(gray, codes, corners);
        drawDataMatrixCodes(image, codes, corners);

        // ROI
        // optimized? -=> yes
        int top = 0;
        int left = 0;
        int width = dWidth;
        int height = dHeight;

        Rect roi(left,top,width,height);
        Mat imgROI = image(roi);
        Scalar val = Scalar(0, 0, 0);
        copyMakeBorder(imgROI, imgROI, 2, 2, 2, 2, BORDER_CONSTANT, val);

        // Display the image
        if(showOriginal) {
            namedWindow("Original Image");
            imshow("Original Image",imgROI);
//            imwrite("original.bmp", imgROI);
        }

        // Canny algorithm
        Mat contours;
        Canny(imgROI,contours,100,200);
        Mat contoursInv;
        threshold(contours,contoursInv,128,255,THRESH_BINARY_INV);

        // Display Canny image
        if(showCanny) {
            namedWindow("Contours");
            imshow("Contours1",contours); // use contoursInv for white
//            imwrite("contours.bmp", contours);
        }

        /*
         Hough tranform for line detection with feedback
         Increase by 25 for the next frame if we found some lines.
         This is so we don't miss other lines that may crop up in the next frame
         but at the same time we don't want to start the feed back loop from scratch.
         */
        std::vector<Vec2f> lines;
        if (houghVote < 1 or lines.size() > 2) { // we lost all lines. reset
            houghVote = 300;
        }
        else{ houghVote += 25;}
        while(lines.size() < 4 && houghVote > 0){
            HoughLines(contours,lines,1,PI/180, houghVote);
            houghVote -= 5;
        }
        std::cout << houghVote << "\n";
        Mat result(imgROI.size(),CV_8U,Scalar(255));
        imgROI.copyTo(result);

        // Draw the lines
        std::vector<Vec2f>::const_iterator it= lines.begin();
        Mat hough(imgROI.size(),CV_8U,Scalar(0));
        while (it!=lines.end()) {

            float rho= (*it)[0];   // first element is distance rho
            float theta= (*it)[1]; // second element is angle theta

            if ( (theta > 0.09 && theta < 1.48) || (theta < 3.14 && theta > 1.66) ) { // filter to remove vertical and horizontal lines

                // point of intersection of the line with first row
                Point pt1(rho/cos(theta),0);
                // point of intersection of the line with last row
                Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
                // draw a line: Color = Scalar(R, G, B), thickness
                line( result, pt1, pt2, Scalar(255,255,255), 1);
                line( hough, pt1, pt2, Scalar(255,255,255), 1);
            }

            //std::cout << "line: (" << rho << "," << theta << ")\n";
            ++it;
        }

        // Display the detected line image
        if(showHough){
            namedWindow("Detected Lines with Hough");
            imshow("Detected Lines with Hough",result);
//            imwrite("hough.bmp", result);
        }

        // Create LineFinder instance
        LineFinder ld;

        // Set probabilistic Hough parameters
        ld.setLineLengthAndGap(10,60); // min accepted length and gap
        ld.setMinVote(15); // sit > 3 to get rid of "spiderweb"

        // Detect lines
        std::vector<Vec4i> li= ld.findLines(contours);
        Mat houghP(imgROI.size(),CV_8U,Scalar(0));
        ld.setShift(0,0);
        ld.drawDetectedLines(houghP);
        std::cout << "First Hough" << "\n";

        if(showHoughP){
            namedWindow("Detected Lines with HoughP");
            imshow("Detected Lines with HoughP", houghP);
            imwrite("houghP.bmp", houghP);
        }

        // bitwise AND of the two hough images
        bitwise_and(houghP,hough,houghP);
        Mat houghPinv(imgROI.size(),CV_8U,Scalar(0));
        Mat dst(imgROI.size(),CV_8U,Scalar(0));
        threshold(houghP,houghPinv,150,255,THRESH_BINARY_INV); // threshold and invert to black lines

        if(showHoughP){
            namedWindow("Detected Lines with Bitwise");
            imshow("Detected Lines with Bitwise", houghP);
        }


        Canny(houghPinv,contours,100,350);
        li = ld.findLines(contours);
        // Display Canny image
//        if(showCanny){
//            namedWindow("Contours");
//            imshow("Contours2",contours);
//            imwrite("contours.bmp", contoursInv);
//        }

        // Test to draw point
        //ld.drawPoint(image, Point(320,130));

        // Set probabilistic Hough parameters
        // more strict than above HoughP
        ld.setLineLengthAndGap(5,2);
        ld.setMinVote(1);
        ld.setShift(top, left);

        // draw point on image where line intersection occurs
        int yShift = 25;
        int allowableFrameSkip = 5;
        ld.drawDetectedLines(image);
        cv::Point iPnt = ld.drawIntersectionPunto(image, 2);

        // track hill crest
        int gap = 20;
        cv::Point lptl(0, image.rows / 2 + yShift);
        cv::Point lptr(gap, image.rows / 2 + yShift);
        line(image, lptl, lptr, Scalar(255, 255, 255), 1);// left mid line

        cv::Point rptl(image.cols - gap, image.rows / 2 + yShift);
        cv::Point rptr(image.cols, image.rows / 2 + yShift);
        line(image, rptl, rptr, Scalar(255, 255, 255), 1);// right mid line

        cv::Point ulpt(0, image.rows / 2 - 50 + yShift);
        cv::Point urpt(image.cols, image.rows / 2 - 50 + yShift);
   //     line(image, ulpt, urpt, Scalar(255, 255, 255), 1);// upper line

        bool hillCrestFound = (iPnt.y < (image.rows / 2 + yShift)) && (iPnt.y > (image.rows / 2 - 50 + yShift));
        if(hillCrestFound) {
            crestCount++;
            frameSkip = 0;
        } else if(crestCount != 0 && frameSkip < allowableFrameSkip)
            frameSkip++;
        else {
            crestCount = 0;
            frameSkip = 0;
        }

        cv::Point txtPt(image.cols / 2 - 31, image.rows / 2 - 140);
        if(crestCount > 3)
            putText(image, "tracking", txtPt, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 2, 8);

        std::stringstream stream;
        stream << "Lines Segments: " << lines.size();

        putText(image, stream.str(), Point(10,image.rows-10), 1, 0.8, Scalar(0,255,0),0);
        imshow(window_name, image);
//        imwrite("processed.bmp", image);

        //	oVideoWriter.write(image); //writer the frame into the file

        char key = (char) waitKey(10);
        lines.clear();
    }
}
Exemplo n.º 5
0
/** @function main */
int main( int argc, char** argv )
{
	//-- CV Capture object for camera
	CvCapture* capture;
	//-- Frame Captured from capture object
   	Mat frame;
 
 	//-- Start capture from default camera
	capture = cvCaptureFromCAM( -1 );
	//-- If capture was successful
 	if( capture )
  	{ 
		cv::namedWindow("Detected Lines (2)");
		//-- While this program is running
		while( true )
		{
			//-- Get a frame from the capture
			frame = cvQueryFrame( capture );
			//-- If fram is not empty
			if( !frame.empty() ){
			
					int col1 = 0;
					int col2 = 0;

					cv::Mat image = frame;
					if (!image.data)
						return 0; 

					// Compute Sobel
					EdgeDetector ed;
					ed.computeSobel(image);


					// Apply Canny algorithm
					cv::Mat contours;
					cv::Canny(image,contours,125,350);
					cv::Mat contoursInv;
					cv::threshold(contours,contoursInv,128,255,cv::THRESH_BINARY_INV);


					// Hough tranform for line detection
					std::vector<cv::Vec2f> lines;
					cv::HoughLines(contours,lines,1,PI/180,60);

					// Draw the lines
					cv::Mat result(contours.rows,contours.cols,CV_8U,cv::Scalar(255));
					image.copyTo(result);

					std::cout << "Lines detected: " << lines.size() << std::endl;

					std::vector<cv::Vec2f>::const_iterator it= lines.begin();

					while (it!=lines.end()) {

						float rho= (*it)[0];   // first element is distance rho
						float theta= (*it)[1]; // second element is angle theta

						if (theta < PI/4. || theta > 3.*PI/4.) { // ~vertical line

							// point of intersection of the line with first row
							cv::Point pt1(rho/cos(theta),0);        
							// point of intersection of the line with last row
							cv::Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
							// draw a white line
							cv::line( result, pt1, pt2, cv::Scalar(200,0,0), 10); 

						} else { // ~horizontal line

							// point of intersection of the line with first column
							cv::Point pt1(0,rho/sin(theta));        
							// point of intersection of the line with last column
							cv::Point pt2(result.cols,(rho-result.cols*cos(theta))/sin(theta));
							// draw a white line
							cv::line( result, pt1, pt2, cv::Scalar(200,0,0), 10); 
						}

						//std::cout << "line: (" << rho << "," << theta << ")\n"; 

						++it;
					}


					// Display the detected line image
					//cv::namedWindow("Detected Lines with Hough");
					//cv::imshow("Detected Lines (2)",result);

					// Create LineFinder instance
					LineFinder ld;

					// Set probabilistic Hough parameters
					ld.setLineLengthAndGap(100,20);
					ld.setMinVote(80);

					// Detect lines
					std::vector<cv::Vec4i> li= ld.findLines(contours);
					ld.drawDetectedLines(image);

					// eliminate inconsistent lines
					ld.removeLinesOfInconsistentOrientations(ed.getOrientation(),0.4,0.1);
					
					std::vector<cv::Vec4i>::const_iterator it2= li.begin();
					
					while (it2!=li.end()) {
						
						float x1 = (float)(*it2)[0];
						float x2 = (float)(*it2)[2];
						float y1 = (float)(*it2)[1];
						float y2 = (float)(*it2)[3];
						
						std::cout << "point 1: (" << x1 << "," << y1 << ")\n"; 
						std::cout << "point 2: (" << x2 << "," << y2 << ")\n"; 
						
						float abdist = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
						
						
						std::cout << "abdist: (" << abdist << ")\n"; 
						
						// compute the direction vector D from A to B
						float dx = (x2-x1)/abdist;
						float dy = (y2-y1)/abdist;
						
						// compute the value t of the closest point to the circle center
						float t = dx*(230-x1) + dy*(444-y1);
						
						// This is the projection of C on the line from A to B.
						
						// compute the coordinates of the point E on line and closest to C
						float ex = t*dx+x1;
						float ey = t*dy+y1;
						
						std::cout << "point e: (" << ex << "," << ey << ")\n"; 
						
						// compute the euclidean distance from E to C
						float ecdist = sqrt(pow((ex-230),2)+pow((ey-444),2));
						
						std::cout << "distance: " << ecdist << "\n"; 
						
						// test if the line intersects the circle
						if( ecdist < 20 )
						{
							
							col1 = 1;
							
						}else if( ecdist == 20 ){
							col1 = 1;
						
						}
						
						++it2;	
					}
					

				   // Display the detected line image
					image= frame;
					//ld.drawDetectedLines(image);
					


					if(col1 == 1)
						{					
							cv::circle(image,cv::Point(230,444), 20, cv::Scalar(0,0,255,255),-1,8,0);
						}
					else
						{					
							cv::circle(image,cv::Point(230,444), 20, cv::Scalar(255,0,0,255),-1,8,0);
						}		

					
					if(col2 == 1)
						{					
							cv::circle(image,cv::Point(380,444), 20, cv::Scalar(0,0,255,255),-1,8,0);
						}
					else
						{					
							cv::circle(image,cv::Point(380,444), 20, cv::Scalar(255,0,0,255),-1,8,0);
						}



					//cv::namedWindow("Detected Lines (2)");
					cv::imshow("Detected Lines (2)",image);

		/*			// Create a Hough accumulator
					cv::Mat acc(200,180,CV_8U,cv::Scalar(0));

					// Choose a point
					int x=50, y=30;

					// loop over all angles
					for (int i=0; i<180; i++) 
					{

						double theta= i*PI/180.;

						// find corresponding rho value 
						double rho= x*cos(theta)+y*sin(theta);
						int j= static_cast<int>(rho+100.5);

						std::cout << i << "," << j << std::endl;

						// increment accumulator
						acc.at<uchar>(j,i)++;
					}
*/
			}
			else{
				printf(" --(!) No captured frame -- Break!"); break; 
			}
			int c = waitKey(10);
			if( (char)c == 'c' ) { break; };
		}
	}
  return 0;
  }
int _tmain(int argc, char* argv[])
{
	CvCapture* pCapture = NULL;
	if(argc == 2)
	{
		char* _tempname = "e:\\201505280048_22.mp4";
		if( !(pCapture = cvCaptureFromFile(_tempname)))     
		{   
			fprintf(stderr, "Can not open video file %s\n", argv[1]);   
			return -2;     
		}
	}
	if (argc == 1)
	{
		if( !(pCapture = cvCaptureFromCAM(1)))     
		{   
			fprintf(stderr, "Can not open camera.\n");   
			return -2;     
		} 
	}

	IplImage* pFrame = NULL;
	int countx=0;
	while (pFrame =cvQueryFrame(pCapture))  
	{ 
		countx++;
		IplImage* img1 = cvCreateImage(cvGetSize(pFrame), IPL_DEPTH_8U, 1);//创建目标图像 
		cvCvtColor(pFrame,img1,CV_BGR2GRAY);//cvCvtColor(src,des,CV_BGR2GRAY) 
		//边缘检测   
		cv::Mat result(img1); 
		cv::Mat contours;  
		cv::Canny (result,contours,50,150);
		img1 =&IplImage(contours);	


		int nVer = 1;
		int nHor = 2;
		IplConvKernel* VerKer;
		IplConvKernel* HorKer;
		VerKer = cvCreateStructuringElementEx(1,nVer,0,nVer/2,CV_SHAPE_RECT);
		HorKer = cvCreateStructuringElementEx(nHor,1,nHor/2,0,CV_SHAPE_RECT);
		cvDilate(img1,img1,VerKer);
		cvDilate(img1,img1,HorKer);

		cvMorphologyEx(img1, img1, NULL, NULL, CV_MOP_CLOSE);

		cvSaveImage("a.jpg",img1);

		cv::Mat image(pFrame);
		LineFinder finder;  
		finder.setMinVote (600);  
		finder.setLineLengthAndGap (680,500);
		std::vector<cv::Vec4i> li;
		li = finder.findLines (contours); 
		finder.drawDetectedLines (image); 
		imwrite("123.jpg",image);
		//选择第一条直线 
		//黑色的图像  

// 		for(int i = 0; i < li.size();i++)
// 		{
// 			int n= i;
// 			cv::Mat oneLine(image.size(),CV_8U,cv::Scalar(0));  
// 			cv::Mat oneLineInv;  
// 			//白线  
// 			line(oneLine,cv::Point(li[n][0],li[n][1]),cv::Point(li[n][2],li[n][3]),cv::Scalar(255),5);  
// 			//将轮廓与白线按位与  
// 			bitwise_and(contours,oneLine,oneLine); 		
// 			threshold(oneLine,oneLineInv,128,255,cv::THRESH_BINARY_INV);
// 			//把点集中的点插入到向量中  
// 			std::vector<cv::Point> points;  
// 			//遍历每个像素  
// 			for(int y = 0; y < oneLine.rows;y++)  
// 			{  
// 				uchar* rowPtr = oneLine.ptr<uchar>(y);  
// 				for(int x = 0;x < oneLine.cols;x++)  
// 				{  
// 					if(rowPtr[x])  
// 					{  
// 						points.push_back(cv::Point(x,y));  
// 					}  
// 				}  
// 			}  
// 			//储存拟合直线的容器  
// 			cv::Vec4f line;  
// 			//直线拟合函数  
// 			fitLine(cv::Mat(points),line,CV_DIST_L12,0,0.01,0.01);  
// 			//画一个线段  
// 			int x0= line[2];  
// 			int y0= line[3];  
// 			int x1= x0-200*line[0];  
// 			int y1= y0-200*line[1]; 
// 			if(y0 == y1 /*|| x0 == x1*/)
// 			{
// 				cv::line(image,cv::Point(x0,y0),cv::Point(x1,y1),cv::Scalar(0,255,0),1); 	
// 				imwrite("123.jpg",image);
// 			}
// 		}
// 		
	}
	return 0;
}