推理
对一张图(一帧)跑推理,结果输出 JSON 对象。连续帧在循环里每次调一次。阻塞调用,耗时随 Provider / 硬件而定。不承诺硬实时。
同一会话可并发调用;吞吐扩展推荐每线程一个会话,而不是多线程抢一个会话。会话已关闭再调抛 InternalError。
本绑定公开四个格式常量。未知 format 抛 InternalError(码 18),不把契约违反拖到 native。
功能概览
| 类别 | 属性 | 类型 | 访问 | 说明 |
|---|---|---|---|---|
| 推理 | infer_image | dict | 方法 | 对一张图(一帧)跑推理,返回结果 JSON 对象。连续帧循环调用 |
| 图像格式 | IMAGE_AUTO | int(0) | 常量 | 按字节魔数自嗅探 JPG/PNG/BMP。裸缓冲禁止用 AUTO |
IMAGE_ENCODED | int(1) | 常量 | 显式已编码字节流;当前行为同 AUTO | |
IMAGE_RGB888 | int(2) | 常量 | 裸 RGB888。必须给 width/height | |
IMAGE_BGR888 | int(3) | 常量 | 裸 BGR888(工业相机常见)。必须给 width/height |
常量唯一定义见 类型 · 图像格式。本绑定没有 GRAY8 / RGBA8888。
推理
infer_image()
def infer_image(
self,
image_bytes: bytes | bytearray | memoryview,
*,
format: int = IMAGE_AUTO,
width: int = 0,
height: int = 0,
stride: int = 0,
) -> dict
对一张图(一帧)跑推理。连续帧循环调用本方法。
参数:
image_bytes(bytes | bytearray | memoryview) — 图像字节format(int) — 图像格式,默认IMAGE_AUTOwidth(int) — 裸缓冲必须>0,默认0height(int) — 裸缓冲必须>0,默认0stride(int) — 每行字节数。0= 紧凑排列(width × 3),默认0
返回值:
dict— 结果 JSON 对象(envelope 见 类型 · 推理结果)。永不包含模型明文、密钥等任何敏感字节
IMAGE_AUTO / IMAGE_ENCODED:image_bytes 为 JPG/PNG/BMP 编码字节流,忽略宽高。IMAGE_RGB888 / IMAGE_BGR888:裸像素,必须给 width/height;缺宽高、stride < 0、长度不足或未知 format 抛 InternalError(码 18)。image_bytes 不是 bytes / bytearray / memoryview 同样抛 InternalError。裸缓冲禁止 IMAGE_AUTO(嗅探不出通道序)。len(image_bytes) 必须 ≥ stride * height(stride 为 0 时按紧凑宽度 width * 3 计)。
典型异常:IoDeniedError(裸缓冲指针不可读)/ InternalError(参数契约违反)。
示例:
from darra_ai import IMAGE_AUTO, Session
jpg = open("photo.jpg", "rb").read()
with Session.open("model.darmodel", key_path="model.darmkey") as s:
print(s.infer_image(jpg, format=IMAGE_AUTO))
完整示例
相机循环:每次一张图(一帧)。
from darra_ai import IMAGE_BGR888, Session
with Session.open("model.darmodel", key_path="model.darmkey") as s:
while True:
frame = grab_bgr() # 相机一帧,1920×1080 BGR 紧凑
result = s.infer_image(
frame, format=IMAGE_BGR888, width=1920, height=1080, stride=0,
)
handle(result)
envelope 字段(schema / task / provider / elapsedMs / image / results)恒定;results 元素随 task 而变:
detect:{label, score, box:[x,y,w,h]}classify:{label, score}top-k 按分降序segment:{label, score, maskRle}- 其余 task 的逐元素 schema 随对应 Provider 落地,本契约只承诺 envelope
结果坐标基于 image 字段(解码后、送入模型前的尺寸);裸缓冲输入时等于传入的宽高。