Ultralytics YOLOv8.0.226 区域计数

博客介绍了区域计数相关内容,包括对本地视频文件进行区域计数,以及对摄像头拍到的实时视频进行区域计数。

regional_counting

对本地视频文件进行区域计数

import argparse
from collections import defaultdict
from pathlib import Path
import cv2
import numpy as np
from shapely.geometry import Polygon
from shapely.geometry.point import Point
from ultralytics import YOLO
from ultralytics.utils.files import increment_path
from ultralytics.utils.plotting import Annotator, colors
from datetime import datetime, timedelta
import re
from ultralytics.utils import LOGGER, colorstr
import openpyxl

track_history = defaultdict(list)
current_region = None


def mouse_callback(event, x, y, flags, param):
    global current_region
    if event == cv2.EVENT_LBUTTONDOWN:
        for region in counting_regions:
            if region['polygon'].contains(Point((x, y))):
                current_region = region
                current_region['dragging'] = True
                current_region['offset_x'] = x
                current_region['offset_y'] = y
    elif event == cv2.EVENT_MOUSEMOVE:
        if current_region is not None and current_region['dragging']:
            dx = x - current_region['offset_x']
            dy = y - current_region['offset_y']
            current_region['polygon'] = Polygon([
                (p[0] + dx, p[1] + dy) for p in current_region['polygon'].exterior.coords])
            current_region['offset_x'] = x
            current_region['offset_y'] = y
    elif event == cv2.EVENT_LBUTTONUP:
        if current_region is not None and current_region['dragging']:
            current_region['dragging'] = False


def main():
    global counting_regions
    counting_regions = [
        {
            'name': 'YOLOv8 Polygon Region',
            'polygon': Polygon([(x1, y1), (x1 + width1, y1), (x1 + width1, y1 + height1), (x1, y1 + height1)]),
            'counts': 0,
            'dragging': True,
            'region_color': (255, 0, 0),
            'text_color': (0, 0, 0)
        },
        {
            'name': 'YOLOv8 Rectangle Region',
            'polygon': Polygon([(x2, y2), (x2 + width2, y2), (x2 + width2, y2 + height2), (x2, y2 + height2)]),  # Polygon points
            'counts': 0,
            'dragging': True,
            'region_color': (0, 255, 225),
            'text_color': (0, 0, 0),
        },
        {
            'name': 'YOLOv8 Rectangle Region',
            'polygon': Polygon([(x3, y3), (x3 + width3, y3), (x3 + width3, y3 + height3), (x3, y3 + height3)]),  # Polygon points
            'counts': 0,
            'dragging': True,
            'region_color': (0, 255, 0),
            'text_color': (0, 0, 0),
        }
    ]
    vid_frame_count = 0
    i = 1
    if not Path(video_path).exists():
        raise FileNotFoundError(f"Source path '{source}' does not exist.")
    model = YOLO(f'{weights}')
    model.to('cuda') if device == '0' else model.to('cpu')
    names = model.model.names
    videocapture = cv2.VideoCapture(video_path)
    frame_width, frame_height = int(videocapture.get(3)), int(videocapture.get(4))
    fps, fourcc = int(videocapture.get(5)), cv2.VideoWriter_fourcc(*'mp4v')
  
### Ultralytics 8.0.99 的解压与运行 要完成 `ultralytics-8.0.99.tar.gz` 文件的解压和运行操作,可以按照以下方式处理: #### 解压文件 对于 `.tar.gz` 类型的压缩包,通常使用 Linux 或 macOS 提供的标准工具来解压。以下是具体的命令: ```bash tar xzvf ultralytics-8.0.99.tar.gz ``` 这条命令会将压缩包中的内容提取到当前目录下[^1]。 #### 安装依赖项 进入解压后的目录后,可能需要安装一些 Python 库作为项目的依赖项。如果项目附带了一个 `requirements.txt` 文件,则可以通过 pip 来自动安装这些库: ```bash pip install -r requirements.txt ``` 如果没有提供 `requirements.txt` 文件,则可以根据文档说明手动安装必要的库,比如 PyTorch 和其他支持库。 #### 运行程序 Ultralytics 是一个基于 YOLOv5/YOLOv8 的目标检测框架,其具体运行方式取决于所使用的功能模块。一般情况下,可以从官方文档或 README.md 中找到启动脚本的信息。常见的运行方式如下所示: ##### 训练模型 训练一个新的模型通常涉及指定数据集路径和其他参数: ```python from ultralytics import YOLO model = YOLO('yolov8n.pt') # 加载预训练权重 results = model.train(data='path/to/data.yaml', epochs=100, imgsz=640) ``` ##### 推理测试 加载已有的模型并对图像或视频执行推理: ```python from ultralytics import YOLO model = YOLO('yolov8n.pt') # 使用预定义模型 results = model('https://ultralytics.com/images/bus.jpg') ``` 以上代码片段展示了如何通过 API 调用来实现基本的功能调用[^2]。 --- #### 注意事项 在实际操作过程中需要注意以下几点: - 确保环境配置正确,特别是 CUDA 和 cuDNN 版本需匹配 GPU 驱动版本。 - 如果遇到权限问题,在某些场景下可尝试加上 `sudo` 命令前缀以提升权限。 - 对于大型数据集或者复杂计算任务,建议优先选用性能更强的工作站或云端实例。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值