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

相关推荐
EasyDSS44 分钟前
私有化视频会议系统/私有化音视频系统EasyDSS在社交娱乐领域实时互动场景中的应用
实时互动·音视频·娱乐
Ulyanov2 小时前
基于ttk的现代化Python音视频播放器:UI设计与可视化技术深度解析
python·ui·音视频
Black蜡笔小新3 小时前
GB28181视频汇聚平台EasyCVR构建智慧环保可视化监测解决方案,赋能生态可持续发展
音视频
Byron Loong4 小时前
【机器视觉】标注软件 labelMe和lableImg对比
yolo·计算机视觉
肖爱Kun4 小时前
SRT协议封装MPEG-TS 流的视频和音频PES头结构
音视频
这张生成的图像能检测吗4 小时前
(论文速读)UWDET:基于物联网的资源有限水下目标探测训练增强
人工智能·深度学习·物联网·目标检测·计算机视觉·水下目标检测
QQ676580085 小时前
AI赋能识别之围栏破损识别 围栏缺陷检测数据集 栅栏破损识别数据集围栏孔洞识别植被入侵检测图像数据集 目标检测图像数据集第10125期
人工智能·yolo·目标检测·目标跟踪·围栏破损识别·围栏缺陷识别·栅栏破损识别
reasonsummer5 小时前
【教学类-160-02】20260409 AI视频培训-练习2“豆包AI视频《小班-抢玩具》+豆包图片风格:手办”
python·音视频·ai视频·豆包·通义万相
肖爱Kun6 小时前
SRT协议封装MPEG-TS 流的视频和音频TS头结构
网络·音视频
Cxiaomu6 小时前
Flutter 录制视频+大文件上传 MinIO + NodeJS落库
flutter·音视频·文件上传