"Notes" Python stitching multiple pictures

insert image description here

The simplest artboard filling method used for image stitching, first create a large blank artboard, and then copy the image into each sub-area of ​​the artboard according to the number of stitching sheets. Here, it should be noted that the image needs to be resized before copying Deal with it, otherwise an error will be reported if the size is inconsistent!

# 创建空白画板
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

The full version of the splicing code, img_list is a list of all image paths to be spliced, one image path per line, save_path is the path to the saved folder of the spliced ​​images.

In addition, it is used for YOLO model verification, so the annotation information is also saved together, only a simple annotation frame, and the annotation information of YOLO is: class x1 y1 w h, where x1, y1is the center point of the annotation frame. For those who don’t need to mark the information, just comment it out

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)

Guess you like

Origin blog.csdn.net/ViatorSun/article/details/130084075