Extract eyes from haarcascade - python

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)

Related

Trying to blur just the face (python)

I am trying to blur just the face by using the following script, but end up blurring the entire image. Any suggestions on how to change the script such that it blurs only the faces?
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('beatles.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detecting faces
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]
# To show the detected faces
cv2.imshow('img',img)
cv2.waitKey(5000)
cv2.destroyAllWindows()
k = np.array(([1/9, 1/9, 1/9], [1/9, 1/9, 1/9], [1/9, 1/9, 1/9]), np.float32)
# Blurring of just the faces in a picture
skaldetlykkes = cv2.filter2D(img, -1, k)
cv2.imshow("Ladetskje", skaldetlykkes)
cv2.waitKey (5000)
cv2.destroyAllWindows()
The following code sample will apply your box filter only on the faces:
import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('test.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Blur the faces, i.e. only the ROIs defined by faces
k = np.array(([1/9, 1/9, 1/9], [1/9, 1/9, 1/9], [1/9, 1/9, 1/9]), np.float32)
for (x, y, w, h) in faces:
img[y:y+h,x:x+w] = cv2.filter2D(img[y:y+h,x:x+w], -1, k)
# Display the output
cv2.imshow('img', img)
cv2.waitKey()
this code sample
import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('test.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# Display the output
cv2.imshow('img', img)
cv2.waitKey()
from Face Detection should compute the rectangle area you want to blur.
Then you just need to apply an average function on the area :) (Blur = window average)

Python OpenCV face detection

How can I check for the location of an eye for example.
Its in this function?
eyes = eye_cascade.detectMultiScale(gray, 1.4, 7)
How to read the input of this?
i would like to calculate in a face detection program if on the picture for example a nose or an eye is the place as should be, in a human.
OpenCV-Python Tutorials’s documentation has a good example for face detection.
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('sachin.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]
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()

Save the face detected in a png/jpg file

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).

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()

Attribute error while using opencv for face recognition

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)

Categories

Resources