上一篇博文主要介绍了如何使用object_detection进行图片的识别。本文将在上一篇的基础上介绍一下如何进行视频的识别。
视频识别主要是将视频分为一帧一帧的图片,然后对图片进行识别。本文主要分为对摄像头拍摄的内容直接识别和对一段视频文件的识别。
1. 采用VideoCapture对视频进行处理的方法:
首先需要依赖于opencv里面包含的视频处理方式。所以需要在python中安装opencv。安装链接为 opencv安装地址。具体安装方式为,采用pip指令:pip install opencv-contrib-python。安装完成之后运行import cv2 。如果不报错则安装成功。
使用VideoCapture函数打开摄像头或者文件。然后调用read方法得到对应的每一帧图片(frame)。最后将图片进行识别。具体代码如下:(代码的模型加载过程和使用tensorflow进行图片识别的部分相同)
#cap = cv2.VideoCapture("test3.MOV") cap = cv2.VideoCapture(0) with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while (1): start = time.clock() # 按帧读视 ret, 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) # 释放捕捉的对象和内存 cap.release() cv2.destroyAllWindows()
如果VideoCapture传入的是0则打开默认摄像头,如果传入的是文件,则打开视频文件。例如当传入"test3.mov",结果是对视频文件进行识别:(下图为视频文件中截取的两张图片)
2: 基于moviepy中的VideoFileClip进行的识别。
在采用该方式识别之前要确保已经安装了对应的包:安装方式为:pip install moviepy。安装完之后可以采用VideoFileClip对视频文件进行提取。然后采用fl_image函数对提取出的文件进行识别并最终保存成视频文件。具体代码如下:
import detection_demo.object_detection_model as model import matplotlib import cv2 import time matplotlib.use('Agg') import imageio imageio.plugins.ffmpeg.download() from moviepy.editor import VideoFileClip from IPython.display import HTML white_output = 'video1_out3.mp4' clip1 = VideoFileClip("test3.MOV").subclip(0, 10) white_clip = clip1.fl_image(model.run_unterence_for_single_image) white_clip.write_videofile(white_output, audio=False)
其中model.run_unterence_for_single_image为模型中的加载部分。可以参照上篇博文中官方demo的模型加载部分。
此时会产生一个mp4的视频文件,文件的内容和上述图片的内容相同。由于上传视频不方便就不在此上传。