Haar- Cascade face detection OpenCv - python

I used the following code to detect a face using Haar cascade classifiers provided by OpenCv Python. But the faces are not detected and the square around the face is not drawn. How to solve this?
import cv2
index=raw_input("Enter the index No. : ")
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cap = cv2.VideoCapture(0)
cont=0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=10,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
#cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame',frame)
inpt=cv2.waitKey(1)
if inpt & 0xFF == ord('q'):
break
elif inpt & 0xFF == ord('s') :
#name='G:\XCODRA\Integrated_v_01\EigenFaceRecognizer\img2'+index+"."+(str(cont))+".png"
name='IC_image\\'+index+"."+(str(cont))+".png"
resized = cv2.resize(gray,None,fx=200, fy=200, interpolation = cv2.INTER_AREA)
img=cv2.equalizeHist(resized)
cv2.imwrite(name,img)
print cont
cont+=1

Use the full path for the classifier.

Related

<class 'cv2.CascadeClassifier'> returned a result with an error set

so, I'm trying to code face detection but its not working. this is my code:
import cv2
import sys
cascPath = sys.argv[0]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I'm very new to coding so I don't know if I'm missing something obvious
Change your code as follows:
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
This worked for me.

Webcam window alwasy crash while trying to detect a face

I'm trying to make a simple haar cascade program to detect a face.
faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalcatface.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')
video_capture = cv2.VideoCapture(0)
img_counter = 0
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('FaceDetection', frame)
k = input()
# ESC Pressed
if k % 256 == 27:
break
video_capture.release()
cv2.destroyAllWindows()
But every time I launch it, my webcam window just froze and crash :(
My PC is powerful enough for sure, why could it happen?
I have made few changes to your code. For human face use haarcascade_frontalface_default.xml and for the cat face use haarcascade_frontalcatface.xml. Try the code below and it will work like a charm :)
import cv2
#faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalcatface.xml')
faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')
video_capture = cv2.VideoCapture(0)
img_counter = 0
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('FaceDetection', frame)
#k = input()
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# ESC Pressed
# if k % 256 == 27:
# break
video_capture.release()
cv2.destroyAllWindows()

Cropping live video input from a webcam for facial identification

I am working with OpenCV in Python for facial identification and I want to crop the live video from my webcam to just output the face it recognizes.
I have tried using ROI but I do not know how to correctly implement it.
import cv2
import sys
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
roi = frame[y:y+h, x:x+w]
cropped = frame[roi]
# Display the resulting frame
cv2.imshow('Face', cropped)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
.
Traceback (most recent call last):
File "C:/Users/Ben/Desktop/facerecog/facerecog2.py", line 31, in <module>
cv2.imshow('Face', cropped)
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\array.cpp:2492: error: (-206:Bad flag (parameter or structure field)) Unrecognized or unsupported array type in function 'cvGetMat'
You get cropped image with
cropped = frame[y:y+h, x:x+w]
and then you can display it.
But sometimes there is no face on frame and it will not create cropped and you can get error. Better create this variabel before for and check it after for
cropped = None
for (x, y, w, h) in faces:
cropped = frame[y:y+h, x:x+w]
if cropped is not None:
cv2.imshow('Face', cropped)
#else:
# cv2.imshow('Face', frame)
or
if faces:
(x, y, w, h) = faces[0]
cropped = frame[y:y+h, x:x+w]
cv2.imshow('Face', cropped)
I don't know what you want to do if there will be many faces on frame.

OpenCV - Function to paint text to the Canvas

I am detecting a face from the camera and draw a rectangle around it.
Code below:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 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) & 0xFF == ord('q'):
break
Are there any functions in OpenCV that can print text?
When it detects a face on the screen say "Hi"?
Thank you for your time.
Should have done this first before asking the question but after some Googling and trying out a few things, here is the solution:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(frame,'Hello There!',(x+w, h),font, 0.8,(255,0,0),2,cv2.LINE_AA)
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) & 0xFF == ord('q'):
break
This will add "Hello There!" to the top right corner of the detection frame rectangle.

OpenCV +Python take sample automatically

I want to take some sample of face image from webcam. I want to take about 8 samples. So when i press button "s", it will take 8 samples. So i try to make looping like this:
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if cv2.waitKey(1) & 0xFF == ord('s'):
ROI = frame[y:y+h,x:x+w]
nameUser = raw_input("Input yourname: ")
for i in range(0,8):
i_string = str(i)
cv2.imwrite(nameUser+i_string+'.jpg',ROI)
time.sleep(3)
But 8 image that i got all is exactly same. There is a way to make program take sample face but not exactly same?
i think, it's just a logic problem, try to re-organize it:
recording = 0 # use it as a flag/counter
while(True):
ok, frame= cap.read();
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY);
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if cv2.waitKey(1) & 0xFF == ord('s'):
recording = 8
nameUser = raw_input("Input yourname: ")
if recording >= 0 && len(faces)>0:
ROI = frame[y:y+h,x:x+w]
i_string = str(recording)
cv2.imwrite(nameUser+i_string+'.jpg',ROI)
recording -= 1
time.sleep(3)

Categories