Permalink
Browse files

Files added.

  • Loading branch information...
1 parent 5d67759 commit 3fc3d47e2c7430a66a1f4e8d3dfe04fe9140599b @bytefish committed Feb 8, 2012
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@@ -0,0 +1,92 @@
+# Copyright (c) 2012. Philipp Wagner <bytefish[at]gmx[dot]de>.
+# Released to public domain under terms of the BSD Simplified license.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# * Neither the name of the organization nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# See <http://www.opensource.org/licenses/bsd-license>
+import cv2
+# cv2 helper
+from helper.common import *
+from helper.video import *
+# add facerec to system path
+import sys, os
+sys.path.append("../..")
+# facerec imports
+from facerec.dataset import DataSet
+from facedet.detector import CascadedDetector
+from facerec.preprocessing import TanTriggsPreprocessing
+from facerec.feature import LBP
+from facerec.classifier import NearestNeighbor
+from facerec.operators import ChainOperator
+from facerec.model import PredictableModel
+
+help_message = '''USAGE: createsamples.py [<video source>] [<dst dir>] [<subject name>]
+
+Keys:
+ s - save current face(s)
+ ESC, q - exit
+'''
+
+class App(object):
+ def __init__(self, video_src, dst_dir, subject_name, face_sz=(130,130), cascade_fn="/home/philipp/projects/opencv2/OpenCV-2.3.1/data/haarcascades/haarcascade_frontalface_alt2.xml"):
+ self.dst_dir = dst_dir
+ self.subject_name = subject_name
+ self.face_sz = face_sz
+ self.cam = create_capture(video_src)
+ self.detector = CascadedDetector(cascade_fn=cascade_fn, minNeighbors=5, scaleFactor=1.1)
+ self.stored = 0
+
+
+ def saveImage(self, src):
+ out_fn = "%s_%d.png" % (self.subject_name, self.stored)
+ out_fn = os.path.join(self.dst_dir,out_fn)
+ cv2.imwrite(out_fn, src)
+ self.stored = self.stored + 1
+
+ def run(self):
+ while True:
+ ret, frame = self.cam.read()
+ # resize the frame to half the original size
+ img = cv2.resize(frame, (frame.shape[1]/2, frame.shape[0]/2), interpolation = cv2.INTER_CUBIC)
+ imgout = img.copy()
+ faces = []
+ for i,r in enumerate(self.detector.detect(img)):
+ x0,y0,x1,y1 = r
+ # get face, convert to grayscale & resize to face_sz
+ face = img[y0:y1, x0:x1].copy()
+ face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)
+ face = cv2.resize(face, self.face_sz, interpolation = cv2.INTER_CUBIC)
+ # draw a rectangle to show the detection
+ cv2.rectangle(imgout, (x0,y0),(x1,y1),(0,255,0),1)
+ # and append to currently detected faces
+ faces.append(face)
+ cv2.imshow("detections", imgout)
+ # wait for a key press
+ ch = cv2.waitKey(10)
+ # store the currently detected faces
+ if (ch == ord('s')) and (len(faces) > 0):
+ for face in faces:
+ self.saveImage(face)
+ if ch == 27 or ch == ord('q'):
+ break
+
+if __name__ == '__main__':
+ import sys
+ print help_message
+ if len(sys.argv) < 4:
+ sys.exit()
+ # get params
+ video_src = sys.argv[1]
+ dataset_fn = sys.argv[2]
+ subject_name = sys.argv[3]
+ # start facerec app
+ App(video_src, dataset_fn, subject_name).run()
No changes.
@@ -1,54 +0,0 @@
-import sys
-# append facerec to module search path
-sys.path.append("..")
-import cv2
-from facedet.detector import SkinFaceDetector
-import numpy as np
-import os
-
-
-def extract_faces(src_dir, dst_dir, detector, face_sz = (130,130)):
- """
- Extracts the faces from all images in a given src_dir and writes the extracted faces
- to dst_dir. Needs a facedet.Detector object to perform the actual detection.
-
- Args:
- src_dir [string]
- dst_dir [string]
- detector [facedet.Detector]
- face_sz [tuple]
- """
- if not os.path.exists(dst_dir):
- try:
- os.mkdir(dst_dir)
- except:
- raise OSError("Can't create destination directory (%s)!" % (dst_dir))
- for dirname, dirnames, filenames in os.walk(src_dir):
- for subdir in dirnames:
- src_subdir = os.path.join(dirname, subdir)
- dst_subdir = os.path.join(dst_dir,subdir)
- if not os.path.exists(dst_subdir):
- try:
- os.mkdir(dst_subdir)
- except:
- raise OSError("Can't create destination directory (%s)!" % (dst_dir))
- for filename in os.listdir(src_subdir):
- name, ext = os.path.splitext(filename)
- src_fn = os.path.join(src_subdir,filename)
- img = cv2.imread(src_fn)
- rects = detector.detect(img)
- for i,rect in enumerate(rects):
- x0,y0,x1,y1 = rect
- face = img[y0:y1,x0:x1]
- face = cv2.resize(face, face_sz, interpolation = cv2.INTER_CUBIC)
- print os.path.join(dst_subdir, "%s_%s_%d%s" % (subdir, name,i,ext))
- cv2.imwrite(os.path.join(dst_subdir, "%s_%s_%d%s" % (subdir, name,i,ext)), face)
-
-if __name__ == "__main__":
- if len(sys.argv) < 3:
- print "usage: python extract_faces.py <src_dir> <dst_dir>"
- sys.exit()
- src_dir = sys.argv[1]
- dst_dir = sys.argv[2]
- detector = SkinFaceDetector(threshold=0.3, cascade_fn="/home/philipp/projects/opencv2/OpenCV-2.3.1/data/haarcascades/haarcascade_frontalface_alt2.xml")
- extract_faces(src_dir=src_dir, dst_dir=dst_dir, detector=detector)
@@ -1,46 +0,0 @@
-from facerec.dataset import DataSet
-from facerec.feature import *
-from facerec.distance import *
-from facerec.classifier import NearestNeighbor, SVM
-from facerec.model import PredictableModel
-from facerec.validation import KFoldCrossValidation
-from facerec.visual import plot_eigenvectors
-from facerec.preprocessing import *
-from facerec.operators import ChainOperator
-from facerec.svm import grid_search
-from facerec.lbp import *
-
-import numpy as np
-import logging,sys
-# set up a handler for logging
-handler = logging.StreamHandler(sys.stdout)
-formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
-handler.setFormatter(formatter)
-# add handler to facerec modules
-logger = logging.getLogger("facerec")
-logger.addHandler(handler)
-logger.setLevel(logging.DEBUG)
-# load a dataset
-dataSet = DataSet("/home/philipp/facerec/data/c2", sz=(100,100))
-# define Fisherfaces as feature extraction method
-feature = Identity()
-#from svmutil import *
-# define a SVM with RBF Kernel as classifier
-#param = svm_parameter("-q")
-#param.kernel_type = RBF
-#classifier = SVM(param=param)
-# define a 1-NN classifier with Euclidean Distance
-classifier = NearestNeighbor(dist_metric=EuclideanDistance(), k=5)
-# define the model as the combination
-model = PredictableModel(feature=feature, classifier=classifier)
-
-#best_parameter, results = grid_search(model, dataSet.data, dataSet.labels, k=5)
-#print results
-# show fisherfaces
-#model.compute(dataSet.data, dataSet.labels)
-#plot_eigenvectors(model.feature.eigenvectors, 1, sz=dataSet.data[0].shape, filename="/home/philipp/01.png")
-#plot_eigenvectors(model.feature.model2.eigenvectors, 1, sz=(dataSet.data[0].shape[0]-2,dataSet.data[0].shape[1]-2), filename="/home/philipp/01.png")
-# perform a 5-fold cross validation
-cv = KFoldCrossValidation(model, k=10)
-cv.validate(dataSet.data, dataSet.labels)
-print cv

0 comments on commit 3fc3d47

Please sign in to comment.