OpenCV 直线检测

 

 

 

 

 

 

/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 7 of the cookbook:
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.

   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#if !defined LINEF
#define LINEF

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define PI 3.1415926

class LineFinder {

  private:

	  // original image
	  cv::Mat img;

	  // vector containing the end points
	  // of the detected lines
	  std::vector<cv::Vec4i> lines;

	  // accumulator resolution parameters
	  double deltaRho;
	  double deltaTheta;

	  // minimum number of votes that a line
	  // must receive before being considered
	  int minVote;

	  // min length for a line
	  double minLength;

	  // max allowed gap along the line
	  double maxGap;

  public:

	  // Default accumulator resolution is 1 pixel by 1 degree
	  // no gap, no mimimum length
	  LineFinder() : deltaRho(1), deltaTheta(PI/180), minVote(10), minLength(0.), maxGap(0.) {}

	  // Set the resolution of the accumulator
	  void setAccResolution(double dRho, double dTheta)
	  {

		  deltaRho= dRho;
		  deltaTheta= dTheta;
	  }

	  // Set the minimum number of votes
	  void setMinVote(int minv)
	  {

		  minVote= minv;
	  }

	  // Set line length and gap
	  void setLineLengthAndGap(double length, double gap)
	  {

		  minLength= length;
		  maxGap= gap;
	  }

	  // Apply probabilistic Hough Transform
	  std::vector<cv::Vec4i> findLines(cv::Mat& binary)
	  {

		  lines.clear();
		  cv::HoughLinesP(binary,lines,deltaRho,deltaTheta,minVote, minLength, maxGap);

		  return lines;
	  }

	  // Draw the detected lines on an image
	  void drawDetectedLines(cv::Mat &image, cv::Scalar color=cv::Scalar(255,255,255))
	  {

		  // Draw the lines
		  std::vector<cv::Vec4i>::const_iterator it2= lines.begin();

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

			  cv::Point pt1((*it2)[0],(*it2)[1]);
			  cv::Point pt2((*it2)[2],(*it2)[3]);

			  cv::line( image, pt1, pt2, color);

			  ++it2;
		  }
	  }

	  // Eliminates lines that do not have an orientation equals to
	  // the ones specified in the input matrix of orientations
	  // At least the given percentage of pixels on the line must
	  // be within plus or minus delta of the corresponding orientation
	  std::vector<cv::Vec4i> removeLinesOfInconsistentOrientations(
		  const cv::Mat &orientations, double percentage, double delta)
	  {

			  std::vector<cv::Vec4i>::iterator it= lines.begin();

			  // check all lines
			  while (it!=lines.end()) {

				  // end points
				  int x1= (*it)[0];
				  int y1= (*it)[1];
				  int x2= (*it)[2];
				  int y2= (*it)[3];

				  // line orientation + 90o to get the parallel line
				  double ori1= atan2(static_cast<double>(y1-y2),static_cast<double>(x1-x2))+PI/2;
				  if (ori1>PI) ori1= ori1-2*PI;

				  double ori2= atan2(static_cast<double>(y2-y1),static_cast<double>(x2-x1))+PI/2;
				  if (ori2>PI) ori2= ori2-2*PI;

				  // for all points on the line
				  cv::LineIterator lit(orientations,cv::Point(x1,y1),cv::Point(x2,y2));
				  int i,count=0;
				  for(i = 0, count=0; i < lit.count; i++, ++lit) { 

					  float ori= *(reinterpret_cast<float *>(*lit));

					  // is line orientation similar to gradient orientation ?
					  if (std::min(fabs(ori-ori1),fabs(ori-ori2))<delta)
						  count++;

				  }

				  double consistency= count/static_cast<double>(i);

				  // set to zero lines of inconsistent orientation
				  if (consistency < percentage) {

					  (*it)[0]=(*it)[1]=(*it)[2]=(*it)[3]=0;

				  }

				  ++it;
			  }

			  return lines;
	  }
};

#endif

 

 

// HoughLines.cpp : 定义控制台应用程序的入口点。
//

// findContours.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 7 of the cookbook:
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.

   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "HoughLines.h"

#pragma comment(lib,"opencv_core2410d.lib")
#pragma comment(lib,"opencv_highgui2410d.lib")
#pragma comment(lib,"opencv_imgproc2410d.lib")

#define PI 3.1415926

