博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

OpenCV (十六) 霍夫变换-直线检测、圆检测

 

#include<opencv2/opencv.hpp>	
#include<iostream>

using namespace std;
using namespace cv;

Mat src, dst;

int main(int argc, char** argv) {
	src = imread("D:/OpenCVprj/image/test7.jpg");
	imshow("src", src);

	Mat src_gray;
	Canny(src, src_gray, 150, 200, 3, true);
	imshow("canny", src_gray);
	cvtColor(src_gray, dst, COLOR_GRAY2BGR);//很重要,没有后面imshow("dst", dst)会报错。因为line所画的线有颜色,图片变为BGR了!
	//imshow("wa", dst);
	Scalar color = Scalar(0, 255, 0);
	vector<Vec4f> plines;
	HoughLinesP(src_gray, plines, 1, CV_PI / 180, 10, 0, 10);
	for (size_t i = 0; i < plines.size(); i++) {
		Vec4f hline = plines[i];
		line(dst, Point(hline[0], hline[1]), Point(hline[2], hline[3]), color, 1, LINE_AA);
	}

	imshow("dst", dst);
	waitKey(0);
	return 0;
}

  

 

 

霍夫圆检测:

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace std;
using namespace cv;

Mat src, dst;

int main(int argc, char** argv) {
	src = imread("D:/OpenCVprj/image/test8.jpg");
	imshow("src", src);

	Mat median_blur, gray;
	medianBlur(src, median_blur, 3);

	cvtColor(src, gray, COLOR_BGR2GRAY);

	vector<Vec3f> circles;
	HoughCircles(gray, circles, HOUGH_GRADIENT, 1, 30, 100, 40, 10, 50);
	src.copyTo(dst);
	for (size_t i = 0; i < circles.size(); i++) {
		Vec3f c = circles[i];
		circle(dst, Point(c[0], c[1]), c[2], Scalar(0, 0, 255), 2, LINE_AA);
		circle(dst, Point(c[0], c[1]), 2, Scalar(255, 0, 255),2, LINE_AA);
	}
	imshow("dst", dst);
	waitKey(0);
	return 0;
}

  

  

 

posted @ 2019-07-25 20:45  haibochina  阅读(337)  评论(0编辑  收藏  举报