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

相关推荐
bj_bluewei_tech2 分钟前
拯救者外接耳机麦克风没声音,更换耳机无效,排查主板音频信号电路
电脑·笔记本电脑·音视频
jay神1 小时前
一文讲清楚YOLOv26模型
人工智能·深度学习·yolo·机器学习·计算机视觉
pullyysusie1 小时前
展厅无线按钮触控点播音视频解决方案及应用
网络协议·音视频·集成学习·智能硬件
VidDown2 小时前
# VP9 还是 H.265?一次压缩选型翻车后的复盘
ffmpeg·音视频·h.265·视频编解码·视频·vp9
qq_25294131682 小时前
无人机目标检测数据集(UAV Detection Dataset)| 无人机检测 反无人机 低空安防5001期
人工智能·yolo·目标检测·计算机视觉·视觉检测·无人机·反无人机
xywww1683 小时前
商品图生成视频怎么做:Seedance 2.0在电商素材生产中的实操流程
音视频
leoZ2314 小时前
AI+前端提效-08 AI自动化文档:前端组件、接口、项目文档自动生成
前端·人工智能·深度学习·神经网络·目标检测·自然语言处理·自动化
lugsicher5 小时前
LUZ105 软包装紫外激光标识系统:从单机替换到产线闭环的工程拆解
目标检测·信息可视化·视觉检测·制造·材质
YOLO数据集集合5 小时前
蚊子视觉验证数据集 | 蚊虫识别 疟疾防控 病媒生物 细粒度分类 YOLO格式 深度学习数据集
深度学习·yolo·分类·数据集·蚊子分类·蚊虫分类·蚊虫识别
爱分享的康康6 小时前
从“识别已知”到“发现未知”:3D通用目标检测如何打开智驾感知新边界
人工智能·目标检测·3d