English 繁體中文 简体中文

AI 如何在视频中计算人数?

林邦源博士 · AI 笔记 · 2026 年 11 月 5 日 · 约 8 分钟阅读

排队这件事人人都懂,但要量清楚却出奇地难。在 AI 出现之前,想知道有多少人走过某个位置, 通常要有人拿着计数器站在那里,一个一个用手按——每来一个人按一下,一小时又一小时。

这篇笔记用一个简短的 Python 程序替你计数。它读取一段视频,用一个叫 YOLO 的 AI 模型, 统计每一个走过画面中那条线的人。最后,它会把画好框和累计数字的视频另存一份,并打印总数。

这里用的视频是一段 33 秒的片段,拍到人们排队走过。程序报出的结果是 In count: 6:六个人从左到右走过那条线。

queue-management-demo.mp4 是 Ultralytics 的示范视频,放在 GitHub 的 ultralytics/notebooks 仓库: https://github.com/ultralytics/notebooks/releases/tag/v0.0.0

YOLO 和 ObjectCounter 是做什么的?

YOLO 是 You Only Look Once 的缩写。它是一个 AI 模型,看一张图片一次,就列出它看到的东西——人、车、狗—— 并在每一样东西外面画一个框。发布 YOLO 的 Ultralytics 还附带一个现成的工具,叫 ObjectCounter。这个工具会画框、逐帧追踪每一个框, 并保留两个总数:一个是往一个方向越线的物体,另一个是往反方向越线的。

第一步:加载模型并打开视频

from ultralytics.solutions import ObjectCounter
import cv2
model_path = "yolo26n.pt"
video_path = "queue-management-demo.mp4"
# Get video properties: width, height, FPS (frame/second)
cap = cv2.VideoCapture(video_path)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

第一行引入计数工具,第二行引入 OpenCV,也就是负责读写视频文件的库。 model_path 指定 AI 模型:yolo26n.pt, 其中 n 代表 nano,是体积最小、速度最快的一档。第一次运行时会自动下载这个模型,大约 5 MB。

cv2.VideoCapture 打开 queue-management-demo.mp4, 接着三行读出它的宽、高和速度(每秒 25 帧)。程序需要这些数字有两个原因:计数线是用像素描述的, 而另存的视频必须与原片有完全相同的大小和速度。

第二步:画出计数线

region_points = [(width-400, 300), (width-400, height), (width-350, height), (width-350, 300)]

四组数字描述一个细长区域的四个角:左上、左下、右下、右上。每一个点都以画面左上角为起点度量, 左上角是 (0, 0),右下角是 (width, height): x 向右递增,y 向下递增。横向来说,这个区域宽 50 像素, 从 x = width-400 到 x = width-350。纵向来说, 它从 y = 300 一直到底部边缘 y = height(674)。

这个区域是直立的,因为人们是横向走过画面,从左到右。

方向很重要:从左到右越过区域的人会记为 IN,从右到左则记为 OUT。 这段视频里所有人都从左往右走,所以六次越线都算 IN。

第三步:创建计数器

# Initialize ObjectCounter 
counter = ObjectCounter(
    model=model_path,
    region=region_points,
    show=True,
    show_labels = False,
    show_conf = False,
    show_in=True,
    show_out=False
)

这一个对象就做完了所有工作。model 是 AI 模型, region 是第二步那个区域,show=True 会打开一个窗口, 让你实时看到视频被处理的过程。

show_labels = False 会隐藏每个框上方的类别名称,这里就是 person 这个字;show_conf = False 会隐藏置信度分数—— 像 0.85 这种表示模型有多大把握的数字。两者都隐藏后,只会看到干净的框,在拥挤的队伍里容易看得多。 show_in=True 和 show_out=False 表示只在视频上画出 IN 的累计数。

第四步:另存一份标好框的视频

