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

相关推荐
小二·2 小时前
多模态RAG实战:用LangChain+Milvus打造支持图文音视频的企业级知识库
langchain·音视频·milvus
田里的水稻2 小时前
EP_局域网传输音视频的主流方案
运维·人工智能·机器人·音视频
hz567892 小时前
手术示教及远程会诊系统一体化方案:赋能医院教学与精准诊疗
安全·音视频·实时音视频·信息与通信
中微极客2 小时前
剪枝与量化:让YOLO在边缘设备上高效部署
算法·yolo·剪枝
潜创微科技3 小时前
ITE联阳IT6520:Type-C口进、双MIPI出,一颗芯片把PD充电+DP视频+2屏驱动全包了
音视频
禹亮科技3 小时前
中型会议室音视频工程方案|20-40㎡无桌面麦部署:Poly X52+思必驰MCS06+DP44落地实战
音视频·视频会议系统集成·高端会议室设备选择·视频会议解决方案
CHY_1284 小时前
Arm Ethos‑U65:YOLOv8n 模型准备与 Vela 编译
arm开发·人工智能·yolo·目标检测
前网易架构师-高司机4 小时前
带标注的带标注的医用采血管分类和标签识别数据集,识别率80.7%,5524张图,支持yolo,coco json,voc xml,文末有模型训练代码
yolo·数据集·标签·医学·颜色·医院·采血管
西柚研究生1234565 小时前
论文分析10:基于改进YOLOv8模型的雨雾天气目标识别算法
yolo
西柚研究生1234565 小时前
论文分析9:基于尺度特征交互改进的YOLOv8在低能见度环境下的船舶目标检测
人工智能·yolo·目标检测