「笔记」Python 拼接 多张图片

在这里插入图片描述

图像拼接采用的最简单的画板填充方法,首先创建一张大的空白画板,然后按照拼接张数,以此在画板的各个子区域将图像复制进去,此处需要注意在复制之前需要对图像进行 resize处理,不然尺寸不一致会报错!

# 创建空白画板
mage = np.zeros((900, 900, 3), np.uint8)

# 将要拼接的四张图像覆盖到大图上
mage[  0:450,  0:450] = img1
mage[  0:450,450:900] = img2
mage[450:900,  0:450] = img3
mage[450:900,450:900] = img4

完整版拼接代码,img_list 是待拼接的所有图像路径列表,每行一个图像路径,save_path 是拼接好的图像保存文件夹路径。

此外,用于 YOLO模型验证,因此也将 标注信息一同保存了,仅简单标注框,YOLO 的标注信息为:class x1 y1 w h,其中x1, y1为标注框中心点位置。对于不需要标注信息的小伙伴直接注释掉就可以

def split_join(img_list, save_path):

    if not os.path.exists(save_path):
        os.mkdir(save_path)

    num = 0
    rand = [4,6]
    
    while (len(img_list) > 5):
        r = random.choice(rand)         # 随机数
        mage = np.zeros((900, 900, 3), np.uint8) if r ==4 else np.zeros((900, 1350, 3), np.uint8)

        img_path_lst = [img_list.pop() for i in range(r)]

        txt_path = os.path.join(save_path , str(num+1)+'.txt')
        txt_file = open(txt_path, 'w')


        for p in range(r):
            h, w = 2, int(r / 2)
            path = img_path_lst[p]
            img_cv = cv.imread(path)

            if img_cv is None:
                print("Error img_cv is None!!!", path)
                os.remove(path)
                continue

            img = cv.resize(img_cv, ((900//h), mage.shape[1] // w ) )
            
            i = int((p // w) * (900 / h))
            j = int((p % w) * (mage.shape[1] / w))

            # print(r, i, j)
            mage[i:i+int(900/h), j:j+int(mage.shape[1]/w)] = img

            # 保存 标注信息
            cls = int( os.path.basename(os.path.dirname(path)) ) -1     # "{:.6f}".format(3.14159)

            x = (j+225)/mage.shape[1]           # mage h
            y = (i+225)/mage.shape[0]           # mage w

            line = str(cls) + ' ' + \
                "{:.6f}".format(x) + ' ' + "{:.6f}".format(y) + ' '+ \
                "{:.6f}".format(1/w -0.05) + ' ' + "{:.6f}\n".format(1/h -0.05)      # 中心 + w h
            
            txt_file.write(line)
            
        num += 1
        img_path = os.path.join(save_path , str(num)+'.jpg')
        
        txt_file.close()
        cv.imwrite(img_path ,mage)

猜你喜欢

转载自blog.csdn.net/ViatorSun/article/details/130084075