Zetland
Zetland

Reputation: 567

How to get the values of a circle of pixels on an image?

I'm currently using MatLab as part of a Digital Imaging course and trying to get the values of a circle of pixels on an image. The idea is to start with a central pixel (x, y) and then collect all of the pixels with the radius r and return their values.

So far, all I've managed to create is this (where A_grey is an image):

function [localMean] = getLocalMean(x, y, radius)
for x = 1:size(A_grey, 1)
    for y = 1:size(A_grey, 2)
       <code> 
    end
end

But I'm not entirely sure what I'm doing and I could really do with some beginner level advice here. Any tips?

Upvotes: 0

Views: 2330

Answers (1)

rayryeng
rayryeng

Reputation: 104555

I'll throw you a bone. This is actually quite easy. Given the size of the image / viewing window, stored in width and height that you want to examine, generate a meshgrid of points, then search for those (x,y) values that satisfy the equation of the circle. In other words, you want to search for all (x,y) values given a centre of your circle (x0,y0) such that:

(x - x0)^2 + (y - y0)^2 = r^2

r is the radius of your desired circle. As such, it's as simple as:

[x,y] = meshgrid(1:width, 1:height);
p = (x - x0).^2 + (y - y0).^2 == r^2;
pts = [x(p) y(p)];

We first generate a meshgrid of points. Think of a meshgrid as a set of 2D arrays where each unique spatial location in the same spot of these arrays gives you the x and y coordinates at that spatial location in 2D. Take a look at the following example:

[x,y] = meshgrid(1:3, 1:3)

x =

     1     2     3
     1     2     3
     1     2     3


y =

     1     1     1
     2     2     2
     3     3     3

In terms of pixel coordinates, the top-left corner is (x,y) = (1,1). The top right corner is (x,y) = (3,1) and so on. Note that the convention is that x is horizontal while y is vertical, as what most digital image processing literature will give you. If this is not what you want, replace meshgrid with ndgrid to respect the row/column convention.

Once we generate this grid of points, we simply put this through our circle equation and see which values of (x,y) at a given centre (x0,y0) satisfy the equation of the circle. Once we find such locations, we simply index into our meshgrid of points and return those (x,y) values, corresponding to those points that lie along the perimeter of your circle.

Upvotes: 3

Related Questions