gpt4 book ai didi

python - 图像批处理中的随机补丁

转载 作者:行者123 更新时间:2023-12-03 23:39:17 25 4
gpt4 key购买 nike

我正在尝试创建一个 transform打乱批次中每个图像的补丁。
我的目标是以与 torchvision 中的其余转换相同的方式使用它。 :

trans = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
ShufflePatches(patch_size=(16,16)) # our new transform
])
更具体地说,输入是 BxCxHxW张量。我想将批次中的每个图像拆分为大小为 patch_size 的不重叠补丁,将它们打乱,然后重新组合成单​​个图像。
给定图像(大小为 224x224 ):
enter image description here
使用 ShufflePatches(patch_size=(112,112))我想生成输出图像:
enter image description here
我认为解决方案与 torch.unfold 有关和 torch.fold ,但没能更进一步。
任何帮助,将不胜感激!

最佳答案

确实 unfold and fold 在这种情况下似乎合适。

import torch
import torch.nn.functional as nnf

class ShufflePatches(object):
def __init__(self, patch_size):
self.ps = patch_size

def __call__(self, x):
# divide the batch of images into non-overlapping patches
u = nnf.unfold(x, kernel_size=self.ps, stride=self.ps, padding=0)
# permute the patches of each image in the batch
pu = torch.cat([b_[:, torch.randperm(b_.shape[-1])][None,...] for b_ in u], dim=0)
# fold the permuted patches back together
f = nnf.fold(pu, x.shape[-2:], kernel_size=self.ps, stride=self.ps, padding=0)
return f
这是一个补丁大小为 16 的示例:
enter image description here

关于python - 图像批处理中的随机补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66962837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com