# Creating border of an image

113 views (last 30 days)
Mayank Nautiyal on 28 Aug 2019
Commented: Geoff Hayes on 28 Aug 2019
I need a create black border around an image:
My code:
I=ones(256,256); //size of an image
border = 2;
I(end:end+border,end:end+border)=0;
I(1:1+border,1:1+border)=0; // I know the problem is here
imshow(I)

Geoff Hayes on 28 Aug 2019
Mayank - is you have a colour image, then you could do something like
myImage = uint8(randi(255,256,256,3));
border = 2;
myImage(1:border,:,:) = 0;
myImage(end-border+1:end,:,:) = 0;
myImage(:,1:border,:) = 0;
myImage(:,end-border+1:end,:) = 0;
image(myImage)
The above can probably be simplified though...
With your code, the problem seems to be with
I(end:end+border,end:end+border)=0;
In the above, you are trying to add 2 to the last row and last column. Are you trying to augment your 256x256 matrix to be 258x258? Or do you just want to set the last two rows and last two columns to all zeros? If the latter, you need to do something like
I(end-border+1:end,:) = 0;
which will set all columns in the last two rows to be all zeros. If we just do
I(end-border+1:end,end-border+1:end) = 0;
then we are only setting the last two columns of the last two rows to be all zeros. We need to use the : to indicate all. Your code could then become
I(end-border+1:end,:) = 0;
I(:, end-border+1:end) = 0;
I(1:border,:) = 0;
I(:, 1:border) = 0;

Geoff Hayes on 28 Aug 2019
Hi thanks for helping.
Actually I need to create an 8 bit gray scale image of size M*N such that after adding the border the size of the image size becomes (M+2*border)x(N+2*border).
From code:
I(end:end+border,end:end+border)=0; // I think this line is correct
Replacing I(1:1+border,1:1+border)=0; with
I(1:border,:) = 0;
I(:, 1:border) = 0;
actually helped me.
Can u tell me what is the problem with this line: I(1:1+border,1:1+border)=0;
Geoff Hayes on 28 Aug 2019
The problem with
I(1:1+border,1:1+border)=0;
is how you are indexing into I. Note that
I(1:1+border,
means that you are considering the first three rows of I (assuming border is 2) and that
I(...,1:1+border)
means that you are considering the first three columns of I. Putting the two together as
I(1:1+border,1:1+border)
means that are considering the first three columns of the first three rows...so 9 elements only of your matrix and not all the elements of the first three rows and first three columns. That is why you need to handle the rows and columns separately.
But given that you need to add a border to increase your image dimensions to (M+2*border)x(N+2*border), then this won't be exactly what you want. You could create a larger image of all zeros and then insert your smaller image into that. For example, you could try
border = 2;
M = 256;
N = 256;
imageWithBorder = zeros(M+2*border,N+2*border);
imageWithBorder(1+border:end-border,1+border:end-border) = I;