1.概率霍夫变换
HoughLinesP能够检测出线端,即能够检测出图像中直线的两个端点,确切地定位图像中的直线。
void HoughLinesP(InputArray image,
OutputArray lines,
double rho,
double theta,
int threshold,
double minLineLength=0,
double maxLineGap=0 )
image为输入图像,要求是8位单通道图像
lines为输出的直线向量,每条线用4个元素表示,即直线的两个端点的4个坐标值
rho和theta分别为距离和角度的分辨率
threshold为阈值,即步骤3中的阈值
minLineLength为最小直线长度,在步骤5中要用到,即如果小于该值,则不被认为是一条直线
maxLineGap为最大直线间隙,在步骤4中要用到,即如果有两条线段是在一条直线上,但它们之间因为有间隙,所以被认为是两个线段,如果这个间隙大于该值,则被认为是两条线段,否则是一条。
首先来检测棋盘的竖直线段:
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src=imread("D://vvoo//qipan.jpg");
Mat gray,canny;
cvtColor(src,gray,CV_RGB2GRAY);
Canny(gray,canny,50,100);
//imshow("canny",canny);
vector<Vec4i> lines;
HoughLinesP(canny,lines,1,CV_PI/180,20,20,600);
//select approprivate lines acoording to the slope
for (int i = 0;i < lines.size();i ++)
{
Vec4i I=lines[i];
int dx=I[2]-I[0];
int dy=I[2]-I[1];
double angle = atan2(double(dy),dx) * 180 /CV_PI;
if (abs(angle) <= 20) // reject near horizontal lines
continue;
if((I[1]>I[3]+90)||(I[1]<I[3]-90))//the height of two points should more than 90 pixels
{
line(src,Point(I[0],I[1]),Point(I[2],I[3]),Scalar(0,0,255),1,CV_AA);
}
}
//vector
lines;
//HoughLinesP(canny,lines,1,CV_PI/180,20,200,1000); //horizontal
//select approprivate lines acoording to the slope
//for (int i = 0;i < lines.size();i ++)
//{
//Vec4i I=lines[i];
//int dx=I[2]-I[0];
//int dy=I[3]-I[1];
//double angle = atan2(double(dy),dx) * 180 /CV_PI;
//if (abs(angle) >=5) // reject near horizontal lines
// continue;
// if((I[0]>I[2]+90)||(I[0]<I[2]-90))//the height of two points should more than 90 pixels
// {
//line(src,Point(I[0],I[1]),Point(I[2],I[3]),Scalar(0,0,255),2,