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 筆記。

限制

延伸閱讀