绘图值未在OpenCV的VideoCapture中更新

时间:2019-06-15 18:20:57

标签: python opencv

我正在尝试使用Open CV Video Capture在视频帧上绘制面部关键点。我正在使用训练有素的pytorch CNN模型。这是代码:

cap = cv.VideoCapture(0)
time.sleep(2.0)

while cap.isOpened():
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        face_gray = gray[y:y+h, x:x+w]

    sample = cv.resize(face_gray, (96, 96))
    sample = sample.astype('float32')/255
    sample = np.asarray(sample).reshape(1,96,96)
    sample = torch.from_numpy(sample).unsqueeze(0).to(device)
    output = saved_model(sample)
    output = output.view(-1, 2).detach()
    output = (output * 48) + 48
    output = output.cpu().numpy()
    print(output)
    for i in range(15):
        cv.circle(frame, (output[i][0], output[i][1]), 1, (0, 0, 255), -1)

    cv.imshow("Frame", frame)
    key = cv.waitKey(1) & 0xFF


    if key == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

输入尺寸:torch.Tensor([1,1,96,96]),1个灰度图像

输出尺寸:15个面部关键点的割炬.Tensor([15,2]),(x,y)

在视频捕获中检测到脸部(使用Haar Cascade)时,由于关键点图不变,因此输出值相同。

2 个答案:

答案 0 :(得分:0)

该代码最初在某些迭代中没有处理len(faces) > 0的情况,随后在len(faces) == 0中没有处理。如果发生这种情况,face_gray将保留其先前的价值,并且您将基于陈旧的frame来使用新的face_gray

答案 1 :(得分:0)

我没有看到您的代码块有任何问题。可能发生错误的唯一可能性是,当您在视频帧中有一张静态脸并且被HaarCascade检测器检测为最后一张脸时。通过查看代码块,很明显,您试图在每个视频帧中仅检测到一张面部。尝试移动sample = ...output = ...for ...:块以将关键点呈现到面孔的for ...迭代器中。

建议的修改后的代码块如下所示:

cap = cv.VideoCapture(0)
time.sleep(2.0)

while cap.isOpened():
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        face_gray = gray[y:y+h, x:x+w]

        # Push this block into for iterator of faces
        sample = cv.resize(face_gray, (96, 96))
        sample = sample.astype('float32')/255
        sample = np.asarray(sample).reshape(1,96,96)
        sample = torch.from_numpy(sample).unsqueeze(0).to(device)
        output = saved_model(sample)
        output = output.view(-1, 2).detach()
        output = (output * 48) + 48
        output = output.cpu().numpy()
        print(output)
        for i in range(15):
            cv.circle(frame, (output[i][0], output[i][1]), 1, (0, 0, 255), -1)
        # End block

    cv.imshow("Frame", frame)
    key = cv.waitKey(1) & 0xFF


    if key == ord('q'):
        break

cap.release()
cv.destroyAllWindows()