Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehrenfeu/cb9a9482da0a42dd6c7d4cfb99d995b8 to your computer and use it in GitHub Desktop.
Save ehrenfeu/cb9a9482da0a42dd6c7d4cfb99d995b8 to your computer and use it in GitHub Desktop.
Face detection
# Use local scikit-image
import sys
sys.path.insert(0, "/home/dan/University/projects/gsoc_face_detection/scikit-image/")
from skimage.feature import multiblock_local_binary_pattern
from skimage.transform import integral_image
import numpy as np
import skimage.io as io
import xml.etree.ElementTree as ET
EPS = 1e-5
tree = ET.parse('lbpcascade_frontalface.xml')
# Load all the features
features = tree.find('.//features')
# Load stages
stages = tree.find('.//stages')
stages_amount = int(tree.find('.//stageNum').text)
#img_big = io.imread('face_big_1.jpg', as_grey=True)
def detect_face(img):
integral_img = integral_image(img)
for stage_number in xrange(stages_amount):
current_stage = stages[stage_number]
stage_threshold = float(current_stage.find('stageThreshold').text)
weak_classifiers_amount = int(current_stage.find('maxWeakCount').text)
weak_classifiers = current_stage.find('weakClassifiers')
stage_points = 0
for weak_classifier_number in xrange(weak_classifiers_amount):
current_weak_classifier = weak_classifiers[weak_classifier_number]
# Weights that will be added to current image score.
# If image is probably to have face the positive weight is
# added. Otherwise, negative.
leaf_values = current_weak_classifier.find('leafValues').text
leaf_values = map(lambda x: float(x), leaf_values.split())
# Extract the elements only starting from second.
# First two are useless
internal_nodes = current_weak_classifier.find('internalNodes')
internal_nodes = internal_nodes.text.split()[2:]
# Extract the feature number and respective parameters.
# The MBLBP position and size.
feature_number = int(internal_nodes[0])
feature_params = features[feature_number][0].text.split()
feature_params = map(lambda x: int(x), feature_params)
# Compute the MB-LBP with extracted params
lbp_code = multiblock_local_binary_pattern(integral_img, *feature_params)
#skimage.feature.visualize_multiblock_lbp(img, *feature_params, **{'lbp_code': lbp_code})
# Extract look-up table
lut = map(lambda x: int(x), internal_nodes[1:])
lut = np.asarray(lut, dtype='uint32')
# Get the bit that shows whether or not
# current image contains a face.
bit = (lut[lbp_code >> 5] >> (lbp_code & 31)) & 1
# Add respective leaf value
stage_points += leaf_values[0] if bit else leaf_values[1]
if stage_points < (stage_threshold - EPS):
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment