15

I have this:

enter image description here

And I need to know all pixels in array inside the circle.

Thanks.

Eli Lansey
  • 1,130
  • 2
  • 15
  • 28
Yuri Morales
  • 2,351
  • 4
  • 25
  • 52

2 Answers2

25

You are looking for the following set of pixels:

Circle equation

with r being the radius of your circle and (m1, m2) the center.

In order to get these pixels iterate over all positions and store those which meet the criteria in a list:

List<int> indices = new List<int>();

for (int x = 0; x < width; x++)
{
    for (int y = 0; y < height; y++)
    {
        double dx = x - m1;
        double dy = y - m2;
        double distanceSquared = dx * dx + dy * dy;

        if (distanceSquared <= radiusSquared)
        {
            indices.Add(x + y * width);
        }
    }
}
Lucius
  • 3,705
  • 2
  • 22
  • 41
  • 5
    You're welcome. By the way, you can speed things up by only iterating over the pixels in the bounding rectangle of the circle. – Lucius Jan 23 '13 at 19:50
  • Does approach include border pixels? – POV Aug 20 '17 at 23:05
  • @OPV If we define a border pixel as one that satisfies (x-m1)²+(y-m2)²=r² you can include them if you check with "less than or equal" (<=) and exclude them if you check for "less than" (<). – Lucius Aug 21 '17 at 10:45
  • Than how to resolve this the equation when I have two undefined variables? – POV Aug 21 '17 at 12:22
  • @OPV There aren't any undefined variables, or equations to solve. See the code above. – Jim Balter Oct 14 '17 at 21:07
  • This code is really amazing! Very clever!! I was wondering if there is any faster way in order to check if a randomly chosen point (pixel) in the image is inside or outside the circle without having to run through the hole image? – just_learning Mar 06 '22 at 18:38
  • 1
    @just_learning Thanks, and of course there is a faster way. If you have a random point, just check it using the condition above. No iteration required. – Lucius Mar 06 '22 at 21:39
1

Shouldn´t this be an more efficient approach? (Don't iterating over the whole picture, just the desired square)

List<int> indices = new List<int>();

xmin = m1 - r;
xmax = m1 + r;
ymin = m2 - r;
ymax = m2 + r;

for (int x = xmin; x < xmax ; x++)
{
    for (int y = ymin; y < ymax; y++)
    {
        double dx = x - m1;
        double dy = y - m2;
        double distanceSquared = dx * dx + dy * dy;

        if (distanceSquared <= radiusSquared)
        {
            indices.Add(x + y * width);
        }
    }
}
Blanko
  • 11
  • 2