www.pudn.com > image_merge11.rar > image_merge.m, change:2013-05-07,size:1682b


function merged_img = image_merge( img1,img2,mask,x,y,location ) 
%MERGE img2 to img1 
% Created on 2013.5.6 
% By Heaven 
% Version 1.0 
narginchk(0,6) 
if nargin<6 
    if nargin<=2 
        mask=ones(size(img2,1),size(img2,2)); 
    end 
    if nargin<=3 
        x=0; 
    end 
    if nargin<=4 
        y=0; 
    end 
    location='T'; % top left for 'T', centroid for 'C' 
end 
 
if location~='C' && location~='T' 
    error('location must be one of the values [''T'', ''C''].') 
end 
 
[r1,c1,n1]=size(img1); 
[r2,c2,n2]=size(img2); 
 
% if img1 is smaller than img2 in any dimension, then rsize img2 and mask 
if r1/r2<1 || c1/c2<1 
    ratio=min(r1/r2,c1/c2); 
    img2=imresize(img2,ratio); 
    mask=imresize(mask,ratio); 
    [r2,c2,n2]=size(img2); 
end 
if location=='C' 
    x=x-floor(c2/2); 
    y=y-floor(r2/2); 
end 
if x<0 
    x=0; 
end 
if x>c1-c2 
    x=c1-c2; 
end 
if y<0 
    y=0; 
end 
if y>r1-r2 
    y=r1-r2; 
end 
 
% pad img2 and mask 
img2_pad=padarray(img2,[y,x],'pre'); 
img2_pad=padarray(img2_pad,[r1-y-r2,c1-x-c2],'post'); 
mask_pad=padarray(mask,[y,x],'pre'); 
mask_pad=logical(padarray(mask_pad,[r1-y-r2,c1-x-c2],'post')); 
 
if n1==1 && n2==1 % img1 and img2 are gray images 
    merged_img=img1; 
    merged_img(mask_pad)=img2_pad(mask_pad); 
else 
    if n1==1 
        img1_rgb=cat(3,img1,img1,img1); 
    else 
        img1_rgb=img1; 
    end 
    if n2==1 
        img2_rgb=cat(3,img2_pad,img2_pad,img2_pad); 
    else 
        img2_rgb=img2_pad; 
    end 
    merged_img=img1_rgb; 
    for i=1:3 
        t1=img1_rgb(:,:,i); 
        t2=img2_rgb(:,:,i); 
        t1(mask_pad)=t2(mask_pad); 
        merged_img(:,:,i)=t1; 
    end 
end 
end