推理
快速开始
inf = ai.infer("a.jpg")
先调 open 打开模型,再做推理。没打开就推,调用返回失败,不会抛异常。
基础用法
infer_file()
inf = ai.infer_file("a.jpg")
JPG / PNG / BMP 会按编码自动识别。一次调用对应一张图 / 一帧。
参数
- 文件路径。读不到时返回失败。
示例
inf = ai.infer_file("a.jpg")
if inf.ok:
print(inf.content)
infer_image()
inf = ai.infer_image(image)
图已经在内存里时,不必先写盘。裸像素走 infer_buffer(data, format=, width=, height=),处理方式一样。
参数
image 收三种形态:编码字节(bytes / bytearray / memoryview)、numpy.ndarray、PIL.Image。ndarray 里 (H,W) 按 GRAY8,(H,W,3) 按 RGB888,(H,W,4) 按 RGBA8888,format= 可覆盖。PIL 按 mode 自动映射。
width/height— 传裸缓冲时必填,要大于 0。AUTO / ENCODED 时忽略,填 0。stride— 每行字节数。填 0 表示紧凑排列。RGB/BGR 是width*3。GRAY 是width*1。RGBA 是width*4。alpha_premultiplied— 用来标记预乘 alpha。
示例
inf = ai.infer_image(image)
if inf.ok:
print(inf.content)
submit()
submit(image, **kwargs) -> int
异步投一张,不阻塞,返回票号 int。
参数
image— 同infer_image(),三种形态都收。
wait()
wait(ticket) -> AiResult
按票号拿结果。
参数
ticket—submit返回的票号。
空闲机实测(197,det.onnx,3 轮中位):
- 单任务基线:1×(约 0.2s)
max_workers=2双投:两任务同时完成,各约 1–1.5 倍- 多实例 2–4 个:总吞吐约等于串行(0.88–0.94×) 并发收益随机器负载变化。
日志出口
打开 / 选路 / 降级 / 警告都走标准 logging,logger 名是 darra_ai.model。
import logging
logging.getLogger("darra_ai.model").setLevel(logging.DEBUG)
LogLevel:ERROR=0 / WARN=1 / INFO=2 / DEBUG=3。
高级类型
InferenceResult
@dataclass
class InferenceResult:
schema: int | None
task: str | None
provider: str | None
elapsed_ms: float | None
image_width: int | None
image_height: int | None
items: list
from_json / to_json / columns / __iter__ / __len__ 可用,items 返回副本。task 为任务短名:detect / classify / segment / pose / obb / ocr,另有 anomaly / depth / embedding。
items 字段(按任务族给,detect / pose / obb 同源):
| 字段 | 类型 | 说明 |
|---|---|---|
| label | str | 类别名 |
| class_id | int | 类别下标 |
| score | float | 置信分数 |
| box | list | [x, y, w, h],image 空间 |
| polygon | list | [[x, y], ...],至少 3 个点,image 坐标空间,可以缺席 |
| keypoints | list | [[x, y, conf], ...],只有 pose 有 |
| angle | float | 角度,只有 obb 有 |
classify 只给 label / class_id / score;ocr 的 det 形给 label / score / box / polygon,rec 形给 text / score。anomaly / depth / embedding 无类别维度:
| 字段 | 类型 | 说明 |
|---|---|---|
| score | float | anomaly 图像级分数 |
| anomalyScore | list | 逐像素连续分数,行主序;模型带 anomaly 输出时才有 |
| anomaly_width | int | 分数图宽;模型带 anomaly 输出时才有 |
| anomaly_height | int | 分数图高;模型带 anomaly 输出时才有 |
| depth | list | 深度图,量纲由模型定;模型带 depth 输出时才有 |
| depth_width | int | 深度图宽;模型带 depth 输出时才有 |
| depth_height | int | 深度图高;模型带 depth 输出时才有 |
| embedding | list | 原始特征向量(未做 L2 归一化);模型带 embedding 输出时才有 |
| embeddingDim | int | 向量维度;模型带 embedding 输出时才有 |
segment 实例掩码(ONNX 族)字段:
| 字段 | 类型 | 说明 |
|---|---|---|
| label | str | 类别名 |
| class_id | int | 类别下标 |
| score | float | 置信分数 |
| box | list | [x, y, w, h],image 空间 |
| mask | list | 掩码位图。没有掩码原型时,mask 三个键整体缺席,退回只给框 |
| mask_width | int | 掩码宽;模型带 mask 输出时才有 |
| mask_height | int | 掩码高;模型带 mask 输出时才有 |
segment 整图类别图(Paddle 族)只有 maskRle:
| 字段 | 类型 | 说明 |
|---|---|---|
| size | list | [H, W],模型输出光栅尺寸,不是 image 宽高 |
| values | list | 每段的类别下标,0 表示背景,照实保留 |
| counts | list | 每段的像素长度,行优先,逐段拼接长度为 H*W |
maskRle 是整图类别图的游程编码,停在模型输出空间;只有 box / keypoints / angle 换算到 image 空间。
图片格式
infer_image / infer_buffer 的输入格式,传裸缓冲时必须给宽高:
| 值 | 名称 | 说明 |
|---|---|---|
| 0 | IMAGE_AUTO | 按字节魔数嗅探 JPG / PNG / BMP,裸缓冲禁用 |
| 1 | IMAGE_ENCODED | 已编码字节流,行为同 AUTO |
| 2 | IMAGE_RGB888 | 裸 RGB 8bit |
| 3 | IMAGE_BGR888 | 裸 BGR 8bit |
| 4 | IMAGE_GRAY8 | 裸灰度 8bit |
| 5 | IMAGE_RGBA8888 | 裸 RGBA 8bit |
SessionOptions
@dataclass
class SessionOptions:
intra_op_threads: int = 0
inter_op_threads: int = 0
cpu_affinity_mask: int = 0
gpu_device: int = 0
device_kind: DeviceKind = DeviceKind.GPU
unique: bool = False
weight: int = 0
parallel: int = 0
wrap_ticket: WrapTicket | None = None
conf_threshold: float = 0.0
nms_threshold: float = 0.0
top_k: int = 0
ctc_blank_index: int = 0
mask_threshold: float = 0.0
ocr_dictionary: str | None = None
precision: Precision = Precision.UNSPECIFIED
InferOverflow
队列满时的三种策略。
| 值 | 名称 | 说明 |
|---|---|---|
| 0 | FAIL | 这次投递立即失败,工业默认用这个 |
| 1 | BLOCK | 卡住,等队列有空位 |
| 2 | DROP_OLDEST | 丢掉最旧的未开跑任务,被挤掉的票在 wait 时失败读结果里的错误码 |
InferPoolOptions
同模型推理池的选项,InferPool.open 接收这个结构。
@dataclass
class InferPoolOptions:
max_workers: int = 0
queue_capacity: int = 0
overflow: InferOverflow = InferOverflow.FAIL
worker: SessionOptions | None = None
weight: int = 0
阈值
default_thresholds 是实例级默认阈值表,按类别下标给分数下限,范围 [0,1],填 None 不过滤。thresholds= 只覆盖这一次调用,不改默认表。
ai.default_thresholds = [0.5, 0.8]
inf = ai.infer_file("a.jpg", thresholds=[0.9])
值超出范围,或者长度和 class_count 对不上时调用失败读结果里的错误码。