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

相关推荐
召田最帅boy2 小时前
为博客每日一句添加音频播放功能
spring boot·html·音视频
爱淋雨的男人2 小时前
yolo系列模型详解-yolov5
yolo
balmtv2 小时前
Gemini 3多模态统一架构深度拆解:从稀疏注意力到原生视频生成的工程实现
人工智能·架构·音视频
EasyCVR3 小时前
从流媒体转发到智能分析:EasyCVR的视频技术演进
人工智能·ffmpeg·音视频·视频监控·gb28181
EasyDSS3 小时前
EasyDSS视频流媒体WebRTC技术解析:智慧校园直播、点播与会议一体化融合实践
运维·网络·人工智能·架构·音视频·m3u8·点播技术
雾江流3 小时前
BV电视版 0.3.14.r877 | 纯净好用的第三方B站TV,支持8K视频
音视频·软件工程
FriendshipT3 小时前
Ultralytics Docker 安装使用教程(以训练 YOLO26 模型为例)
linux·运维·人工智能·目标检测·ubuntu·docker·容器
视***间3 小时前
视程空间(VisionSpace):以音视频技术创新,构筑全行业智能化新基座
人工智能·音视频·边缘计算·传感器·视程空间
山半仙xs3 小时前
pointNet做点云的分割和分类
人工智能·yolo·分类·自动驾驶·视觉检测
WX186163619093 小时前
索尼相机视频变为RSV格式怎么封装修复转换为MP4视频
数码相机·音视频