本章主要内容是利用mqtt、多线程、队列实现模型一次加载,批量图片识别分类功能

目录结构如下:

mqtt连接及多线程队列管理

MqttManager.py

  1. # -*- coding:utf8 -*-
  2. import paho.mqtt.client as mqtt
  3. from multiprocessing import Process, Queue
  4. import images_detect
  5. MQTTHOST = "192.168.3.202"
  6. MQTTPORT = 1883
  7. mqttClient = mqtt.Client()
  8. q = Queue()
  9. # 连接MQTT服务器
  10. def on_mqtt_connect():
  11. mqttClient.connect(MQTTHOST, MQTTPORT, 60)
  12. mqttClient.loop_start()
  13. # 消息处理函数
  14. def on_message_come(mqttClient, userdata, msg):
  15. q.put(msg.payload.decode("utf-8")) # 放入队列
  16. print("产生消息", msg.payload.decode("utf-8"))
  17. def consumer(q, pid):
  18. print("开启消费序列进程", pid)
  19. # 多进程中发布消息需要重新初始化mqttClient
  20. ImagesDetect = images_detect.ImagesDetect()
  21. ImagesDetect.detect(q)
  22. # subscribe 消息订阅
  23. def on_subscribe():
  24. mqttClient.subscribe("test", 1) # 主题为"test"
  25. mqttClient.on_message = on_message_come # 消息到来处理函数
  26. # publish 消息发布
  27. def on_publish(topic, msg, qos):
  28. mqttClient.publish(topic, msg, qos);
  29. def main():
  30. on_mqtt_connect()
  31. on_subscribe()
  32. for i in range(1, 3):
  33. c1 = Process(target=consumer, args=(q, i))
  34. c1.start()
  35. while True:
  36. pass
  37. if __name__ == '__main__':
  38. main()

图片识别

images_detect.py

  1. # coding: utf-8
  2. import numpy as np
  3. import os
  4. import sys
  5. import tarfile
  6. import tensorflow as tf
  7. from object_detection.utils import label_map_util
  8. from object_detection.utils import visualization_utils as vis_util
  9. import cv2
  10. import decimal
  11. import MyUtil
  12. context = decimal.getcontext()
  13. context.rounding = decimal.ROUND_05UP
  14. class ImagesDetect():
  15. def __init__(self):
  16. sys.path.append("..")
  17. MODEL_NAME = 'faster_rcnn_inception_v2_coco_2018_01_28'
  18. MODEL_FILE = MODEL_NAME + '.tar.gz'
  19. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  20. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
  21. # List of the strings that is used to add correct label for each box.
  22. PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
  23. NUM_CLASSES = 90
  24. tar_file = tarfile.open(MODEL_FILE)
  25. for file in tar_file.getmembers():
  26. file_name = os.path.basename(file.name)
  27. if 'frozen_inference_graph.pb' in file_name:
  28. tar_file.extract(file, os.getcwd())
  29. # ## Load a (frozen) Tensorflow model into memory.
  30. self.detection_graph = tf.Graph()
  31. with self.detection_graph.as_default():
  32. od_graph_def = tf.GraphDef()
  33. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  34. serialized_graph = fid.read()
  35. od_graph_def.ParseFromString(serialized_graph)
  36. tf.import_graph_def(od_graph_def, name='')
  37. # ## Loading label map
  38. # Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine
  39. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  40. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  41. self.category_index = label_map_util.create_category_index(categories)
  42. self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
  43. # 每个框代表一个物体被侦测到
  44. self.boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
  45. # 每个分值代表侦测到物体的可信度.
  46. self.scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
  47. self.classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
  48. self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
  49. def detect(self, q):
  50. with self.detection_graph.as_default():
  51. config = tf.ConfigProto()
  52. # config.gpu_options.allow_growth = True
  53. config.gpu_options.per_process_gpu_memory_fraction = 0.2
  54. with tf.Session(graph=self.detection_graph, config=config) as sess:
  55. while True:
  56. img_src = q.get()
  57. print('------------start------------' + MyUtil.get_time_stamp())
  58. image_np = cv2.imread(img_src)
  59. # 扩展维度,应为模型期待: [1, None, None, 3]
  60. image_np_expanded = np.expand_dims(image_np, axis=0)
  61. # 执行侦测任务.
  62. (boxes, scores, classes, num_detections) = sess.run(
  63. [self.boxes, self.scores, self.classes, self.num_detections],
  64. feed_dict={self.image_tensor: image_np_expanded})
  65. # 检测结果的可视化
  66. vis_util.visualize_boxes_and_labels_on_image_array(
  67. image_np,
  68. np.squeeze(boxes),
  69. np.squeeze(classes).astype(np.int32),
  70. np.squeeze(scores),
  71. self.category_index,
  72. use_normalized_coordinates=True,
  73. line_thickness=8)
  74. print('------------end------------' + MyUtil.get_time_stamp())
  75. # cv2.imshow('object detection', cv2.resize(image_np, (800, 600)))
  76. if cv2.waitKey(25) & 0xFF == ord('q'):
  77. cv2.destroyAllWindows()
  78. break

