how to make cropping for image ?

조회 수: 7(최근 30일)
ElizabethR
ElizabethR 2016년 4월 19일
댓글: Sven 2016년 4월 21일
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 :)

답변(1개)

Sven
Sven 2016년 4월 19일
편집: Sven 2016년 4월 21일
Hi Eliz, try this:
% Read your original image
Img1 = imread('http://www.mathworks.com/matlabcentral/answers/uploaded_files/50194/6.jpg');
% 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')
  댓글 수: 2
Sven
Sven 2016년 4월 21일
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:
Img1 = imread('http://www.mathworks.com/matlabcentral/answers/uploaded_files/50194/6.jpg');
image1 = im2bw(Img1);
image2 = image1(31:201, 83:244);

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by