图像自动标注Python代码
时间: 2023-11-21 19:10:32 浏览: 171
图像语义自动标注代码
4星 · 用户满意度95%
以下是一个基于深度学习的图像自动标注Python代码示例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
import os
import tensorflow as tf
from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img
from tensorflow.keras.layers import Input, Dense, Dropout, GlobalAveragePooling2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.optimizers import Adam
# 加载InceptionV3模型
base_model = InceptionV3(include_top=False, weights='imagenet', input_tensor=Input(shape=(299, 299, 3)))
# 添加全局平均池化层和全连接层
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(20, activation='softmax')(x)
# 构建模型
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结InceptionV3模型的前249层
for layer in model.layers[:249]:
layer.trainable = False
# 编译模型
model.compile(optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
# 定义图像数据生成器
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
# 加载数据
train_generator = train_datagen.flow_from_directory('train/',
target_size=(299, 299),
batch_size=32,
class_mode='categorical')
test_generator = test_datagen.flow_from_directory('test/',
target_size=(299, 299),
batch_size=32,
class_mode='categorical')
# 训练模型
history = model.fit_generator(train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=test_generator,
validation_steps=len(test_generator))
# 保存模型
model.save('image_captioning_model.h5')
```
说明:
- 该代码使用了InceptionV3模型作为基础模型,添加了全局平均池化层和全连接层构建了一个新的模型。
- 冻结了InceptionV3模型的前249层,只训练新模型的层。
- 定义了图像数据生成器,并加载了训练和测试数据。
- 训练模型,并保存了模型。
阅读全文