× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Extending the size of an image by padding the borders with 1s

Ray Phan
Jul 09, 2015
<p>If you want to extend the image so that original contents are in the middle, you can calculate the middle of the output image which is initialized to all 1s, then make sure you place the image so that it spans the width and height of the original one. This will get messy if you have input images that are even in dimension... but assuming you have <strong>odd</strong> dimensions, do this:</p> <pre><code>rows_out = 600; cols_out = 600; out = ones(rows_out, cols_out, size(im,3)); rows_in = size(im,1); cols_in = size(im,2); rows_half = floor(rows_in/2); cols_half = floor(cols_in/2); out_half_rows = floor(rows_out/2); out_half_cols = floor(cols_out/2); out(out_half_rows-rows_half : out_half_rows+rows_half, ... out_half_cols-cols_half : out_half_cols+cols_half, :) = im; </code></pre> <p>As an additional check, you can check to see if your image has even rows or columns by checking the remainder of dividing by 2 and if there is a reminder, we can remove the last row and/or column for example:</p> <pre><code>rows_in = size(im,1) - (mod(size(im,1),2) + 1); cols_in = size(im,2) - (mod(size(im,2),2) + 1); im = im(1:rows_in, 1:cols_in, :); </code></pre> <p>Take note that the above code will remove the last two rows and two columns for the case of it being odd. </p> <hr> <p>Here's an example with a 256 x 256 dark square on a 600 x 600 white background:</p> <pre><code>out = ones(600,600); im = zeros(256,256); </code></pre> <p>Using the above checks to ensure odd image sizes, we get:</p> <p><img src="http://i.stack.imgur.com/gqS5Q.png" alt="enter image description here"></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31269886/Extending%20the%20size%20of%20an%20image%20by%20padding%20the%20borders%20with%201s/31270229">Stack Overflow</a>.</p>
comments powered by Disqus