目标检测实战(二)--调取摄像头进行物体检测

上一节,我们完成了对鼠标图像的检测,这一节我们使用opencv调用电脑摄像头检测鼠标
参考代码博客:
https://blog.csdn.net/Ch97CKd/article/details/82700777
文件名:object_detection_converted.py

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tensorflow as tf
 
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from object_detection.utils import ops as utils_ops
import cv2
sys.path.append("..")
CWD_PATH = os.getcwd()
PATH_TO_CKPT = os.path.join(CWD_PATH,'frz_out','frozen_inference_graph.pb')
 
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join(CWD_PATH,'training', 'label.pbtxt')
cap = cv2.VideoCapture(0)
NUM_CLASSES = 1
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='')
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)
with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.read()
            # 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=8)
 
            cv2.imshow('object detection', cv2.resize(image_np, (800,600)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
cap.release()
cv2.destroyAllWindows()

文中有两处需要修改成自己的文件名:
1.PATH_TO_CKPT:导出的模型文件
2.PATH_TO_LABELS:pbtxt文件
在object_detection_converted.py文件所在位置使用以下命令:

python object_detection_converted.py

效果如下:
目标检测实战(二)--调取摄像头进行物体检测_第1张图片
效果其实不是很好,主要因为数据量太小的缘故,只用了几百张图片,不过练手还是可以的

你可能感兴趣的:(目标检测,目标检测,tensorflow,摄像头)