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

本文详细介绍使用OpenCV实现霍夫圆检测的过程,通过代码示例展示了如何从图像中检测圆形物体,包括图像预处理、霍夫圆变换参数设置及结果可视化。适用于计算机视觉和图像处理领域的初学者和开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

using namespace cv;
using namespace std;


int main(int argc, char** argv)
{
    Mat src, src_gray, dst;
    src = imread("test1.jpg");

    char INPUT_TITLE[] = "input image";

    imshow(INPUT_TITLE, src);

    Canny(src, src_gray, 150, 200);
    cvtColor(src_gray, dst, CV_GRAY2BGR);
    imshow("edge image", src_gray);
    imshow("gray", dst);

    //方法1(标准霍夫变换)
    //vector<Vec2f> lines;
    //HoughLines(src_gray, lines, 1, CV_PI / 180, 150, 0, 0);
    //for (size_t i = 0; i < lines.size(); i++) {
    //    float rho = lines[i][0]; // 极坐标中的r长度
    //    float theta = lines[i][1]; // 极坐标中的角度
    //    Point pt1, pt2;
    //    double a = cos(theta), b = sin(theta);
    //    double x0 = a * rho, y0 = b * rho;
    //    // 转换为平面坐标的四个点
    //    pt1.x = cvRound(x0 + 1000 * (-b));//对一个double型的数进行四舍五入,并返回一个整型数!
    //    pt1.y = cvRound(y0 + 1000 * (a));
    //    pt2.x = cvRound(x0 - 1000 * (-b));
    //    pt2.y = cvRound(y0 - 1000 * (a));
    //    line(dst, pt1, pt2, Scalar(0, 0, 255), 1, CV_AA);
    //}


    //第二种方法(概率霍夫变换)
    vector<Vec4f> plines;
    HoughLinesP(src_gray, plines, 1, CV_PI / 180.0, 10, 0, 10);
    Scalar color = Scalar(0, 0, 255);
    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, 3, LINE_AA);
    }

    imshow("效果图",dst);

    waitKey(0);
    return 0;

}

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

using namespace cv;
using namespace std;


int main(int argc, char** argv)
{
    Mat src, src_gray;
    src = imread("3 input.bmp");

    char INPUT_TITLE[] = "input image";

    imshow(INPUT_TITLE, src);

  //转成灰度图
    cvtColor(src, src_gray, COLOR_BGR2GRAY);

    GaussianBlur(src_gray, src_gray, Size(9, 9), 2, 2);

    //进行霍夫圆变换
    vector<Vec3f> circles;
    HoughCircles(src_gray, circles, HOUGH_GRADIENT, 1.5, 10, 200, 100, 0, 0);

    for (size_t i = 0; i < circles.size(); i++)
    {
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
        int radius = cvRound(circles[i][2]);
            //绘制圆心
        circle(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);       //绘制圆的轮廓
        circle(src, center, radius, Scalar(155, 50, 255), 3, 8, 0);

    }

    imshow("效果图", src);

    waitKey(0);
    return 0;

}

霍夫圆检测一般只会找出最大的一个圆

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值