Created
February 8, 2014 12:58
-
-
Save erogol/8883355 to your computer and use it in GitHub Desktop.
detect faces and show them on separate windows. You give the image path as an argument to that python script and see the magic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
import cv2 | |
import cv2.cv as cv | |
import sys | |
import pdb | |
def detect(img, cascade): | |
rects = cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=3, minSize=(10, 10), flags = cv.CV_HAAR_SCALE_IMAGE) | |
if len(rects) == 0: | |
return [] | |
rects[:,2:] += rects[:,:2] | |
return rects | |
def draw_rects(img, rects, color): | |
for x1, y1, x2, y2 in rects: | |
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2) | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: ## Check for error in usage syntax | |
print "Usage : python faces.py <image_file>" | |
else: | |
img = cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR) ## Read image file | |
img_x = img.shape[0] | |
img_y = img.shape[1] | |
print img_x | |
print img_y | |
img_ratio = img_x / img_y | |
if img_x > 512 : | |
#newx,newy = img.shape[1]/4,img.shape[0]/4 #new size (w,h) | |
new_x = 512 | |
new_y = new_x * img_ratio | |
img = cv2.resize(img,(new_x, int(new_y))) | |
print "Image resized :" | |
print new_x | |
print new_y | |
if (img == None): ## Check for invalid input | |
print "Could not open or find the image" | |
else: | |
cascade = cv2.CascadeClassifier("/home/erogol/Desktop/rsom_face/haarcascade_frontalface_alt.xml") | |
gray = cv2.cvtColor(img, cv.CV_BGR2GRAY) | |
gray = cv2.equalizeHist(gray) | |
# cv2.namedWindow('Display image') ## create window for display | |
# cv2.imshow('Display image', gray) ## Show image in the window | |
# cv2.waitKey(0) ## Wait for keystroke | |
# cv2.destroyAllWindows() | |
#pdb.set_trace() | |
rects = detect(gray, cascade) | |
## Extract face coordinates | |
if len(rects) == 0: | |
print "No face detected!!" | |
else: | |
for i,rect in enumerate(rects): | |
x1 = rect[1] | |
y1 = rect[0] | |
x2 = rect[3] | |
y2 = rect[2] | |
## Extract face ROI | |
faceROI = gray[x1:x2, y1:y2] | |
## Show face ROI | |
cv2.namedWindow(str(i)) ## create window for display | |
cv2.imshow(str(i), faceROI) | |
vis = img.copy() | |
draw_rects(vis, rects, (0, 255, 0)) | |
cv2.namedWindow('Display image') ## create window for display | |
cv2.imshow('Display image', vis) ## Show image in the window | |
print "size of image: ", img.shape ## print size of image | |
cv2.waitKey(0) ## Wait for keystroke | |
cv2.destroyAllWindows() ## Destroy all windows |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment