注意
点击此处下载完整的示例代码
09. 在您的网络摄像头上运行对象检测模型¶
本文将展示如何通过直接在您的网络摄像头视频流上运行预训练的对象检测模型来与其互动。
注意
本教程仅在 MacOS 环境下测试过
所需 Python 包:cv2, matplotlib
您需要一个网络摄像头 :)
与 matplotlib 渲染兼容的 Python,在 MacOS 中作为框架安装,参见此处的指南
加载模型和网络摄像头¶
准备好了吗?让我们开始吧!首先,将必要的库导入 Python。
import time
import gluoncv as gcv
from gluoncv.utils import try_import_cv2
cv2 = try_import_cv2()
import mxnet as mx
在本教程中,我们使用 ssd_512_mobilenet1.0_voc
,这是一个速度快、精度高的网络,在大多数笔记本电脑上应该能达到远高于 1 帧每秒的速度。欢迎尝试Gluon 模型库中的其他模型!
# Load the model
net = gcv.model_zoo.get_model('ssd_512_mobilenet1.0_voc', pretrained=True)
# Compile the model for faster speed
net.hybridize()
我们在 opencv 中创建网络摄像头处理程序以便获取帧
# Load the webcam handler
cap = cv2.VideoCapture(0)
time.sleep(1) ### letting the camera autofocus
检测循环¶
检测循环包含四个阶段
加载网络摄像头帧
预处理图像
通过网络运行图像
使用预测结果更新输出
axes = None
NUM_FRAMES = 200 # you can change this
for i in range(NUM_FRAMES):
# Load frame from the camera
ret, frame = cap.read()
# Image pre-processing
frame = mx.nd.array(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)).astype('uint8')
rgb_nd, frame = gcv.data.transforms.presets.ssd.transform_test(frame, short=512, max_size=700)
# Run frame through network
class_IDs, scores, bounding_boxes = net(rgb_nd)
# Display the result
img = gcv.utils.viz.cv_plot_bbox(frame, bounding_boxes[0], scores[0], class_IDs[0], class_names=net.classes)
gcv.utils.viz.cv_plot_image(img)
cv2.waitKey(1)
我们在退出脚本前释放网络摄像头
cap.release()
cv2.destroyAllWindows()