Unable to detect face and eye with OpenCV in Python - python

This code is to detect face and eyes using webcam but getting this error
Traceback (most recent call last):
File "D:/Acads/7.1 Sem/BTP/FaceDetect-master/6.py", line 28, in <module>
eyes = eyeCascade.detectMultiScale(roi)
NameError: name 'roi' is not defined
but when i use this code do detect faces and eyes in a image its working properly without any error
import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
faces = faceCascade.detectMultiScale(frame)
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]
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

I think it is just a problem of indentation.
roi is out of scope when you go out of the faces loop.
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]
# eyes detection runs for each face
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)

Related

AttributeError: module 'cv2' has no attribute 'CascadeClassifier'

im using cv2 to try to take a picture here is my code
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
eye_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
for (x, y, w, h) in faces:
#print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
img_item = "my-image.png"
cv2.imwrite(img_item, roi_color)
stroke = 2
color = (0, 255, 0)
end_cord_x = x + w
end_cord_y = y + h
ecolor = (50, 50, 50)
cv2.rectangle(frame, (x,y), (end_cord_x, end_cord_y), color, stroke)
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex,ey), (ex+ew,ey+eh), ecolor, 1)
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
i get the error:
File "c:NothereForPrivacyReasons\imagerecognition\face\picture.py", line 3, in
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
AttributeError: module 'cv2' has no attribute 'CascadeClassifier'

why does the haarcascades does not work on opencv

I am trying to detect faces in opencv,but I'm running in some issues:
1-When I put the following syntax:gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY),it shows up in red and does not work.
2-The haarcascade also shows up in red:faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30),flags = cv2.CV_HAAR_SCALE_IMAGE).I tried to do like in some tutorials but it does not work.Would you have any idea?
Here is my code:
#importing packages
import cv2
import numpy as np
#variables
webcam = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
w_size = (700,500)
#turn the webcam on
while (True):
#reading camera and turing into frames
ret,frames = webcam.read()
frames = cv2.resize(frames,w_size)
#detection
gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30),flags = cv2.CV_HAAR_SCALE_IMAGE)
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('face_recognition',frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#running script
webcam.release()
cv2.destroyAllWindows()
i simply:
added cv2.data.haarcascades as prefix of the type CascadeClassifier
deleted cv2.CV_HAAR_SCALE_IMAGE (parameter not used anymore)
Code:
import cv2
import numpy as np
import cv2.data
#variables
webcam = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
w_size = (700,500)
#turn the webcam on
while (True):
#reading camera and turing into frames
ret,frames = webcam.read()
frames = cv2.resize(frames,w_size)
#detection
gray = cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale( gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('face_recognition',frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#running script
webcam.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 3.4.0.12 with Python3.5 AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'

I'm trying out facial recognition for the first time with python 3.5 and OpenCV 3.4.0.12 and I get this error when I run my code.
File "/Users/connorwoodford/anaconda3/envs/chatbot/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/connorwoodford/Desktop/temp.py", line 11, in <module>
ret, img = cap.imread()
AttributeError: 'cv2.VideoCapture' object has no attribute 'imread'
Code:
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('CascadeClassifier')
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.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]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) 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()
Your eye_cascade is referring to wrong cascade file, it should end with .xml extension. You can download it from here haarcascade_eye.xml.
Also note that your call to cv2.rectangle is not in correct format.
change it from
cv2.rectangle(img, (x+y), (x+w, y+h), (255,0,0), 2)
to
cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
All you need to make this work is to wrap the capture logic in a method. Full code goes as follows:
import numpy as np
import cv2
def sample_demo():
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.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,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,eh) 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()
and simply call method sample_demo()
sample_demo()

Haar- Cascade face detection OpenCv

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.

Categories