MATLAB: Add a background image to the existing image.

animationbackground

clear all
close all
background = imread('background.jpeg')
background = rgb2gray(background)
imshow(background)
load Angle.mat;
for i=1:3
A=angle(i,:);
I = imread('hex08.jpg');
I = rgb2gray(I);
J = imrotate(I,A);
pause(0.1)
imshow(J);
imwrite(J,['hex08',num2str(i),'.jpg'])
end
Above is my code, I basically want to make an animation which rotated one original picture(hex08) to form a image series and then create a avi. I now need to add a background to my avi. so the background won't move.
Is there anyway I can do that?
Thank you very much for helping.

Best Answer

Try this:
background = imread('onion.png');
background = rgb2gray(background);
imshow(background)
angles = 70:30:360;
grayImage = imread('cameraman.tif');
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Convert it to gray scale by taking only the green channel.
grayImage = grayImage(:, :, 2); % Take green channel.
end
% Resize background
background = imresize(background, [rows, columns]);
for k = 1 : length(angles)
% Rotate the image.
rotatedImage = imrotate(grayImage, angles(k), 'crop');
% Get a mask.
mask = rotatedImage == 0;
mask = bwareafilt(mask, 4);
% Replace black background with image
rotatedImage(mask) = background(mask);
pause(0.6)
imshow(rotatedImage);
% Make background the same si
% imwrite(J,['hex08',num2str(i),'.jpg'])
end