Check for a detected face in Python OpenCV? - python

I want to check if a face has been detected.
I have the variable face_detect and when a face is detected I want to turn this variable to True however I don't know how to check for a detected face. I tried using faces.size() to check if it was greater than zero but it said
AttributeError: 'tuple' object has no attribute 'size'
So I don't know why that is not working.
import cv2
import numpy as np
import winsound
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
face_detect = False
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,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()

I've slightly modified your code to update the face_detect variable to True whenever a face is detected.
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
face_detect = False
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if len(faces) > 0:
face_detect = True
else:
face_detect = False
print(face_detect)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()

Related

I'm trying a project with OpenCV and can't get past this error

cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-2y91i_7w\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-2y91i_7w\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
this is the error i'm facing
below is my code
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
def detect(gray,frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x,y), ((x+w),(y+h)), (2555,0,0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = frame[y:y + h, x:x +w]
smiles = smile_cascade.detectMultiScale(roi_gray, 1.8,20)
for (sx,sy,sw,sh) in smiles:
cv2.rectangle(roi_color ,(sx,sy), ((sx + sw) , (sy + sh)),(0,0,225),2)
return frame
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitkey(1) & xff == qrd('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I got a different error and fixed the indentation of the return line of the detect() method, see the comment.
Also, there were some errors with waytkey() function, which actually is waitKey().
This should work (at least it does on my machine):
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x,y), ((x+w),(y+h)), (2555,0,0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = frame[y:y + h, x:x +w]
smiles = smile_cascade.detectMultiScale(roi_gray, 1.8,20)
for (sx,sy,sw,sh) in smiles:
cv2.rectangle(roi_color ,(sx,sy), ((sx + sw) , (sy + sh)),(0,0,225),2)
return frame # << outdent
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
# changed here below the waitKey() and added ret:
keypressed = cv2.waitKey(10)
if keypressed == ord('q') or not ret:
break
video_capture.release()
cv2.destroyAllWindows()

Opencv (in python) gives error - !_src.empty() in function 'cv2::cvtColor '

I'm currently trying to run a simple python program to detect face and eyes.
I downloaded the appropriate classifiers and they're in the same directory. I even checked my camera settings and it's set to on with permission to python. Any ideas how to solve this?
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while True:
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.rectange(img, (x,y), (x+w, y+h), (255,0,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,ehh) in eyes:
cv2.rectangle(roi_color, (ex,ey), (ex+ew,ey+eh), (0,255,0), 2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
Why does this OpenCV program give the error:
My camera settings show that python is using it:
Thank you!
!_src.empty() means you have an empty frame
You can check the frame to make sure you actually get the image:
ret, img = cap.read()
if img is not None:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else: < implement how you want to deal with empty frame >

Open Cv + Numpy + Python face detection for mac

How can I make an OpenCV face detection for Python 2.7 on a Mac. I have tried many different codes but they all don't work. I am running them in terminal.
I get this error:
cv2.error: OpenCV(4.0.0) /Users/travis/build/skvark/opencv-python/opencv/modules/objdetect/src/cascadedetect.cpp:1658: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'
This seems to be right but I can't figure out what the error is. Here is the code for the face detection.
import numpy as np
import cv2
faceCascade =
cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
while True:
ret, img = cap.read()
img = cv2.flip(img, -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(20, 20)
)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imshow('video',img)
k = cv2.waitKey(30) & 0xff
if k == 27: # press 'ESC' to quit
break
cap.release()
cv2.destroyAllWindows()
Your error message indicates that the file path may be invalid, the program can't find .xml file. And you may want to replace 'Cascades/haarcascade_frontalface_default.xml' with a absolute path such as 'username/file/../cascade.xml'

auto detect face and take a snapshot with opencv

i'm working on face recognition project with my college. what i'm trying to take a snapshot and save it if the face is detected automatically before closing the webcam.
what I have now is open cam and wait if face is detected and press "q" to take snapshot and save the image.
Here is the code:
import numpy as np
import cv2
import time
#import the cascade for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def TakeSnapshotAndSave():
# access the webcam (every webcam has a number, the default is 0)
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# to detect faces in video
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
x = 0
y = 20
text_color = (0,255,0)
# write on the live stream video
cv2.putText(frame, "Press q when ready", (x,y), cv2.FONT_HERSHEY_PLAIN, 1.0, text_color, thickness=2)
# if you want to convert it to gray uncomment and display gray not fame
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',frame)
# press the letter "q" to save the picture
if cv2.waitKey(1) & 0xFF == ord('q'):
# write the captured image with this name
cv2.imwrite('try.jpg',frame)
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
TakeSnapshotAndSave()
thank you in advance
I adapted your code to save 10 images just for testing, if you want infinite photos, just change the while condition. So in your code you were overwriting the current image so I changed the string parameter so that it was possible to take lots of pictures.
import numpy as np
import cv2
import time
#import the cascade for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def TakeSnapshotAndSave():
# access the webcam (every webcam has a number, the default is 0)
cap = cv2.VideoCapture(0)
num = 0
while num<10:
# Capture frame-by-frame
ret, frame = cap.read()
# to detect faces in video
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
x = 0
y = 20
text_color = (0,255,0)
cv2.imwrite('opencv'+str(num)+'.jpg',frame)
num = num+1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
TakeSnapshotAndSave()
Perform imwrite() in the for (x,y,w,h) in faces: loop itself. If you use a constant filename, your last detected face will be saved and the rest will be overwritten

cropping images in python

I'm trying to detect a face and then crop it to use it in a face recognition algorithm. Here is my code.
import numpy as np
import cv2
import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('xD.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
print x
print y
print w
print h
img.crop((x,y,w,h))
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
When I print (x,y,w,h), it gives precise coordinates, but when I crop it, it gives me this error.
img.crop((x,y,w,h))
AttributeError: 'numpy.ndarray' object has no attribute 'crop'
import numpy as np
import cv2
from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('xD.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cropped = img[y:y+h, x:x+w]
cv2.imwrite("thumbnail.png", cropped)
cv2.imshow("cropped", cropped)
cv2.waitKey(0)

Categories

Resources