Clearing Image Borders
From MATLAB Techniques for Image Processing by Steve Eddins.
Sometimes when processing objects in binary images, it is necessary to treat differently objects that touch the border. Use the Image Processing Toolbox function imclearborder to identify such objects.
bw = imread('segmented_rice.png');
imshow(bw)

Remove objects touching the border using imclearborder.
bw2 = imclearborder(bw); imshow(bw2)

What if we wanted to identify border-touching objects instead removing them?
Answer: Start with imclearborder and then use logical operators.
removed_objects = bw & ~bw2; imshow(removed_objects)

What if we want to remove objects touching only some of the borders? For example, suppose we want to estimate the number of objects per unit area. If we include all the objects in the image, even those touching the border, our estimate will be biased too high. On the other hand, if we include none of the objects touching the border, our estimate will be biased too low.
One solution is to remove objects touching only two of the boundaries, such as the right and lower boundaries.
There are several ways you might do this using Image Processing Toolbox functions. Here's one way using imclearborder and padarray.
First, pad the image with a row and column of zeros on the top and the left sides. The function padarray helps with this.
bw3 = padarray(bw,[1 1],0,'pre'); imshow(bw3) % Zoom on corners to compare

Now use imclearborder on the padded image.
bw4 = imclearborder(bw3); imshow(bw4)

Finally, remove the extra row and column of zeros.
bw5 = bw4(2:end,2:end); % Did you know about using end this way?
imshow(bw5)

Here's a useful visualization technique to show the two sets of objects, those preserved and those removed. Make an indexed image to show the two sets using different colors.
X = zeros(size(bw),'uint8'); % Did you know about % this way to call zeros? X(bw5) = 1; % Logical indexing! removed_objects = bw & ~bw5; X(removed_objects) = 2;
Now we just need to pick some colors. Make the background a light shade of gray.
map(1,:) = [0.9 0.9 0.9];
Make the preserved objects purple-ish.
map(2,:) = [0.7 0.3 0.8];
Use a green shade for the removed objects.
map(3,:) = [0.4 0.8 0.7]; imshow(X,map)
