You can find the pixel coordinates from the mask BWmm
and then use the coordinates with imcrop
.
To find the extermal points of BWmm
use
projX = any( BWmm, 1 ); % projection of mask along x direction
projY = any( BWmm, 2 ); % projection of mask along y direction
fx = find( projX, 1, 'first' ); % first column with non-zero val in mask
tx = find( projX, 1, 'last' ); % last column with non-zero val in mask
fy = find( projY, 1, 'first' ); % first row with non-zero val in mask
ty = find( projY, 1, 'last' ); % last row with non-zero val in mask
cropRect = [fx, fy, tx-fx+1, ty-fy+1];
cImg = imcrop( I, cropRect );