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

相关推荐
小雨青年13 小时前
鸿蒙 HarmonyOS 6 | Video 组件网络视频播放异常排查实战
网络·音视频·harmonyos
ai产品老杨14 小时前
异构计算与边缘协同:基于 X86/ARM 的企业级 AI 视频中台架构解析
arm开发·人工智能·音视频
桑榆肖物16 小时前
有字幕,没配音?用浏览器自带语音能力,让网页视频直接“开口说话”
数据库·edge·音视频·tts
ai产品老杨18 小时前
源码交付与全协议兼容:企业级 AI 视频中台的二次开发实战
人工智能·音视频
2403_8961775319 小时前
怎么把AVI改成mp4?把AVI改成mp4的5种方法
microsoft·音视频
琪伦的工具库20 小时前
视频素材库迁移后的完整性验证:我们团队的检测方案
音视频
视频技术分享20 小时前
视频会议如何重构智能硬件生态?适配难点与场景落地深度解析
音视频
FelixZhang02821 小时前
从 PDF 到 AI 知识库:RAG 数据预处理的六步标准流水线 (SOP)
人工智能·python·目标检测·计算机视觉·语言模型·ocr·numpy
EasyDSS1 天前
企业级私有化部署视频直播点播平台EasyDSS如何构建企业远程会议安全防线
安全·音视频