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

相关推荐
javaDocker2 分钟前
电视台自建AI短视频生产线与算力底座:技术架构、关键实现与优化实践
人工智能·架构·音视频
2601_962066931 小时前
短视频批量制作怎么做?2026年用 huasheng-cli 的 --json 与退出码,一张选题表批量出片
json·音视频
动物园猫2 小时前
道路设施目标检测数据集:4类别、5,000张图像 | 目标检测
人工智能·目标检测·计算机视觉
半壶清水2 小时前
使用Cambridge Dictionary Audio Downloader插件下载剑桥在线词典音频完整教程
音视频
刘广睿4 小时前
视频字幕从提取到烧录:SRT/ASS 格式与 ffmpeg 字幕滤镜全流程
ffmpeg·音视频·效率工具·剪辑·字幕
刘广睿5 小时前
多素材对比同步播放怎么设计?对齐播放与差异高亮的功能复盘
音视频·效率工具·架构设计·桌面客户端·素材管理
2601_962100736 小时前
AI批量生成视频的工程化复盘(2026):一条能断点续跑、不重复扣量的出片脚本
人工智能·音视频
小柯南敲键盘6 小时前
跨境电商批量图片翻译与视频字幕翻译,就用跨马AI工具
大数据·人工智能·python·音视频
YOLO视觉与编程6 小时前
YOLO / Labelme目标分割数据集增强扩充软件v1.0.0适用于YOLO全版本
人工智能·深度学习·yolo·计算机视觉
可乐鸡翅yeah_7 小时前
FFmpeg 与浏览器 HLS 播放表现差异,定位跨客户端兼容问题
ffmpeg·音视频·m3u8·m3u8在线·音视频在线播放