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

相关推荐
K姐研究社4 小时前
怎么用AI制作电商口播视频,开拍APP一键生成
人工智能·音视频
EasyDSS7 小时前
私有化视频会议平台/视频高清直播点播EasyDSS构建智慧校园音视频协作新生态
音视频
txp玩Linux9 小时前
音频 AI 模型开源方案与音频 3A / ASR / TTS 全链路解析
人工智能·音视频
runafterhit9 小时前
显示调研专题-OLED行业技术趋势分析报告
音视频
灰灰勇闯IT10 小时前
DVPP 视频预处理:YOLO 视频检测的瓶颈与解法
yolo·音视频
Luna-player11 小时前
音频服务未运行,未安装音频设备,Windows 无法启动 Windows Audio 服务,错误 0x80070005:拒绝访问,本计算机无法播放音频
音视频
中小企业实战军师刘孙亮12 小时前
小微企业生存发展指南:从求稳到扩张的实战策略-佛山鼎策创局破局增长咨询
架构·产品运营·音视频·制造·业界资讯
视频号下载助手12 小时前
2026视频号视频下载去水印方法!4种无水印视频提取方法
音视频
青w韵12 小时前
视频链接处理 + 提取字幕
音视频
ting945200013 小时前
Vivago Video Agent 技术深度解析:大模型驱动的叙事视频全链路生成
人工智能·音视频