图像分类代码python
时间: 2023-11-16 21:57:00 浏览: 37
这里提供的是一个简单的图像分类代码Python示例,使用了TensorFlow库。代码中包括了加载和预处理数据的函数以及训练和测试数据集的加载。你可以根据自己的需求进行修改和扩展。
```
import tensorflow as tf
import numpy as np
import os
# 定义预处理图像的函数
def preprocess_image(image):
# 将图像转换为张量
image = tf.image.decode_jpeg(tf.io.read_file(image), channels=3)
image = tf.image.resize(image, (224, 224))
image = tf.image.convert_image_dtype(image, tf.float32)
# 归一化处理
image = (image - 0.5) / 0.5
return image
# 定义加载数据集的函数
def load_dataset(data_path):
images = []
labels = []
# 遍历数据集文件夹
for class_name in os.listdir(data_path):
class_path = os.path.join(data_path, class_name)
# 遍历类别文件夹中的图像
for image_name in os.listdir(class_path):
image_path = os.path.join(class_path, image_name)
# 预处理图像并添加到列表
images.append(preprocess_image(image_path))
labels.append(class_name)
return np.array(images), np.array(labels)
# 加载训练数据集和测试数据集
train_images, train_labels = load_dataset('train_data_path')
test_images, test_labels = load_dataset('test_data_path')
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 训练模型
model.fit(train_images, train_labels, epochs=10)
# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
# 预测新数据
predictions = model.predict(test_images)
```