def pw_affine(fromim,toim,fp,tp,tri): """ Warp triangular patches from an image. fromim = image to warp toim = destination image fp = from points in hom. coordinates tp = to points in hom. coordinates tri = triangulation. """ im = toim.copy() # check if image is grayscale or color is_color = len(fromim.shape) == 3 # create image to warp to (needed if iterate colors) im_t = zeros(im.shape, 'uint8') for t in tri: # compute affine transformation H = homography.Haffine_from_points(tp[:,t],fp[:,t]) if is_color: for col in range(fromim.shape[2]): im_t[:,:,col] = ndimage.affine_transform( fromim[:,:,col],H[:2,:2],(H[0,2],H[1,2]),im.shape[:2]) else: im_t = ndimage.affine_transform( fromim,H[:2,:2],(H[0,2],H[1,2]),im.shape[:2]) # alpha for triangle alpha = alpha_for_triangle(tp[:,t],im.shape[0],im.shape[1]) # add triangle to image im[alpha>0] = im_t[alpha>0] return im
def image_in_image(im1,im2,tp): """ Put im1 in im2 with an affine transformation such that corners are as close to tp as possible. tp are homogeneous and counter-clockwise from top left. """ # points to warp from m,n = im1.shape[:2] fp = array([[0,m,m,0],[0,0,n,n],[1,1,1,1]]) # compute affine transform and apply H = homography.Haffine_from_points(tp,fp) im1_t = ndimage.affine_transform(im1,H[:2,:2], (H[0,2],H[1,2]),im2.shape[:2]) alpha = (im1_t > 0) return (1-alpha)*im2 + alpha*im1_t
imshow(im1) subplot(142) axis('off') imshow(im2) subplot(143) axis('off') imshow(im3) # set from points to corners of im1 m,n = im1.shape[:2] fp = array([[0,m,m,0],[0,0,n,n],[1,1,1,1]]) # first triangle tp2 = tp[:,:3] fp2 = fp[:,:3] # compute H H = homography.Haffine_from_points(tp2,fp2) im1_t = ndimage.affine_transform(im1,H[:2,:2], (H[0,2],H[1,2]),im2.shape[:2]) # alpha for triangle alpha = warp.alpha_for_triangle(tp2,im2.shape[0],im2.shape[1]) im3 = (1-alpha)*im2 + alpha*im1_t # second triangle tp2 = tp[:,[0,2,3]] fp2 = fp[:,[0,2,3]] # compute H H = homography.Haffine_from_points(tp2,fp2) im1_t = ndimage.affine_transform(im1,H[:2,:2], (H[0,2],H[1,2]),im2.shape[:2]) # alpha for triangle alpha = warp.alpha_for_triangle(tp2,im2.shape[0],im2.shape[1]) im4 = (1-alpha)*im3 + alpha*im1_t