select all pixels from x,y in an image by 20 pixels radially in matlab in matlab

To select all pixels from a given point (x,y) in an image by 20 pixels radially, we can convert the Cartesian coordinates to polar coordinates, then loop over the polar radius r from 0 to 20 pixels, and for each radius r, select all the pixels lying on a circle of radius r centered at the point (x,y) in the image.

Here's a sample code that does that:

main.m
%// read the image (replace with your own image file)
img = imread('cameraman.tif');

%// parameters
x = 100;    %// x-coordinate of the center point
y = 100;    %// y-coordinate of the center point
r_max = 20; %// maximum radial distance

%// get image size
[height, width] = size(img);

%// convert cartesian (x,y) to polar (theta,r) coordinates
[xx,yy] = meshgrid(1:width, 1:height);
[theta, r] = cart2pol(xx-x, yy-y);

%// initialize the mask
mask = false(size(img));

%// loop over each radius from 0 to r_max, and select all pixels on the circle
for r_i = 0:r_max
    %// find all pixels lying on the circle of radius r_i
    idx = abs(r - r_i) < 0.5; %// allow for some tolerance in rounding errors
    
    %// set the mask for these pixels to true
    mask(idx) = true;
end

%// apply the mask to select the pixels
pixels = img(mask);
844 chars
30 lines

The above code reads an image (replace with your own image file), sets the x and y coordinates of the center point, and the maximum radial distance to 20 pixels. Then, it converts the Cartesian (x,y) coordinates to polar (theta,r) coordinates using the cart2pol function.

Next, it initializes a binary mask mask that has the same size as the image, and sets all its elements to false. Then, it loops over each radius from 0 to r_max, and for each radius, finds all pixels lying on a circle of radius r_i using the abs(r - r_i) < 0.5 condition that checks if the distance r from the center point is within 0.5 of the target radius r_i. Note that we allow for some tolerance in rounding errors by using the < operator instead of ==. Finally, we set the mask for these pixels to true.

After the loop, the mask mask contains true values for all pixels lying within 20 pixels radially from the center point (x,y) of the image. We can then apply this mask to select the pixels using the standard indexing syntax img(mask).

gistlibby LogSnag