使用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 小时前
esp32开发与应用(边采样边播放音频)
音视频
中微极客3 小时前
Veo视频生成与Gemini Agent平台集成实践
数据库·人工智能·oracle·音视频
OpenApi.cc4 小时前
来了,来了,我来了,Mocode
人工智能·深度学习·神经网络·目标检测·数据挖掘
码龙-DragonCoding4 小时前
一键批量提取音频、提取视频
android·音视频·提取
中微极客5 小时前
2026年AI视频生成模型技术选型与工程实践
人工智能·音视频
cellurw6 小时前
20260723 六组件全流程编译打通与音频项目启动
linux·服务器·音视频
小柯南敲键盘6 小时前
跨马翻译:批量图片与视频字幕翻译,支持智能抠图
大数据·人工智能·python·音视频
SEO_juper6 小时前
2026_GEO_AI搜索技术实战_CSDN
人工智能·chrome·目标检测·seo·geo·谷歌优化
前网易架构师-高司机7 小时前
带标注的扑克牌识别数据集,识别率99.5%,3083张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·数字·扑克牌·纸牌
前网易架构师-高司机7 小时前
带标注的浮游藻类24种数据集,识别率91.5 %数据集, 23175张图,支持yolo,coco json,voc xml,文末有模型训练代码
yolo·json·数据集·微观·生物·浮游·藻类