文件夹中的多张png图片转化为tensor,并进行标准化处理后保存的完整代码
时间: 2024-03-22 09:39:56 浏览: 64
好的,下面是针对您的问题的代码。这里我们使用PyTorch来进行图片的转换和标准化处理。
```python
import torch
import torchvision.transforms as transforms
from PIL import Image
import os
# 定义标准化处理
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
# 定义转换器
transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize
])
# 设置路径
path = "/path/to/folder"
# 获取文件夹中所有文件名
files = os.listdir(path)
# 遍历文件夹中的所有图片
for file in files:
# 判断是否为png图片
if file.endswith(".png"):
# 打开图片
img = Image.open(os.path.join(path, file))
# 进行转换和标准化处理
img_tensor = transform(img)
# 保存处理后的tensor
torch.save(img_tensor, os.path.join(path, file.replace(".png", ".pt")))
```
这段代码将会遍历指定路径下的所有png图片,并将其转换为tensor,并进行标准化处理后保存到同一文件夹下,文件名将会替换为`.pt`格式。
请注意,这段代码假设您已经安装了PyTorch和Pillow(PIL)库。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)