pytorch 读取图片
时间: 2023-12-21 12:31:49 浏览: 111
pytorch读取图像数据转成opencv格式实例
以下是三种PyTorch读取图片的方法:
1. 使用`torchvision.io`库中的`image.read_image()`函数:
```python
from torchvision.io import image
path = '../dataset/train/hazy/8902.jpg'
img = image.read_image(path)
print(type(img)) # 输出:<class 'torch.Tensor'>
print(img.shape) # 输出:torch.Size([3, 344, 550])
```
2. 使用`torchvision.transforms`库中的`ToTensor()`函数和`PIL`库中的`Image`类:
```python
from torchvision.transforms import ToTensor
from PIL import Image
path = '../dataset/train/hazy/8902.jpg'
img = Image.open(path)
img = ToTensor()(img)
print(type(img)) # 输出:<class 'torch.Tensor'>
print(img.shape) # 输出:torch.Size([3, 344, 550])
```
3. 使用`cv2`库和`numpy`库:
```python
import cv2
import numpy as np
path = '../dataset/train/hazy/8902.jpg'
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = np.transpose(img, (2, 0, 1))
img = torch.from_numpy(img)
print(type(img)) # 输出:<class 'torch.Tensor'>
print(img.shape) # 输出:torch.Size([3, 344, 550])
```
阅读全文