3

I have a binary image of 18x18 pixels and I want to put margins around this image with the purpose of obtaining an image 20x20 pixels.

Description of the problem

The image is binary and it can be represented by a matrix of 1s and 0s. The 0 pixels are in black colour and the 1 pixels are in white colour. I need to put margins of 1 pixel of zeros around the image that I have.

How can I do it?

Community
  • 1
  • 1

4 Answers4

3

The padarray function from the image processing toolbox can be used for this purpose:

B=padarray(A,[1,1])
Daniel
  • 36,610
  • 3
  • 36
  • 69
1
A=ones(18,18);%// your actual image
[M,N] = size(A);
B = zeros(M+2,N+2);%// create matrix
B(2:end-1,2:end-1) = A; %// matrix with zero edge around.

This first gets the size of your image matrix, and creates a zero matrix with two additional columns and rows, after which you can set everything except the outer edges to the image matrix.

Example with a non-square matrix of size [4x6]:

B =

     0     0     0     0     0     0     0     0
     0     1     1     1     1     1     1     0
     0     1     1     1     1     1     1     0
     0     1     1     1     1     1     1     0
     0     1     1     1     1     1     1     0
     0     0     0     0     0     0     0     0
Adriaan
  • 17,741
  • 7
  • 42
  • 75
0

First make a matrix of 20 by 20 zeroes, Zimg, then insert your image matrix into the matrix of zeroes:

Zimg(2:end-1,2:end-1)=img;
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Stefan
  • 622
  • 1
  • 5
  • 17
0

Let's get hackish:

%// Data:
A = magic(3);                 %// example original image (matrix)
N = 1;                        %// margin size

%// Add margins:
A(end+N, end+N) = 0;          %// "missing" values are implicitly filled with 0
A = A(end:-1:1, end:-1:1);    %// now flip the image up-down and left-right ...
A(end+N, end+N) = 0;          %// ... do the same for the other half ...
A = A(end:-1:1, end:-1:1);    %// ... and flip back
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • thanks! It is the most efficient solution. In my machine,the elapsed time by this method is approximately 10 times less than the method with the padarray function :D –  Dec 10 '15 at 14:11
  • 1
    Great! Yes, implicit zero-filling [has a name](http://undocumentedmatlab.com/blog/preallocation-performance/) for [being fast](http://stackoverflow.com/a/14195309/2586922) in Matlab – Luis Mendo Dec 10 '15 at 16:05