Ultralytics YOLO26による領域内の物体カウント
Ultralytics YOLO26のRegionCounterソリューションは、動画フレーム全体で物体を追跡し、各フレームでバウンディングボックスの中心が定義した各領域内にある物体をカウントします。各領域はリアルタイムのカウント数とともにフレーム上に描画されるため、Pythonの呼び出しまたはCLIコマンド1つで、店舗の通路、道路の車線、生産エリアなど、複数のゾーンを監視できます。
視聴: Ultralytics YOLO を使って異なる領域の物体をカウント | Ultralytics Solutions
領域カウントを使う理由#
- 1回の処理で複数ゾーン: 名前付きポリゴンの辞書を渡すと、各ゾーンの独立したカウント数がフレーム上に描画されるため、1つの動画ストリームで必要なすべてのエリアを網羅できます。
- 追跡機能を内蔵: このソリューションは内部でYOLO26の検出と物体追跡を実行するため、別途追跡パイプラインを構築する必要はありません。
- プログラムから利用できるカウント: 処理済みの各フレームは領域ごとのカウントを格納した辞書を含む結果オブジェクトを返すため、ダッシュボード、アラート、ログに利用できます。
実際の用途#
| 小売 | 市場の通り |
|---|---|
![]() | ![]() |
| Ultralytics YOLOによる領域内の人物カウント | Ultralytics YOLOによる領域内の群衆カウント |
Ultralytics YOLOで領域内の物体をカウントする方法#
CLIまたはPythonから動画ソースに対してRegionCounterソリューションを実行します。領域には点のリスト(単一ゾーン)またはゾーン名と点のリストを対応付ける辞書を指定できます。以下のPythonの例では、名前付きの2つの領域内の物体をカウントし、処理済みフレームを出力動画ファイルに書き込みます。
# Run a region counting example
yolo solutions region show=True
# Pass a source video
yolo solutions region source="path/to/video.mp4"
# Pass a custom region
yolo solutions region region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"RegionCounter()の引数#
RegionCounterの引数を以下の表に示します。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
model | str | None | Ultralytics YOLOモデルファイルへのパスです。 |
region | listまたはdict | None | 関心領域を定義するポイントです。(x, y)タプルのリスト、または複数領域用に領域名とポイントリストを対応付ける辞書(RegionCounterのみ)を指定します。Noneの場合、領域が必要なSolutionsでは定義済みのデフォルト値が使用されます。 |
line_width | int | 2 | Solutionが描画するボックス、キーポイント、カウント表示の線幅です。 |
verbose | bool | True | 各フレームの入力shape、クラス数、処理速度を記録するSolutionのログを有効にします。トラッキング呼び出し自体は常にログを出力しません。 |
RegionCounterソリューションでは、物体追跡のパラメーターを使用できます。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | 使用するトラッキングアルゴリズムを指定します。組み込みのオプション:botsort.yaml、bytetrack.yaml、ocsort.yaml、deepocsort.yaml、fasttrack.yaml、tracktrack.yaml。 |
conf | float | 0.25 | 検出の信頼度しきい値を設定します。値を低くすると、より多くの物体を追跡できますが、誤検出が含まれる可能性があります。 |
iou | float | 0.5 | 重複する検出をフィルタリングするためのIntersection over Union(IoU)しきい値を設定します。 |
classes | list | None | クラスインデックスで結果をフィルタリングします。たとえば、classes=[0, 2, 3]を指定すると、指定したクラスのみを追跡します。 |
device | str | None | 推論に使用するデバイスを指定します(例:cpu、cuda:0、0)。モデル実行に使用するCPU、特定のGPU、その他の計算デバイスを選択できます。 |
imgsz | int or tuple | 640 | 推論時の入力画像サイズです。正方形の場合は整数、または(height, width)のペアを指定します。形状はモデルのストライドに合わせて調整されます。 |
max_det | int | 300 | トラッキング前にフレームごとに保持する検出の最大数です。混雑したシーンでソリューションが処理する物体数を制限します。 |
quantize | int or str | None | 推論精度: CPU以外で実行するPyTorchおよびTorchScriptモデルでは、16(FP16)または32/未設定(FP32)を使用します。その他の形式では、アーティファクトとランタイムによって選択される精度が使用されます。非推奨のhalf引数を置き換えます。 |
さらに、以下の可視化設定もサポートされています。
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
show | bool | False | Trueの場合、注釈付き画像または動画をウィンドウに表示します。開発やテスト中にすぐ視覚的なフィードバックを得るのに便利です。 |
show_conf | bool | True | 各検出のラベルとともに信頼度スコアを表示します。各検出に対するモデルの確信度を確認できます。 |
show_labels | bool | True | 可視化出力で各検出のラベルを表示します。検出されたオブジェクトをすぐに把握できます。 |
領域カウントの仕組み#
RegionCounterソリューションは、渡された各領域を、3点以上からなるポリゴンに変換します。点の単純なリストはRegion#01という名前の単一ゾーンになり、辞書を渡すと指定したゾーン名が保持されます。各ゾーンはUltralyticsのカラーパレットから選ばれた色で描画されます。各フレームは次の3つの手順で処理されます。
- YOLO26のトラッキングで、フレーム内のすべてのオブジェクトを検出し、追跡します
- 追跡された各物体について、ソリューションはバウンディングボックスの中心を計算し、どの領域ポリゴンに含まれるかを確認します
- 各領域のカウント数はその中心に描画され、次のフレームの処理前にリセットされます
カウントはフレームごとにリセットされるため、領域に表示される数は累計ではなく、その時点で領域内にある物体の数、つまり現在の占有数です。境界を越えた物体を累積してカウントするには、代わりにObjectCounterソリューションを使用してください。
各呼び出しは結果オブジェクトも返します。このオブジェクトのplot_im属性には注釈付きフレームが格納され、region_counts辞書では領域名とカウント数が対応付けられているため、数値を独自のアプリケーションロジックに渡せます。
結論#
Ultralytics YOLO26のRegionCounterソリューションは、数行のコードで必要な数の名前付きゾーンについて、リアルタイムの物体数を監視します。さらに活用するには、物体カウントで境界を越える物体を数え、TrackZoneで単一ゾーン内の物体を追跡するか、ほかのUltralytics Solutionsをご覧ください。
よくある質問#
Ultralytics YOLO26は、フレーム内のすべての物体を追跡し、各物体のバウンディングボックスの中心がユーザー定義ポリゴン内にあるかを判定して、領域内の物体をカウントします。領域に表示されるカウント数は累計ではなく、そのフレーム時点の占有数です。設定オプションは
RegionCounter()引数のセクションに記載されています。メインの例のように、
region引数にゾーン名と点のリストを対応付けた辞書を渡します。from ultralytics import solutions region_points = { "region-01": [(50, 50), (250, 50), (250, 250), (50, 250)], "region-02": [(640, 640), (780, 640), (780, 720), (640, 720)], } regioncounter = solutions.RegionCounter(region=region_points, model="yolo26n.pt", show=True)名前付きの各ゾーンはそれぞれ異なる色で描画され、独立してカウントされます。
各
regioncounter(im0)呼び出しが返すオブジェクトには、領域名とカウント数を対応付けたregion_counts辞書のほか、plot_im(注釈付きフレーム)とtotal_tracks(追跡された物体の数)が含まれます。結果オブジェクトを出力して、利用可能なすべてのフィールドを確認してください。はい。保持するクラスインデックスを指定して
classes引数を渡します。たとえば、COCOで事前学習したモデルで人物のみをカウントするにはclasses=[0]を指定します。トラッキング関連の引数一覧は、RegionCounter()引数セクションに記載されています。RegionCounterは現在のフレーム内の各ポリゴンゾーンに含まれるオブジェクト数を表示します。一方、ObjectCounter は、オブジェクトがラインまたは領域の境界を通過するたびに累積カウントし、進入数と退出数を追跡します。1つ以上のゾーンのリアルタイムの占有状況にはRegionCounterを、進入と退出のカウントにはObjectCounterを使用してください。ライン状の領域に対応しているのはObjectCounterのみです。
コメント99
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
pedmindset
Been trying to figure this out for a while now. I want to ask, can I use object counting in regions with instance sementation and tracking? You want to count vehicles that cross two specific regions, like so Object 001 crossed region A and region B. Is this possible to do
1
Glenn JocherUltralytics@pedmindset yes, it is possible to count objects crossing multiple regions using Ultralytics YOLO11. You can utilize the
RegionCounterclass to define multiple regions and track objects across them. The objects' movement through these regions can be tracked using persistent IDs, enabling you to determine which object crossed which regions. For implementation details, refer to the Region Counting Guide.1
amulyaamaggididivami
import cv2 from ultralytics import solutions # Load video file cap = cv2.VideoCapture("retail-store.mp4") assert cap.isOpened(), "Error reading video file" # Define the counting line coordinates (adjust as per your scene) region_points = [(1135, 714), (1134, 416)] # Get video properties w, h, fps = (int(cap.get(x)) for x in ( cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS, )) # Setup video writer for output video_writer = cv2.VideoWriter( "object_counting_output.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h), ) # Initialize the object counter counter = solutions.ObjectCounter( show=False, # Don't show live preview region=region_points, # Line coordinates model="yolo11n.pt", # YOLO model classes=[0], # Class 0 = person line_width=3, ) # Process video frame by frame while cap.isOpened(): success, frame = cap.read() if not success: print("Video processing complete.") break # Run the counter on the frame results = counter(frame) # Write to output video video_writer.write(results.plot_im) # Cleanup cap.release() video_writer.release() cv2.destroyAllWindows() print(f"✅ Processing complete. Saved as 'object_counting_output.mp4'")I’m getting the count reversed — the number of people entering is shown as OUT, and those exiting are shown as IN. How can I fix this?
RizwanMunawar
@amulyaamaggididivami Hi, can you please try reversing the region coordinates, like mentioned? I believe this will work.
region_points = [(1134, 416), (1135, 714)]amulyaamaggididivami
I have tried that, but it is not working
RizwanMunawar(編集済み)
@amulyaamaggididivami, well, in that case, you can clone the
ultralyticsrepository and build it locally with the changes in the code line here: https://github.com/ultralytics/ultralytics/blob/fa5d0bffbd63adfc302e9c118ffe5caa6447a044/ultralytics/solutions/object_counter.py#L135Edit: Can you please also try using the region points, rather than line points?
amulyaamaggididivami
Sure, thanks
1
Glenn JocherUltralytics@SudhanshuBlaze IN/OUT for line counters is image-axis based, not compass: for a mostly vertical line, IN = motion to the right (+x) and OUT = left; for a mostly horizontal line, IN = down (+y) and OUT = up; you can relabel to N/S/E/W post-process like this:
def label_dirs(results, p1, p2): (x1, y1), (x2, y2) = p1, p2 vertical = abs(x1 - x2) < abs(y1 - y2) return ({"eastbound": results.in_count, "westbound": results.out_count} if vertical else {"southbound": results.in_count, "northbound": results.out_count})Details of the IN/OUT logic are in the count_objects method of the ObjectCounter reference.
Forlin12
Hello, I would like to know how it works to remove how many objects there are per instant region because I can't extract this information.
SudhanshuBlaze
Hi,
I was wondering in the case of LINE counters, if there's a thumb rule to translate the IN, OUT count to North->South, East-> West, something like this. How do I know which direction is IN and which direction is OUT in the case of LINE counters?
My coordinates: line_counter1 = [(842, 1434), (640, 2200)]
line_counter2 = [(1028, 1304), (1094, 1038)]
line_counter3 = [(1068, 1038), (684, 1048)]
line_counter4 = [(2498, 546), (3276, 572)]
line_counter5 = [(3244, 786), (3414, 904)]
line_counter6 = [(1830, 958), (1668, 710)]Thanks in advance
morussk
Hey, I am trying to use solutions.RegionCounter() with conf less than 0.25 but it seems to be ignoring it, is that by design? If I use conf > 0.25 it is taken into account and counts only detections with confidence higher than conf in particular region but lower then 0.25 seems to be ignored and those detections have not chance of being counted by solutions.RegionCounter(). Please advice.
RizwanMunawar
@morussk Hi, thanks for sharing the details. The counting in region feature relies on object tracking rather than standalone predictions. As a result, detections with a confidence score below 0.25 are ignored by default.
However, this behaviour can be modified by adjusting the track_high_thresh parameter. Currently, the
Solutionsclass doesn’t support adjusting tracking configuration core options directly, but you can adjust it by cloning the code and modifying the tracker's configurations file.Note: We always recommend using the latest version of the Ultralytics Python package. You can update it by running:
pip install -U ultralytics.Thanks.
1
dimasfadhila
hello, what dataset do you use for object detection in this region?
Glenn JocherUltralytics@dimasfadhila for region-based object counting in the Ultralytics example, we use models pre-trained on the COCO dataset by default, which includes 80 common object classes. You can see the full class list in our COCO dataset documentation. If you need to count custom objects, you'll want to train on your own dataset using YOLO's training mode.
rejens
Process video
while cap.isOpened(): success, im0 = cap.read() # Read the video frame. if not success: break im0 = region.count(im0) # Count the objects in different regions of frame. cv2.imshow("frame", im0) if cv2.waitKey(1) & 0xFF == ord('q'): break
this successfully did count and display the objects inside the region, how can i retrieve the number of counts, seems region.count(im0) returns the image only.
thanks
Glenn JocherUltralytics(編集済み)@rejens
RegionCounterreturns a results object, so call it on each frame and read the per-region counts fromregion_counts:results = region(im0) print(results.region_counts) # e.g. {'Region#01': 3} im0 = results.plot_imThe counts are for the current frame (they reset on every frame). Let me know if you need further clarification!
Darkbutbright
hi,counter = solutions.ObjectCounter(paras),im0 = counter.count(im0),Can the type information, font size, and position of the count in the video be set?
Glenn JocherUltralytics(編集済み)@Darkbutbright yes, you can customize the text information, font size and position of the count by modifying the solution source code. For
ObjectCounter, the counts are drawn in itsdisplay_counts()method (inultralytics/solutions/object_counter.py) through theSolutionAnnotator, so you can adjust the text rendering there. You can also call the solution and draw your own text on the returnedplot_imwithcv2.putText(), usingresults.in_countandresults.out_count. Let me know if you need further clarification!Darkbutbright
Thank you for your patient answer, but I really don't know where to get the detailed instructions (documents) of the solutions class. Could you please tell me how to get it (including more clear instructions for using other classes of yolo)?
Glenn JocherUltralytics@Darkbutbright thank you for your question! You can find detailed instructions and documentation for the
solutionsclass and other YOLO functionalities in the Ultralytics Docs. For specific examples, such as region counting or object tracking, check the solutions guide or the respective sections in the repository. Let me know if you need assistance with a particular use case!
kemalfrk
Hello, select the area with mouse events how to write the code that counts these classes if it enters a class.Thanks
Glenn JocherUltralytics@kemalfrk to implement object counting in specific regions using mouse events, you can modify the region points dynamically by capturing mouse click events and updating the region coordinates in real-time. You can refer to the Ultralytics YOLOv8 region counting example for guidance on how to set up and use the
RegionCounter. If you have further questions or need additional customization, feel free to ask!
MuhammedEnesGurkan
Hello, I use object counter but ı want to count only sheeps how can ı set classes_names to sheeps. Please help me
Glenn JocherUltralytics@MuhammedEnesGurkan to count only sheep, use the
--classesargument to specify the class index for sheep in your model. For example, if sheep are class 2, run:python yolov8_region_counter.py --source "path/to/video.mp4" --classes 2. Adjust the class index as needed based on your model's class mapping.

