def detect_face(im, face_cascade): img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) fd = FaceDetector(face_cascade) img = imutils.resize(img, width=500) faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100)) if len(faceRects) > 0: (x, y, w, h) = max(faceRects, key=lambda b: (b[2] * b[3])) face = img[y:y + h, x:x + w].copy(order="C") else: raise ValueError('No face deteted.') return face
def run(im, dataset_path, base64_path, models_path, face_cascade, repre_path, confidence_t=100): repres = read_repre(repre_path) img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) fd = FaceDetector(face_cascade) img = imutils.resize(img, width=500) faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100)) if len(faceRects) > 0: (x, y, w, h) = max(faceRects, key=lambda b: (b[2] * b[3])) face = img[y:y + h, x:x + w].copy(order="C") else: raise ValueError('No face deteted.') train_recognizer.run(dataset_path, base64_path, models_path, face_cascade) results = [] for (i, model_path) in enumerate(glob.glob(models_path + "/*.model")): fr = FaceRecognizer.load(model_path) fr.setConfidenceThreshold(confidence_t) name = model_path.split('/')[-1].replace('.model', '') confidence = fr.predict(face) results.append((name, confidence)) results = sorted(results, key=lambda res: res[1]) print results # visualize the results k = 5 plt.figure() plt.subplot(231) plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) plt.axis('off') plt.title('query') for (i, (name, score)) in enumerate(results[:k]): plt.subplot(2, 3, i + 2) plt.imshow(cv2.cvtColor(repres[name], cv2.COLOR_BGR2RGB)) plt.title("#%d %s: %.4f" % (i + 1, name, score)) plt.axis('off') plt.show()
def create_base64_files(dataset_path, base64_path, face_cascade): if not os.path.exists(base64_path): os.mkdir(base64_path) fd = FaceDetector(face_cascade) print("[INFO] Extracting faces from dataset...") files = paths.list_images(dataset_path) data_dict = {} for f in files: # name = f.split('/')[-2][:f.split('/')[-1].rfind('.')] # label = name[:name.rfind('_')] label = f.split('/')[-2] img = cv2.imread(f, 0) img = imutils.resize(img, width=500) # faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=9, minSize=(100, 100)) faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=9, minSize=(40, 40)) if len(faceRects) > 0: (x, y, w, h) = max(faceRects, key=lambda b: (b[2] * b[3])) face = img[y:y + h, x:x + w].copy(order="C") else: # cv2.imshow('No face detected', img) # cv2.waitKey(0) # raise ValueError('No face deteted.') continue if data_dict.has_key(label): data_dict[label].append(face) else: data_dict[label] = list((face, )) # for fname in files: for k, v in data_dict.items(): filename = k + '.txt' filepath = os.path.join(base64_path, filename) f = open(filepath, 'a+') total = 0 for face in v: f.write("{}\n".format(encodings.base64_encode_image(face))) total += 1 print("[INFO] wrote {} frames to file {}".format(total, filename)) f.close()
def create_base64_files(dataset_path, base64_path, face_cascade): if not os.path.exists(base64_path): os.mkdir(base64_path) fd = FaceDetector(face_cascade) print("[INFO] Extracting faces from dataset...") files = paths.list_images(dataset_path) data_dict = {} for f in files: # name = f.split('/')[-2][:f.split('/')[-1].rfind('.')] # label = name[:name.rfind('_')] label = f.split('/')[-2] img = cv2.imread(f, 0) img = imutils.resize(img, width=500) # faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=9, minSize=(100, 100)) faceRects = fd.detect(img, scaleFactor=1.1, minNeighbors=9, minSize=(40, 40)) if len(faceRects) > 0: (x, y, w, h) = max(faceRects, key=lambda b: (b[2] * b[3])) face = img[y:y + h, x:x + w].copy(order="C") else: # cv2.imshow('No face detected', img) # cv2.waitKey(0) # raise ValueError('No face deteted.') continue if data_dict.has_key(label): data_dict[label].append(face) else: data_dict[label] = list((face,)) # for fname in files: for k, v in data_dict.items(): filename = k + '.txt' filepath = os.path.join(base64_path, filename) f = open(filepath, 'a+') total = 0 for face in v: f.write("{}\n".format(encodings.base64_encode_image(face))) total += 1 print("[INFO] wrote {} frames to file {}".format(total, filename)) f.close()
def data2files(data_dir, face_cascade, res_file_path, label_dict_path): # initializing face detector fd = FaceDetector(face_cascade) dataset = [] files = paths.list_images(data_dir) file_dict = process_files(files) for key in file_dict.keys(): print 'Processing %s ...' % key, celeb_files = file_dict[key] n_files = len(celeb_files) ok = 0 for f in celeb_files: item = create_data_item(f, fd) if item is not None: dataset.append(item) ok += 1 print 'done, face found: %i/%i (%i%%)' % (ok, n_files, int(100 * ok / n_files)) print 'Saving data in pickle format...', # data_fname = os.path.join(res_dir, 'data.npz') data_file = gzip.open(res_file_path, 'wb', compresslevel=1) pickle.dump(dataset, data_file) # np.save(data_file, np.array(data_cubes_resh)) data_file.close() print 'done' print 'Saving label dictionary ...' label_dict = {} names = file_dict.keys() for i, n in enumerate(names): label_dict[n] = i labels_file = gzip.open(label_dict_path, 'wb', compresslevel=1) pickle.dump(label_dict, labels_file) labels_file.close() print 'done'
from pyimagesearch.face_recognition import FaceDetector from imutils import encodings import argparse import imutils import cv2 # construct the argument parse and parse command line arguments ap = argparse.ArgumentParser() ap.add_argument("-f", "--face-cascade", required=True, help="path to face detection cascade") ap.add_argument("-o", "--output", required=True, help="path to output file") ap.add_argument("-w", "--write-mode", type=str, default="a+", help="write method for the output file") args = vars(ap.parse_args()) # initialize the face detector, boolean indicating if we are in capturing mode or not, and # the bounding box color fd = FaceDetector(args["face_cascade"]) captureMode = False color = (0, 255, 0) # grab a reference to the webcam and open the output file for writing camera = cv2.VideoCapture(0) f = open(args["output"], args["write_mode"]) total = 0 # loop over the frames of the video while True: # grab the current frame (grabbed, frame) = camera.read() # if the frame could not be grabbed, then we have reached the end of the video if not grabbed:
help="path to face detection cascade") ap.add_argument("-c", "--classifier", required=True, help="path to the classifier") ap.add_argument( "-t", "--confidence", type=float, default=100.0, help="maximum confidence threshold for positive face identification") args = vars(ap.parse_args()) # initialize the face detector, load the face recognizer, and set the confidence # threshold fd = FaceDetector(args["face_cascade"]) fr = FaceRecognizer.load(args["classifier"]) fr.setConfidenceThreshold(args["confidence"]) # grab a reference to the webcam camera = cv2.VideoCapture(0) # loop over the frames of the video while True: # grab the current frame (grabbed, frame) = camera.read() # if the frame could not be grabbed, then we have reached the end of the video if not grabbed: break
import argparse import imutils import cv2 # construct the argument parse and parse command line arguments ap = argparse.ArgumentParser() ap.add_argument("-f", "--face-cascade", required=True, help="path to face detection cascade") ap.add_argument("-c", "--classifier", required=True, help="path to the classifier") ap.add_argument("-t", "--confidence", type=float, default=100.0, help="maximum confidence threshold for positive face identification") ap.add_argument("-v", "--video", help="path to the (optional) video file") args = vars(ap.parse_args()) # initialize the face detector, load the face recognizer, and set the confidence # threshold fd = FaceDetector(args["face_cascade"]) fr = FaceRecognizer.load(args["classifier"]) fr.setConfidenceThreshold(args["confidence"]) # if a video path was not supplied, grab the reference to the webcam if not args.get("video", False): camera = cv2.VideoCapture(0) # otherwise, grab a reference to the video file else: camera = cv2.VideoCapture(args["video"]) # keep looping while True: # grab the current frame (grabbed, frame) = camera.read()