Automatically trim/remove/crop black borders/margins from images / volumes

21 views (last 30 days)
Is there any way to easily and efficiently automate "trimming / removing / cropping" of "black / 0", "borders / margins" from "images / volumes" in Matlab?
In particular, I am working with 3D volumes and even 4D volumes of medical image datasets, in which the CT or MR reconstruction algorithms occasionally leave a geometric, contiguous, unused, black margin around the images.
For purposes of doing image analysis and statistics, it helps to remove this useless, spurious, zero data which tends to be problematic and contaminating when performing image analysis.
  5 Comments
Eric Diaz
Eric Diaz on 14 May 2014
Edited: Eric Diaz on 15 May 2014
Can anyone else help with this problem? It seems that everyone yet has given up or is no longer interested in helping.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 3 May 2014
Get the black pixels imageArray == 0. Then invert and call imclearborder and subtract or XOR the two to get only those black pixels touching the border. Then use that mask to set the pixels to the desired gray level imageArray(mask) = desiredGrayLevel.
  32 Comments
Eric Diaz
Eric Diaz on 17 May 2014
That is a solution that works. I like it.
I think I have just figured out how to fuse the two solutions to beta solution which works best for me.
I can use the aggressive crop to retain main body and perform means clustering on that subset of images. And I can use the above, XOR solution to perform noise estimation on just the useful pixels.
The additional problem, which I needed to address was the degrees of freedom when performing clustering.
Thanks for your help and suggestions, Image Analyst.
lt c
lt c on 24 Feb 2022
mask = grayImage > 300; % Mask is bright stuff.
% Fill in the body
mask = imfill(mask, 'holes'); % Mask is whole solid body.
% OR it in with the zeros
mask = mask | (grayImage == 0); % Mask now includes pure zeros.
% Extract pixels that are not masked
darkNonZeroOutsidePixels = grayImage(~mask);
Quick question:
I ran code above and get a column vector (darkNonZeroOutsidePixels). Does it mean to be a part of 2D image (without the middle bright and the 0 value edge)?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!