简体   繁体   English

查找在OpenCV Python中屏幕上是否可见绘制的矩形

[英]Find if drawn rectangle is visible on screen in opencv python

I have some code which will draw a rectangle using cv2.rectangle function based on other parameters. 我有一些代码将基于其他参数使用cv2.rectangle函数绘制一个矩形。 This is part of a face detection program. 这是面部检测程序的一部分。 The rectangle is shown on screen within an image using imshow . 使用imshow在图像中的屏幕上显示矩形。 However, due to the variable nature of the rectangle's dimensions, there are situations when the rectangle is not visible. 但是,由于矩形尺寸的可变性,在某些情况下矩形不可见。 After the line of code which draws the rectangle in the image, how do I detect if the rectangle is visible or not. 在绘制图像中矩形的代码行之后,如何检测矩形是否可见。 I want this so that I can find when a face is not detected. 我想要这样做,以便可以在未检测到脸部时找到。 This is my code: 这是我的代码:

import numpy as np
import cv2

# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades

# https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x + (w / 4), y + (h / 4)),(x+(3 * w / 4),y + (3 * h / 4)),(255,0,0),2)

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

Thanks! 谢谢!

Add print len(faces) in the while loop. 在while循环中添加print len(faces) If its zero, then no face detected. 如果其值为零,则没有检测到人脸。 No rectangle. 没有矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM