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

相关推荐
桐桐桐38 分钟前
视频画面裁剪与尺寸压缩实战:ffmpeg crop/scale 用法与在线替代
ffmpeg·音视频·视频
阿童木写作2 小时前
跨境电商图片翻译工具推荐:批量AI翻译+视频字幕+智能抠图
大数据·人工智能·python·音视频
勤劳X码农3 小时前
2026年四款免费配音轻量工具参数记录与实测数据
音视频
乐橙开放平台3 小时前
老旧小区监控事件驱动派单:基于 setMessageCallback 的 msgType 分级与工单闭环实现
后端·物联网·音视频
赵药师4 小时前
YOLOv11中C3k2以及常见改进
yolo
lailai04104 小时前
视频离线观看工具的多维度比较分析
音视频
精英的英5 小时前
记一次 i.MX6 SL YOLO 模型编译和性能调优
yolo
程序员老陆6 小时前
音频为什么不编码成“声卡格式”(例如S16)?因为声卡只负责响,编码器只负责省
ffmpeg·音视频
调试到凌晨6 小时前
免费配音工具长文本处理能力实测:做长视频和有声书,谁更稳?
音视频
具身新纪元7 小时前
CVPR 2026|新缺陷不断上线,如何让工业视觉检测模型不忘旧账?
人工智能·深度学习·目标检测·机器学习·计算机视觉·目标跟踪·视觉检测