## how to make cropping for image ?

### ElizabethR (view profile)

on 19 Apr 2016
Latest activity Commented on by Sven

### Sven (view profile)

on 21 Apr 2016
i have an image ( image 1) , i want to crop this image, so i have the result like image 2. How to make crop image so the result like image 2 ??
thanks :)

on 19 Apr 2016
Edited by Sven

### Sven (view profile)

on 21 Apr 2016

Hi Eliz, try this:
% Make it black/white
BW1 = im2bw(Img1);
% It seems to have a border. Crop down to the corners
[toprow,leftcol] = find(~BW1,1);
[botrow,rightcol] = find(~BW1,1,'last');
BW_tight = BW1(toprow:botrow, leftcol:rightcol);
% Here, we COULD just divide the picture by its outer size.
sz = size(BW_tight);
szMid = ceil(sz/2);
% But the pattern isn't perfectly centered. So instead, let's find the
% centroid of ALL the white pattern parts and divide at that point
stats = regionprops(double(BW_tight));
szMid = fliplr(round(stats.Centroid)); % Centroid was XY, we want indices;
% Crop
ImgTopL = BW_tight(1:szMid(1),1:szMid(2));
ImgBotL = BW_tight(szMid(1):end,1:szMid(2));
ImgTopR = BW_tight(1:szMid(1),szMid(2):end);
ImgBotR = BW_tight(szMid(1):end,szMid(2):end);
% Display
figure
subplot(1,2,1), imshow(BW1), title('Original')
subplot(1,2,2), imshow(BW_tight), title('Cropped with centroid')
hold on, plot(szMid(2),szMid(1),'go')
figure
subplot(2,2,1), imshow(ImgTopL), title('Top left')
subplot(2,2,2), imshow(ImgTopR), title('Top right')
subplot(2,2,3), imshow(ImgBotL), title('Bottom left')
subplot(2,2,4), imshow(ImgBotR), title('Bottom right')

ElizabethR

### ElizabethR (view profile)

on 21 Apr 2016
thanks for answare my question, i try your code, but there's error :
Undefined function 'flip' for input arguments of type 'double'.
Error in coba (line 14) szMid = flip(round(stats.Centroid)); % Centroid was XY, we want indices;
and i confused read your code. I want to crop the image 1 so the result is one image like image 2.
Sven

### Sven (view profile)

on 21 Apr 2016
Hi eliz, I have update the line from
flip(...)
to
fliplr(...)
flip is more flexible but only available in newer versions of MATLAB, but fliplr is perfectly fine for your purposes so just use that.
My code is designed to do things in a smart way so that if you have a slightly different image (for example with slightly different white shapes in a slightly different position) it will still work. I wrote the code with comments, and I made it show each of the four "corners" to help you learn some useful techniques. You can just use one of those corners if you'd like.
If you ONLY want to make image2 from image1 and don't want any flexibility, then maybe this is all you need: