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

相关推荐
Prannt16 小时前
星朗智能语音——语音合成——上传文件配音
ai·音视频·语音识别
音沐mu.16 小时前
【70】室内物品数据集(有v5/v8模型)/YOLO室内物品检测
yolo·目标检测·数据集·室内物品数据集·室内物品检测
byte轻骑兵17 小时前
【AVRCP】规范精讲[7]: 打通AVCTP互操作底层,吃透事务标签与分片规则
人工智能·音视频·avrcp·音视频控制
EasyGBS17 小时前
国标GB28181视频平台EasyGBS即将重磅新增WHIP推流功能!低延迟直播体验再升级
音视频
jiejiejiejie_19 小时前
Flutter for OpenHarmony 萌系实战合集:地图功能 + 音频播放一站式指南
flutter·音视频
jbk331119 小时前
10分钟翻译一条视频,实现语音、字幕翻译后与画面同步对齐,视频翻译助手使用教程
人工智能·音视频·剪辑软件·剪映自动化软件
带娃的IT创业者19 小时前
DaVinci Resolve – Photo:当视频调色之王,跨界“修图”,意味着什么?
图像处理·音视频·工作流·davinci resolve·后期制作·视频调色·色彩管理
2zcode20 小时前
基于深度学习的高速公路违章停车检测系统的设计与实现
yolo·高速公路违章停车
nashane1 天前
HarmonyOS Video组件预览图片优化实践:告别黑屏,提升视频播放体验
华为·音视频·harmonyos·harmonyos 5
时间之里1 天前
【深度学习】:RF-DETR与yolo对比
人工智能·深度学习·yolo