关闭

OpenCV 霍夫变换

标签: opencv霍夫变换
175人阅读 评论(0) 收藏 举报
分类:

一. 实验内容

用OpenCV的霍夫变换来检测图片中的直线和圆。

二. 实验代码

//霍夫变换
class Task18 {
public:
    void deal() {
        Mat src_img = imread("img\\4.jpg");

        imshow("霍夫变换[原图]", src_img);

        Mat gray_img;
        cvtColor(src_img, gray_img, COLOR_BGR2GRAY);

        Mat mid_img;
        Canny(gray_img, mid_img, 50, 200, 3);
        imshow("边缘检测", mid_img);

        vector<Vec2f> lines1;

        HoughLines(mid_img, lines1, 1, CV_PI / 180, 150, 0, 0);

        Mat out1;
        out1.create(gray_img.size(), gray_img.type());
        for (int i = 0; i < lines1.size(); ++i) {
            double rho = lines1[i][0], theta = lines1[i][1];
            Point p1, p2;
            double a = cos(theta), b = sin(theta);
            double x0 = a * rho, y0 = b * rho;
            p1.x = cvRound(x0 + 1000 * (-b));
            p1.y = cvRound(y0 + 1000 * a);
            p2.x = cvRound(x0 - 1000 * (-b));
            p2.y = cvRound(y0 - 1000 * a);
            line(out1, p1, p2, 255, 1, LINE_AA);
        }

        imshow("霍夫变换[效果图1]", out1);

        vector<Vec4i> lines2;
        Mat out2;
        out2.create(gray_img.size(), gray_img.type());
        HoughLinesP(mid_img, lines2, 1, CV_PI / 180, 80, 50, 10);
        for (int i = 0; i < lines2.size(); ++i) {
            Vec4i l = lines2[i];
            line(out2, Point(l[0], l[1]), Point(l[2], l[3]), 255, 1, LINE_AA);
        }
        imshow("霍夫变换[效果图2]", out2);

        Mat src_img2 = imread("img\\5.jpg");
        imshow("霍夫圆变换[原图]", src_img2);
        Mat gray_img2;
        cvtColor(src_img2, gray_img2, COLOR_BGR2GRAY);
        GaussianBlur(gray_img2, gray_img2, Size(3, 3), 2, 2);

        vector<Vec3f> circles;
        HoughCircles(gray_img2, circles, HOUGH_GRADIENT, 1.5, 10, 200, 100, 0, 0);

        Mat out3;
        out3.create(gray_img2.size(), gray_img2.type());
        for (int i = 0; i < circles.size(); ++i) {
            Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
            int radius = cvRound(circles[i][2]);
            circle(out3, center, radius, 255, 3, 8, 0);
        }
        imshow("霍夫圆变换[效果图]", out3);

        waitKey(0);
    }
};

三. 实验结果

这里写图片描述

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:116618次
    • 积分:3220
    • 等级:
    • 排名:第10572名
    • 原创:213篇
    • 转载:3篇
    • 译文:0篇
    • 评论:36条
    最新评论