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

相关推荐
思绪无限4 小时前
YOLOv5至YOLOv12升级:血细胞检测系统的设计与实现(完整代码+界面+数据集项目)
人工智能·python·深度学习·目标检测·计算机视觉·yolov12·血细胞检测
H Journey6 小时前
yolov8n.pt介绍
yolo·yolov8n.pt
思绪无限6 小时前
YOLOv5至YOLOv12升级:金属锈蚀检测系统的设计与实现(完整代码+界面+数据集项目)
人工智能·python·深度学习·目标检测·计算机视觉·yolov12
VOOHU_20187 小时前
VOOHU沃虎:音频变压器的主要作用是什么?什么情况下必须使用?
网络·物联网·音视频·电子元器件
APIshop8 小时前
小红书笔记视频详情接口深度解析:smallredbook.item_get_video_pro
数据库·笔记·音视频
AI服务老曹10 小时前
【架构深评】深度解析异构计算下的 AI 视频管理平台:从 GB28181 接入到 X86/ARM 容器化部署的全链路实战
人工智能·架构·音视频
mahtengdbb111 小时前
RepViT块改进YOLOv26重参数化与双路径特征混合双重突破
人工智能·yolo·目标跟踪
YWamy11 小时前
视频会议如何重构智能硬件生态?适配难点与场景落地全解析
音视频
ai产品老杨11 小时前
【架构深析】打破硬件壁垒:支持 X86/ARM 异构计算与源码交付的 GB28181 视频 AI 平台设计实践
arm开发·架构·音视频
羊羊小栈12 小时前
基于「YOLO目标检测 + 多模态AI分析」的智慧植物辣椒病害智能检测分析预警系统
人工智能·yolo·目标检测·计算机视觉·毕业设计·大作业