Python:如果检测到 X 超过 T 秒:

Python: if X is detected more than T seconds:

我正在寻找知识。

我是 python 的新手,需要用相机 Gravity: HuskyLens 做一个项目。 它允许您在检测到面部时显示块(在面部周围,它正在跟踪摘要) 我想,当我检测到一个块时,知道它是否被检测到超过 7 秒。

import time
import json
from huskylib import HuskyLensLibrary

# Initialize
#hl = HuskyLensLibrary("I2C", "", address = 0x32)
hl = HuskyLensLibrary("SERIAL", "/dev/ttyUSB0", 3000000)

# Change to face recognition algorithms
hl.algorithms("ALGORITHM_FACE_RECOGNITION")

timer = time.time()

while True:
    blocks = hl.requestAll()

    for block in blocks:
        if block.type == "BLOCK": # If a block is detected
            print("Face !")
            if BLOCK DETECTED MORE THAN 7 SECONDS: # If a block is detected more than 7 seconds
                print("SCREAMER ! BOO !")
                time.sleep(0.5)
        else:
            print("No Face !")
            time.sleep(0.5)

不知道说的够不够清楚,我对任何能让我进步的信息感兴趣

ps: 我已经去时光图书馆逛了逛,但我还没有全部看懂,所以找到了我的快乐。

我可能错了,但你可以尝试跟踪最新的块是什么,然后只要最新块的类型是"BLOCK",你就可以增加计时器。

我的意思是:

face_apparition_time = 0  # We haven't seen a face yet, so apparition time is 0
# Gives a time in seconds since a fixed point we don't control, we'll use it as a checkpoint
timer = time.time()
last_block_seen = None  # Begin with None, we haven't seen any block yet

while True:
    blocks = hl.requestAll()

    for block in blocks:
        if block.type == "BLOCK":  # If a block is detected
            print("Face !")

            # Then we check if the last block was also a "BLOCK". If yes, we increase our timer.
            if last_block_seen == "BLOCK":
                # We count the number of seconds between the last checkpoint and now.
                face_apparition_time = time.time() - timer

            # Then we chack if a face has appeared for more than 7 seconds:
            if face_apparition_time > 7:  # If a block is detected more than 7 seconds.
                print("SCREAMER ! BOO !")

        else:
            print("No Face !")

            # As we don't see no face, we have to reset our checkpoint to "now"
            timer = time.time()
            face_apparition_time = 0

        # Do not forget that we are going to look at the next block, so this block must be stored :)
        last_block_seen = block.type
        time.sleep(0.5)

我不确定time.sleep()应该去哪里,你可以自己试试哪个更适合:) 希望这对您有所帮助,请不要犹豫,提出更多问题!