int main()
{
	// Read input image
	cv::Mat image= cv::imread("road.jpg",0);
	if (!image.data)
		return 0; 

	// Display the image
	cv::namedWindow("Original Image");
	cv::imshow("Original Image",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);

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

	// 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(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("Detected Lines with Hough");
	cv::imshow("Detected Lines with Hough",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);
	cv::namedWindow("Detected Lines with HoughP");
	cv::imshow("Detected Lines with HoughP",image);

	cv::waitKey();
	return 0;
}

 

实现效果:

 

 

时间: 2025-01-27 03:17:55

OpenCV 直线检测的相关文章

OpenCV轮廓检测,计算物体旋转角度

    效果还是有点问题的,希望大家共同探讨一下     // FindRotation-angle.cpp : 定义控制台应用程序的入口点. // // findContours.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/cor

OpenCV肤色检测

前三种方式转载:http://blog.csdn.net/onezeros/article/details/6342567   第一种:RGB color space 第二种:RG color space 第三种:Ycrcb之cr分量+otsu阈值化 第四种:YCrCb中133<=Cr<=173 77<=Cb<=127 第五种:HSV中 7<H<29  下一步需要滤波操作 因为检测结果中有许多瑕疵 [cpp] view plaincopy #include "

OpenCv 人脸检测的学习

最近公司要组织开发分享,但是自己还是新手真的不知道分享啥了,然后看了看前段时间研究过OpenCv,那么就分享他把. openCv就不介绍了,说下人脸检测,其实是通过openCv里边已经训练好的xml文件来进行的,我只是在学习. 我测试中我写了俩个Demo,其中一个是通过Carame来通过摄像头来进行人脸检测看看效果图: 可以看出检测出来的面部有线框. 第一个Dmeo是通过Jni编程来实现的人脸检测, (1)这是本地方法 package com.example.opencv.checkface2;

NVIDIA Jetson TK1学习与开发(九):基于GPU加速的OpenCV人体检测(Full Body Detection)

基于GPU加速的OpenCV人体检测(Full Body Detection) 1.CUDA和OpenCV的安装 首先,确定一下自己的平台是否安装好了CUDA和OpenCV. CUDA的安装可以参考:http://blog.csdn.net/frd2009041510/article/details/42042807和http://blog.csdn.net/frd2009041510/article/details/42925205 OpenCV的安装可以参考:http://blog.csdn

usb相机-opencv如何检测USB相机的通断?

问题描述 opencv如何检测USB相机的通断? 我使用openCV调用USB相机,使用过程中USB相机突然断开,这个过程应如何进行检测?谢谢 解决方案 下面代码,打开就继续,不打开直接返回么,不知道这样可以不? VideoCapture cap(0); //打开默认的摄像头号 if(!cap.isOpened()) //检测是否打开成功 return -1; 解决方案二: http://blog.csdn.net/carson2005/article/details/6705198 解决方案三

脸部识别-android Opencv 人脸检测

问题描述 android Opencv 人脸检测 请问有大神做过opencv人脸识别的相关demo吗?找了好长时间都是人脸检测 解决方案 最近在做人脸识别,现在初步只做了人脸检测,比较简单,仅供参考. 功能是打开图片,进行人脸检测,输出人脸个数和检测范围. .......省略包 public class Staticdetection2Activity extends Activity { final private static String TAG = "Staticrecognition.

opencv 运动目标检测 性能问题

问题描述 opencv 运动目标检测 性能问题 使用混合高斯背景模型背景差分法进行运动目标检测时,发现实时解码视频流会出现,背景差分效率跟不上的情况,占用资源高,而且还容易丢帧,请问各位大虾怎样提高解码性能,以及怎样提高背景差分的性能? 解决方案 主要是处理速度跟不上,简单的说如果你的视频是25/s帧 那么至少40ms要解一帧,并且做背景差分,电脑处理速度跟不上,就会丢帧.建议你看看实时解码出来的图像是否花屏严重,如果不严重,可以适当减小图片的大小,从而达到处理速度的目的.至于你说的占用资源高,

opencv 区域检测-Opencv中cvfindcontours原理

问题描述 Opencv中cvfindcontours原理 Opencv中的cvfindcontours原理是什么啊,有没有什么比较著名的算法在里面,自己看不懂代码,网上也没有介绍~但是想学习一下轮廓检测-- 解决方案 OpenCV人脸识别的原理 .OpenCV人脸识别的原理 .opencv cvFindContours---------------------- 解决方案二: opencv文档中的内容有写: "") The function retrieves contours fro

OpenCV 轮廓检测

读入彩色3通道图像,转换成灰度图像,再转换成二值图像,完后检测轮廓.   // cvtcolor.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp&g