0001 function trimImage( filename, doCrop )
0002
0003
0004
0005
0006
0007
0008 if nargin<2
0009 doCrop = true;
0010 end
0011
0012 cdata = imread( filename );
0013 isWhite = all( cdata==255, 3 );
0014
0015
0016
0017
0018 whiteRowRatio = sum( isWhite, 2 ) / size( isWhite, 2 );
0019 firstCanvasRow = find( whiteRowRatio < 0.75, 1, 'first' );
0020 lastCanvasRow = find( whiteRowRatio < 0.75, 1, 'last' );
0021 whiteColRatio = sum( isWhite, 1 ) / size( isWhite, 1 );
0022 firstCanvasCol = find( whiteColRatio < 0.75, 1, 'first' );
0023 lastCanvasCol = find( whiteColRatio < 0.75, 1, 'last' );
0024
0025 alpha = ~isWhite;
0026 alpha(firstCanvasRow:lastCanvasRow, firstCanvasCol:lastCanvasCol) = 1;
0027
0028
0029 if doCrop
0030 whiteRows = all( isWhite, 2 );
0031 firstRow = find( ~whiteRows, 1, 'first' );
0032 cdata = cdata(firstRow:end, :, :);
0033 alpha = alpha(firstRow:end, :, :);
0034 end
0035
0036
0037 imwrite( cdata, filename, 'Alpha', double(alpha) );