Code for converting tensor, ndarray, and PIL image formats to each other in Pytorch

1. Data and ndarray conversion in PIL format

Use PIL to read image information, and then convert it to the format in numpy

image = Image.open(img_path).convert("RGB")
image = np.array(image)
## 需要将numpy 的格式转为 np.float32.这样以后转成tensor 才会是 torch.float32
image = (image / 255.0).astype(np.float32) 

2. Data and tensor conversion in ndarray format

  1. Use the torch.from_numpy() function
  1. Use transform to convert ndarray into a variable of type Tensor
import albumentations as A
from albumentations.pytorch import ToTensorV2

transform = A.Compose(
        [       A.Resize(height=Image_height,width=Image_width),
            A.Normalize(
                mean=[0,0,0],
                std=[1.0,1.0,1.0],
                max_pixel_value=255.0,
            ),
            ToTensorV2(),  ## numpy 转化为tensor
        ],
    )


 augmentation = transform(image = image)
 img = augumentation['image'] ### 得到img 的tensor 类型的数据
Tensor can be directly converted to numpy array:
a = tensor.randn(3,3)
a.cpu().numpy()   ## 将tensor 转为numpy数组

3. Tensor format data and PIL image data conversion

method 1:

from torchvision.transforms import ToPILImage
## image 是一个tensor 类型的数据
image = ToPILImage()(image)
image.save('1.png')

Method 2:

import torchvision
 predit = torch.sigmoid(model(img))
 predit = (predit>0.5).float()
## 可以直接 调用save_image 函数保存4维度的 tensor 为image
 torchvision.utils.save_image(predit,'1.png')   

Guess you like

Origin blog.csdn.net/qq_41623632/article/details/126290781