spaderdabomb
spaderdabomb

Reputation: 942

Creating a circular mask for my graph

I'm plotting a square image, but since my camera views out of a circular construction, I want the image to look circular as well. So to do this, I just wanted to create a mask for the image (basically create a matrix, and multiply my data by the mask, so if I want to retain my image I am multiplying by one, and if I want that part of the image to go to black, I multiply by 0).

I'm not sure the best way to make a matrix that will represent a circular opening though. I just want every element within the circle to be a "1" and every element outside the circle to be a "0" so I can color my image accordingly. I was thinking of doing a for loop, but I was hoping there was a faster way to do it. So...all I need is:

My attempt

mask = zeros(1280,720)
for i = 1:1280
    for j = 1:720
        if i + j > 640 && i + j < 1360
            mask(i,j) = 1;
        end
    end
end

Well the above obviously doesn't work, I need to look at it a little better to form a better equation for determing when to add a 1 =P but ideally I would like to not use a for loop

Thanks, let me know if anything is unclear!

Upvotes: 3

Views: 6480

Answers (2)

PeterM
PeterM

Reputation: 2692

@kol 's answer looks correct. You can do this with vectorized code using the meshgrid function.

width = 1280;
height = 720;
radius = 360;
centerW = width/2;
centerH = height/2;
[W,H] = meshgrid(1:width,1:height);
mask = ((W-centerW).^2 + (H-centerH).^2) < radius^2;

Upvotes: 10

kol
kol

Reputation: 28688

Here is a possible solution:

width = 160;
height = 120;
mask = zeros(width, height);

center_x = width / 2;
center_y = height / 2;
radius = min(width, height) / 2;
radius2 = radius ^ 2;
for i = 1 : width
  for j = 1 : height
    dx = i - center_x;
    dy = j - center_y;
    dx2 = dx ^ 2;
    dy2 = dy ^ 2;
    mask(i, j) = dx2 + dy2 <= radius2;
  end;
end;

picture = randn(width, height); % test image :)
masked_image = picture .* mask;
imagesc(masked_image);

Upvotes: 1

Related Questions