Randomly position an ellipse and create a cutout
Show older comments
I am attempting to randomly position ellipses onto an image and create cut outs from them (the end goal is to create multiple ellipse cutouts from the image). I have previously found imellipse - however my code is getting stuck whilst waiting for the position I think (orignally from a previous Ask https://au.mathworks.com/matlabcentral/answers/335146-how-can-i-automatically-crop-an-image-in-an-elliptical-shape )
I=imread('background.png');
h = imshow(I) ;
%%call imellipse
% set some positon for ellipse
x = 100;
y = 150;
d1 = 10;
d2 = 100;
e = imellipse(gca, [x y d1 d2]);
% wait to change the positon
position = wait(e);
% update the positon
pos = getPosition(e);
x = pos(1);
y = pos(2);
d1 = pos(3);
d2 = pos(4);
%
BW = createMask(e,h);
% here assuming your image is uint8
BW = uint8(BW);
I2 = I.*BW; % everything outside circle to black
imwrite(I2,'oval_cropped.png','Transparency',0);
I also found from searching Random2d which allows me to randomly position a rectangle onto the image as well as use it to create crops ( https://au.mathworks.com/help/images/ref/randomwindow2d.html )
I = imread("background.png");
imshow(I)
inputSize = size(I);
targetSize = [40 60];
rect = randomWindow2d(inputSize,targetSize);
rectXYWH = [rect.XLimits(1) rect.YLimits(1) ...
diff(rect.XLimits)+1 diff(rect.YLimits)+1];
annotatedI = insertShape(I,"rectangle",rectXYWH,"LineWidth",3);
imshow(annotatedI)

Answers (1)
Depending on what you mean by "crop", this may suffice:
That uses a joke tool to create a mask containing arbitrarily positioned/rotated ellipses (and other shapes), and it doesn't require figure thrashing or manual user interaction.
If you're after something else, you'll need to elaborate.
Categories
Find more on Blocked Images in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!