精华内容
下载资源
问答
  • opencv直线检测

    2010-08-06 16:28:12
    图像处理 直线检测 opencv 霍夫变换 c++
  • opencv 直线检测

    2021-03-25 17:25:14
    第一个参数是一个二值化图像,所以在进行霍夫变换之前要首先进行二值化,或者进行 Canny 边缘检测。 rho:像素精度,一般设置为1; theta:角度精度,一般设置为CV_PI/180; threshold:表示累计的像素达到多少才能...

    直线检测必须对着边缘检测的结果二值图检测,不能对着灰度图检测

    二值图和边缘检测的结果图还是不一样的,

    二值图的检测结果:

    api:

    cv.HoughLines(image, rho, theta, threshold, lines=None, srn=None, stn=None, min_theta=None, max_theta=None)

    参数:
    第一个参数是一个二值化图像,所以在进行霍夫变换之前要首先进行二值化,或者进行 Canny 边缘检测。

     

    opencv的HoughLinesP函数是统计概率霍夫线变换函数,该函数能输出检测到的直线的端点 ,其函数原型为:HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines

    image参数表示边缘检测的输出图像,该图像为单通道8位二进制图像。

    rho参数表示参数极径  以像素值为单位的分辨率,这里一般使用 1 像素。

    theta参数表示参数极角  以弧度为单位的分辨率,这里使用 1度。一般设置为CV_PI/180;

    threshold参数表示检测一条直线所需最少的曲线交点。

    lines参数表示储存着检测到的直线的参数对  的容器,也就是线段两个端点的坐标。

    minLineLength参数表示能组成一条直线的最少点的数量,点数量不足的直线将被抛弃。

    maxLineGap参数表示能被认为在一条直线上的亮点的最大距离。
     

    demo:

     

    import cv2
    import numpy as np
    image=cv2.imread("erzhi.jpg")
    
    start=time.time()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 120)
    line = 100
    minLineLength = 15
    lines = cv2.HoughLinesP(edges, 1, np.pi / 90, 10, lines=line, minLineLength=minLineLength)
    lines1 = lines[:, 0, :]
    print(time.time()-start,lines.shape)
    for x1, y1, x2, y2 in lines1:
    
    
        cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    cv2.imshow("edges",edges)
    cv2.imshow("lines",image)
    cv2.waitKey()

    展开全文
  • OpenCV 直线检测

    千次阅读 2014-12-10 17:22:48
    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 ...

     

     

     

     

     

     

    /*------------------------------------------------------------------------------------------*\
       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;
    }


     

    实现效果:

     

     

    展开全文
  • python-opencv直线检测+直线拟合+计算偏移量 计算边界直线与x坐标轴的距离=首先canny边缘检测——>直线检测——>直线拟合——>计算与x坐标轴的距离。 直接上代码: import cv2 #opencv读取的格式是BGR ...

    python-opencv直线检测+直线拟合+计算偏移量

    计算边界直线与x坐标轴的距离=首先canny边缘检测——>直线检测——>直线拟合——>计算与x坐标轴的距离。

    直接上代码:

    import cv2 #opencv读取的格式是BGR
    import numpy as np 
    
    vc = cv2.VideoCapture('D:/Desktop/duizhong/fangzhen.mp4')
    
    if vc.isOpened(): #判断能否读取
        open, frame = vc.read()
    else:
        open = False
    while open:
        ret, frame = vc.read()
        if frame is None:#读取为空
            break
        if ret == True:#读取不为空
    
    
    #边缘检测
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            blur = cv2.blur(gray, (3, 3))#矩阵维度3*3
            aussian = cv2.GaussianBlur(frame, (5, 5), 1) 
            v1=cv2.Canny(blur,80,150)#minval、maxval的值
            #值小时检测更仔细
            cv2.imshow("canny",v1)
    
    #直线检测
            roi = frame[150:400,300:700]
            gray1 = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            blur1 = cv2.blur(gray1, (3, 3))#矩阵维度3*3
            v2=cv2.Canny(blur1,80,150)#minval、maxval的值
            minLineLength = 5
            maxLineGap =10
            lines = cv2.HoughLinesP(v2, 1, np.pi/180, 10, minLineLength, maxLineGap) 
    
            while lines is None:
                break
            else:
            	
                for line in lines:
    
                    x1,y1,x2,y2 = line[0]
                    loc=[]
                    cv2.line(roi,(x1,y1), (x2,y2), (0,255,0),2)
                    loc.append([x1,y1])
                    loc.append([x2,y2])
                    loc= np.array(loc)
                    #print(line[0])
                    #print(lines)
                    output =cv2.fitLine(loc,cv2.DIST_L2,0,0.01,0.01)
                    k = output[1] / output[0]
                    c = output[3] - k * output[2]+150#因为在roi窗口坐标系与原坐标系相差150
                    s=frame.shape
                    a=s[0]//2
                    #print(c)
                    dx=c-a#偏移量
                    print(dx)
                cv2.imshow("line",frame)
    
    #轮廓检侧
            blur1 = cv2.blur(gray1, (3, 3))#矩阵维度3*3
            ret, thresh = cv2.threshold(blur1, 127, 255, cv2.THRESH_BINARY)
            contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
            res = cv2.drawContours(roi, contours, -1, (0, 0, 255), 2)#-1表示绘制所有,改数选择绘制的图像、2线条宽度
           
            #cv2.imshow('res',res)
    
    #中心线也就是坐标轴x轴
            s=frame.shape
            a=s[0]//2
            b=s[1]
            cv2.line(frame,(0,a),(b,a),(0, 0, 255),2) 
            cv2.imshow("line",frame) 
    
    
            if cv2.waitKey(10) & 0xFF == 27:
               break
    vc.release()
    cv2.destroyAllWindows()
    

    视频:

    python-opencv直线检测+直线拟合+计算直线间距离

     

    展开全文
  • #include <QCoreApplication> #include "opencv2/opencv.hpp" using namespace cv; using namespace std;...//直线检测 int main() { src=imread("../image/8.jpg"); if(src.empty()) { print...

    在这里插入图片描述在这里插入图片描述

    #include <QCoreApplication>
    #include "opencv2/opencv.hpp"
    
    using namespace cv;
    using namespace std;
    //直线检测
    int main()
    {
        src=imread("../image/8.jpg");
        if(src.empty())
        {
            printf("could not load image ...");
            return ;
        }
        imshow("src",src);
       cvtColor(src,src,CV_BGR2GRAY);
        //裁剪图像
       // Rect rect=Rect(10,10,src.cols-20,src.rows-20);
      //  src=src(rect);
    
    
        //binary image
        Mat binary,morhpImg;
        //THRESH_BINARY_INV 返色
        //二值化
        threshold(src,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
    
        //morhpology形态学开操作
        Mat kernel=getStructuringElement(MORPH_RECT,Size(20,1),Point(-1,-1));
        morphologyEx(binary,morhpImg,MORPH_OPEN,kernel,Point(-1,-1));
    
        imshow("output",morhpImg);
        //膨胀操作
        kernel=getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
        dilate(morhpImg,morhpImg,kernel);
        imshow("output",morhpImg);
    
        vector<Vec4i> lines;
        
        HoughLinesP(morhpImg,lines,1,CV_PI/180.0,30,20.0,0);
        Mat result=src.clone();
        cvtColor(result,result,CV_GRAY2BGR);
        for(int i=0;i<lines.size();i++)
        {
            Vec4i lin=lines[i];
    
            line(result,Point(lin[0],lin[1]),Point(lin[2],lin[3]),Scalar(0,0,255),2,8,0);
        }
    imshow("output",result);
    
    return 0;
    }
    
    

    在这里插入图片描述

    展开全文
  • Python+OpenCV 直线检测

    2020-02-03 10:57:44
    1、Hough Line Transform用来做直线检测 2、前提条件——边缘检测已经完成 3、平面空间到极坐标空间转换 import cv2 as cv import numpy as np def line_detection(image): gray = cv.cvtColor(image, cv....
  • python-opencv 直线检测

    千次阅读 2019-12-10 14:21:07
    文章目录1 原理2 使用HoughLines()检测直线 1 原理 众所周知, 一条直线在图像二维空间可由两个变量表示. 例如: 在 笛卡尔坐标系: 可由参数: (m,b)(m,b)(m,b) 斜率和截距表示. 在 极坐标系: 可由参数: (r,θ)(r,\...
  • 【C++】OpenCV直线检测示例程序 by浅墨

    千次下载 热门讨论 2014-05-26 12:53:41
    我们用滑动条来控制阈值参数,利用OpenCV中的霍夫变换动态进行直线检测,得到不同效果的直线检测图。 程序的核心函数为HoughLinesP。 博文《【OpenCV入门教程之十四】OpenCV霍夫变换:霍夫线变换,霍夫圆变换合辑...
  • 感觉我学opencv就是单纯学API。。对原理还是单纯了解。。 霍夫变换 霍夫变换是图像处理中从图像中识别几何形状的基本方法之一 主要用来从图像中分离出...def line_detection(image): # 直线检测 gray = cv.cvtColor(i
  • #include "opencv2/imgproc.hpp" 类定义 cv::LineSegmentDetector Class Reference Example 官方示例地址 #include <iostream> #include <string> #include "opencv2/core/core.hpp" #include ...
  • 霍夫变换是在图像处理中进行直线、圆形检测和拟合一种非常重要的手段。无论是对直线还是圆形进行检测和拟合,霍夫变换的中心思想就是将图像像素坐标转换到参数坐标。关于直线的霍夫变换原理,下面一张图描述得非常...
  • opencv直线检测直线提取算法与总结

    万次阅读 2016-05-01 04:08:25
    有些情况, 我们会需要提取直线的详细参数, 下面介绍如何提取直线 即便是在现实中的直线, 在图像中能找到对应绝对直线的特征也是很难的, 所以一般是采用近似的方法 比如投票法(霍夫变换等), 拟合法(最小二乘,...
  • 上图是待检测的图,主要目标是识别图中填空题的下划线,这样也就找到了试卷中的答案 1.配置OpenCV 环境:Win10+VS2015 + OpenCV3.4.1 1.下载OpenCV,到官网下载相对应的版本:https://opencv.org/ 2.下载后直接解压...
  • OpenCV直线拟合检测

    2021-05-25 00:55:35
    点击上方“小白学视觉”,选择加"星标"或“置顶”重磅干货,第一时间送达 本文转自:opencv学堂OpenCV直线拟合检测霍夫直线检测容易受到线段形状与噪声的干扰而失真,...
  • OpenCV 直线和圆检测

    2021-01-20 02:16:10
    OpenCV3计算机视觉Python语言实现- 直线和圆检测直线检测代码运行结果使用到的函数分析1.概率霍夫变换-cv2.HoughLinesP圆检测代码运行结果使用到的函数分析1.霍夫圆变换-cv2.HoughCircles 本文根据《OpenCV3计算机...
  • OPENCV直线距离检测.rar

    2021-03-06 11:11:37
    本程序主要做到能自动识别直线,并测试两直线的距离
  • OpenCV检测直线

    2018-11-07 11:32:22
    OpenCV检测直线
  • OpenCV---直线检测

    2020-11-18 20:50:54
    原文链接:opencv直线检测 目录 直线检测相关  Opencv学习笔记-----霍夫变换直线检测及原理理解  OpenCV-Python教程(9、使用霍夫变换检测直线)  变换图示霍夫直线检测的两种方法  一:HoughLines霍夫...
  • OpenCV——直线检测

    千次阅读 2018-10-05 15:05:41
    直线检测可以通过OpenCV的HoughLines和HoughLinesP函数来完成,它们仅有的差别是:第一个函数使用标准的Hough变换,第二个函数使用概率Hough变换,即只通过分析点的子集并估计这些点都属于一条直线的概率,这在计算...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,370
精华内容 548
关键字:

opencv直线检测