# Removing white pixels from a b/w image in MATLAB?

Consider this MATLAB code:

mg=imread(........bmp');
level=graythresh(mg);
x=im2bw(mg,level);
figure,imshow(x);
BW2 = bwperim(~x);
figure,imshow(BW2);


operating on this image (NOTE has white margin, see here): The result was (original link 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?

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

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);
imshow(BW3)


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).