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

相关推荐
简鹿视频1 小时前
视频转mp4格式具体作步骤
ffmpeg·php·音视频·实时音视频
Yutengii1 小时前
如何下载b站视频到本地(b站视频本地化指南)
音视频
夏天是冰红茶1 小时前
YOLO目标检测模型如何对接Apipost平台
yolo
q_30238195561 小时前
告别“笨重”检测!VA-YOLO算法让疲劳驾驶识别更轻更快更准
算法·yolo
AI街潜水的八角3 小时前
基于YOLOv12摔倒检测系统1:摔倒检测数据集说明(含下载链接)
yolo
qq_310658514 小时前
mediasoup源码走读(十二)——router
服务器·c++·音视频
音视频牛哥5 小时前
SmartMediakit技术白皮书:与主流云厂商(PaaS)的技术定位对比与选型指南
人工智能·深度学习·机器学习·音视频·gb28181对接·rtsp服务器·rtsp播放器rtmp播放器
YANQ6625 小时前
13.长视频和短视频的目标追踪(yolo_insightface模型)
yolo
Katecat996635 小时前
卡簧目标检测基于改进YOLO11-C3k2-Star模型的实现
人工智能·目标检测·计算机视觉
一条数据库6 小时前
鸟类声音识别数据集-206中鸟类28721条音频记录-带完整特征文件和多级标签标注
音视频