当前位置: 首页 > article >正文

使用YOLOv11进行视频目标检测

使用YOLOv11进行视频目标检测
完整代码

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


http://www.kler.cn/news/340869.html

相关文章:

  • Leetcode 18. 四数之和
  • C++面试速通宝典——13
  • 报销系统数据库设计
  • 系统架构设计师教程 第13章 13.6 物联网层次架构设计 笔记
  • 动态规划算法专题(六):回文串问题
  • Fetch获取内容乱码问题
  • 【python机器学习】线性回归 拟合 欠拟合与过拟合 以及波士顿房价预估案例
  • Spring Boot 自动配置原理
  • LeetCode hot100---滑动窗口专题(C++语言)
  • NUKE 15有哪些新的改进功能?影视后期特效合成NUKE 15 安装包分享 【Mac/win】
  • 3D看车如何实现?有哪些功能特点和优势?
  • Clio——麻省理工学院增强机器人场景理解算法
  • 【SQL】换座位
  • 什么是物联网nb水表?
  • MSTP、MPLS和SD-WAN组网技术对比
  • Java重修笔记 第六十三天 坦克大战(十三)IO 流 - ObjectInputStream 和 ObjectOutputStream、对处理流的细节整理
  • 基于hadoop和springboot的高校固定资产管理系统的设计与实现
  • 搭建企业域名服务器案例
  • 【VUE】虚拟DOM真的比真实DOM性能好吗
  • 【FastAdmin】全栈视角下的页面跳转实现:从原生html、javascrpt、php技术到jQuery、FastAdmin框架