有若干图像,进行读取,转为二维数组,将图片像素值归一化到0~1,改变图片尺寸为 [N, C, H, W],,获取图像一维标签
时间: 2024-04-29 17:22:55 浏览: 81
,最终返回由图像二维数组和对应标签组成的数据集。
以下是Python代码示例:
```python
import os
import numpy as np
from PIL import Image
def read_images(data_path, img_size):
images = []
labels = []
for foldername in os.listdir(data_path):
folderpath = os.path.join(data_path, foldername)
if os.path.isdir(folderpath):
for filename in os.listdir(folderpath):
if filename.endswith(".jpg"):
filepath = os.path.join(folderpath, filename)
img = Image.open(filepath).convert("L") # 转为灰度图
img = img.resize(img_size) # 改变图片尺寸
img_arr = np.array(img) / 255.0 # 归一化到0~1
images.append(img_arr)
labels.append(int(foldername))
images = np.array(images)
labels = np.array(labels)
return images, labels
data_path = "path/to/images"
img_size = (28, 28) # 图像尺寸
images, labels = read_images(data_path, img_size)
# 转为 [N, C, H, W] 形式
images = images.reshape(images.shape[0], 1, img_size[0], img_size[1])
# 返回数据集
dataset = {"images": images, "labels": labels}
```
阅读全文