Attribute error while using opencv for face recognition - python

I am teaching myself how to use openCV by writing a simple face recognition program I found on youtube. I have installed opencv version 2 as well as numpy 1.8.0. I am using python 2.7.
I copyed this code exactly how it was done in the video and article links below, yet I keep getting errors.
AttributeError: 'module' object has no attribute 'cv'
What am I doing wrong?
Here is the code I'm using.
import cv2
import sys
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = (faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE)
)
print "Found {0} faces!".format(len(faces))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
https://www.youtube.com/watch?v=IiMIKKOfjqE
https://realpython.com/blog/python/face-recognition-with-python/

The latest openCV no longer allows importing the legacy cv module. Furthermore the naming convention of the constants generally does away with the leading "CV_..." and several/many of the names have been altered somewhat. I think you are running into both problems.
Specifically, the error you are reporting is in regards to this expression in your code: cv2.cv.CV_HAAR_SCALE_IMAGE. This expression is trying to find the named constant CV_HAAR_SCALE_IMAGE within the cv submodule of the cv2 package you imported. But alas, there is no cv2.cv anymore.
In openCV 3, I believe this constant is now referenced as follows: cv2.CASCADE_SCALE_IMAGE
Also, you may find this link useful. It is to the facedetect.py sample script found in the OpenCV source code. You can see the usage of the new constant name in this example, and you may also inspect it for other changes from older sources/tutorials.

This code is working fine for me i'm using the opencv3 lib, please try it
import cv2
import sys
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
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(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)

Here is the updated code which works into jupyter notebook with OpenCV3:
[]
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
[]
# Get user supplied values
imagePath = "abba.png"
cascPath = "haarcascade_frontalface_default.xml"
[]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
[]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
[]
# Read the image
image = cv2.imread(imagePath)
[]
plt.imshow(image)
plt.show()
[]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
[]
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE #flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
[]
print("Found {0} faces!".format(len(faces)))
[]
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
[]
plt.imshow(image)
plt.show()

Appears that the haarcascades aren't downloaded.
https://github.com/opencv/opencv/tree/master/data/haarcascades
Download the haarcascades available in the above link, should work for Open CV 4.2.0
Please read the Licence Agreement mentioned in the xml

This code works well for me :
import cv2
imagePath = (
"path to image")
cascPath = ("..\haarcascade_frontalface_default.xml")
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
# flags = cv2.CV_HAAR_SCALE_IMAGE
)
# print "Found {0} faces!".format(len(faces))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)

Related

My OpenCV Face Recognition isn't drawing a bounding box / recognizing a face

