adding borders to images

18 views (last 30 days)
Jackie
Jackie on 23 Apr 2016
Answered: DGM on 16 Jul 2022
Hello, I understand how to draw a black border around an image,by padding the image with zeros. However, I would like to know how I would be able to add different kind of borders around an image. For example, a colored border, or "fancy" border with a pattern. Thanks.
  2 Comments
Gautam Mohan
Gautam Mohan on 27 Apr 2016
Hi Jackie,
To draw a fancy border, you would need to replace the zero-padding with whatever pattern or color you desire.
One way to do this would be to add a border around the existing image. I will go through a short example where we first create an initial image containing the entirety of our border and then overlay our actual image on it. I'll go with a black and white checkered border for this example.
%read the image and get its dimensions
i = im2double(imread('autumn.tif'));
[nrows,ncols,~] = size(i);
%10px border on all sides, so we increase the border size by 20px in both dimensions -- start with all black for now
x = zeros(nrows+20,ncols+20,3);
%create a checkered border by alternating between white and black pixels
x(1:2:226,1:2:365,:) = 255;
%fill our image in the middle of the larger matrix
x(11:end-10,11:end-10,:) = i;
%image now has a checkered border
image(x)
If you want a border that isn't a regular pattern, I suggest creating each strip separately, then concatenating them all together as a larger matrix. I hope this helps!
osmancakir cakir
osmancakir cakir on 19 Jun 2018
Dear Mohan,
Thanks for your script but I have couple of questions ;
- How should I edit this code when I do not need a checkered border but just a white border
- why doesn't it work when I change x = zeros(nrows+20,ncols+20,3) to x = zeros(nrows+ 40,ncols+ 40,3). I wanted to increase the border.
Thanks in advance

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 27 Apr 2016
I suggest you just create your fancy image first, like in Photoshop or whatever. Then simply call imread() for both images, paste your image onto the larger background image, then call imwrite().
Attached is a copy and paste demo.

DGM
DGM on 16 Jul 2022
The following reference answer covers black/gray/white borders, colored borders, and patterned/textured borders using MATLAB/IPT tools and freely available third-party tools.

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!