Keras 训练 inceptionV3 并移植到OpenCV4.0 in C++
1. 训练
# --coding:utf---
import os
import sys
import glob
import argparse
import matplotlib.pyplot as plt from keras import __version__
from keras.applications.inception_v3 import InceptionV3, preprocess_input
#from keras.applications.inception_v3_matt import InceptionV3, preprocess_input from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import SGD def get_nb_files(directory):
"""Get number of files by searching directory recursively"""
if not os.path.exists(directory):
return
cnt =
for r, dirs, files in os.walk(directory):
for dr in dirs:
cnt += len(glob.glob(os.path.join(r, dr + "/*")))
return cnt
#train_num = get_nb_files('/home/pandafish/AnacondaProjects/Inceptionv3/dataset_my/train')
#print(train_num)
#input('wait...') # 数据准备
IM_WIDTH, IM_HEIGHT = , #InceptionV3指定的图片尺寸
FC_SIZE = # 全连接层的节点个数
##NB_IV3_LAYERS_TO_FREEZE = # 冻结层的数量
NB_IV3_LAYERS_TO_FREEZE = # 冻结层的数量 train_dir = '/home/dl/local_repo/data/mosaic1/mosaic_train' # 训练集数据
val_dir = '/home/dl/local_repo/data/mosaic1/mosaic_valid' # 验证集数据
output_model_file = '/home/dl/local_repo/data/mosaic1/mosaic.hdf5'
wights_path = '/home/dl/local_repo/data/mosaic1/mosaic.h5' nb_classes=
nb_epoch =
batch_size = nb_train_samples = get_nb_files(train_dir) # 训练样本个数
nb_classes = len(glob.glob(train_dir + "/*")) # 分类数
nb_val_samples = get_nb_files(val_dir) #验证集样本个数
nb_epoch = int(nb_epoch) # epoch数量
batch_size = int(batch_size) # 图片生成器
train_datagen = ImageDataGenerator(
preprocessing_function=preprocess_input,
##rotation_range=,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
test_datagen = ImageDataGenerator(
preprocessing_function=preprocess_input,
##rotation_range=,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
) # 训练数据与测试数据
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(IM_WIDTH, IM_HEIGHT),
batch_size=batch_size,class_mode='categorical') validation_generator = test_datagen.flow_from_directory(
val_dir,
target_size=(IM_WIDTH, IM_HEIGHT),
batch_size=batch_size,class_mode='categorical') # 添加新层
def add_new_last_layer(base_model, nb_classes):
"""
添加最后的层
输入
base_model和分类数量
输出
新的keras的model
"""
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(FC_SIZE, activation='relu')(x) #new FC layer, random init
predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer
model = Model(input=base_model.input, output=predictions)
return model
# 冻上NB_IV3_LAYERS之前的层
def setup_to_finetune(model):
"""Freeze the bottom NB_IV3_LAYERS and retrain the remaining top layers. note: NB_IV3_LAYERS corresponds to the top inception blocks in the inceptionv3 arch Args:
model: keras model
"""
for layer in model.layers[:NB_IV3_LAYERS_TO_FREEZE]:
layer.trainable = False
for layer in model.layers[NB_IV3_LAYERS_TO_FREEZE:]:
layer.trainable = True
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy']) # 设置网络结构
model = InceptionV3(weights='imagenet', include_top=False)
model = add_new_last_layer(model, nb_classes)
setup_to_finetune(model) # 模式二训练
history_ft = model.fit_generator(
train_generator,
samples_per_epoch=nb_train_samples,
nb_epoch=nb_epoch,
validation_data=validation_generator,
nb_val_samples=nb_val_samples,
class_weight='auto1') # 模型保存
model.save(output_model_file)
model.save_weights(wights_path)
# 画图
def plot_training(history):
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'r.')
plt.plot(epochs, val_acc, 'r')
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'r.')
plt.plot(epochs, val_loss, 'r-')
plt.title('Training and validation loss')
plt.show() # 训练的acc_loss图
plot_training(history_ft)
2 . 服务器上测试图片
# --coding:utf---
# 定义层
import sys
import argparse
import numpy as np
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt from keras.preprocessing import image
from keras.models import load_model
from keras.applications.inception_v3 import preprocess_input # 狂阶图片指定尺寸
target_size = (, ) #fixed size for InceptionV3 architecture # 预测函数
# 输入:model,图片,目标尺寸
# 输出:预测predict
def predict(model, img, target_size):
"""Run model prediction on image
Args:
model: keras model
img: PIL format image
target_size: (w,h) tuple
Returns:
list of predicted labels and their probabilities
"""
if img.size != target_size:
img = img.resize(target_size) x = image.img_to_array(img)
x = np.expand_dims(x, axis=)
x = preprocess_input(x)
preds = model.predict(x)
return preds[] # 画图函数
# 预测之后画图,这里默认是猫狗,当然可以修改label labels = ("mosaic", "normal")
def plot_preds(image, preds,labels):
"""Displays image and the top-n predicted probabilities in a bar graph
Args:
image: PIL image
preds: list of predicted labels and their probabilities
"""
plt.imshow(image)
plt.axis('off')
plt.figure()
plt.barh([, ], preds, alpha=0.5)
plt.yticks([, ], labels)
plt.xlabel('Probability')
plt.xlim(,1.01)
plt.tight_layout()
plt.show() # 载入模型
model = load_model('/home/dl/local_repo/data/mosaic1/mosaic.model') # 本地图片
img = Image.open('test.jpg')
preds = predict(model, img, target_size)
print preds
##plot_preds(img, preds,labels)##因为没有显示器 所以不画图了
3. hdf5 转为 pb
# -*- coding: utf- -*-
from keras.models import load_model
import tensorflow as tf
import os
import os.path as osp
from keras import backend as K
#路径参数
# input_path = 'input path'
# weight_file = 'weight.h5'
# weight_file_path = osp.join(input_path,weight_file) weight_file = 'mosaic.hdf5'
weight_file_path = '/home/dl/local_repo/data/mosaic1/mosaic.hdf5' output_graph_name = weight_file[:-] + '.pb' #转换函数
def h5_to_pb(h5_model,output_dir,model_name,out_prefix = "output_",log_tensorboard = True):
if osp.exists(output_dir) == False:
os.mkdir(output_dir)
out_nodes = []
for i in range(len(h5_model.outputs)):
out_nodes.append(out_prefix + str(i + ))
tf.identity(h5_model.output[i],out_prefix + str(i + ))
sess = K.get_session()
from tensorflow.python.framework import graph_util,graph_io
init_graph = sess.graph.as_graph_def()
main_graph = graph_util.convert_variables_to_constants(sess,init_graph,out_nodes)
graph_io.write_graph(main_graph,output_dir,name = model_name,as_text = False)
if log_tensorboard:
from tensorflow.python.tools import import_pb_to_tensorboard
import_pb_to_tensorboard.import_to_tensorboard(osp.join(output_dir,model_name),output_dir)
#输出路径
output_dir = osp.join(os.getcwd(),"trans_model")
#加载模型
h5_model = load_model(weight_file_path)
h5_to_pb(h5_model,output_dir = output_dir,model_name = output_graph_name)
print('model saved')
TEST(Test_TensorFlow, read_inception)
{
Net net;
{
const string model = findDataFile("dnn/tensorflow_inception_graph.pb", false);
net = readNetFromTensorflow(model);
ASSERT_FALSE(net.empty());
}
net.setPreferableBackend(DNN_BACKEND_OPENCV); Mat sample = imread(_tf("grace_hopper_227.png"));
ASSERT_TRUE(!sample.empty());
Mat input;
resize(sample, input, Size(, ));
input -= ; // mean sub Mat inputBlob = blobFromImage(input); net.setInput(inputBlob, "input");
Mat out = net.forward("softmax2"); std::cout << out.dims << std::endl;
}
这里是由于FusedBatchNorm 越界了 blobs的size是3 取不到blobs[3]
2. 提示libnvinfer.so.5 找不到
下载对应版本的 TensorRT https://developer.nvidia.com/nvidia-tensorrt-5x-download
tar ***.tar.gz
cd TensorRT*/lib
cp libnvinfer.so.5.0.2 /usr/lib/x86_64-linux-gnu/
ln -s /usr/lib/x86_64-linux-gnu/libnvinfer.so.5.0.2 /usr/lib/x86_64-linux-gnu/libnvinfer.so.5
Keras 训练 inceptionV3 并移植到OpenCV4.0 in C++的更多相关文章
- keras训练cnn模型时loss为nan
keras训练cnn模型时loss为nan 1.首先记下来如何解决这个问题的:由于我代码中 model.compile(loss='categorical_crossentropy', optimiz ...
- keras训练和保存
https://cloud.tencent.com/developer/article/1010815 8.更科学地模型训练与模型保存 filepath = 'model-ep{epoch:03d}- ...
- 【tf.keras】TensorFlow 1.x 到 2.0 的 API 变化
TensorFlow 2.0 版本将 keras 作为高级 API,对于 keras boy/girl 来说,这就很友好了.tf.keras 从 1.x 版本迁移到 2.0 版本,需要修改几个地方. ...
- [MFC] VS2013版本MFC工程移植到VC6.0上
:VS虽号称“宇宙最强IDE”,但是有时候安装包太大,动不动就几个G:而且安装好之后也会多出很多几乎很难用到的部分,这对于那些处女座的人如何忍受!本文不是吐槽,而是给出一种在应急场景下,不用安装新版本 ...
- 车牌定位与畸变校正(python3.7,opencv4.0)
一.前言及思路简析 目前车牌识别系统在各小区门口随处可见,识别效果貌似都还可以.查阅资料后,发现整个过程又可以细化为车牌定位.畸变校正.车牌分割和内容识别四部分.本篇随笔主要介绍车牌定位及畸变校正两部 ...
- VS 2017 + opencv4.0
完全参考这一文章, 非常详细: https://blog.csdn.net/qq_41175905/article/details/80560429 记录自己遇到的问题: 1. VS 2017 专业版 ...
- pycharm opencv4.0安装使用
pycharm+opencv4.0 还记得去年冬天装了两回opencv3,每次都搞得死去活来的.. 今天也是查了一上午,什么anaconda,vs,但是我是在pycharm的虚拟环境中安装,突然看到一 ...
- 在VS2017(VC15)上配置opencv4.0.1环境
在VS2017(VC15)上配置opencv4.0.1环境 转 https://blog.csdn.net/GoldenBullet/article/details/86016921 作为萌新最初 ...
- vs2017+opencv4.0.1安装配置详解(win10)
一.说明 笔者之前已经安装过了vs2017,对应的opencv是3.4.0版本的.但现在想体验下opencv4的改变之处,所以下载了最新的opencv4.0.1. vs2017的安装请自行搜索安装,本 ...
随机推荐
- matlab将多张图片合成视频
文件夹内多张图合成为视频: route='D:\文件及下载相关\桌面\**\Matlab_code\result';%基本路径 %d=dir([route '\*.bmp']);%.jpg格式 Wri ...
- 阶段5 3.微服务项目【学成在线】_day18 用户授权_10-前端集成认证授权-需求分析
4 前端集成认证授权 4.1 需求分析 截至目前认证授权服务端的功能已基本完成,本章实现前端集成认证授权功能. 前端集成认证授权功能需要作如下工作: 1.前端页面校验用户的身份,如果用户没有登录则跳转 ...
- 在过滤器中获取在web.xml配置的初始化参数
在过滤器中获取在web.xml配置的初始化参数 例如 <filter> <filter-name>cross-origin</filter-name> < ...
- Qt编写自定义控件39-导航标签
一.前言 在很多菜单导航界面中,当单击了二级菜单或者三级菜单以后,顶部会显示带箭头或者其他标识的导航标签,可以单击该标签快速切换到对应的界面,也作为指示当前处于哪一级菜单下的界面,主要在WEB中大肆流 ...
- SpringCloud学习成长之路七 高可用配置中心
上一篇文章讲述了一个服务如何从配置中心读取文件,配置中心如何从远程git读取配置文件,当服务实例很多时,都从配置中心读取文件,这时可以考虑将配置中心做成一个微服务,将其集群化,从而达到高可用,架构图如 ...
- jQuery前端插件以及图片延迟加载
插件名称 用途 插件官网地址 fontawsome CSS图标插件 http://fontawesome.io easyui 基于jQuery的用户界面插件集合 http://www.jeasyui. ...
- PPT做交互效果
1 做交互效果(点击一个按钮,弹出某个框或者跳转到某个页面)其实就是若干个PPT页面,利用给按钮增加超链接或者动作 达到点击一个按钮 跳转到另外一个PPT的效果. 2 选择一个形状组件(或者其他组件) ...
- 连载三:RobotFramework+Selenium+Jenkins分布式构建
目标:Jenkins安装在服务器上,而使用Jenkins调用本机的脚本并在本机执行. 步骤: (1)需要有RobotFrameWork+Selenium的运行环境: python2.7,Robotfr ...
- laravel进程管理supervisor的简单说明
原文地址:https://www.cnblogs.com/zhoujinyi/p/6073705.html 背景: 项目中遇到有些脚本需要通过后台进程运行,保证不被异常中断,之前都是通过nohup.& ...
- 【转载】Globelmposter勒索病毒最新变种预警
近日,深信服安全团队观察到Globelmposter勒索病毒又出现最新变种,加密后缀有Ares666.Zeus666.Aphrodite666.Apollon666等,目前国内已有多家大型医院率先发现 ...