Tensorflow2加载图片数据集并训练

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import random
import pathlib
import numpy as np
def load_image_label(dirpath):
    data_path = pathlib.Path(dirpath)
    all_image_paths  = list(data_path.glob('*/*'))
    all_image_paths = [str(path) for path in all_image_paths]
    random.shuffle(all_image_paths)
    label_names = sorted(item.name for item in data_path.glob('*/') if item.is_dir())
    label_count = len(label_names)
    label_to_index = dict((name, index) for index, name in enumerate(label_names))
    labels = [label_to_index[pathlib.Path(path).parent.name] for path in all_image_paths]
    return all_image_paths, labels, label_count
path = './Train'
all_image_paths, labels, label_count = load_image_label(path)
all_iamge_labels = np.zeros((len(all_image_paths),label_count))
for num, each_label in enumerate(labels):
    all_iamge_labels[num, each_label] = 1
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_iamge_labels))
def load_and_preprocess_from_path_label(path, label):
    image = tf.io.read_file(path)  # 读取图片
    image = tf.image.decode_jpeg(image, channels=3)
    image = tf.image.resize(image, [60, 60])  
    image /= 255.0  # 归一化到[0,1]范围
    return image, label
image_label_ds = ds.map(load_and_preprocess_from_path_label)
train_image = []
train_label = []
for image, label in zip(all_image_paths, all_iamge_labels):
    r_image, r_label = load_and_preprocess_from_path_label(image, label)
    train_image.append(r_image)
    train_label.append(r_label)
train_images = np.array(train_image)
train_labels = np.array(train_label)
print(train_images.shape)
print(train_labels.shape)

from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential(
[
    layers.Conv2D(5,3,activation = 'relu',padding = 'same',input_shape=[60, 60, 3]),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
             loss='categorical_crossentropy',
             metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5,batch_size=3)

import cv2 as cv
test_img = cv.imread("test.jpg")
test_img = cv.resize(test_img,[60,60])
print(test_img.shape)
test_img = np.expand_dims(np.array(test_img),axis=0)
result = model.predict(test_img)
print(result)

参考文档

https://blog.csdn.net/qq_36758914/article/details/106883812
https://blog.csdn.net/Black_Friend/article/details/104529859

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值