问题
Im using the following code to generate each person an id. It works partially however the problem is that when more people comes in, each of them are getting the same id. Lets say if there are totally 3 persons, it is assigning the id 3 to everyone. I want it to be unique in incremental order. How can I sort this out?
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
回答1:
Look at your code closely:
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 is writing user_id on each of the rectangles that it is drawing.
Within the scope of the for loop, you're not updating the user_id parameter, hence the for loop is writing the same constant value on all the rectangles.
You should increment the value that you wish to see on the rectangle, within this for loop itself.
For example:
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)
Now unlike user_id, the value i is incremented in every iteration of the for loop, hence cv2.putText will print the incremented value for each iteration, which should suffice your requirement
来源:https://stackoverflow.com/questions/46049109/assigning-unique-face-id-realtime