MATLAB Answers

How to center and add margin around image?

50 views (last 30 days)
Elliot Wyllie
Elliot Wyllie on 28 Feb 2021
Answered: Image Analyst on 28 Feb 2021
Here is my code, what im trying to do is to put image I2 on top of image I1 center it and create a white margin around it that is 50 pixels. Ive googled some possible solutions for the margin and im not having any luck in implementing those solutions. Any help?
I1 = imread('blue-lake.jpg');
I2 = imread('portrait.jpg');
I1 = imresize(I1, 1);
IM2 = imresize(I2, 2);
I1 = image(I1)
hold on;
image(IM2);

Answers (2)

KALYAN ACHARJYA
KALYAN ACHARJYA on 28 Feb 2021
Edited: KALYAN ACHARJYA on 28 Feb 2021
You can manually adjust the indices and overlap with the main image. Note that the main image pixel values will be lost in the overlap portion. Considering main image is larget than marker image.
main_image=imread('......');
marker=imread('.......');
[r,c]=size(main_image);
[r1,c1,ch]=size(marker);
%Make the white border at the boundary
pix_add=50; % In each boundary, 100 for Both sides
im_data=uint8(255*ones(r1+2*pix_add,c1+2*pix_add,3));
im_data(pix_add+1:r1+pix_add,pix_add+1:c1+pix_add,:)=marker;
% White Border in the marker is done
imshow(im_data);
Next: Find the coordinates where you want to place the marker in the main image. You can find data of approximately middle rows and columns from R and C. Once you get the coordinates, the next task is to put im_data in the main_image as I did in the marker (last line of code)
Note: A fairly simple problem, first use pen and paper to decide the coordinates.
Hope you can do the next step. :)

Image Analyst
Image Analyst on 28 Feb 2021
Have you tried padarray()? Then use indexing to paste it onto the other image. I'm attaching a copying and pasting demo. Check out the pasting part, or Kalyan's code to see how to paste your padded array onto the image.

Community Treasure Hunt

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

Start Hunting!

Translated by