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

相关推荐
luoqice14 小时前
Windows下局域网rtsp流媒体服务器搭建-测试
服务器·windows·音视频
PersistJiao15 小时前
视频下载工具 yt-dlp
音视频
王哈哈^_^16 小时前
【源码教程+数据集】农作物分类检测数据集 10712 张,农作物分类检测系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·毕业设计·数据集
Dfreedom.16 小时前
目标检测中的非极大值抑制(NMS):原理、实现与调优指南
人工智能·目标检测·目标跟踪
钓了猫的鱼儿18 小时前
基于深度学习+AI的电梯内电动车目标检测与预警系统(Python源码+数据集+UI可视化界面+YOLOv11训练结果)
人工智能·深度学习·目标检测
YOLO数据集集合18 小时前
输电线缺陷目标检测|无人机电力巡检深度学习数据集|电网线缆散股智能识别数据
人工智能·深度学习·yolo·目标检测·无人机
七牛云行业应用19 小时前
Grok Imagine Video 1.5 实战指南:图生视频 API 完整接入与参数调优
音视频
王哈哈^_^19 小时前
YOLO分类任务训练教程:从数据准备到模型部署全流程
人工智能·yolo·计算机视觉·分类·数据挖掘
动物园猫19 小时前
无人机角度的道路损害检测数据集分享(适用于YOLO系列深度学习分类检测任务)
深度学习·yolo·无人机