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

相关推荐
好游科技8 分钟前
赋能私有化沟通:定制即时通讯与音视频系统助推企业数字化转型
音视频·社交软件·社交聊天软件开发·社交语音视频软件·私有化部署im即时通讯
萧鼎9 分钟前
告别 PR!用 Python + MoviePy 自动化剪辑视频
python·自动化·音视频
DO_Community19 分钟前
碾压GPT-5,Qwen3-VL开源多模态新标杆:99.5%长视频定位准确率
人工智能·gpt·开源·llm·音视频
小白狮ww22 分钟前
从几秒走向几分钟:长视频生成进入 LongCat 时刻
人工智能·深度学习·音视频·文生视频·图片处理·视频生成·图生视频
G311354227336 分钟前
音视频互动 Demo、即时通信 IM 服务搭建
音视频
传道Ace39 分钟前
使用cursor开一个视频转文本,文本转字幕,字幕转文本网站
音视频·cursor·视频转字幕,文本转字幕
AI大模型学徒42 分钟前
大模型应用开发(六)_大模型文字生成音频和图片
chatgpt·音视频·文字转图片·deepseek·文字转音频
pu_taoc44 分钟前
FFmpeg-实战1-解码音频
ffmpeg·音视频
八月的雨季 最後的冰吻1 小时前
FFmepg--29- C++ 音频混音器实现
开发语言·c++·音视频
qq_3106585111 小时前
mediasoup源码走读(二)环境搭建与 Demo 运行
服务器·c++·音视频