做出Vit的patch块,用于Visio画图,如下所示:
\
代码实现:
from PIL import Image
# 读取原始图像
img_path = 'input/0001_c016_00012925_0_orgin.jpg'
img = Image.open(img_path)
# 将图像调整到150x150像素大小(如果原始图像不是这样)
img_resized = img.resize((240, 240))
# 每个patch的大小和空隙大小
patch_size = 30
gap_size = 5
patch_num = 8
# 计算画布的尺寸
canvas_width = (patch_size + gap_size) * patch_num - gap_size
canvas_height = (patch_size + gap_size) * patch_num - gap_size
# 创建拼接画布,白色背景
stitched_image = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255))
# 截取并拼接带空隙的patch
for i in range(patch_num):
for j in range(patch_num):
# 截取30x30的区域
patch = img_resized.crop((j * patch_size, i * patch_size, (j + 1) * patch_size, (i + 1) * patch_size))
# 计算画布上的粘贴位置
# patch.save(f'output/patch_mask_{i * 5 + j + 1}.jpg')
pos_x = j * (patch_size + gap_size)
pos_y = i * (patch_size + gap_size)
# 粘贴patch到画布上,不需要mask
stitched_image.paste(patch, (pos_x, pos_y))
# 保存拼接后的图像
stitched_image.save(f'output/patch_{img_path.split("/")[-1].split(".")[0]}.jpg')
stitched_image.show()
上述代码,根据自己设定的patch块数量,微调resize,patch_size和缝隙大小即可
上述代码执行后效果为:
pathch_num=5,图像大小设置为(150,150)后: