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

相关推荐
ReinaXue1 小时前
大模型【进阶】(六)QWen2.5-VL视觉语言模型详细解读
图像处理·人工智能·神经网络·目标检测·计算机视觉·语言模型·transformer
来知晓2 小时前
语音处理:音频移形幻影,为何大振幅信号也无声
开发语言·音视频
阿酷tony2 小时前
开源项目:FlyCut Caption智能视频字幕裁剪工具
音视频·智能视频字幕裁剪·视频字幕裁剪
CodeJourney.2 小时前
Sora引爆AI视频革命
人工智能·音视频
2501_920955572 小时前
MP4格式视频无法播放怎么修?4个修复方法,解决难题
音视频
ZEGO即构开发者2 小时前
【ZEGO即构开发者日报】谷歌推出新款视频生成模型 Veo 3.1;腾讯开源通用文本表示模型Youtu-Embedding;AI 陪伴赛道观察……
人工智能·音视频·实时音视频·业界资讯
给大佬递杯卡布奇诺3 小时前
FFmpeg 基本API avformat_open_input函数内部调用流程分析
c++·ffmpeg·音视频
CoookeCola5 小时前
Google Landmarks Dataset v2 (GLDv2):面向实例级识别与检索的500万图像,200k+类别大规模地标识别基准
图像处理·人工智能·学习·目标检测·计算机视觉·视觉检测
JANGHIGH5 小时前
YOLO系列——OpenCV DNN模块在YOLOv11检测物体时输出的边界框坐标问题
opencv·yolo·dnn
宁若风5 小时前
如何将yolov5模型部署到RK3588开发板上
yolo