使用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

相关推荐
中议视控10 小时前
RTSP和RTSM编码推送软件让中控系统控制实现可视化播控
网络·分布式·物联网·5g·音视频
Unknown To Known11 小时前
基于DyHead和YOLOv11的错题自动切分系统
yolo
愚公搬代码15 小时前
【愚公系列】《剪映+DeepSeek+即梦:短视频制作》025-字幕:用文字来美化画面(添加字幕)
音视频
EasyCVR16 小时前
安防监控/视频存储/云存储平台EasyCVR全场景智能视频监控解决方案深度解析
音视频
呆萌小新@渊洁17 小时前
音频识别入门内容
macos·音视频·xcode
云边散步18 小时前
godot2D游戏教程系列二(20)
笔记·学习·音视频
唯创知音18 小时前
低BOM、高集成:WT2605A8-24SS蓝牙音频芯片在电动牙刷中的应用方案
音视频·wt2605a·蓝牙音频芯片·电动牙刷方案
线束线缆组件品替网18 小时前
Amphenol RJE1Y36610644401 CAT6A网线组件选型与替代指南
网络·人工智能·数码相机·电脑·音视频·硬件工程·游戏机
JicasdC123asd20 小时前
Converse2D频域卷积上采样改进YOLOv26图像重建与细节恢复能力
人工智能·yolo·目标跟踪
云和数据.ChenGuang20 小时前
chromadb为什么需要模拟数据运行
人工智能·神经网络·目标检测·机器学习·计算机视觉