Python图像分类:读取训练集数据并展示示例图片

本文将介绍如何使用 Python 读取图像分类模型的训练集数据,并展示部分样本图片及其类别。

1. 读取训练集数据

code = {'Long sleeved': 0, 'Short sleeve': 1, 'cotton-padded jacket': 2, 'longuette': 3, 'shorts': 4}

def getcode(n):
    for x, y in code.items():
        if n == y:
            return x
x_train = []
y_train = []
for folder in os.listdir(train_dir):
    files = gb.glob(pathname=str(train_dir + folder + '/*'))
    for file in files:
        imag = cv2.imread(file)
        imag_array = cv2.resize(imag, (150, 150))
        x_train.append(list(imag_array))
        y_train.append(code[folder])

2. 展示训练集示例图片

可以使用以下代码展示训练集中的部分图片及其类别:

import random

# 随机选择25张训练集图片
sample_images = random.sample(list(zip(x_train, y_train)), 25)

# 展示训练集中的部分图片及其种类
plt.figure(figsize=(20, 20))
for i, (image, label) in enumerate(sample_images):
    plt.subplot(5, 5, i + 1)
    plt.imshow(image)
    plt.axis('off')
    plt.title(getcode(label))
plt.show()

该代码首先使用 random.samplex_trainy_train 的组合中随机选择 25 张图片,然后使用 plt.subplot 展示这些图片,并使用 plt.title 显示图片对应的类别。

通过以上代码,我们可以方便地读取训练集数据并展示示例图片,帮助我们理解图像分类模型的训练过程。

Python图像分类:读取训练集数据并展示示例图片

原文地址: https://www.cveoy.top/t/topic/pcYO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录