Bartrae
Bartrae

Reputation: 37

OpenCV HoughCircles detecting only 1 circle

I am trying to detect and localise and pick up blue marbles. The aim of my project is to detect only 1 marble at a time. For my detection I am using the HoughCircles function from OpenCV. I would like to the code to give me the X and Y position only the first detected circle.

This is the code that I use for this:

vector<Vec3f> circles;
HoughCircles(OutputImage, circles, HOUGH_GRADIENT, 1,
    OutputImage.rows / rows,      //change to detect circles that are closer to eachother
    para1, para2, minRad, maxRad);        //chang last to parameters to detect larger or smaller circles


for (size_t i = 0; i < circles.size(); i++)
{
    Vec3i c = circles[i];
    Point center = Point(c[0], c[1]);
    // circle center
    circle(imgHSV, center, 1, Scalar(0, 255, 0), 3, LINE_AA);
    // circle outline
    int radius = c[2];
    circle(imgHSV, center, radius, Scalar(255, 0, 0), 3, LINE_AA);

    cout << "The center of the detection is located at pixel: " << Point(c[0], c[1]) << endl;

    x = c[0];
    y = c[1];


}

However this still detects all circles and print out the X, Y info for all circles. I have tried changing circles.size() to 1 in the for loop but this gives me the following error: Expression: vector subscript out of range

Would anyone here be able to help me, this is my first OpenCV application, so sorry if I'm misunderstanding things.

If you need my complete code feel free to ask.

Upvotes: 0

Views: 962

Answers (2)

Emile
Emile

Reputation: 11721

Well, circles will contain however many circles HoughCircles() finds. WHich could be >=0.

The for{} loop is looping through circles and reporting the details for each one. So essentially you could either break; out of the loop. i.e.

for (size_t i = 0; i < circles.size(); i++)
{
     ...
     break; /// i think this works in c++
}

or change the for loop for a simple conditional check

if (circles.size() > 0)
{
   Vec3i c = circles[0];
   ...
}

Upvotes: 0

RoQuOTriX
RoQuOTriX

Reputation: 3001

The method HoughCircles gaves you all the found circles:

To access the "first" circle you would do:

if(circles.size() > 0) {
    Vec3i c = circles.at(0);
    Point center = Point(c[0], c[1]);
    // circle center
    circle(imgHSV, center, 1, Scalar(0, 255, 0), 3, LINE_AA);
    // circle outline
    int radius = c[2];
    circle(imgHSV, center, radius, Scalar(255, 0, 0), 3, LINE_AA);

    cout << "The center of the detection is located at pixel: " << Point(c[0], c[1]) << endl;

    x = c[0];
    y = c[1];
}

But your question seems to me, that you don't understand the C++ code you wrote...

Upvotes: 1

Related Questions