opencv 直线检测 HoughLines HoughLinesP

#include "iostream"
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

void drawline(Mat img, vector lines, double rows, double cols,Scalar scalar)
{
	Point p1, p2;
	for (int i = 0; i < lines.size(); i++)
	{
		float jl = lines[i][0];
		float jd = lines[i][1];
		double a = cos(jd);
		double b = sin(jd);

		double x0 = jl * a;
		double y0 = jl * b;

		double len = max(rows, cols);
		p1.x = cvRound(x0 + len * (-b));
		p1.y = cvRound(y0 + len * a);

		p2.x = cvRound(x0 - len * (-b));
		p2.y = cvRound(y0 - len * a);

		line(img, p1, p2, scalar);
	}
}

int main()
{
	Mat  img,smallimg,gray, edge,gau, smallimg1, smallimg2, smallimg3, smallimg4;

	img = imread("shubiaodian.jpg");

	resize(img, smallimg, Size(0, 0), 0.1, 0.1);

	smallimg.copyTo(smallimg1);
	smallimg.copyTo(smallimg2);
	smallimg.copyTo(smallimg3);
	smallimg.copyTo(smallimg4);
	cvtColor(smallimg, gray, COLOR_BGR2GRAY);
	GaussianBlur(gray, gau, Size(3, 3), 5, 5);

	Canny(gau, edge, 150, 255);

	vector lines1;
	vector lines2;

	HoughLines(edge, lines1, 1, CV_PI * 2 / 180, 30);
	HoughLines(edge, lines2, 1, CV_PI * 2 / 180, 80);

	drawline(smallimg1, lines1, edge.rows, edge.cols, Scalar(0, 0, 255));
	drawline(smallimg2, lines2, edge.rows, edge.cols, Scalar(0, 0, 255));

	vector lines3;
	vector lines4;

	HoughLinesP(edge, lines3, 1, CV_PI / 180, 30, 0, 10);
	HoughLinesP(edge, lines4, 2, CV_PI / 180, 60, 150, 80);

	cout << "lines1:" << lines1.size() << endl;
	cout << "lines2:" << lines2.size() << endl;
	cout << "lines3:" << lines3.size() << endl;
	cout << "lines4:" << lines4.size() << endl;
	for (int i = 0; i < lines3.size(); i++)
	{
		line(smallimg3, Point(lines3[i][0], lines3[i][1]), Point(lines3[i][2], lines3[i][3]), Scalar(0,0,255));
	}
	for (int i = 0; i < lines4.size(); i++)
	{
		line(smallimg4, Point(lines4[i][0], lines4[i][1]), Point(lines4[i][2], lines4[i][3]), Scalar(0,0,255));
	}

	imshow("smallimg", smallimg);
	imshow("canny", edge);
	imshow("smallimg1", smallimg1);
	imshow("smallimg2", smallimg2);
	imshow("smallimg3", smallimg3);
	imshow("smallimg4", smallimg4);

	waitKey(0);

	return 1;
}

opencv 直线检测 HoughLines HoughLinesP_第1张图片

opencv 直线检测 HoughLines HoughLinesP_第2张图片

opencv 直线检测 HoughLines HoughLinesP_第3张图片

你可能感兴趣的:(Opencv,opencv,人工智能,计算机视觉)