MATLAB: Deleting leadind and trail zeros in an image

cropping black boundaryimage processingImage Processing Toolbox

Hi all I am working on enhancing a grayscal images, the first step should be cropping the image by removing lead and trail zeros (zeros rows an columns surrounding the image). i want t remove the surrounding zeros. please be advised that the cropping has be applied on zeros rows and columns that surrounding the image for different images, so i need a function or an algorithm does this cropping on different images. thanks in advance

Best Answer

  • Try this:
    mask = grayImage ~= 0; % Find all zeros, even those inside the image.
    mask = imfill(mask, 'holes'); % Get rid of zeros inside image.
    % Invert mask and get bounding box.
    props = regionprops(~mask, 'BoundingBox');
    % Crop image.
    croppedImage = imcrop(grayImage, props.BoundingBox);