Last active
December 16, 2015 04:48
-
-
Save why-not/5379296 to your computer and use it in GitHub Desktop.
Given a folder full of jpegs, this gist prints out if you have a face in it which is frontal (not profile), and its ratio between face size and image size. If it finds more than one face, it treats it as if no faces were found. (Use case: profile pictures)
This file contains 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
import sys, os | |
from cv import * | |
from cv2 import * | |
import glob | |
def detect_face(image): | |
"""Converts an image to grayscale and prints the ratio of face to image if _one_ face is found""" | |
grayscale = CreateImage((image.width, image.height), 8, 1) | |
CvtColor(image, grayscale, CV_BGR2GRAY) | |
storage = CreateMemStorage(0) | |
EqualizeHist(grayscale, grayscale) | |
cascade = Load('/usr/local/Cellar/opencv/2.4.0/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml') | |
faces = HaarDetectObjects(grayscale, cascade, storage, 1.2, 2, | |
CV_HAAR_DO_CANNY_PRUNING, (50, 50)) | |
if len(faces) == 1: | |
for f in faces: | |
print (f[0][2]*f[0][3], | |
image.width*image.height, | |
(f[0][2]*f[0][3])*100/(image.width*image.height)) | |
else: | |
print 0, image.width*image.height, 0 | |
def main(): | |
print 'user_id', 'face_area', 'image_area', 'ratio' | |
file_list = glob.glob('/path/to/folder/*jpg') | |
for f in file_list: | |
image = LoadImage(f) | |
print os.path.basename(f)[:-4], | |
detect_face(image) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment