MATLAB: how do I crop out a circle from an image
11,960
One way to do this is to create a binary mask with ones inside the circle and zeros outside. You can then use this array to either mask everything outside the circle with NaNs, or to read the pixel values of the image inside the mask.
To create a circle mask, an easy way is to create coordinate arrays centered on the iris, and threshold the distance, like this:
[xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));
mask = (xx.^2 + yy.^2)<ci(3)^2;
Related videos on Youtube
Author by
Leo.peis
Updated on June 04, 2022Comments
-
Leo.peis almost 2 years
I need to crop a circle in MATLAB.
I need to perform iris segmentation, and I´ve identified the center point and the radius of the iris, and I need to cut it off from the image.
I have a vector ci that ci(1) is X-coordinate ci(2) is Y-coordinate and ci(3) is the radius of the circle.
-
Marnix over 13 yearsThere goes my answer... =) Very nice. +1. In order to segment the image, just multiply it with the mask. Let there be zeros on the outside.
-
Jonas over 13 years@Marnix: Sorry :). Anyway, I suggest putting NaNs outside, such as
image(~mask) = NaN;
, so that the autoscale inimshow(image,[])
doesn't get thrown off by all the zeros in the image. -
Leo.peis over 13 yearsI have this error: ??? Undefined function or method 'sqrt' for input arguments of type 'logical'. in this line mask = sqrt((xx.^2 + yy.^2)<ci(3));
-
Jonas over 13 years@Leo.peis: sorry, was a parenthesis error. Actually, it's not even necessary to take the square root (you can just square the radius instead for the circle inequality), so I fixed it like that.
-
Tin about 10 years@Jonas thanks for your code! I'm trying to optimize a function that is taking to much time to compute and it's based on circular neighboorhoods. More precisely, I've different circular neighboorhoods and inside of each of them, I want to compute the mean, std, and median of the pixel values underlying them. This is done in the context of the DoG scale representation. The size of the circular filter is given by radius associated at a specific scale (
scalespace_radii
): pastebin.com/WkS5ShMf Any suggestion on how to improve the computation is welcomed! -
Jonas about 10 years@tin: I suggest you ask this as a question on this site, which will allow me, and others, to respond with enough space.
-
Tin about 10 years@Jonas, thanks for your suggestion :-) I posted already the question in => stackoverflow.com/questions/21724404/…