打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
利用OpenCV dnn调用keras深度学习模块,实现图像分类

1. 导入库文件

  1. # import the necessary packages
  2. from keras.models import Sequential
  3. from keras.layers.convolutional import Conv2D
  4. from keras.layers.convolutional import MaxPooling2D
  5. from keras.layers.core import Activation
  6. from keras.layers.core import Flatten
  7. from keras.layers.core import Dense
  8. from keras import backend as K


  9. # import the necessary packages
  10. from keras.preprocessing.image import ImageDataGenerator
  11. from keras.optimizers import Adam

  12. from keras.preprocessing.image import img_to_array
  13. from keras.utils import to_categorical
  14. from imutils import paths
  15. import matplotlib.pyplot as plt
  16. import numpy as np

  17. import random
  18. import cv2
  19. import os
  20. import sys
  21. sys.path.append('..')

2. 定义常量

  1. # initialize the number of epochs to train for, initial learning rate,
  2. # and batch size
  3. EPOCHS = 35
  4. INIT_LR = 1e-3
  5. BS = 32
  6. CLASS_NUM = 62
  7. norm_size = 32

3. 读取数据

  1. def load_data(path):
  2. print("[INFO] loading images...")
  3. data = []
  4. labels = []
  5. # grab the image paths and randomly shuffle them
  6. imagePaths = sorted(list(paths.list_images(path)))
  7. random.seed(42)
  8. random.shuffle(imagePaths)
  9. # loop over the input images
  10. for imagePath in imagePaths:
  11. # load the image, pre-process it, and store it in the data list
  12. image = cv2.imread(imagePath)
  13. image = cv2.resize(image, (norm_size, norm_size))
  14. image = img_to_array(image)
  15. data.append(image)

  16. # extract the class label from the image path and update the
  17. # labels list
  18. label = int(imagePath.split(os.path.sep)[-2])
  19. labels.append(label)

  20. # scale the raw pixel intensities to the range [0, 1]
  21. data = np.array(data, dtype="float") / 255.0
  22. labels = np.array(labels)

  23. # convert the labels from integers to vectors
  24. labels = to_categorical(labels, num_classes=CLASS_NUM)
  25. return data,labels

4. 训练并保存模型

  1. def train(aug,trainX,trainY,testX,testY):
  2. # initialize the model
  3. print("[INFO] compiling model...")
  4. model = build(width=norm_size, height=norm_size, depth=3, classes=CLASS_NUM)
  5. opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
  6. model.compile(loss="categorical_crossentropy", optimizer=opt,
  7. metrics=["accuracy"])

  8. # train the network
  9. print("[INFO] training network...")
  10. H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),
  11. validation_data=(testX, testY), steps_per_epoch=len(trainX) // BS,
  12. epochs=EPOCHS, verbose=1)

  13. # save the model to disk
  14. print("[INFO] serializing network...")
  15. model.save('traffic.h5')

5. 评估训练模型

  1. # plot the training loss and accuracy
  2. plt.style.use("ggplot")
  3. plt.figure()
  4. N = EPOCHS
  5. plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
  6. plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
  7. plt.plot(np.arange(0, N), H.history["acc"], label="train_acc")
  8. plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc")
  9. plt.title("Training Loss and Accuracy on traffic-sign classifier")
  10. plt.xlabel("Epoch #")
  11. plt.ylabel("Loss/Accuracy")
  12. plt.legend(loc="lower left")
  13. plt.show()

6. 训练模型主函数

  1. #python train.py --dataset_train ../../traffic-sign/train --dataset_test ../../traffic-sign/test --model traffic_sign.model
  2. if __name__ == '__main__':
  3. train_file_path = './data/train'
  4. test_file_path = './data/test'
  5. trainX,trainY = load_data(train_file_path)
  6. testX,testY = load_data(test_file_path)
  7. # construct the image generator for data augmentation
  8. aug = ImageDataGenerator(
  9. rotation_range=15,
  10. width_shift_range=0.1,
  11. height_shift_range=0.1,
  12. horizontal_flip=True,
  13. vertical_flip=False
  14. )
  15. train(aug,trainX,trainY,testX,testY)

7. 模型转换,由keras的h5转换为tensorflow的pb模型

  1. import keras
  2. import tensorflow as tf
  3. import os

  4. #这个函数参考自网上
  5. def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
  6. """
  7. Freezes the state of a session into a pruned computation graph.
  8. Creates a new computation graph where variable nodes are replaced by
  9. constants taking their current value in the session. The new graph will be
  10. pruned so subgraphs that are not necessary to compute the requested
  11. outputs are removed.
  12. @param session The TensorFlow session to be frozen.
  13. @param keep_var_names A list of variable names that should not be frozen,
  14. or None to freeze all the variables in the graph.
  15. @param output_names Names of the relevant graph outputs.
  16. @param clear_devices Remove the device directives from the graph for better portability.
  17. @return The frozen graph definition.
  18. """
  19. graph = session.graph
  20. with graph.as_default():
  21. freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
  22. output_names = output_names or []
  23. output_names += [v.op.name for v in tf.global_variables()]
  24. input_graph_def = graph.as_graph_def()
  25. if clear_devices:
  26. for node in input_graph_def.node:
  27. node.device = ''
  28. frozen_graph = tf.graph_util.convert_variables_to_constants(
  29. session, input_graph_def, output_names, freeze_var_names)
  30. return frozen_graph


  31. if __name__ == '__main__':
  32. input_path = './'
  33. #keras训练保存的h5文件
  34. input_file = 'traffic.h5'
  35. weight_file_path = os.path.join(input_path, input_file)
  36. output_graph_name = weight_file_path[:-3] + '.pb'

  37. # 加载模型
  38. keras.backend.set_learning_phase(0)
  39. h5_model = keras.models.load_model(weight_file_path)
  40. frozen_graph = freeze_session(keras.backend.get_session(), output_names=[out.op.name for out in h5_model.outputs])
  41. tf.train.write_graph(frozen_graph, input_path, output_graph_name, as_text=False)
  42. print('Finished')

  43. # import cv2
  44. # model = cv2.dnn.readNetFromTensorflow("traffic.pb")
  45. # print('Load')


