Search code examples
pythonopencvimage-processingpython-imaging-library

How can i im1 warp to img2 python opencv?


I have to warp the image1 and add to image2.

This is images link.

https://drive.google.com/drive/folders/1IitVGsbx72vSYPqeARd5Xlh7kMpGyPO4?usp=sharing

So I have to use this function.

added_image = cv2.addWeighted(img2,1,Affinedst,1,0)

But I can't see the image1 on the added_image. We have to keep the img2's overlay value to 1.

M=cv2.getPerspectiveTransform(src_interest_pts ,Affine_interest_pts)

Affinedst = cv2.warpPerspective(img1,M,(cols,rows))

added_image = cv2.addWeighted(img2,1,Affinedst,1,0)

Solution

  •     import cv2
        import numpy as np
        img2 = cv2.imread("img2.png")
        deformation_image = cv2.imread("img1.png")
    
    
        #img1.png shape(550,350)
    
        rows, cols, ch = img2.shape
    
        src_interest_pts = np.float32([[0,0],[550,0],[550,350],[0,350]])
        Affine_interest_pts = np.float32([[487, 149], [852, 160], [901, 437], [619, 476]])
        M=cv2.getPerspectiveTransform(src_interest_pts ,Affine_interest_pts)
        Affinedst = cv2.warpPerspective(deformation_image,M,(cols,rows))
        cv2.imwrite("text.png",Affinedst)
        file_name = "text.png"
        src = cv2.imread(file_name, 1)
        
        tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
        
        _, alpha = cv2.threshold(tmp, 0, 255, cv2.THRESH_BINARY)
        
        b, g, r = cv2.split(src)
        
        rgba = [b, g, r, alpha]
        
        dst = cv2.merge(rgba, 4)
        
        cv2.imwrite("gfg_white.png", dst)
        bimg = img2
    
        hh, ww = bimg.shape[:2]
    
        fimg = cv2.imread('gfg_white.png', cv2.IMREAD_UNCHANGED)
    
        fimg_small = fimg
        ht, wd = fimg_small.shape[:2]
    
        fimg_new = np.full((hh,ww,4), (0,0,0,0), dtype=np.uint8)
    
        fimg_new[0:ht, 0:wd] = fimg_small
    
        alpha = fimg_new[:,:,3]
        alpha = cv2.merge([alpha,alpha,alpha])
    
        base = fimg_new[:,:,0:3]
    
        added_image = np.where(alpha==(0,0,0), bimg, base)
        cv2.imshow("result", added_image)
        cv2.waitkey(0)