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

相关推荐
悟乙己3 小时前
Github | MoneyPrinterTurbo:自动化视频内容生成系统
自动化·github·音视频
wan5555cn4 小时前
多张图片生成视频模型技术深度解析
人工智能·笔记·深度学习·算法·音视频
格林威4 小时前
机器视觉检测的光源基础知识及光源选型
人工智能·深度学习·数码相机·yolo·计算机视觉·视觉检测
AI360labs_atyun10 小时前
2025世界智博会,揭幕AI触手可及的科幻生活
人工智能·ai·音视频·生活
骄傲的心别枯萎11 小时前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
纳祥科技13 小时前
分享:一种为蓝牙、WIFI、U段音频发射设备提供ARC回传数字音频桥接功能的方案
网络·单片机·音视频
shao91851613 小时前
Gradio全解11——Streaming:流式传输的视频应用(3)——YOLO系列模型技术架构与实战
yolo·coco·yolov10·yoloe
Francek Chen18 小时前
【深度学习计算机视觉】03:目标检测和边界框
人工智能·pytorch·深度学习·目标检测·计算机视觉·边界框
ai产品老杨1 天前
打通各大芯片厂商相互间的壁垒,省去繁琐重复的适配流程的智慧工业开源了
人工智能·开源·音视频·能源
JoinApper1 天前
目标检测系列-Yolov5下载及运行
人工智能·yolo·目标检测