使用YOLOv11进行视频目标检测

使用YOLOv11进行视频目标检测

完整代码

bash 复制代码
import cv2
from ultralytics import YOLO

def predict(chosen_model, img, classes=[], conf=0.5):
    if classes:
        results = chosen_model.predict(img, classes=classes, conf=conf)
    else:
        results = chosen_model.predict(img, conf=conf)

    return results

def predict_and_detect(chosen_model, img, classes=[], conf=0.5, rectangle_thickness=2, text_thickness=1):
    results = predict(chosen_model, img, classes, conf=conf)
    for result in results:
        for box in result.boxes:
            cv2.rectangle(img, (int(box.xyxy[0][0]), int(box.xyxy[0][1])),
                          (int(box.xyxy[0][2]), int(box.xyxy[0][3])), (255, 0, 0), rectangle_thickness)
            cv2.putText(img, f"{result.names[int(box.cls[0])]}",
                        (int(box.xyxy[0][0]), int(box.xyxy[0][1]) - 10),
                        cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), text_thickness)
    return img, results

# defining function for creating a writer (for mp4 videos)
def create_video_writer(video_cap, output_filename):
    # grab the width, height, and fps of the frames in the video stream.
    frame_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(video_cap.get(cv2.CAP_PROP_FPS))
    # initialize the FourCC and a video writer object
    fourcc = cv2.VideoWriter_fourcc(*'MP4V')
    writer = cv2.VideoWriter(output_filename, fourcc, fps,
                             (frame_width, frame_height))
    return writer

model = YOLO("yolo11x.pt")

output_filename = "YourFilename.mp4"

video_path = r"YourVideoPath.mp4"
cap = cv2.VideoCapture(video_path)
writer = create_video_writer(cap, output_filename)
while True:
    success, img = cap.read()
    if not success:
        break
    result_img, _ = predict_and_detect(model, img, classes=[], conf=0.5)
    writer.write(result_img)
    cv2.imshow("Image", result_img)
    
    cv2.waitKey(1)
writer.release()

参考资料:

1.https://blog.csdn.net/qq_42589613/article/details/142729428

2.https://blog.csdn.net/java1314777/article/details/142665078

相关推荐
FL162386312943 分钟前
[C++]使用纯opencv部署yolov12目标检测onnx模型
c++·opencv·yolo
苏三福3 小时前
rk3588/3576板端编译程序无法运行视频推理
arm开发·音视频
江同学_4 小时前
RTSP场景下RTP协议详解及音视频打包全流程
音视频
EasyNVR13 小时前
EasyRTC智能硬件:实时畅联、沉浸互动、消音护航
运维·服务器·网络·安全·音视频·webrtc·p2p
倒霉蛋小马14 小时前
【YOLOv8】损失函数
深度学习·yolo·机器学习
Erekys16 小时前
视觉分析之边缘检测算法
人工智能·计算机视觉·音视频
IT古董16 小时前
【深度学习】计算机视觉(CV)-目标检测-DETR(DEtection TRansformer)—— 基于 Transformer 的端到端目标检测
深度学习·目标检测·计算机视觉
LensonYuan16 小时前
视觉目标检测之小目标检测技术调研与实验
目标检测·计算机视觉·目标跟踪
三年呀17 小时前
计算机视觉之图像处理-----SIFT、SURF、FAST、ORB 特征提取算法深度解析
图像处理·python·深度学习·算法·目标检测·机器学习·计算机视觉
EasyNVR21 小时前
EasyRTC:全平台支持与自研算法驱动的智能音视频通讯解决方案
运维·服务器·小程序·音视频·webrtc·p2p·智能硬件