OpenCV finds the circle in the picture and marks the center of the circle

1 Overview

  Case: Enter a picture to find a circle in the picture, and mark the center of the circle

  Implementation steps:

    1. Input the original image

    2. Image image grayscale

    3. Image binarization

    4. Perform morphological operations to remove noise

    5. Edge detection

    6. Contour Discovery

    7. Filter object contours based on area and aspect ratio

    8. Find the center of the circle and draw the center of the circle

    9. Draw the center of the circle on the original image and output it

2. Code example

//【1】载入图像
    Mat src = imread(filePath);
    Mat src_clone = src.clone();
    if(src.empty()){
        qDebug()<<"图片为空";
        return;
    }
    imshow("src",src);
    //21】转灰度图
    Mat gray;
    cvtColor(src,gray,COLOR_BGR2GRAY);
    //【3】图像二值化
    threshold(gray,gray,0,255,THRESH_BINARY|THRESH_OTSU);
    imshow("threshold",gray);
    //【4】执行形态学开操作去除噪点
    Mat kernel = getStructuringElement(MORPH_RECT,Size(20,20),Point(-1,-1));
    morphologyEx(gray,gray,MORPH_OPEN,kernel,Point(-1,-1),1);
    imshow("morphologyEx",gray);

    //【5】边缘检测
    Canny(gray,gray,0,255);
    imshow("canny",gray);

    //【6】轮廓发现
    vector<vector<Point>> contours;
    vector<Vec4i> her;
    findContours(gray,contours,her,RETR_TREE,CHAIN_APPROX_SIMPLE);
    Mat resultImage = Mat::zeros(gray.size(),CV_8UC3);
    RNG rng(12345);
    double area = 0.0;
    Point pRadius;
    for(size_t i = 0;i<contours.size();i++){
        double area = contourArea(contours[i],false);
         //【7】根据面积及纵横比过滤轮廓
        if(area>200){
            Rect rect = boundingRect(contours[i]);
            float scale = float(rect.width)/float(rect.height);
            if(scale<1.1&&scale>0.9){
                drawContours(resultImage,contours,i,Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)),-1);
                int x = rect.width/2;
                int y = rect.height/2;
                 //【8】找出圆心并绘制
                pRadius=Point(rect.x+x,rect.y+y);
                circle(resultImage,pRadius,2,Scalar(0,0,255),2);
            }
        }

    }
     imshow("resultImage",resultImage);
    //【9】在原图上绘制圆心,这一步要不要都行,因为坐标都找出来了,可以随便标注
    circle(src_clone,pRadius,2,Scalar(0,0,255),2);
    imshow("src_clone",src_clone);

3. Picture example

 The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_60259116/article/details/129047762