为每个面分配ID

时间:2017-07-24 05:16:08

标签: python opencv

我使用以下代码来检测面部。检测后,我在脸部周围绘制矩形。然后我分配面部的id,即面部编号。如果有两个面,一个面的面值为1,另一个面为2.以下是我的代码。

detections = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags=cv2.CASCADE_SCALE_IMAGE
)

# Draw a rectangle around the faces
for (x, y, w, h) in detections:
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    face_no = detections.shape[0];

    cv2.putText(frame, str(face_no), (x, y - 30), cv2.FONT_HERSHEY_TRIPLEX,
                .7, (0, 0, 0), 1, cv2.LINE_AA)

但是这段代码总是返回面部总数。我怎样才能得到每张脸的数字?

2 个答案:

答案 0 :(得分:3)

如果你使用from scipy.interpolate import griddata # points is the original pair (x, y) grid_z0 = griddata(points, z, (grid_x, grid_y), method='nearest') ,你每次都会得到相同的值,因为那里没有基于循环变化的变量。您可以做的是使用detections.shape[0]标记面部,enumerateface_no设置为循环迭代次数:

for face_no, (x, y, w, h) in enumerate(detections):
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.putText(frame, str(face_no), (x, y - 30), cv2.FONT_HERSHEY_TRIPLEX,
                .7, (0, 0, 0), 1, cv2.LINE_AA)

答案 1 :(得分:2)

detections是检测到的面孔列表,len(detections)应该为您提供面部数量。所以,detections[i]是第i个脸,让我成为那张脸的ID。

如果您的循环更改为

for i in range(o,len(detections):
    faceID = i
    currentFace = detections[i]

等等,您可以通过ID访问它们。

相关问题