(Python)图片的切分与合并


'''
    @Author: feizzhang
    Created on: 02.02.2021
'''

def split_img_to_anypieces(img_path, output_dir, ratio_w = 2, ratio_h = 2):
    '''

    Args:
        img_path: the path of the img that needed to split
        output_dir: the output img dir
        ratio_w: the pieces of weight
        ratio_h: the pieces of height

    Returns:
        None

    '''

    img = cv2.imread(img_path)
    assert np.shape(img) != ()

    weight = np.shape(img)[1]
    height = np.shape(img)[0]

    step_w = np.ceil(weight/ratio_w).astype(np.int)
    step_h = np.ceil(height/ratio_h).astype(np.int)

    for bottom in range(0, height, step_h):
        b = bottom
        t = bottom + step_h

        if t > height:
            t = height

        for left in range(0, weight, step_w):
            l = left
            r = left + step_w

            if r > weight:
                r = weight

            basename = '_'+str(b)+'_'+str(l)+'_'+str(t)+'_'+str(r)+".png"
            output_path = os.path.join(output_dir, custombasename(img_path)+basename)
                                       
            cv2.imwrite(output_path, img[b:t, l:r, :])


def merge_img(img_dir, output_dir):
    '''

    Args:
        img_dir: the dir of split img
        output_dir: the dir of save img

    Returns:
        None
    '''

    img_list = os.listdir(img_dir)

    base_name_h = img_list[0].split('_')[0] + '_'
    base_name_t = '_' + img_list[0].split('_')[-2] + '_' + img_list[0].split('_')[-1]

    b_list = sorted(list(set([int(name.split('_')[1]) for name in img_list])))
    l_list = sorted(list(set([int(name.split('_')[2]) for name in img_list])))
    t_list = sorted(list(set([int(name.split('_')[3]) for name in img_list])))
    r_list = sorted(list(set([int(name.split('_')[4]) for name in img_list])))

    new_img = np.zeros([np.array(t_list).max(), np.array(r_list).max(), 3], dtype=np.int)

    for b,t in zip(b_list, t_list):
        for l,r in zip(l_list, r_list):
            base_name_m = str(b)+'_'+str(l)+'_'+str(t)+'_'+str(r)
            sub_img = cv2.imread(os.path.join(img_dir, base_name_h+base_name_m+base_name_t))

            new_img[b:t,l:r,:] = np.array(sub_img)

    cv2.imwrite(os.path.join(output_dir,base_name_h+"merge.png"), new_img)