数字图像处理--实现两个图像的合成

复现书中代码,尝试将一个图片选转、缩小等操作后与另一张图片进行合成:

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('合成图片');

实现结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值