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

相关推荐
视频技术分享2 小时前
B端音视频SDK:从底层组件到企业业务能力的蜕变
音视频
工具派6 小时前
口播视频怎么自动剪掉冷场?视频静音删除的阈值实测
ffmpeg·音视频·视频
彭祥.6 小时前
基于DeepSeek智能体+YOLO+ResNet的饮食健康分析系统技术实现
yolo
天天进步20156 小时前
Pixelle-Video 源码解析 #22:竖屏、横屏、方形视频:多尺寸适配是怎么实现的?
人工智能·音视频
sweetone6 小时前
索尼MHC-V7700组合音响一修一改
经验分享·嵌入式硬件·音视频
霸道流氓气质9 小时前
通义千问 VL & Audio:图像、视频、语音多模态 Java 集成深度解析
java·开发语言·音视频
TechVoyager_824611 小时前
IT9205技术解析:4K60 HDR over IP与视频墙的单芯片实现路径
网络协议·音视频·音视频编解码·it9205·专业视听·视频墙芯片·avoverip
论文复现现场12 小时前
工业缺陷检测训练选 YOLO11 还是 RT-DETR?一张 24GB RTX 4090 跑通 PoC 的完整方案
yolo·计算机视觉·rtx4090
Είναι η κοπέλα12 小时前
YOLO 演进 v5→v11 与 2026 选型指南
人工智能·yolo
hhzz12 小时前
【OpenCV 入门到精通 04】视频入门与绘图交互:从摄像头到鼠标画笔
人工智能·python·opencv·计算机视觉·音视频·交互