只有在OpenCV中存在矩形时才执行操作

问题描述 投票:2回答:1

我正在学习OpenCV(和Python),并设法让OpenCV检测我的鼻子并用鼻子的动作移动鼠标,但由于它经常失去我的鼻子轨迹,我希望它能够回到使用我的脸部移动如果需要,而不是我的鼻子。我设法在视频中围绕我的脸和鼻子绘制矩形。

我试着变得厚颜无耻,只是把我的脸部矩形的循环放在“if cv2.rectangle”(鼻子)中,但它总是如此。我的问题是如何创建一个测试,以查看是否检测到鼻子后退以移动带有脸部的鼠标,如果重新检测到鼻子则返回使用鼻子。

我的循环截至目前

  # Here we draw the square around the nose, face and eyes that is detected.
    for (x,y,w,h) in nose_rect:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 3)
        if cv2.rectangle:
            m.move(x * 4, y * 4) # TODO: Write and if that goes into face if nose is not visible
            break
        else:
            for (x, y, w, h) in face_rect:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
                break

    for (x,y,w,h) in eye_rect:
        cv2.rectangle(frame, (x,y), (x+w,y+h), (205,0,0), 3)
        break

我可以发布我的整个程序,如果这有帮助,我已经尝试做一堆OpenCV官方教程,但没有设法找到我的问题的答案。

谢谢你的回复!

PS:我使用的是Python 3.5

python opencv
1个回答
1
投票

以下是您应在代码中使用的代码段 -

    if(len(nose_rect)>0): 
        print ("Only Nose")
        for (x,y,w,h) in nose_rect:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255), 3)
            #Here we say that m (the variable created before, should move the mouse using the x, and y variable from the nose rect.
            # We have acellerated movement speed by 4 to make it possible to navigate the cursor through the whole screen.
            m.move(x * 4, y * 4) # TODO: Write and if that goes into face if nose is not visible
    elif (len(face_rect)>0):
        print ("Only Face")
        for (x,y,w,h) in face_rect:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
    elif (len(face_rect)>0):
        print ("Only Eye")
        for (x,y,w,h) in eye_rect:
            cv2.rectangle(frame, (x,y), (x+w,y+h), (205,0,0), 3)
    else:
        print ("Nothing detected.")

另外,等待使用time.sleep()方法

    time.sleep(0.001) # Waiting 1 millisecond to show the next frame.
    if (cv2.waitKey(1) & 0xFF == ord('q')):#exit on pressing 'q'
     break
© www.soinside.com 2019 - 2024. All rights reserved.