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()
Related
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.")
I know how to identify a face and the eyes, with opencv and haarcascade. But how can I crop or get only the eyes from webcam capture? Just one, or even the both, so I can use as a new frame in imshow...
See on this post:
How to crop an image in OpenCV using Python
import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
Your "img[y:y+h, x:x+w]" is just the output from your haarcascade. Maybe you recieve multiple output so you have to choose one.
After detect face you can do this.
eyes = eye_cascade.detectMultiScale(roi_gray)
for ex, ey, ew, eh in eyes:
roi = roi_color[ey:ey + ew, ex:ex + eh]
Then can show roi using cv2.imshow().
The haarcascade_eye.xml and haarcascade_frontalface_default.xml link file
import cv2
eye_cascade = cv2.CascadeClassifier("haarcascade_eye.xml")
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
#load image saved in the same directory
img = cv2.imread("your_image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for f in faces:
x, y, w, h = [ v for v in f ]
cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
alt_gray = gray[y:y+h, x:x+w]
alt_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(alt_gray)
eye_crop = []
for f in eyes:
x, y, w, h = [ v for v in f ]
cv2.rectangle(alt_color, (x,y), (x+w, y+h), (255,0,0), 2)
# Define the region of interest in the image
eye_crop.append(alt_gray[y:y+h, x:x+w])
for eye in eye_crop:
cv2.imshow('eye',eye)
cv2.waitKey(0)
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)
I am trying to save the face and eye detected using opencv in a separate png/jpg file, what can I use to do it.(I would want the rectangle as well). The code is as below: (I do not have GUI enabled)
import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('/Users/i855838/opencv/data/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/Users/i855838/opencv/data/haarcascades/haarcascade_eye.xml')
img = cv2.imread('/Users/i855838/Desktop/xfiles4.jpg')
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)
cv2.waitKey(0)
cv2.destroyAllWindows()
Simply use cv2.imwrite. For example, to save to a file called 'face_color.png' you would do cv2.imwrite('face_color.png', roi_color).
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)