trimImage

PURPOSE ^

trimImage Trim white-space from around an image

SYNOPSIS ^

function trimImage( filename, doCrop )

DESCRIPTION ^

trimImage  Trim white-space from around an image

   gpubench.trimImage(filename, doCrop)

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function trimImage( filename, doCrop )
0002 %trimImage  Trim white-space from around an image
0003 %
0004 %   gpubench.trimImage(filename, doCrop)
0005 
0006 %   Copyright 2011 The MathWorks, Inc.
0007 
0008 if nargin<2
0009     doCrop = true;
0010 end
0011 
0012 cdata = imread( filename );
0013 isWhite = all( cdata==255, 3 );
0014 
0015 % Try to work out where the canvas starts so that we can turn everything
0016 % outside transparent. We assume any row or column which is >75% white is
0017 % outside the axes.
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 % Create the alpha channel
0025 alpha = ~isWhite;
0026 alpha(firstCanvasRow:lastCanvasRow, firstCanvasCol:lastCanvasCol) = 1;
0027 
0028 % Crop any spare white-space
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 % Write the result back
0037 imwrite( cdata, filename, 'Alpha', double(alpha) );

Community support and wiki are available on Redmine. Last update: 18-Apr-2019.