复现书中代码,尝试将一个图片选转、缩小等操作后与另一张图片进行合成:
clear,clc,close all;
bg = imread("caocong.jpg");
hudie = imread("hudie.jpg");
subplot(2, 2, 1);
imshow(bg);
title('原始背景图');
scaleFactor = 0.3; % 缩小比例
hudie = imresize(hudie, scaleFactor);
subplot(2, 2, 2);
imshow(hudie);
title('蝴蝶');
[h,w,c] = size(bg);
population = 20;
num = 4;
for k = 1:population
type = randi(4,1,num);
thudie = hudie;
for n = 1:num
switch type(n)
case 1
scale = rand();
thudie = imresize(hudie,scale,'bilinear');
case 2
angle = round(rand()*100);
thudie = imrotate(thudie,angle,'bilinear');
case 3
shear = rand()/2;
tform1 = affinetform2d([1 0 0;shear 1 0;0 0 1]);
tform2 = affinetform2d([1 shear 0;0 1 0;0 0 1]);
thudie = imwarp(thudie,tform1);
thudie = imwarp(thudie,tform2);
case 4
thudie = flip(thudie,2);
end
end
[newh,neww,newc] = size(thudie);
positionx = randi(w - 2*neww,1,1);
positiony = randi(h - 2*newh,1,1);
temp = bg(positiony:positiony + newh-1,positionx:positionx+neww-1,:);
colorchange = randi(3,1,2);
if colorchange(1)~= colorchange(2)
color = thudie(:,:,colorchange(1));
thudie(:,:,colorchange(1)) = thudie(:,:,colorchange(2));
thudie(:,:,colorchange(2)) = color;
end
c = thudie(:,:,1)&thudie(:,:,2)&thudie(:,:,3);
pos = find(c(:) == 0);
thudie(pos) = temp(pos);
thudie(pos + newh*neww) = temp(pos + newh*neww);
thudie(pos + 2*newh*neww) = temp(pos+ 2*newh*neww);
temp = thudie;
bg(positiony:positiony+newh-1,positionx:positionx+neww-1,:)=temp;
end
figure;
imshow(bg);
title('合成图片');
实现结果: