How to crop circles (found with Hough Transform) i

2019-03-01 15:08发布

问题:

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 HoughCircles() such that the code returns only 1 circle.

How can I crop my original image so that the new image has only the circle (and area within it) and save the new image as a JPEG or PNG file?

Based upon original code, the center of the circle is given by

(cvRound(circles[1][0]), cvRound(circles[1][1]));

and the radius is given by

cvRound(circles[1][2]);

回答1:

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;
}


回答2:

HoughCircles(src, circles, CV_HOUGH_GRADIENT, 1, parameter_1, parameter_2, parameter_3, parameter_4, parameter_5);

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]);
    circleroi = src(Rect(center.x - radius, coordinate
                    center.y - radius, 
                    radius *2,         
                    radius * 2));       
}


回答3:

You can define a Region of Interest (ROI) on your image based on the coordinates of the circle, then imwrite will only save the cropped portion:

cv::Rect roi(x, y, w, h); // I let you do the math ;)
cv::Mat cropped = original(roi);
cv::imwrite("cropped.png", cropped);


回答4:

To crop circle after circles=HoughCircles(...)

if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)