tensorflwo的object_detection(视频,电脑摄像头,手机摄像头)+opencv+多线程实现以

1、获取protobuf

https://github.com/google/protobuf/releases/tag/v2.6.1
下载protoc-2.6.1-win32.zip
是一个exe文件,不要安装滴

2、编译proto配置文件

在models\research\下执行

protoc.exe object_detection/protos/*.proto --python_out=.

3、检测API是否正常

这里的tensorflow的models下载地址:
https://github.com/tensorflow/models
1.将models\research\slim\nets目录复制到models\research下
2.将models\research\object_detection\builders下的model_builder_test.py复制到models\research
用spyder将model_builder_test.py打开运行,检测API是否正常
4、下载预训练模型
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md
模型解压的地址看代码里面,我这里直接放在research目录下面。
5.代码

指定模型名称

MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'

指定模型文件所在的路经

PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

创建图来存放google训练好的模型

读写文件,句柄具有.read()方法,实测凡是使用tf.gfile.FastGFile()
的地方换乘open()并不会报错(包括读取普通文件和读取tf模型文件)

#with tf.gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:  # 使用tf.gfile.FastGFile()函数的方法
with open(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:                 # 使用open()函数的方法
    graph_def = tf.GraphDef()                                              # 生成图
    graph_def.ParseFromString(f.read())                                    # 图加载模型
    bottleneck_tensor,jpeg_data_tensor = tf.import_graph_def(              # 从图上读取张量,同时把图设为默认图
        graph_def,
        return_elements=[BOTTLENECK_TENSOR_NAME,JPEG_DATA_TENSOR_NAME])
 
 
print(gfile.FastGFile(image_path,'rb').read()==open(image_path,'rb').read())
# True

接下来就是载入数据集标签

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
#得到分类集合
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
#得到分类索引
category_index = label_map_util.create_category_index(categories)        

对图片进行数据强制转化

def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)        

拿到模型里的占位符,如下:
image_tensor ,boxes,scores ,classes ,num_detections

      image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
      # 每个框代表一个物体被侦测到
      boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
      # Each score 代表识别出的物体与标签匹配的相似程度,在类型标签后面
      # 分数与成绩标签一起显示在结果图像上。
      scores = detection_graph.get_tensor_by_name('detection_scores:0')
      classes = detection_graph.get_tensor_by_name('detection_classes:0')
      num_detections = detection_graph.get_tensor_by_name('num_detections:0')

输入数据开始检测

      (boxes, scores, classes, num_detections) = sess.run(
          [boxes, scores, classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})

对检测的结果进行可视化

      # 可视化结果.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)
      plt.figure(figsize=IMAGE_SIZE)
      plt.imshow(image_np) 

下面借鉴大神代码改编的,复制就行了(电脑版)

main.py

# -*- coding: utf-8 -*-

import numpy as np
import os

import tensorflow as tf
from matplotlib import pyplot as plt
from PIL import Image
from tensorflow.models.research.object_detection.utils import label_map_util

from tensorflow.models.research.object_detection.utils import visualization_utils as vis_util

#指定模型名称
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'

# 指定模型文件所在的路经
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# 数据集对应的label.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

tf.reset_default_graph()

od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')       
#载入coco数据集标签文件        
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
#得到分类集合
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
#得到分类索引
category_index = label_map_util.create_category_index(categories)        
        
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)        
        
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# 从PATH_TO_TEST_IMAGES_DIR路径下读取测试图形文件
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]

# 设置输出图片大小
IMAGE_SIZE = (12, 8)        
       
def detect_objects(image_np, sess, detection_graph):
    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
    image_np_expanded = np.expand_dims(image_np, axis=0)
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

    # Each box represents a part of the image where a particular object was detected.
    boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    scores = detection_graph.get_tensor_by_name('detection_scores:0')
    classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')

    # Actual detection.
    (boxes, scores, classes, num_detections) = sess.run(
        [boxes, scores, classes, num_detections],
        feed_dict={image_tensor: image_np_expanded})

    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=3)
    return image_np

detection_graph = tf.get_default_graph()  
with tf.Session(graph=detection_graph) as sess:
    for image_path in TEST_IMAGE_PATHS:
        image = Image.open(image_path)#读入图片文件    
        image_np = load_image_into_numpy_array(image)
        detect_objects(image_np, sess, detection_graph)
        plt.figure(figsize=IMAGE_SIZE)
        plt.imshow(image_np) 

手机作为摄像头的代码

首先下载任意款网络摄像头
本人手机魅蓝note2,在应用超市筛选出来这款手机app摄像头


打开app后,点击开启云服务

就会出现以下内容了

这里出现192.168.2.104:8080等字样


高潮来了

把地址复制在cam_url='http://192.168.2.104:8080/video'
就行了

import numpy as np
import os
import time
import tensorflow as tf
from matplotlib import pyplot as plt
from PIL import Image
from tensorflow.models.research.object_detection.utils import label_map_util

from tensorflow.models.research.object_detection.utils import visualization_utils as vis_util

import cv2
from threading import Thread

#指定模型名称
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'

# 指定模型文件所在的路经
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# 数据集对应的label.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

tf.reset_default_graph()  
#载入coco数据集标签文件        
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
#得到分类集合
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
#得到分类索引
category_index = label_map_util.create_category_index(categories)        
        
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)        
        
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# 从PATH_TO_TEST_IMAGES_DIR路径下读取测试图形文件
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]

# 设置输出图片大小
IMAGE_SIZE = (12, 8)        
       
def detect_objects(image_np, sess, detection_graph):
    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
    image_np_expanded = np.expand_dims(image_np, axis=0)
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

    # Each box represents a part of the image where a particular object was detected.
    boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    scores = detection_graph.get_tensor_by_name('detection_scores:0')
    classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')

    # Actual detection.
    (boxes, scores, classes, num_detections) = sess.run(
        [boxes, scores, classes, num_detections],
        feed_dict={image_tensor: image_np_expanded})

    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=3)
    return image_np


detection_graph = tf.get_default_graph()  


cam_url='http://192.168.2.104:8080/video'

cap = cv2.VideoCapture(cam_url)
with detection_graph.as_default():
     with tf.Session(graph=detection_graph) as sess:
           while (1):
              start = time.clock()
              frame = None
              while( str(frame) == 'None'):
                  if cap.isOpened(): 
                    rval, frame = cap.read()
                  else:
                    cap.open(cam_url)
                    rval, frame = cap.read()
              # 按帧读视
              
              if cv2.waitKey(1) & 0xFF == ord('q'):
                 break
              image_np = frame
              image_np_expanded = np.expand_dims(image_np, axis=0)
              image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
              boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
              scores = detection_graph.get_tensor_by_name('detection_scores:0')
              classes = detection_graph.get_tensor_by_name('detection_classes:0')
              num_detections = detection_graph.get_tensor_by_name('num_detections:0')
              # Actual detection.
              (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})
              vis_util.visualize_boxes_and_labels_on_image_array(
                  image_np,
                  np.squeeze(boxes),
                  np.squeeze(classes).astype(np.int32),
                  np.squeeze(scores),
                  category_index,
                  use_normalized_coordinates=True,
                  line_thickness=8)
              end = time.clock()
              #print('frame:', 1.0 / (end - start))
              cv2.imshow("capture", image_np)
              cv2.waitKey(1)
              if cv2.waitKey(1) & 0xFF == ord('q'):
                  break
 
# 释放捕捉的对象和内存
cap.release()
cv2.destroyAllWindows()

效果图(这个网速和计算速度跟不上)

在多线程时候出现了问题,在spyder中无法创建多个进程,只能创建多个线程,所以只能在cmd窗口执行程序。如果发现无法出图,不妨试一试用cmd窗口咯!!!!!!!!!!!!!!!

import numpy as np
import os

import tensorflow as tf
from matplotlib import pyplot as plt
from PIL import Image
from tensorflow.models.research.object_detection.utils import label_map_util
from multiprocessing import Queue,Pool
from tensorflow.models.research.object_detection.utils import visualization_utils as vis_util
import time
import cv2
from threading import Thread

#指定模型名称
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'

# 指定模型文件所在的路经
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# 数据集对应的label.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

tf.reset_default_graph()

#载入coco数据集标签文件        
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
#得到分类集合
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
#得到分类索引
category_index = label_map_util.create_category_index(categories)        
        
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)        
     
def detect_objects(image_np, sess, detection_graph):
    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
    image_np_expanded = np.expand_dims(image_np, axis=0)
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

    # Each box represents a part of the image where a particular object was detected.
    boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    scores = detection_graph.get_tensor_by_name('detection_scores:0')
    classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')

    # Actual detection.
    (boxes, scores, classes, num_detections) = sess.run(
        [boxes, scores, classes, num_detections],
        feed_dict={image_tensor: image_np_expanded})

    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=3)
    return image_np

# 多线程,高效读视频
class WebcamVideoStream:
    def __init__(self, src, width, height):
        # initialize the video camera stream and read the first frame
        # from the stream
        self.stream = cv2.VideoCapture(src)
        self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        (self.grabbed, self.frame) = self.stream.read()

        # initialize the variable used to indicate if the thread should
        # be stopped
        self.stopped = False

    def start(self):
        # start the thread to read frames from the video stream
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
        # keep looping infinitely until the thread is stopped
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return

            # otherwise, read the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # return the frame most recently read
        return self.frame

    def stop(self):
        # indicate that the thread should be stopped
        self.stream.release()
        self.stopped = True


class configs(object):
     def __init__(self):
         self.num_workers = 2 # worker数量
         self.queue_size = 5  # 多进程,输入输出,队列长度
         self.video_source = 0 # 0代表从摄像头读取视频流
         self.width = 720 # 图片宽
         self.height = 490 # 图片高


def worker(input_q, output_q):
    # Load a (frozen) Tensorflow model into memory.
    detection_graph = tf.Graph()
    with detection_graph.as_default():
        od_graph_def = tf.GraphDef()
        with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
            serialized_graph = fid.read()
            od_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(od_graph_def, name='')

        sess = tf.Session(graph=detection_graph)

    while True:
        frame = input_q.get()
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        output_q.put(detect_objects(frame_rgb, sess, detection_graph))

    sess.close()

if __name__ == '__main__':
    args = configs()
    input_q = Queue(maxsize=args.queue_size)
    output_q = Queue(maxsize=args.queue_size)
    pool = Pool(args.num_workers, worker, (input_q, output_q))
    
    video_capture = WebcamVideoStream(src=args.video_source,
                                      width=args.width,
                                      height=args.height).start()
    
    while True:  # fps._numFrames < 120
    
        frame = video_capture.read()
        input_q.put(frame)
        t = time.time()
        if output_q.empty():
            pass  # fill up queue
        else:
            output_rgb = cv2.cvtColor(output_q.get(), cv2.COLOR_RGB2BGR)
            cv2.imshow('Video', output_rgb)
    
    
        print('[INFO] elapsed time: {:.2f}'.format(time.time() - t))
    
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    pool.terminate()
    video_capture.stop()
    cv2.destroyAllWindows()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容