PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

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

 July 28, 2022     c++, crop, geometry, image, opencv     No comments   

Issue

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]);

Solution

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


Answered By - Miki
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing