原创 Wade129 最后发布于2018-11-06 15:25:19 阅读数 6302

收藏

发布于2018-11-06 15:25:19

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

运行环境

  • python2.7
  • tensorflow1.8.0
  • opencv
  • VNC viewer远程控制树莓派

硬件

环境安装配置

  • 默认已安装好python2.7和pip
  • 安装matplotlib库
    sudo pip install matplotlib
  • 下载1.8.0的tensorflow
    因为之后要调用的神经网络模型是在tensorflow1.8下训练的,所以为了避免不必要的问题,用1.8.0版本
    tensorflow所有版本下载
    树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图1
    适用于Raspberry pi 2/3的tensorflow1.8.0下载
    为了指定版本,用以下指令下载安装
    sudo pip uninstall tensorflow
    wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp27-none-linux_armv7l.whl
    sudo pip install tensorflow-1.8.0-cp27-none-linux_armv7l.whl
  • opencv下载安装
    因为我只用到了opencv的python接口,所以不用源码安装,用最简单暴力的pip安装
    sudo pip uninstall opencv-python
    sudo pip install opencv-python

准备模型

  • tensorflows models API下载
    下载tensorflow提供的models API并解压成为一个models文件夹
    models API下载路径
    git clone https://github.com/tensorflow/models.git

  • 下载用COCO训练集预训练的模型
    下载训练好的模型并放到上一步models下的object_detection/models目录
    模型下载路径
    本文使用的是ssd_mobilenet_v1_coco(SSD是专门为速度优化过最快的网络)
    树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图2
    模型下载
    wget download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2018_01_28.tar.gz
    解压出文件夹ssd_mobilenet_v1_coco_2018_01_28
    tar -xzvf ssd_mobilenet_v1_coco_2018_01_28.tar.gz

  • 将proto格式的数据转换为python格式
    protobuf是Google开发的一种混合语言数据标准,提供了一种轻便高效的结构化数据存储格式,可以用于结构化数据序列化。
    安装tensorflow的时候会附带下载protobuf依赖包,
    进入目录models/research,运行:
    protoc object_detection/protos/*.proto --python_out=.
    转换完毕后可以看到在object_detection/protos/目录下多了许多*.py文件。

硬件准备

  • 树莓派摄像头安装激活
    将树莓派摄像头与树莓派3b连接好
    在树莓派终端运行:
    sudo raspi-config
    进入Interfacing Options, Enable开通Camera(摄像头)、SSH和VNC服务

个人PC远程连接树莓派

  • 命令行ssh远程连接树莓派
    ssh pi@树莓派IP地址
  • 在树莓派上安装Tight VNC 包
    sudo apt-get install tightvncserver
  • 启动VNC server
    vncserver :1
    当提示输入密码时,创建一个密码 (这个密码是远程用户访问时用的)
  • 在远程计算机(windows)上访问
  1. 下载 VNC Viewer
  2. 运行 VNC-Viewer
  3. 在 VNC Server栏中,输入树莓派的IP地址,后面加上 :1 字样
  4. 按 connect 连接
  5. 输入你的树莓派用户名和密码后就可以看到树莓派桌面了(一般默认用户名pi,默认密码raspberry,如果你没改的话)

运行代码

  1. import numpy as np
  2. import os
  3. import sys
  4. import tarfile
  5. import tensorflow as tf
  6. import cv2
  7. import time
  8. from collections import defaultdict
  9. sys.path.append("../..")
  10. from object_detection.utils import label_map_util
  11. from object_detection.utils import visualization_utils as vis_util
  12. MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
  13. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
  14. PATH_TO_LABELS = os.path.join('/home/pi/models/research/object_detection/data', 'mscoco_label_map.pbtxt')
  15. model_path = "/home/pi/models/research/object_detection/models/ssd_mobilenet_v1_coco_2018_01_28/model.ckpt"
  16. start = time.clock()
  17. NUM_CLASSES = 90
  18. end= time.clock()
  19. print('load the model' ,(end -start))
  20. detection_graph = tf.Graph()
  21. with detection_graph.as_default():
  22. od_graph_def = tf.GraphDef()
  23. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  24. serialized_graph = fid.read()
  25. od_graph_def.ParseFromString(serialized_graph)
  26. tf.import_graph_def(od_graph_def, name='')
  27. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  28. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  29. category_index = label_map_util.create_category_index(categories)
  30. cap = cv2.VideoCapture(0)
  31. with detection_graph.as_default():
  32. with tf.Session(graph=detection_graph) as sess:
  33. writer = tf.summary.FileWriter("logs/", sess.graph)
  34. sess.run(tf.global_variables_initializer())
  35. loader = tf.train.import_meta_graph(model_path + '.meta')
  36. loader.restore(sess, model_path)
  37. while(1):
  38. start = time.clock()
  39. ret, frame = cap.read()
  40. if cv2.waitKey(1) & 0xFF == ord('q'):
  41. break
  42. image_np =frame
  43. image_np_expanded = np.expand_dims(image_np, axis=0)
  44. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  45. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  46. scores = detection_graph.get_tensor_by_name('detection_scores:0')
  47. classes = detection_graph.get_tensor_by_name('detection_classes:0')
  48. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  49. (boxes, scores, classes, num_detections) = sess.run(
  50. [boxes, scores, classes, num_detections],
  51. feed_dict={image_tensor: image_np_expanded})
  52. vis_util.visualize_boxes_and_labels_on_image_array(
  53. image_np, np.squeeze(boxes),
  54. np.squeeze(classes).astype(np.int32),
  55. np.squeeze(scores),
  56. category_index,
  57. use_normalized_coordinates=True,
  58. line_thickness=6)
  59. end = time.clock()
  60. print 'One frame detect take time:' ,end - start
  61. cv2.imshow("capture", image_np)
  62. print('after cv2 show')
  63. cv2.waitKey(1)
  64. cap.release()
  65. cv2.destroyAllWindows()
  • 将代码保存为test.py保存在models/research/object_detection/models目录下,
  • 在个人PC用VNC viewer远程连接树莓派,并打开terminal
    注意:之前的操作都可以在个人PC命令行操作,接下来的操作要在树莓派界面操作
  • 进入目录models/research/object_detection/models,运行:
    sudo chmod 666 /dev/video0
    python test.py
  • 运行成功以后回弹出capture窗口,就可以进行物体识别了

效果

树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图3树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图4

  • 加载SSD模型时间:
    约9s(相当于开机需要9秒的时间)
  • 识别时间:
    平均约为4s
  • 识别效果
    拿摄像头拍了一下实验室的办公桌,
    识别出了饮料瓶(bottle),手提电脑(laptop),还有书本(book),并给出了相应的判断百分比

参考文章

https://www.jianshu.com/p/ea5abe01aaf1

树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图5 树莓派   tensorflow   opencv   摄像头实现物体检测_人工智能_Wade's blog-CSDN博客 - 图6

发布了2 篇原创文章 · 获赞 15 · 访问量 6542