使用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 小时前
【音频可视化】通过canvas绘制音频波形图
前端·音视频
林学长@F5 AI社区3 小时前
【AI人脸融合】FaceFusion 3.0一键整合包,支持AI视频/图片人脸融合、数字人视频、表情修复、年龄修改等
人工智能·音视频
美狐美颜sdk3 小时前
如何搭建直播美颜平台?视频美颜SDK的核心技术详解
人工智能·音视频·直播美颜sdk·第三方美颜sdk·美狐美颜sdk
Slaunch3 小时前
目标检测指标:AP,mAP
人工智能·python·深度学习·目标检测
音视频牛哥3 小时前
计算机视觉之YOLO算法基本原理和应用场景
算法·yolo·计算机视觉·yolo11·yolo10·yolo目标检测
Rick66Ashley4 小时前
DHASH感知算法计算视频相邻帧的相似度
音视频
六神就是我5 小时前
【音频生成】mac安装ffmpeg
macos·ffmpeg·音视频
如果能为勤奋颁奖6 小时前
YOLO11改进|注意力机制篇|引入矩形自校准模块RCM
yolo
Tinghua_M6 小时前
基于Android11简单分析audio_policy_configuration.xml
音视频·audio