Consider this MATLAB code:

BW2 = bwperim(~x); 

operating on this image (NOTE has white margin, see here): enter image description here

The result was (original link here):

enter image description here

How can I remove the white pixels from the second image and then obtain the first image with everything but the white pixels removed from the second image.

In other words, how can I remove the boundaries from the second image and then get the original image without these boundaries?

  • $\begingroup$ I don't understand. Are you just trying to remove the borders from the image, or doing something with the hand boundary? $\endgroup$
    – endolith
    Commented Feb 4, 2012 at 15:29
  • $\begingroup$ @endolith.yes i want only to remove the border from the hand because then i will need to work on hand without its border. $\endgroup$
    – ruaa
    Commented Feb 6, 2012 at 20:16
  • $\begingroup$ @ruaa Please don't post comments in the "answer" box. $\endgroup$
    – Phonon
    Commented Feb 6, 2012 at 20:19

1 Answer 1


So...you want to remove the fat white borders from around the black region??

You could try search for the first and last row,column that are 0 in the second image, using (e.g.) find:

% assuming BW2 is 2D, one channel.
% the reason the first has a BW2' and the second is BW
% is because of Matlab being column-major when it does `find`:
% have to make sure we actually get the first/last indices.
[col1,row1] = find(BW2'==0,1,'first'); % top-left corner
[row2,col2] = find(BW2==0,1,'last'); % bottom-right corner
BW3 = BW(row1:row2, col1:col2);

This does assume that the top-left and bottom-right corner of the image proper won't be part of the outline - this is a very low chance.

If you want to be sure however, you could instead look for the first row that is not all 255 and first col that is not all 255, and similarly for the last row/col (ie locate margin by looking for entire rows/cols being 255) and crop like that:

cols = sum(abs(255-BW2),1); % work out difference from 255
rows = sum(abs(255-BW2),2);
col1 = find(cols,1,'first');
col2 = find(cols,1,'last');
row1 = find(rows,1,'first');
row2 = find(rows,1,'last');
BW3 = BW(row1:row2,col1:col2);

(Note this will fail on your jpeg because of the compression it uses -- the border is not uniquely 255, there are a few 251's in there. But it will work on your code if you don't save BW out as a jpeg first and then read it back in. If you're going to save images, use a lossless format like TIF or PNG).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.