sensors_channel.py

# 本作品采用MIT许可证授权。
# 版权所有 (c) 2026 OpenMV LLC。保留所有权利。
# https://github.com/openmv/openmv/blob/master/LICENSE
#
# 传感器通道示例(ToF + 人脸检测)
#
# 传感器数据和ToF深度图(通过CBOR协议通道)。
# 使用protocol库中的CBORChannel以便快速设置。

import csi
import tof
import struct
import random
from protocol import CBORChannel
import protocol
import ml
from ml.postprocessing.mediapipe import BlazeFace

# 初始化相机。
csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.QVGA)

# 加载内置的人脸检测模型。
model = ml.Model(
    "/rom/blazeface_front_128.tflite",
    postprocess=BlazeFace(threshold=0.5),
)
print(model)

# 初始化ToF传感器。
tof.init()
tof_w = tof.width()
tof_h = tof.height()

# 注册传感器通道。
sensors = CBORChannel()
sensors.add("temp", type="label", unit="Cel")
sensors.add("humidity", type="label", unit="%RH")
sensors_ch = protocol.register(name="sensors", backend=sensors)

# 注册深度通道。
depth = CBORChannel()
depth.add("depth", type="depth", width=tof_w, height=tof_h)
depth_ch = protocol.register(name="ToF depth", backend=depth)

# 模拟的传感器状态。
temp = 25.0
humidity = 50.0

while True:
    # 捕获帧并运行人脸检测。
    img = csi0.snapshot()

    for r, score, keypoints in model.predict([img]):
        ml.utils.draw_predictions(img, [r], ("face",), ((0, 0, 255),), format=None)
        ml.utils.draw_keypoints(img, keypoints, color=(255, 0, 0))

    # 用随机漂移模拟传感器读数。
    temp += random.uniform(-0.3, 0.3)
    temp = max(15.0, min(35.0, temp))
    humidity += random.uniform(-0.5, 0.5)
    humidity = max(20.0, min(80.0, humidity))

    # 读取ToF深度图。
    try:
        depth_data, dmin, dmax = tof.read_depth(vflip=True, hmirror=True)
    except RuntimeError:
        continue

    # 将深度浮点数打包为二进制(每个浮点数4字节)。
    depth_bytes = struct.pack("<%df" % len(depth_data), *depth_data)

    # 更新通道。
    sensors["temp"] = round(temp, 1)
    sensors["humidity"] = round(humidity, 1)
    depth["depth"] = depth_bytes

    depth_ch.send_event(0xFFFF)
    sensors_ch.send_event(0xFFFF)

    print(
        "temp=%.1f | humidity=%.1f | depth=%d bytes"
        % (temp, humidity, len(depth_bytes))
    )

results matching ""

    No results matching ""