8. 预测模型,通过keras的loadModel实现

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Aug 24 10:08:04 2020

  4. @author: Yonghong Li
  5. """


  6. # import the necessary packages
  7. from keras.preprocessing.image import img_to_array
  8. from keras.models import load_model
  9. import numpy as np
  10. import argparse
  11. import imutils
  12. import cv2

  13. norm_size = 32


  14. def predict():
  15. # load the trained convolutional neural network
  16. print("[INFO] loading network...")
  17. model = load_model('traffic.h5')

  18. #load the image
  19. image = cv2.imread('E:/python learn/TrafficClassify/data/test/00058/00413_00000.png')
  20. orig = image.copy()

  21. # pre-process the image for classification
  22. image = cv2.resize(image, (norm_size, norm_size))
  23. image = image.astype("float") / 255.0
  24. image = img_to_array(image)
  25. image = np.expand_dims(image, axis=0)

  26. # classify the input image
  27. result = model.predict(image)[0]
  28. print (result)


  29. proba = np.max(result)
  30. print(proba)

  31. label = str(np.where(result==proba)[0])
  32. label = "{}: {:.2f}%".format(label, proba * 100)
  33. print(label)

  34. if True:
  35. # draw the label on the image
  36. output = imutils.resize(orig, width=400)
  37. cv2.putText(output, label, (10, 25),cv2.FONT_HERSHEY_SIMPLEX,
  38. 0.7, (0, 255, 0), 2)
  39. # show the output image
  40. cv2.imshow("Output", output)
  41. cv2.waitKey(0)


  42. #python predict.py --model traffic_sign.model -i ../2.png -s
  43. if __name__ == '__main__':
  44. predict()

9. 预测模型,通过OpenCV dnn 加载

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat Aug 29 15:57:15 2020

  4. @author: Yonghong Li
  5. """


  6. import cv2
  7. import imutils
  8. import numpy as np

  9. norm_size = 32

  10. def predict():
  11. # load the trained convolutional neural network
  12. print("[INFO] loading network...")

  13. net = cv2.dnn.readNetFromTensorflow('traffic.pb')


  14. #load the image
  15. image = cv2.imread('E:/python learn/TrafficClassify/data/test/00058/00413_00000.png')
  16. orig = image.copy()

  17. img_tensor = cv2.dnn.blobFromImage(image, 1 / 255.0, (norm_size, norm_size), swapRB=True, crop=False)
  18. net.setInput(img_tensor)
  19. #ln = net.getUnconnectedOutLayersNames()
  20. result = net.forward()
  21. print(result)
  22. # proba = np.max(result)
  23. # print(proba)
  24. # label = str(np.where(result==proba)[2])
  25. #
  26. # print(label)
  27. #
  28. # label = "{}: {:.2f}%".format(label, proba * 100)
  29. # print(label)
  30. ## # classify the input image
  31. #

  32. min_val,max_val,min_indx,max_indx=cv2.minMaxLoc(result)
  33. print(min_val,max_val,min_indx,max_indx)
  34. label = "{}: {:.2f}%".format(max_indx, max_val * 100)
  35. ##
  36. if True:
  37. # draw the label on the image
  38. output = imutils.resize(orig, width=400)
  39. cv2.putText(output, label, (10, 25),cv2.FONT_HERSHEY_SIMPLEX,
  40. 0.7, (0, 255, 0), 2)
  41. # # show the output image
  42. cv2.imshow("Output", output)
  43. cv2.waitKey(0)

  44. if __name__ == '__main__':
  45. predict()

10. 通过OpenCV dnn加载深度学习模块,在传统的C++代码上实现了深度学习,能够根据输入的图像实现图像分类,完整代码 https://download.csdn.net/download/mr_liyonghong/12785394

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
深入探索图像处理:从基础到高级应用
入门指南:用Python实现实时目标检测(内附代码)
瞌睡检测系统介绍
基于端到端深度学习的自动驾驶:AirSim教程(包含Ubuntu18.04下配置AIrsim仿真环境解决方案)
使用CNN(卷积神经网络)和OpenCV进行手势识别
CV:基于keras利用算法MobilenetV2实现局部相似域的多人二维姿态实时估计(詹姆斯扣篮+美女跳舞)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服