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

相关推荐
guo_xiao_xiao_3 小时前
YOLOv11高空俯视场景猫狗人目标检测数据集-1488张-bag-1_4
人工智能·yolo·目标检测
数智工坊6 小时前
【RT-DETR论文阅读】:首个实时端到端Transformer检测器,DETR正式超越YOLO
论文阅读·yolo·transformer
科研前沿10 小时前
MatrixFusion™+ 云边端协同,百路视频全域融合实现零延时指令闭环
大数据·人工智能·音视频
极智视界11 小时前
分类数据集 - 糖尿病视网膜病变检测图像分类数据集下载
人工智能·yolo·数据集·图像分类·算法训练·医学影像分析·糖尿病视网膜病变检测
key_3_feng12 小时前
《淡季》推歌视频创作全攻略:用Workbuddy打造治愈系情感短片
音视频·workbuddy
数据法师13 小时前
HandBrake:开源跨平台视频转码工具完全指南
开源·音视频
guo_xiao_xiao_13 小时前
YOLOv11港口码头船只目标检测数据集-3766张-Boat-recognition-1
yolo·目标检测·目标跟踪
hhzz14 小时前
(深度学习/计算机视觉)手把手教你从零部署YOLOv8目标检测算法-----环境安装(1/4)
深度学习·yolo·计算机视觉
kay_54514 小时前
YOLO26改进| 主干网络 | 提升长距离特征建模与全局上下文理解能力【CVPR】
人工智能·目标检测·计算机视觉·目标跟踪·论文·yolo26·yolo26改进
开开心心就好17 小时前
整合多家平台资源的免费学习应用
人工智能·vscode·学习·游戏·音视频·语音识别·媒体