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

相关推荐
AI学长5 小时前
数据集|多种水果目标检测数据集-苹果、西瓜、番茄、菠萝、洋葱(共 5 类)
人工智能·目标检测·计算机视觉·多种水果目标检测数据集
AI棒棒牛8 小时前
SCI核心论文剖析:ICSD-YOLO:面向工业现场安全的实时智能检测算法
算法·yolo·目标检测·计算机视觉·目标跟踪·yolo26
Linux猿9 小时前
云朵照片数据集,YOLO 目标检测 | 附数据集
人工智能·yolo·目标检测·图像分类·目标检测数据集·yolo目标检测·云朵照片数据集
Coovally AI模型快速验证9 小时前
YOLO训练可以偷懒?Anti-Forgetting Sampling跳过已学会的图片加速收敛
人工智能·yolo·视觉检测·异常检测·工业质检
高山流水&上善9 小时前
基于BERT情感分析与多维度可视化的B站热门视频评论分析系统
人工智能·bert·音视频
FL162386312911 小时前
基于yolov26的荔枝成熟度检测系统python源码+pytorch模型+评估指标曲线+精美GUI界面
pytorch·python·yolo
阿酷tony11 小时前
如何做视频课程的报名观看?实现报名后,才能观看视频?
音视频
福大大架构师每日一题11 小时前
ollama v0.20.0 更新:Gemma 4 全家桶发布,音频、视觉、MoE、BPE 支持全面升级
音视频·ollama
kay_54511 小时前
YOLO26改进 | 卷积模块 | 利用频域特征加强空间细节与纹理表示能力【CVPR2025】
人工智能·目标检测·计算机视觉·目标跟踪·yolo26·yolo26改进·研究生论文
前端摸鱼匠21 小时前
YOLOv11与OpenCV 联动实战:读取摄像头实时视频流并用 YOLOv11 进行检测(三)
人工智能·python·opencv·yolo·目标检测·计算机视觉·目标跟踪