Assign values outside a circle in an image to zero

10 views (last 30 days)
Hello everyone,
I have this image generated from a camera, which is a 2048 by 2048 matrix, called meanB. Each cell in the matrix has its own value, but I have to set the values outside the circle, as shown in the diagram to zero.
I know the centre coordinate of the image (1024,1024), and I know the radius of the circle (1024).
Does any one have any suggestion?
Kind regards,

Accepted Answer

Image Analyst
Image Analyst on 23 Nov 2022
Edited: Image Analyst on 23 Nov 2022
That's answered in the FAQ:
% Create a logical image of a circle with specified
% diameter, center, and image size.
% First create the image.
imageSizeX = 2048;
imageSizeY = 2048;
[columnsInImage rowsInImage] = meshgrid(1:imageSizeX, 1:imageSizeY);
% Next create the circle in the image.
centerX = 1024;
centerY = 1024;
radius = 1024;
circlePixels = (rowsInImage - centerY).^2 ...
+ (columnsInImage - centerX).^2 <= radius.^2;
% circlePixels is a 2D "logical" array.
% Now, display it.
image(circlePixels) ;
colormap([0 0 0; 1 1 1]);
title('Binary image of a circle');
Now that you have the circle mask, you can use it to blacken outside of the original RGB or gray scale image.
% Mask image by multiplying each channel by the mask.
maskedRgbImage = rgbImage .* cast(~mask, 'like', rgbImage); % R2016b or later. Works for gray scale as well as RGB Color images.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!