Reputation: 21
I have an image full of objects of the shape of an ellipse. I need to design an ellipse for each object that is the best fit for the object itself. I have found a code that helps me to plot the ellipses on the image here.
I have changed the final part saving x
and y
in a 3D matrix (one dimension for x
, the other for y
, and the 3rd for the number of objects). Because this code is in a for
loop, I do not want to generate the figure plot ellipses on top of it, save it and upload with imread
to pass it to the rest of the code.
Is there a way to convert this 3D matrix in a bw image full of the fitting ellipses in the correct position in the image?
Upvotes: 2
Views: 704
Reputation: 51224
Ellipses are drawn on top of the existing figure because of the hold on
statement after the image is shown using imshow
. So, instead of this:
imshow(bw)
hold on
Simply create a new figure using the figure
statement:
figure
[Edit]
Ok, first of all, storing only (x, y)
gives you ellipse centers only. To draw an ellipse, you will also need to store its majos/minor axis size (a
, b
) and its orientation angle (theta
).
I would simply reuse the loop that you already have, but replace plot
with simply setting a bw image pixel to 1 for each coordinate:
% get image dimensions
dim = size(bw);
% preallocate a blank bw image
target = false(dim);
% for each ellipse
for k = 1:length(s)
% this part remains the same:
xbar = s(k).Centroid(1);
ybar = s(k).Centroid(2);
a = s(k).MajorAxisLength/2;
b = s(k).MinorAxisLength/2;
theta = pi*s(k).Orientation/180;
R = [ cos(theta) sin(theta)
-sin(theta) cos(theta)];
xy = [a*cosphi; b*sinphi];
xy = R*xy;
x = xy(1,:) + xbar;
y = xy(2,:) + ybar;
% ----------
% but replace plot(x,y) with this:
% limit to image dimensions (1:256)
x(x<1) = 1; x(x>dim(1))=dim(1);
y(y<1) = 1; y(y>dim(2))=dim(2);
% set those pixels to 1
target(sub2ind(dim, round(x),round(y))) = 1;
end
imshow(target);
Right now, there are ellipses which are half outside the image boundaries. That's why their x,y coordinates need to be limited to (1:256); otherwise you get an out-of-range error. You still need to rethink whether these ellipses should be removed entirely, or drawn partially as done here.
Upvotes: 1