import numpy as np
import cv2
import os


def img_add(img_1, img_2):
    upgray = cv2.imread(img_1)
    downgray = cv2.imread(img_2)

    points1 = np.float32([[0,0],[1,0],[0,1],[1,1]])
    points2 = np.float32([[0,0],[1,0],[0,1],[1,1]])

    matrix = cv2.getPerspectiveTransform(points1,points2)

    h,w=upgray.shape[:2]
    h1,w1=downgray.shape[:2]
    if w == w1 and h == h1:
        dst_corners=cv2.warpPerspective(upgray,matrix,(w,h*2))
        dst_corners[h:h*2,0:w]=downgray

        cv2.imwrite(img_1, dst_corners)
        return 1
    return 0

def read_directory(directory_name):
    img_lyst = []
    img_names = os.listdir(directory_name)
    Extension = img_names[0].split('.')[-1]
    print(len(img_names))
    for i in range(len(img_names)):
        a = f'{directory_name}/{i+1}.{Extension}'
        img_lyst.append(a)
    return img_lyst

def img_merge(dir):
    imgs = read_directory(dir)
    m = 0
    for i in range(len(imgs)):
        if i+1 >= len(imgs):
            break
        m = img_add(imgs[i], imgs[i+1])
    if m == 1:
        os.remove(imgs[-1])
    print(f'{dir}图片拼合完成！')

img_merge(r'anhui\d9540653-52ed-442e-bda5-2f888c4e16a1')