# Define the codec and create VideoWriter object to save the output video
fourcc = cv2.VideoWriter_fourcc(*'avc1')  # H.264, plays on Mac
out = cv2.VideoWriter('result_queue.mp4', fourcc, fps, (width, height))
if not out.isOpened():  # avc1 not available (e.g. Windows), use mp4v instead
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('result_queue.mp4', fourcc, fps, (width, height))

VideoWriter 是 VideoCapture 的反面:它负责写出一个新的视频文件。 fourcc 这个代码指定压缩格式。avc1 是 H.264,在 Mac 上播放流畅。 如果你的电脑没有这个格式——Windows 常见——程序会改用 mp4v,仍然能产出文件。

输出文件叫 result_queue.mp4,所以原始视频永远不会被覆盖。

第五步:逐帧读取整段视频

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    results = counter(frame)
    annotated_frame = results.plot_im
    # Write the annotated frame to the output video
    out.write(annotated_frame)
    key = cv2.waitKey(1)
    if key == ord('q') or key == ord('Q'):
        break

视频其实是一长串静止的图片,叫做帧(frame)。循环每次取出一帧。 ret 在还有帧时为 true,到最后变成 false,循环便结束。每一帧会送进 counter(frame),它找出人、更新总数,并返回一份已经画好框和数字的副本。 这份副本就是 results.plot_im,也是写入新视频的内容。

cv2.waitKey(1) 会等待 1 毫秒,看有没有按键。在视频窗口按 q 或 Q 可以提前停止;否则循环会跑到最后一帧。

第六步:关闭所有资源并打印总数

cap.release()
out.release()
cv2.destroyAllWindows()
print("In count:", results.in_count)

释放读取器和写入器,就是把文件交还给操作系统;destroyAllWindows() 关闭预览窗口。最后一行打印 IN 的总数。这段视频打印出:

In count: 6

程序运行时,预览窗口也会显示那个区域、每个人身上的框,以及每有一个人走过、数字就往上涨。

完整程序

from ultralytics.solutions import ObjectCounter
import cv2
model_path = "yolo26n.pt"
video_path = "queue-management-demo.mp4"
# Get video properties: width, height, FPS (frame/second)
cap = cv2.VideoCapture(video_path)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
region_points = [(width-400, 300), (width-400, height), (width-350, height), (width-350, 300)]
# Initialize ObjectCounter 
counter = ObjectCounter(
    model=model_path,
    region=region_points,
    show=True,
    show_labels = False,
    show_conf = False,
    show_in=True,
    show_out=False
)
# Define the codec and create VideoWriter object to save the output video
fourcc = cv2.VideoWriter_fourcc(*'avc1')  # H.264, plays on Mac
out = cv2.VideoWriter('result_queue.mp4', fourcc, fps, (width, height))
if not out.isOpened():  # avc1 not available (e.g. Windows), use mp4v instead
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('result_queue.mp4', fourcc, fps, (width, height))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    results = counter(frame)
    annotated_frame = results.plot_im
    # Write the annotated frame to the output video
    out.write(annotated_frame)
    key = cv2.waitKey(1)
    if key == ord('q') or key == ord('Q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()
print("In count:", results.in_count)

在自己的电脑上运行

下载 zip 文件并解压到一个文件夹。里面有 yolo_queue.py、queue-management-demo.mp4 和 pyproject.toml。用 Visual Studio Code 打开这个文件夹,然后在终端里逐行输入以下三行:

uv python pin 3.12.10
uv sync
uv run yolo_queue.py

第一次运行会下载 YOLO 模型(约 5 MB),然后处理视频。在较新的笔记本电脑上约需一分钟。会打开一个视频窗口; 让它播放,或按 q 提前停止。完成后,同一个文件夹里会出现 result_queue.mp4,终端会打印总数。

如果你还没安装 uv,请先看 如何安装 Visual Studio Code?,再看 Windows 或 Mac 的 uv 笔记。

局限

延伸阅读