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

相关推荐
lichenyang4533 小时前
媒体选择、上传与音频采集 API 实现流程
oracle·音视频·媒体·android-studio
AI服务老曹7 小时前
架构师视角:如何构建支持GB28181/RTSP的异构AI视频平台?从Docker部署到源码交付的深度实践
人工智能·docker·音视频
yantaohk8 小时前
一键下载微信视频号所有页面视频,支持批量下载、加密视频解密、自动去重
网络·微信·音视频
guo_xiao_xiao_11 小时前
YOLOv11室内地面塑料袋目标检测数据集-30张-Plastic-Bag-1
yolo·目标检测·目标跟踪
AGV算法笔记12 小时前
目标检测论文精读:Deformable DETR 为什么被认为是 DETR 真正走向实用的关键一步?
人工智能·深度学习·目标检测·机器学习·计算机视觉·目标跟踪
EasyGBS12 小时前
国标GB28181视频平台EasyGBS解决多格式视频流无缝转换难题
ffmpeg·音视频
探物 AI12 小时前
【感知·yolov11】YOLOv11 部署踩坑录:为什么 INT8 量化后精度往往被直接“腰斩”??
yolo
byte轻骑兵13 小时前
【LE Audio】CAP精讲[2]: 三大角色+服务映射,CAP配置核心流程全拆解
人工智能·音视频·le audio·低功耗音频·蓝牙通话
guo_xiao_xiao_16 小时前
YOLOv11室内果蔬摆放香蕉目标检测数据集-4187张-banana-1_4
yolo·目标检测·目标跟踪
非凡ghost16 小时前
视频下载神器:直播回放、视频链接一键抓取,还能自动监听!
java·前端·javascript·音视频