使用Tensorflow读取视频文件以检测视频中的对象

2024-05-06 10:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经训练了一个tensorflow模型,并提供了一个输入视频来检测其中的对象。我确实了解一点python。 到目前为止,我已经找到了以下代码 下面的代码与以前编写的代码不同,该代码用于检测网络摄像头视频捕获(0)中的对象-

import cv2
cap = cv2.VideoCapture("C://Users/Mahesh/Desktop/videosample/sample1.mp4")

try:
  with detection_graph.as_default():
    with tf.Session() as sess:
            # Get handles to input and output tensors
            ops = tf.get_default_graph().get_operations()
            all_tensor_names = {output.name for op in ops for output in op.outputs}
            tensor_dict = {}
            for key in [
              'num_detections', 'detection_boxes', 'detection_scores',
              'detection_classes', 'detection_masks'
            ]:
                tensor_name = key + ':0'
                if tensor_name in all_tensor_names:
                    tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                  tensor_name)

            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)
                # Actual detection.
                output_dict = run_inference_for_single_image(image_np, detection_graph)
                # Visualization of the results of a detection.
                vis_util.visualize_boxes_and_labels_on_image_array(
                    image_np,
                    output_dict['detection_boxes'],
                    output_dict['detection_classes'],
                    output_dict['detection_scores'],
                    category_index,
                    instance_masks=output_dict.get('detection_masks'),
                    use_normalized_coordinates=True,
                    line_thickness=8)
                cv2.imshow('object_detection', cv2.resize(image_np, (800, 600)))
                if cv2.waitKey(25) & 0xFF == ord('q'):
                    cap.release()
                    cv2.destroyAllWindows()
                    break
except Exception as e:
print(e)
cap.release()

上面的代码成功地指向了视频文件并进行了渲染,但它渲染了每一帧,这需要很长时间。我正在尝试修改代码,以便将路径中的视频作为输入,在检测到视频中的对象时提供检测框,并将其保存到另一个文件中。请帮帮我


Tags: 代码nameinimageforoutputget视频