tf之object detect摄像头物体识别测试

本博客介绍使用TensorFlow实现的SSD MobileNet V1模型进行实时物体检测的过程。该模型可在各种设备上高效运行,特别适用于摄像头输入的实时场景分析。文中详细展示了从模型下载、配置到最终在摄像头视频流中检测并标注物体类别的完整步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
import time  

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

from utils import label_map_util
from utils import visualization_utils as vis_util

# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
#MODEL_NAME = 'faster_rcnn_resnet101_coco_11_06_2017'
#MODEL_NAME = 'ssd_inception_v2_coco_11_06_2017'
MODEL_FILE = MODEL_NAME + '.tar.gz'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('/home/chenqy/tf36/models/object_detection/data', 'mscoco_label_map.pbtxt')

#extract the ssd_mobilenet
start = time.clock()
NUM_CLASSES = 90
opener = urllib.request.URLopener()
#opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# tar_file = tarfile.open(MODEL_FILE)
# for file in tar_file.getmembers():
#   file_name = os.path.basename(file.name)
#   if 'frozen_inference_graph.pb' in file_name:
#     tar_file.extract(file, os.getcwd())
end= time.clock()
print('load the model',(end-start))

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)

cap = cv2.VideoCapture(0)
with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
      writer = tf.summary.FileWriter("logs/", sess.graph)  
      sess.run(tf.global_variables_initializer())  
      while(1):
        start = time.clock()
        ret, frame = cap.read()
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        image_np=frame
        # the array based representation of the image will be used later in order to prepare the
        # result image with boxes and labels on it.
        # 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=6)
        end = time.clock()
        print('frame:',1.0/(end - start))
        #print 'frame:',time.time() - start
        cv2.imshow("capture", image_np)
        cv2.waitKey(1)
cap.release()
cv2.destroyAllWindows() 

测试比较卡,估计电脑以及虚拟机配置比较差,显示结果:



### 基于替代YOLO的Python摄像头物品识别方法 除了YOLO之外,还有多种深度学习框架和模型可以用于实时摄像头物品识别任务。以下是几种常见的替代方案及其特点: #### TensorFlow Object Detection API TensorFlow 提供了一个强大的对象检测工具包——Object Detection API,支持多种预训练模型(如SSD、Faster R-CNN),这些模型同样适用于实时物体检测任务[^3]。 - **安装依赖** 需要先安装 TensorFlow 和其他必要的库: ```bash pip install tensorflow opencv-python matplotlib pillow ``` - **代码示例** 下面是一个简单的基于 SSD 的摄像头物品识别代码示例: ```python import cv2 import numpy as np import tensorflow as tf # 加载预训练模型 model = tf.saved_model.load('path_to_saved_model') cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break input_tensor = tf.convert_to_tensor(frame) input_tensor = input_tensor[tf.newaxis, ...] detections = model(input_tensor) num_detections = int(detections.pop('num_detections')) detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()} scores = detections['detection_scores'] boxes = detections['detection_boxes'] threshold = 0.5 for i in range(len(scores)): if scores[i] > threshold: ymin, xmin, ymax, xmax = tuple(boxes[i]) (left, right, top, bottom) = (xmin * frame.shape[1], xmax * frame.shape[1], ymin * frame.shape[0], ymax * frame.shape[0]) cv2.rectangle(frame, (int(left), int(top)), (int(right), int(bottom)), (0, 255, 0), 2) cv2.imshow('Object Detection', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` #### PyTorch Faster R-CNN PyTorch 中也内置了许多经典的物体检测模型,比如 Faster R-CNN,它是一种两阶段的目标检测算法,具有较高的准确性[^4]。 - **安装依赖** 安装 PyTorch 及其相关库: ```bash pip install torch torchvision opencv-python ``` - **代码示例** 使用 Faster R-CNN 进行摄像头物品识别: ```python import cv2 import torch from torchvision.models.detection import fasterrcnn_resnet50_fpn from torchvision.transforms.functional import to_tensor device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = fasterrcnn_resnet50_fpn(pretrained=True).to(device) model.eval() cap = cv2.VideoCapture(0) with torch.no_grad(): while True: ret, frame = cap.read() if not ret: break image_tensor = to_tensor(frame).unsqueeze(0).to(device) predictions = model(image_tensor)[0] labels = predictions['labels'].cpu().numpy() scores = predictions['scores'].cpu().numpy() boxes = predictions['boxes'].cpu().numpy() threshold = 0.7 for label, score, box in zip(labels, scores, boxes): if score > threshold: x1, y1, x2, y2 = map(int, box) cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.imshow('Object Detection', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` #### OpenCV DNN 模块 OpenCV 自带的 Deep Neural Network (DNN) 模块也可以加载 Caffe 或 Tensorflow 的预训练模型来完成物品识别任务[^5]。 - **安装依赖** 确保已安装最新版本的 OpenCV-Python: ```bash pip install opencv-contrib-python ``` - **代码示例** 使用 MobileNet SSD v2 模型进行物品识别: ```python import cv2 net = cv2.dnn_DetectionModel('frozen_inference_graph.pb', 'ssd_mobilenet_v2_coco_2018_03_29.pbtxt') net.setInputSize(300, 300) net.setInputScale(1.0 / 127.5) net.setInputMean((127.5, 127.5, 127.5)) net.setInputSwapRB(True) classNames = [] classFile = 'coco.names' with open(classFile, 'rt') as f: classNames = f.read().rstrip('\n').split('\n') cap = cv2.VideoCapture(0) while True: success, img = cap.read() if not success: break classIds, confs, bbox = net.detect(img, confThreshold=0.5) if len(classIds) != 0: for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox): cv2.rectangle(img, box, color=(0, 255, 0), thickness=2) cv2.putText(img, classNames[classId - 1], (box[0] + 10, box[1] + 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2) cv2.imshow("Output", img) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` --- ### 总结 上述三种方法均能有效实现 Python 摄像头下的物品识别功能,具体选择取决于实际需求和技术背景。如果追求简单易用性和高性能,则推荐使用 TensorFlow Object Detection API 或 OpenCV DNN 模块;而若更倾向于灵活性和自定义能力,则建议采用 PyTorch 的 Faster R-CNN 实现方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值