如果在带有opencv的面部检测器中

时间:2016-08-15 20:30:41

标签: python python-3.x opencv

注意我是初学者。我制作了一个分析图片的脚本,并在图像中找到的任何面部周围放置一个框,该部分有效,我需要它做的是将“if faces = True”中的“faces”更改为If的效果faces found = true,虽然我不知道那是什么,但face什么也没做。

import cv2
import sys
import time

imagePath = sys.argv[1]
cascPath = sys.argv[2]

faceCascade = cv2.CascadeClassifier(cascPath)

image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(30, 30))#,flags = cv2.cv.CV_HAAR_IMAGE_SCALE)

for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

if faces = True:
    cv2.imshow("(1) Pamela Found" ,image)
else:
    cv2.imshow("(0) Pamela's Found" ,image)

cv2.waitKey(0)&0xFF

代码已经完成了:

if faces = True:
        cv2.imshow("(1) Pamela Found" ,image)
    else:
        cv2.imshow("(0) Pamela's Found" ,image)

不起作用。帮助将不胜感激 - 谢谢!

编辑:现在我已将代码更改为:

import cv2
import sys
import time

imagePath = sys.argv[1]
cascPath = sys.argv[2]

faceCascade = cv2.CascadeClassifier(cascPath)

image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(30, 30))#,flags = cv2.cv.CV_HAAR_IMAGE_SCALE)

for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

if faces == True:
    cv2.imshow("(1) Pamela(s) Found" ,image)
    cv2.waitKey(0)&0xFF
else:
    cv2.imshow("(0) Pamela(s) Found" ,image)
    cv2.waitKey(0)&0xFF

当我运行它时,XML文件和没有面部的图像,它工作,并说,“(0)Pamela(s)Found”应该是,但当我运行它,XML文件,和面对窗口的图像没有弹出,我相信这与if语句下的waitkey没有关系,帮助将不胜感激 - 谢谢!

2 个答案:

答案 0 :(得分:0)

使用faces作为条件:

if faces: # python types can be coerced to boolean
    cv2.imshow("(1) Pamela Found" ,image)
else:
    cv2.imshow("(0) Pamela's Found" ,image)

空列表(或容器)具有 falsy 值,而如果检测到面部(即faces不为空),则可迭代的faces将具有一个 truthy 值。

P.S。 if faces = True会引发语法错误,如果您打算if faces == True,那么它也会缩小为if faces,最好写成 Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes("chmod a=rw /dev/input/event2" + "\n"); os.flush(); os.writeBytes("exit\n"); os.flush(); process.getOutputStream(). final BufferedReader reader = new BufferedReader(newInputStreamReader(process.getInputStream())); int read; final char[] buffer = new char[4096]; while ((read = reader.read(buffer)) > 0) { stringBuilder.append(buffer, 0, read); tv.setText(stringBuilder.toString()); } reader.close(); // Waits for the command to finish. process.waitFor(); }

答案 1 :(得分:0)

根据我发现in OpenCV的文档,faceCascade.detectMultiScale返回对象的集合。

要测试集合(listsettupledict等)是非空的,只需尝试:

if faces:
    cv2.imshow("(1) Pamela Found", image)
else:
    cv2.imshow("(0) Pamela's Found", image)

可能是Best way to check if a list is empty

的副本