How to crop circles (found with Hough Transform) in OpenCV?

前端 未结 4 1718
轻奢々
轻奢々 2021-01-25 13:04

I\'m using the code from the page. It works very well and I get a circle that I am looking for. All my image have only 1 circle and I have modified parameters of HoughCirc

4条回答
  •  情话喂你
    2021-01-25 13:36

    You should use copyTo with a mask to retrieve the part of image inside the circle, and then you can crop according to the bounding box of the circle.

    You save images with imwrite.

    This small example should get you started.

    #include "opencv2/opencv.hpp"
    using namespace cv;
    
    int main()
    {
        // Your initial image
        Mat3b img = imread("path_to_image");
    
        // Your Hough circle
        Vec3f circ(100,50,30); // Some dummy values for now
    
        // Draw the mask: white circle on black background
        Mat1b mask(img.size(), uchar(0));
        circle(mask, Point(circ[0], circ[1]), circ[2], Scalar(255), CV_FILLED);
    
        // Compute the bounding box
        Rect bbox(circ[0] - circ[2], circ[1] - circ[2], 2 * circ[2], 2 * circ[2]);
    
        // Create a black image
        Mat3b res(img.size(), Vec3b(0,0,0));
    
        // Copy only the image under the white circle to black image
        img.copyTo(res, mask);
    
        // Crop according to the roi
        res = res(bbox);
    
        // Save the image
        imwrite("filename.png", res);
    
        // Show your result
        imshow("Result", res);
        waitKey();
    
        return 0;
    }
    

提交回复
热议问题