1
votes

As part of a circle recognition program, I have a background image with a geometrical circle with known coordinates and radius. I want the inside part of the circle filled by an image and the outside left alone. My best idea is some sort of circular mask, but I am not sure this is the best approach. Any suggestions?

X = imread('X.jpg'); % Background image jpg
Y = imread('Y.jpg'); % Filling image jpg
cent = [100,100]; % Center of circle
rad = 20; % Circle radius

% Fill circle ?
...

I have not provided the extended code, due to confidentiality.

1
Are the dimensions of the filling in image Y the same as the circle? Do you want the entire image Y to be filled inside the circle that is inside X? - rayryeng

1 Answers

3
votes


I think the hard part was done by whomever authored this: http://matlab.wikia.com/wiki/FAQ#How_do_I_create_a_circle.3F

Assumptions:

  • I'm assuming you're not going to specify points that are out of range of the image (i.e. I'm not adding validation here).
  • I use the background image to relate the "center" of your circle to the coordinates.
  • I'm assuming radius is in pixels.
  • I didn't create a background image with a circle of known radius because I don't think that's necessary to create the filling effect you're looking for (unless I'm missing something).

Code:

X = imread('rdel_x.png'); % Background image jpg (I used a random image but this can be your blank + geometric circle)
Y = imread('rdel_y.png'); % Filling image jpg
cent = [100,150]; % Center of circle
rad = 70; % Circle radius

% make a mesh grid to provide coords for the circle (mask)
% taken from http://matlab.wikia.com/wiki/FAQ#How_do_I_create_a_circle.3F
[columnsInImage rowsInImage] = meshgrid(1:size(X,2), 1:size(X,1));

% circle points in pixels:
circlePixels = (rowsInImage - cent(1)).^2 ...
    + (columnsInImage - cent(2)).^2 <= rad.^2;
circlePixels3d=repmat(circlePixels,[1 1 3]); % turn into 3 channel (assuming X and Y are RGB)


X((circlePixels3d)) = Y((circlePixels3d)); % assign the filling image pixels to the background image for pixels where it's the desired circle
imagesc(X);
axis image off

Result: from left to right, background image, filling image, result from above code.

enter image description here

Edit: you might not even need the background image if everything is encapsulated in your coordinates. e.g. try appending this to the above code...

Z=zeros(size(X),'uint8'); % same size as your background
Z(circlePixels3d) = Y(circlePixels3d);
figure; % new fig
imagesc(Z);
axis image off

enter image description here