MATLAB: Image processing crop along boundaries

Image Processing Toolbox

Hi guys, I would like some tips to solve this problem. Thank for your help.
I have an image with some geometrical figures in it. I would like to obtain a new image with only the geometrical figures in it ( neglecting the backround). I also want to keep the intensity information of the starting image for the area inside the geometrical figures.
ps: i need to imbinarize the starting picture cause switching to gray image and thresholding the values doesn't work as desired.
I will attach my script.

Best Answer

You forgot to attach tt so we can't see the image or the background. Please attach it. Is it being binarized properly?
You'll probably need to use "hold on" BEFORE you call plot so that you don't blow away the image.
And instead of axis square, you need to use
axis('on', 'image')
And I don't think the call to view() is needed.
Don't use image as the name of your variable since it's the name of a built-in function.
Finally you'll need to crop the image
originalImage = imread('tt');
hFig = figure
h1 = subplot(1, 3, 1);
imshow(originalImage);
BW = imbinarize(originalImage);
BW = bwareaopen(BW,500);
subplot(1, 3, 2);
imshow(BW)
% Make measurements.
props = regionprops(BW, 'BoundingBox');
B = bwboundaries(BW);
hold(h1, 'on');
for k=1:length(B)
% Display boundary in red over the original image.
boundary = B{k};
subplot(1, 3, 1);
plot(boundary(:,2), boundary(:,1), 'r-', 'LineWidth', 2);
axis('on', 'image');
% Display bounding box over image.
thisBB = props(k).BoundingBox;
rectangle('Position', thisBB, 'EdgeColor', 'y');
% Get a cropped image.
croppedImage = imcrop(originalImage, thisBB);
% Display the cropped image.
subplot(1, 3, 3);
imshow(croppedImage);
drawnow;
hFig.WindowState = 'maximized'
pause(0.7);
end