python 图像预处理
时间: 2023-10-27 12:06:39 浏览: 98
在Python中,可以使用OpenCV和torchvision.transforms库进行图像预处理。以下是几个常用的图像预处理操作:
1. 将numpy数组转换为PIL.Image对象:
```
import numpy as np
from PIL import Image
data = np.random.randint(0, 255, size=300, dtype='uint8')
img = data.reshape(10, 10, 3)
img_PIL = Image.fromarray(img)
```
2. 将PIL.Image对象转换为numpy数组:
```
import numpy as np
from PIL import Image
img_PIL = Image.open('image.jpg')
img = np.array(img_PIL)
```
3. 对图像进行归一化操作:
```
import torch
import torchvision.transforms as transforms
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
transform = transforms.Compose([
transforms.ToTensor(),
normalize
])
img_PIL = Image.open('image.jpg')
img_tensor = transform(img_PIL)
```
4. 调整图像大小:
```
from PIL import Image
img_PIL = Image.open('image.jpg')
resized_img = img_PIL.resize((new_width, new_height))
```
以上是一些常用的Python图像预处理操作。根据具体需求,你可以根据这些操作来进行相应的处理。
阅读全文