首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在YOLO中保存视频

在YOLO中保存视频,可以通过以下步骤实现:

  1. 导入所需的库和模块:
代码语言:txt
复制
import cv2
import numpy as np
  1. 加载YOLO模型:
代码语言:txt
复制
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
  1. 读取视频文件:
代码语言:txt
复制
video = cv2.VideoCapture("input_video.mp4")
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(video.get(cv2.CAP_PROP_FPS))
  1. 创建输出视频文件:
代码语言:txt
复制
output_video = cv2.VideoWriter("output_video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
  1. 处理视频帧并保存:
代码语言:txt
复制
while True:
    ret, frame = video.read()
    if not ret:
        break

    # 对每一帧进行目标检测
    blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
    net.setInput(blob)
    outs = net.forward(output_layers)

    # 解析检测结果并绘制边界框
    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5:
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)
                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    font = cv2.FONT_HERSHEY_PLAIN
    colors = np.random.uniform(0, 255, size=(len(classes), 3))
    if len(indexes) > 0:
        for i in indexes.flatten():
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            confidence = str(round(confidences[i], 2))
            color = colors[class_ids[i]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, label + " " + confidence, (x, y + 30), font, 2, color, 2)

    # 将帧写入输出视频文件
    output_video.write(frame)

# 释放资源
video.release()
output_video.release()
cv2.destroyAllWindows()

以上代码使用YOLO模型进行目标检测,并将检测结果绘制在每一帧上,最后将帧保存为输出视频文件。在代码中,需要将YOLO模型的权重文件(yolov3.weights)、配置文件(yolov3.cfg)和类别名称文件(coco.names)放置在同一目录下。

推荐的腾讯云相关产品:腾讯云视频处理服务,详情请参考腾讯云视频处理

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券