How to crop the image?

  • I have above image and I want to crop it such that the white pixels just reach the corners from all sides using Matlab code automatically not manually
how could I do this...thanks In advance

 Accepted Answer

Have you run my Image Segmentation Tutorial http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A31862? It goes over that.
labeledImage = bwlabel(binaryImage);
blobMeasurements = regionprops(labeledImage, 'BoundingBox');
% Find the bounding box of each blob.
thisBlobsBoundingBox = blobMeasurements.BoundingBox; % Get list of pixels in current blob.
% Extract out this blob into it's own image.
% I'm assuming just one blob. If you have multiple, see my tutorial.
subImage = imcrop(binaryImage, thisBlobsBoundingBox);

6 Comments

peyush
peyush on 19 Jul 2015
thanks...it works fine for single blob...but for multiple blobs I need it to crop it and display as a single image not separate images...for example
and I want the result as shown below as single image
how can I do this?...thanks for replying
You could either call bwconvhull() to get the convex hull of the whole thing and then call regionprops(), or you can get the bounding boxes and find the mins and maxes:
bbs = [blobMeasurements.BoundingBox];
leftColumn = min(bbs(1:4:end));
topRow = min(bbs(2:4:end));
bottomRows = bbs(2:4:end) + bbs(4:4:end);
rightColumns = ...
Can you figure out how to finish the last 3 lines of code to find the rightmost column and the bottommost row?
peyush
peyush on 19 Jul 2015
Edited: peyush on 19 Jul 2015
thanks i got the result by your first method...i am new to matlab, but if you explain this line,
leftColumn = min(bbs(1:4:end));
then i will try, and thanks
The bounding box is a 4 element array [x, y, width, height]. When you concatenate them you have bbs = [x1,y1,w1,h1,x2,y2,w2,h2,x3,y3,w3,h3,......xn,yn,wn,hn];
Then you do bbs(1:4:end) you get just [x1,x2,x3,x4,.....xn]. The min of that will be the left most x value.
You should have had this done long long ago - it's not that hard. So I did it for you. See the attached demo.
peyush
peyush on 20 Jul 2015
thank-you so so much ☺

Sign in to comment.

More Answers (0)

Asked:

on 18 Jul 2015

Commented:

on 20 Jul 2015

Community Treasure Hunt

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

Start Hunting!