将图像转换为适当的尺寸 PyTorch

Arp*_*ria 4 python numpy image-processing deep-learning pytorch

我有一个输入图像,作为形状 [H, W, C] 的 numpy 数组,其中 H - 高度,W - 宽度和 C - 通道。
我想将其转换为 [B, C, H, W],其中 B - 批量大小,每次都应等于 1,并更改 C 的位置。

_image = np.array(_image)
h, w, c = _image.shape
image = torch.from_numpy(_image).unsqueeze_(0).view(1, c, h, w)
Run Code Online (Sandbox Code Playgroud)

那么,这是否会正确保留图像,即不会替换原始图像像素值?

小智 6

我更喜欢以下内容,它不修改原始图像,而是根据需要添加一个新轴:

_image = np.array(_image)
image = torch.from_numpy(_image)
image = image[np.newaxis, :] 
# _unsqueeze works fine here too
Run Code Online (Sandbox Code Playgroud)

然后根据需要交换轴:

image = image.permute(0, 3, 1, 2)
# permutation applies the following mapping
# axis0 -> axis0
# axis1 -> axis3
# axis2 -> axis1
# axis3 -> axis2
Run Code Online (Sandbox Code Playgroud)