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

相关推荐
EasyDSS16 分钟前
智能会议管理系统/私有化视频会议平台EasyDSS私有化部署构建企业级私域视频全场景解决方案
人工智能·音视频
QQ676580081 小时前
服装计算机视觉数据集 连衣裙数据集 衣服类别识别 毛衣数据集 夹克衫AI识别 衬衫识别 裤子 数据集 yolo格式数据集
人工智能·yolo·计算机视觉·连衣裙·衣服类别·毛衣数据集·夹克衫ai
潜创微科技4 小时前
切换器芯片主要型号有哪些:潜创微高清音视频领域主流型号与应用场景全解析
音视频
KevinCyao4 小时前
106视频短信接口怎么发?支持高清影音下发的106视频短信服务商
音视频
潜创微科技--高清音视频芯片方案开发5 小时前
2026年切换器方案服务商市场格局分析与主流品牌选型指南
音视频·硬件工程
潜创微科技--高清音视频芯片方案开发6 小时前
2026年高清音视频切换器方案选型分
音视频
二等饼干~za8986687 小时前
源码可控:云罗 GEO 源头工厂,开源搭建 + 二次开发全链路解决方案
服务器·开发语言·开源·php·音视频·ai-native
云程笔记8 小时前
021.损失函数深度解读:YOLO的定位、置信度、分类损失计算
人工智能·yolo·机器学习·计算机视觉·分类·数据挖掘
羊羊小栈8 小时前
基于「YOLO目标检测 + 多模态AI分析」的智慧农业茶叶病害检测预警系统
人工智能·yolo·目标检测·计算机视觉·毕业设计·大作业
feasibility.9 小时前
OpenClaw+LibTV视频生成实测(含安装+配置+分析):ai生成工作流很规范,但画面在“打架“
人工智能·aigc·音视频·内容运营·短剧·openclaw·libtv