【求求你们别复制粘贴了】实现图像均匀切块&拼图

真的很无语,本来想找个图像切片和拼图的方法,网上一搜,全是一样的,还有BUG,简直垃圾的一批。

于是自己实现了一波

图像均分实现

def jiasaw_transform(image, count=3):
    width, height = image.size
    item_width = int(width / count)
    item_height = int(height / count)
    patch_list = []

    for j in range(0, count):
        for i in range(0, count):
            box = (i * item_width, j * item_height, (i + 1) * item_width, (j + 1) * item_height)
            patch = image.crop(box)
            patch_list.append(patch)

    return patch_list

输入:1. PIL图像 2. 等分的数量count
输出:等分切块后的PIL图像数组

图像拼接实现(拼图)

def cancat_image(patch_list, shuffle=True):
    if shuffle:
        random.shuffle(patch_list)
    np_matrix = np.array([np.array(patch) for patch in patch_list])
    count = int(math.sqrt(len(np_matrix)))
    img_list = []
    for i in range(count):
        img = np.concatenate(np_matrix[i*count:(i+1)*count],1)
        img_list.append(img)
    img = np.vstack(img_list)
    return img

输入:1. 等分切块后的PIL图像数组 2. 是否打乱图像块顺序
输出:拼接后的ndarry矩阵

测试

if __name__ == '__main__':
    img = Image.open('./linboli.jpg')
    list = jiasaw_transform(img)
    result = cancat_image(list)
    plt.imshow(result)
    plt.show()

输入

输入的图像

输出

3等分情况

在这里插入图片描述

9等分

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41154636/article/details/121885331