MyUtil.py

  1. import time
  2. def get_time_stamp():
  3. ct = time.time()
  4. local_time = time.localtime(ct)
  5. data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
  6. data_secs = (ct - int(ct)) * 1000
  7. time_stamp = "%s.%03d" % (data_head, data_secs)
  8. return time_stamp

效果:

基于谷歌开源的TensorFlow Object Detection API视频物体识别系统搭建自己的应用(四)的更多相关文章

  1. 对于谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    本教程针对Windows10实现谷歌近期公布的TensorFlow Object Detection API视频物体识别系统,其他平台也可借鉴. 本教程将网络上相关资料筛选整合(文末附上参考资料链接) ...

  2. 谷歌开源的TensorFlow Object Detection API视频物体识别系统实现教程

    视频中的物体识别 摘要 物体识别(Object Recognition)在计算机视觉领域里指的是在一张图像或一组视频序列中找到给定的物体.本文主要是利用谷歌开源TensorFlow Object De ...

  3. 谷歌开源的TensorFlow Object Detection API视频物体识别系统实现(二)[超详细教程] ubuntu16.04版本

    本节对应谷歌开源Tensorflow Object Detection API物体识别系统 Quick Start步骤(一): Quick Start: Jupyter notebook for of ...

  4. 谷歌开源的TensorFlow Object Detection API视频物体识别系统实现(一)[超详细教程] ubuntu16.04版本

    谷歌宣布开源其内部使用的 TensorFlow Object Detection API 物体识别系统.本教程针对ubuntu16.04系统,快速搭建环境以及实现视频物体识别系统功能. 本节首先介绍安 ...

  5. 安装运行谷歌开源的TensorFlow Object Detection API视频物体识别系统

    Linux安装 参照官方文档:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/inst ...

  6. 使用Tensorflow object detection API——训练模型(Window10系统)

    [数据标注处理] 1.先将下载好的图片训练数据放在models-master/research/images文件夹下,并分别为训练数据和测试数据创建train.test两个文件夹.文件夹目录如下 2. ...

  7. 基于TensorFlow Object Detection API进行迁移学习训练自己的人脸检测模型(二)

    前言 已完成数据预处理工作,具体参照: 基于TensorFlow Object Detection API进行迁移学习训练自己的人脸检测模型(一) 设置配置文件 新建目录face_faster_rcn ...

  8. 基于TensorFlow Object Detection API进行相关开发的步骤

    *以下二/三.四步骤确保你当前的文件目录是以research文件夹为相对目录. 一/安装或升级protoc 查看protoc版本命令: protoc --version 如果发现版本低于2.6.0或运 ...

  9. 使用TensorFlow Object Detection API+Google ML Engine训练自己的手掌识别器

    上次使用Google ML Engine跑了一下TensorFlow Object Detection API中的Quick Start(http://www.cnblogs.com/take-fet ...

随机推荐

  1. CSS盒子模型与怪异盒模型

             盒子模型(Box Modle)可以用来对元素进行布局,包括内边距,边框,外边距,和实际内容这几个部分. 盒子模型分为两种 第一种是W3c标准的盒子模型(标准盒模型) .第二种IE标准 ...

  2. 搭建nginx环境(参考腾讯云实验室)

    使用 yum 安装 Nginx: yum install nginx -y 修改 /etc/nginx/conf.d/default.conf,去除对 IPv6 地址的监听,可参考下面的代码示例: s ...

  3. IIS6、IIS7.5设置网站默认首页方法(Directory Listing Denied)

    这篇文章主要介绍了IIS6.IIS7.5设置网站默认首页方法,如果不设置访问目录就会提示Directory Listing Denied,就是不允许列出文档,为了安全网站都会设置不设置默认,需要的朋友 ...

  4. mysql AND运算符 语法

    mysql AND运算符 语法 作用:在 WHERE 子语句中把两个或多个条件结合起来.佛山大理石方尺 语法:SELECT * FROM 表名 WHERE 字段1 运算符 值 AND 字段2 运算符 ...

  5. All men are brothers

    All men are brothers 牛客多校第九场E 给定n个人,起初互不认识 然后m各阶段 每个阶段有两个人x.y认识 求每个阶段选出四个人互不认识的方式 并查集 #include<bi ...

  6. Java数据结构之排序---冒泡排序

    冒泡排序的基本思想: 通过对待排序序列从前到后(从下标小的元素开始),依次比较相邻位置的元素的值,若发现与给定的次序冲突,则交换位置(假设数值大的数放在序列的后面),使数值较大的元素逐渐从前移动到后部 ...

  7. 续上文,Unity3D面试ABC

    http://www.unitymanual.com/blog-3573-685.html 最先执行的方法是: 1.(激活时的初始化代码)Awake,2.Start.3.Update[FixUpdat ...

  8. 8 Django模型层(1)

    知识预览 ore简介 单表操作 章节作业 ore简介 MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可 ...

  9. 《SQL Server 2012 T-SQL基础》读书笔记 - 9.事务和并发

    Chapter 9 Transactions and Concurrency SQL Server默认会把每个单独的语句作为一个事务,也就是会自动在每个语句最后提交事务(可以设置IMPLICIT_TR ...

  10. JavaScript code modules

    https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules Non-standardThis feature is ...