1. 程式人生 > >Tensorflow目標檢測--為視訊中的物品打上標籤

Tensorflow目標檢測--為視訊中的物品打上標籤

視訊檢測

此程式基於Tensorflow object detection API。

視訊演示:https://www.bilibili.com/video/av32418677/?p=2

# By Bend_Function
# https://space.bilibili.com/275177832
# 可以放在任何資料夾下執行(前提正確配置API[環境變數])
# 輸出視訊沒有聲音,pr可解決一切

import numpy as np
import os
import sys
import tensorflow as tf
import cv2
import time

from
object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util start = time.time() os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' cv2.setUseOptimized(True) # 加速cv # This is needed since the notebook is stored in the object_detection folder. sys.
path.append("..") # 可能要改的內容 ###################################################### PATH_TO_CKPT = 'model\\ssd_mobilenet_v1_graph.pb' # 模型及標籤地址 PATH_TO_LABELS = 'model\\mscoco_label_map.pbtxt' video_PATH = "test_video\\cycling.mp4" # 要檢測的視訊 out_PATH = "OUTPUT\\out_cycling1.mp4" # 輸出地址(帶輸出檔名)
NUM_CLASSES = 90 # 檢測物件個數 fourcc = cv2.VideoWriter_fourcc(*'MPEG') # 編碼器型別(可選) # 編碼器: DIVX , XVID , MJPG ,MPEG, X264 , WMV1 , WMV2 # 如果發生寫視訊錯誤很可能是編碼器出現問題 ###################################################### # 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='') # Loading label map 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) # 讀取視訊 video_cap = cv2.VideoCapture(video_PATH) fps = int(video_cap.get(cv2.CAP_PROP_FPS)) # 幀率 width = int(video_cap.get(3)) # 視訊長,寬 hight = int(video_cap.get(4)) videoWriter = cv2.VideoWriter(out_PATH, fourcc, fps, (width, hight)) config = tf.ConfigProto() config.gpu_options.allow_growth = True # 減小視訊記憶體佔用 with detection_graph.as_default(): with tf.Session(graph=detection_graph, config=config) as sess: # Definite input and output Tensors for detection_graph 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. detection_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. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') num = 0 while True: ret, frame = video_cap.read() if ret == False: # 沒檢測到就跳出 break num += 1 print(num) # 輸出檢測到第幾幀了 # print(num/fps) # 檢測到第幾秒了 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}) # 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=4) # 寫視訊 videoWriter.write(image_np) videoWriter.release() end = time.time() print("Execution Time: ", end - start)