I am making an OpenCV Face Recognizer that draws a bounding box around the faces it detects from an image it has read. I am using a cascade classifier (haarcascades)
It shows the picture, not in grayscale (full color) and will not draw the bounding boxes. Not sure what I did, I am new to this.
Here is the code:
import cv2
# Load image
image = cv2.imread("/home/tyler/Downloads/PythonProjects/VN5anAL3_400x400.jpg")
# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Define the cascade classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw bounding boxes
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Show the image
cv2.imshow("faces", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
You are almost there, but you are drawing the bounding boxes on the grayscale image instead of the original image. Instead of using the gray variable, use the image variable in the following line to draw the bounding boxes:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
Also, you may want to check if the cascade classifier is loaded correctly by adding the following line before the detection:
if face_cascade.empty():
raise Exception("Failed to load cascade classifier.")

Trying to blur the background of the image and bring a rectangular box on the face using python

I am trying to bring a rectangular box on the face of the image first then I am trying to blur the background of the image in (frame variable) and extract face in (face variable)
On executing the code I get Error: frame not defined.
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('C:/Users/HP/l.jpg')
#image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image1 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Load the cascade
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
plt.imshow(image1)
faces = detector.detectMultiScale(
image,
scaleFactor=1.2,
minNeighbors=10,
minSize=(10, 50),
)
for (x, y, w, h) in faces:
cv2.rectangle(image1, (x, y), (x+w, y+h), (1, 255, 4), 10)
face=image1[y:y+h,x:x+w]
frame=cv2.blur(image1,ksize = (10,10))
frame[y:y+h,x:x+w]=face
plt.imshow(frame)
plt.show()
plt.imshow(face)
plt.show()
it's working fine only check is image is actually at the provided path because it may be image error try this create a folder in the file where you are running the image as images then replace cv2.imread('\images\imagename.jpg') instead of this cv2.imread('C:/Users/HP/l.jpg') image
import cv2
import matplotlib.pyplot as plt
#image = cv2.imread('C:/Users/HP/l.jpg')
image = cv2.imread('images/1,jpg')
#image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image1 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

Python "OpenCV Error: Assertion failed (size.width>0 && size.height>0)" when using script to load and detect faces from a given directory path

I'm trying to load a set of images from a given directory, detect and count how many faces are detected there.
My code looks like this:
import cv2
import numpy as np
import os
def read_images():
path1 = '/home/sousajf1/Documents/opencv/facedetect/data'
path2 = '/home/sousajf1/Documents/opencv/facedetect/dataprocessed'
countFace=0
listing = os.listdir(path1)
for file in listing:
img = cv2.imread('path1 + file',0)
faceCascade = cv2.CascadeClassifier('haarcascade_profileface.xml')
eyeCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
faces = faceCascade.detectMultiScale(img, 1.3, 5)
cv2.imshow('img',img)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
roiGray=gray[y:y+h, x:x+w]
roiColor=img[y:y+h, x:x+w]
if len(faces)!=0:
countFace+=1
#cv2.imwrite(path2 + file, "JPEG")
print countFace
cv2.waitKey(0)
read_images()
But when I run this I get always 0 faces detected. I thought maybe there were no images being loaded at all, so I added the cv2.imshow line before the first for and I got the following error:
OpenCV Error: Assertion failed (size.width>0 && size.height>0
which is probably because there no image at all to show.
The code seems right to me, and I have no idea what to do now.
Would appreciate some help and a fresh mind. Thanks guys.
UPDATE
I've now tried using the glob function, but it still did not work:
import cv2
import glob
countFace = 0
countEyes = 0
for img in glob.glob("/home/sousajf1/Documents/opencv/*.pgm"):
cvImg = cv2.imread(img,0)
faceCascade = cv2.CascadeClassifier('haarcascade_profileface.xml')
eyeCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(cvImg, 1.3, 5)
#cv2.imshow('img',cvImg)
for (x,y,w,h) in faces:
cv2.rectangle(cvImg, (x,y), (x+w, y+h), (255,0,0), 2)
roiGray=gray[y:y+h, x:x+w]
roiColor=cvImg[y:y+h, x:x+w]
eyes=eyeCascade.detectMultiScale(roiGray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roiColor, (ex,ey), (ex+ew, ey+eh), (0,255,0), 1)
if len(eyes)>0:
countEyes = countEyes +1
if len(faces)>0:
countFace = countFace +1
print countFace
print countEyes
You are trying to read a filename as a string
img = cv2.imread('path1 + file',0)
is not right it will be searching for a file called path1 + file.
Try this:
img = cv2.imread('{0}{1}'.format(path1, file),0)
Solution:
imshow fails when you pass an empty image. In your case, this is most likely due to the fact that you ignore empty frames from cap.read() and call imshow even if cap.read returned an empty image.
To fix this, replace your while True loop with a while cap.isOpened() or check whether cap.isOpened() has been successful before reading frames.

Python - Unable to detect face and eye?

I am trying to create a face and eye detection using OpenCV library. This is the code I been working with. It's running smoothly with no errors but the only problem is not showing any results no faces and eyes are found with this code
import cv2
import sys
import numpy as np
import os
# Get user supplied values
imagePath = sys.argv[1]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascad_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('C:\Users\Karthik\Downloads\Programs\opencv\sources\data\haarcascades\haarcascade_eye.xml')
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
print "Found {0} faces!".format(len(faces))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
eyes = eyeCascade.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("Faces found", image)
print image.shape
cv2.waitKey(0)
For me it works in my jupyter notebook on Ubuntu 15.10 using OpenCV 3.1.0-dev with python 3.4
Could it be, that you have a simple typo?
haarcascad_frontalface_default.xml => haarcascade_frontalface_default.xml
and here:
eyes = eyeCascade.detectMultiscale(roi_gray)
=> eyeCascade.detectMultiScale(roi_gray)
That's my working code:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')
# Read the image
image = cv2.imread('lena.png', 0)
if image is None:
raise ValueError('Image not found')
# Detect faces in the image
faces = faceCascade.detectMultiScale(image)
print('Found {} faces!'.format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), 255, 2)
roi = image[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)
plt.figure()
plt.imshow(image, cmap='gray')
plt.show()

opencv find centre of face in facedetction

I need to find the centre of a rectangle that gets put around a face when it's detected in OpenCV. I am using Python in Visual Studio.
Here is the code I am running:
#!/usr/bin/env python
from cv2 import *
import sys
cascPath = sys.argv[1]
faceCascade = CascadeClassifier(cascPath)
video_capture = VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cvtColor(frame, COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
font = FONT_HERSHEY_SIMPLEX
# Draw text on the frame
putText(frame, 'Hayden' ,(10,100), font, 2,(255,255,255),2,LINE_AA)
# Display the resulting frame
imshow('Video', frame)
if waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
destroyAllWindows()
All I want to do is find the centre of the rectangle, any help will be greatly appreciated!
I'm really sorry but I don't know python. The code for this in C++ is:
Point center = Point(rectangle.x + rectangle.width)/2, (rectangle.y + rectangle.height)/2);
I'd be surprised if this didn't translate almost exactly to python

Categories

Resources