文件夹下面有多个文件夹,里面有若干图像。读取图像,将维度调整为[图像数量,3,224,224],得到一维图像标签
时间: 2024-04-29 07:22:47 浏览: 79
(即每个图像所属的文件夹编号),并将标签转为one-hot编码。最后,将图像数据和标签保存为numpy数组。
代码实现如下:
```python
import os
import numpy as np
from PIL import Image
# 定义图像尺寸
img_size = (224, 224)
# 定义标签字典
label_dict = {'folder1': 0, 'folder2': 1, 'folder3': 2}
# 读取图像并调整尺寸
data = []
labels = []
for folder_name in label_dict.keys():
folder_path = './data/' + folder_name
for filename in os.listdir(folder_path):
img = Image.open(os.path.join(folder_path, filename))
img = img.resize(img_size)
img_data = np.array(img).transpose(2, 0, 1)
data.append(img_data)
labels.append(label_dict[folder_name])
# 转换为numpy数组
data = np.array(data)
labels = np.array(labels)
# 转换为one-hot编码
num_classes = len(label_dict)
labels_onehot = np.eye(num_classes)[labels]
# 保存为numpy数组
np.save('data.npy', data)
np.save('labels.npy', labels_onehot)
```
阅读全文