MATLAB: Creating border of an image

tag

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)
Please help

Best Answer

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;