MATLAB: How to crop only selected part of an image automatically

croppingdigital image processingimage processingimage segmentation

I have some image, from this image I need to identify only some portion that's mean segmentation. After identification, I need to crop this portion automatically. I found some code for automatically cropping but don't work exactly what I want! In my dataset images are different and for that reasons, segmented images also different. For example, a pre-processed image is first one and I need to detect the image in that way, an example is the second one.
Now I want to crop the right image automatically only segmented area.
In my code, it cropped incorrectly different region :(.
In my dataset images is different one from another!
My code is given below:
close all;
I=imread('CL_2_2.jpg');
figure, imshow(I);
I=rgb2gray(I);
BW=I>100;
figure,imshow(BW);
labeledImage = bwlabel(BW);
measurements = regionprops(labeledImage, 'BoundingBox', 'Area');
for k = 1 : length(measurements)
thisBB = measurements(k).BoundingBox;
I2=imcrop(I,[thisBB(1),thisBB(2),thisBB(3),thisBB(4)]);
[rows cols depth]=size(I2);
if rows*cols>200
I2=imresize(I2,[28 28]);
figure,imshow(I2);
end
end

Best Answer

Hi It works. But you have used imresize and have changed the segments. Also your threshold for segments sizes (200) may be large. For showing smaller objects you should take it smaller. I tried this and it worked:
close all;
I=imread('CL_2_2.jpg');
figure, imshow(I);
I=rgb2gray(I);
BW=I>100;
figure,imshow(BW);
labeledImage = bwlabel(BW);
measurements = regionprops(labeledImage, 'BoundingBox', 'Area');
for k = 1 : length(measurements)
thisBB = measurements(k).BoundingBox;
I2=imcrop(I,[thisBB(1),thisBB(2),thisBB(3),thisBB(4)]);
[rows cols depth]=size(I2);
if rows*cols>100
%%%%%%%I2=imresize(I2,[28 28]);
figure,imshow(I2);
end
end