MATLAB Answers

Creating border of an image

116 views (last 30 days)
I need a create black border around an image:
My code:
I=ones(256,256); //size of an image
border = 2;
I(1:1+border,1:1+border)=0; // I know the problem is here
Please help


Sign in to comment.

Accepted Answer

Geoff Hayes
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;
The above can probably be simplified though...
With your code, the problem seems to be with
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
Geoff Hayes on 28 Aug 2019
Mayank's answer moved here
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
Geoff Hayes on 28 Aug 2019
The problem with
is how you are indexing into I. Note that
means that you are considering the first three rows of I (assuming border is 2) and that
means that you are considering the first three columns of I. Putting the two together as
means that are considering the first three columns of the first three 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;

Sign in to comment.

More Answers (0)