实时分配唯一的人脸ID

Assigning unique face id realtime

我正在使用以下代码为每个人生成一个 ID。它部分起作用,但问题是当更多人进来时,每个人都获得相同的 ID。比方说,如果总共有 3 个人,则将 id 3 分配给每个人。我希望它在递增顺序中是唯一的。我该如何解决这个问题?

 while True:
    ret, img = cap.read()

    input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    detected = detector(input_img, 1)
    current_viewers = len(detected)
    if current_viewers > last_total_current_viewers:
        user_id += current_viewers - last_total_current_viewers
    last_total_current_viewers = current_viewers

    for i, d in enumerate(detected):
        x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
        cv2.putText(img, str(user_id), (x1, y1), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)

    cv2.imshow("result", img)
    key = cv2.waitKey(30)

    if key == 27:
        break

仔细看看你的代码:

for i, d in enumerate(detected):
        x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
        cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
        cv2.putText(img, str(user_id), (x1, y1), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)

cv2.putText 正在绘制的每个矩形上写 user_id

for 循环的范围内,您没有更新 user_id 参数,因此 for 循环在所有矩形上写入相同的常量值。

您应该增加您希望在矩形上看到的值,在此 for 循环本身中。

例如:

for i, d in enumerate(detected):
            x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
            cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)
            cv2.putText(img, 'user_'+str(i), (x1, y1), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA)

现在与 user_id 不同,值 ifor 循环的每次迭代中递增,因此 cv2.putText 将打印每次迭代的递增值,这应该能满足你的要求