def main(): # Loading the cascade xml file parser = argparse.ArgumentParser() parser.add_argument("-f", "--face", required=True, help="path to where the face cascade resides") parser.add_argument("-v", "--video", action='store_true', help="detection from WebCam") parser.add_argument("-i", "--image", help="path to where the image resides") args = vars(parser.parse_args()) img = cv2.imread(args["image"], 1) if (args["video"]): # cap points to the WebCam cap = cv2.VideoCapture(0) while True: # Getting images from WebCam ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # using FaceDetector class to detecte the face faceDetector = FaceDetector(args['face']) faces = faceDetector.detect(gray) # draw a box around faces for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # draw image cv2.imshow('img', img) if cv2.waitKey(1) == ord('q'): cv2.destroyAllWindows() break cap.release() elif img != None: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # using FaceDetector class to detecte the face faceDetector = FaceDetector(args['face']) faces = faceDetector.detect(gray) # draw a box around faces for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # draw image cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() else: print("Please enter the correct arguments")
def dealAsian(): detector = FaceDetector() data_path = "./datasets/asianFacesCategory" data_out_path = "./datasets/asianFaces" identities = os.listdir(data_path) new_filenames = [] widths = [] heights = [] for person in identities: dirpath = data_path + "/" + person if person != ".DS_Store" and person != "._.DS_Store": files = os.listdir(dirpath) for file in files: print("=============================") image = cv2.imread(dirpath + "/" + file) if image is not None: print("Load Dir={} and Image={}".format(person, file)) res = detector.detection(image) if res is not None: crop_image, w, h = res cv2.imwrite(data_out_path + "/" + person + "_" + file, crop_image) new_filenames.append(person + "_" + file) widths.append(w) heights.append(h) else: print("No Faces") else: print("Read Image Wrong....") save_height_width(new_filenames, widths, heights)
def load_models(): print('Carregando modelos...') mask_detector = MaskDetector() mask_detector.load_state_dict(torch.load('models/face_mask.ckpt')['state_dict'], strict=False) mask_detector = mask_detector.to(device) mask_detector.eval() face_detector = FaceDetector( prototype='models/deploy.prototxt.txt', model='models/res10_300x300_ssd_iter_140000.caffemodel', ) return face_detector, mask_detector
def main(): # Instantiate Classes detector = FaceDetector(FACE_CLASSIFIER_PATH, EYE_CLASSIFIER_PATH) model = FaceModel() display = Display() capture = Capture() oldTime = time.time() i = 0 frames_num = 0 delta_sum = 0 while True: # escape key for exit, in linux display is not working without that k = cv2.waitKey(30) & 0xff if k == 27: return # Calculate time difference (dt), update oldTime variable newTime = time.time() dt = newTime - oldTime oldTime = newTime frames_num += 1 delta_sum += dt if frames_num % 100 == 0: print "delta:", delta_sum / float( frames_num), "frames pr sec:", 1 / float( delta_sum / float(frames_num)) frames_num = 0 delta_sum = 0 # Grab Frames frames = capture.read() # Detect face 20% of the time, eyes 100% of the time if i % 5 is 0: rects = detector.detect(frames) else: rects = detector.detect(frames, model.getPreviousFaceRects()) i += 1 # Add detected rectangles to model model.add(rects) display.renderScene(frames['display'], model, rects) display.renderEyes(frames['color'], model)
def main(): img_url = ('http://2.bp.blogspot.com/-Ooj8qMem5vo/VRKMGtvmWJI' '/AAAAAAAABjg/DH001_agnPY/s1600/face.jpg') img_np = asarray(bytearray(urlopen(img_url).read()), dtype=uint8) image = imdecode(img_np, IMREAD_COLOR) detr = FaceDetector() fpos = detr.get_faces_pos(image, minNeighbors=15) RGB_GREEN = (0, 255, 0) roi = image.copy() for (x, y, w, h) in fpos: roi = rectangle(roi, (x, y), (x + w, y + h), color=RGB_GREEN, thickness=2) imshow('Face Detection', roi) waitKey(0)
def predict(images, attribute): #predict image wrt given attribute #images: a list of numpy array #attribute: name of the attribute #return: a list of prediction value model_file = [ "./model/pca_" + attribute + ".pkl", "./model/pred_" + attribute + ".pkl" ] pred_list = [] for image in images: facedetect = FaceDetector() cropped_image = facedetect.detection(image) with open(model_file[0], 'rb') as f: pcaObj = pickle.load(f) with open(model_file[1], 'rb') as f: predictObj = pickle.load(f) image_data = pcaObj.transform(cropped_image) pred_list.append(predictObj.predict(image_data)) return pred_list
def get_face_detector(self): if not self.config.has_section('FaceDetector'): raise ValueError('No FaceDetector configuration!') else: cascade_classifier_path = self.config.get( 'FaceDetector', 'cascadeClassifier', fallback='./resources/haarcascade_frontalface_default.xml') scaleFactor = self.config.getfloat('FaceDetector', 'scaleFactor', fallback=1.3) minNeighbors = self.config.getint('FaceDetector', 'minNeighbors', fallback=4) minSize_x = self.config.getint('FaceDetector', 'minSize_x', fallback=40) minSize_y = self.config.getint('FaceDetector', 'minSize_y', fallback=40) return FaceDetector(cascade_classifier_path, scaleFactor, minNeighbors, (minSize_x, minSize_y))
from facedetector import FaceDetector import imutils import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument('-f', '--face', required=True, help='Path to where the face cascade resides') ap.add_argument('-v', '--video', help='Path to Video') args = vars(ap.parse_args()) fd = FaceDetector(args['face']) if not args.get('video', False): camera = cv2.VideoCapture(0) else: camera = cv2.VideoCapture(args['video']) while True: (grabbed, frame) = camera.read() if args.get('video') and not grabbed: break frame = imutils.resize(frame, width=400) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceRects = fd.detect(gray, scaleFactor=1.1, minNeighbors=5,
def __init__(self): self.video = cv2.VideoCapture(0) self.model = load_model('../face_mask.model') self.face_detector = FaceDetector( './haarcascade_frontalface_default.xml')
__author__ = 'XJH' from facedetector import FaceDetector import imutils import cv2 fd = FaceDetector( "H:/Machine Learning/computer vision/[10307938]Books/Books/Case Studies, 3nd Edition/code/face_detection/cascades/haarcascade_frontalface_default.xml" ) camera = cv2.VideoCapture("adrian_face.mov") while True: (grabbed, frame) = camera.read() if not grabbed: break frame = imutils.resize(frame, width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceRects = fd.detect(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) frameClone = frame.copy() for (fX, fY, fW, fH) in faceRects: cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH), (0, 0, 255), 2) cv2.imshow("Face", frameClone) if cv2.waitKey(1) & 0xFF == ord("q"): break camera.release()
import cv2 from facedetector import FaceDetector import imutils # setup the argument parse for command line inputs parser = argparse.ArgumentParser() parser.add_argument("-f", "--face", required=True, help="path to face cascade classifier ") parser.add_argument("-v", "--video", help="path to video (optional)") arguments = vars(parser.parse_args()) detector = FaceDetector(arguments["face"]) # detect if a video file is passed in, otherwise use the camera if not arguments.get("video", False): camera = cv2.VideoCapture(0) else: camera = cv2.VideoCapture(arguments["video"]) # continue processing until the passed in video file is done, or the user # stops the application by pressing the 'q' key while True: (grabbed, frame) = camera.read() # read() returns a boolean value of success and the frame # if nothing is returned don't keep going if arguments.get("video") and not grabbed:
for person in identities: dirpath = data_path + "/" + person if person != ".DS_Store" and person != "._.DS_Store": files = os.listdir(dirpath) for file in files: print("=============================") image = cv2.imread(dirpath + "/" + file) if image is not None: print("Load Dir={} and Image={}".format(person, file)) res = detector.detection(image) if res is not None: crop_image, w, h = res cv2.imwrite(data_out_path + "/" + person + "_" + file, crop_image) new_filenames.append(person + "_" + file) widths.append(w) heights.append(h) else: print("No Faces") else: print("Read Image Wrong....") save_height_width(new_filenames, widths, heights) if __name__ == "__main__": detector = FaceDetector() #image = cv2.imread("./test3.jpeg") dealAsian() print("Finish")
import argparse import cv2 from facedetector import FaceDetector from imutils import resize argparser = argparse.ArgumentParser() argparser.add_argument('-f', '--face', required=True, help='Path to where the face cascade resides.') argparser.add_argument('-v', '--video', required=False, help='Path to the (optional) video file.') arguments = vars(argparser.parse_args()) face_detector = FaceDetector(arguments['face']) if not arguments.get('video', False): camera = cv2.VideoCapture(0) else: camera = cv2.VideoCapture(arguments['video']) while True: (grabbed, frame) = camera.read() if arguments.get('video') and not grabbed: break frame = resize(frame, width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_rectangles = face_detector.detect(gray, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)) frame_clone = frame.copy() green = (0, 255, 0)
# predictImage = gray[y:y+h, x:x+w] # nbrPredicted = recognizer.predict(predictImage) # print("Result is {}".format(nbrPredicted)) # # cv2.imshow("Face", frame) # # waitResult = cv2.waitKey(1) # if waitResult & 0xFF == ord("q"): # break # # camera.release() # cv2.destroyAllWindows() frame = cv2.imread('src.jpg') gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) fd = FaceDetector('haarcascade_frontalface_default.xml') faceRects = fd.detect(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) for (x, y, w, h) in faceRects: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) predictImage = gray[y:y + h, x:x + w] nbrPredicted = recognizer.predict(predictImage) print("Result is {}".format(nbrPredicted)) cv2.imshow("Face", frame) cv2.waitKey(0) # break # camera.release()
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import path from os.path import abspath from os.path import join from os import pardir from cv2 import flip from cv2 import rectangle from cv2 import imshow path.append(abspath(join(__file__, pardir, pardir, 'src'))) from vcapture import vcap from facedetector import FaceDetector DETR = FaceDetector() RGB_GREEN = (0, 255, 0) def process(frm): frame = flip(frm, 1) fpos = DETR.get_faces_pos(frame, minNeighbors=15) for (x, y, w, h) in fpos: frame = rectangle(frame, (x, y), (x+w, y+h), color=RGB_GREEN, thickness=2) imshow('Live Detection', frame) if __name__ == '__main__': with vcap: vcap.run(process)
# limitations under the License. import socket import threading import socketserver import time from facedetector import FaceDetector import io import cv2 import numpy as np import json import base64 from imageio import imread, imwrite import imghdr fd = FaceDetector() class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler): """ This class works similar to the TCP handler class, except that self.request consists of a pair of data and client socket, and since there is no connection the client address must be given explicitly when sending data back via sendto(). """ def handle(self): # print(self.request) data = self.request[0].strip() print("len(data)", len(data), threading.current_thread()) socket = self.request[1]
import cv2 from facedetector import FaceDetector image = cv2.imread("goat1.jpg", 1) cv2.imshow("hi", image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) p = FaceDetector(faceCascadePath="haarcascade_frontalface_default.xml") face = p.detect(image=gray, scaleFactor=1.2, minNeighbors=5, minSize=(30, 30)) print("I found {} face(s)".format(len(face))) for (x, y, w, h) in face: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Faces", image) k = cv2.waitKey(0) if k == 27: cv2.destroyAllWindows()
import argparse import imutils from facedetector import FaceDetector import cv2 ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") args = vars(ap.parse_args()) face_cascade_path = 'haarcascade_frontalface_default.xml' fd = FaceDetector(face_cascade_path) if not args.get("video", False): camera = cv2.VideoCapture(0) else: camera = cv2.VideoCapture(args["video"]) while True: (grabbed, frame) = camera.read() if args.get("video") and not grabbed: break frame = imutils.resize(frame, width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceRects = fd.detect(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) frameClone = frame.copy() for (fX, fY, fW, fH) in faceRects: cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH), (0, 255, 0), 2) cv2.imshow("Face", frameClone) if cv2.waitKey(1) & 0xFF == ord("q"):
""" folder = 'images' for image_path in os.listdir(folder): image = cv2.imread(folder + "\\" + image_path) # cv2.imshow("Image", image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) fd = FaceDetector("cascades\\haarcascade_frontalface_default.xml") faceRects = fd.detect(gray, scaleFactor = 1.2) print("I found {} face(s)".format(len(faceRects))) for (x, y, w, h) in faceRects: cv2.rectangle(image, (x,y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow("Faces", image) cv2.waitKey(0) """ camera = cv2.VideoCapture(0) fd = FaceDetector("cascades\\haarcascade_frontalface_default.xml") while True: (grabbed, frame) = camera.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceRects = fd.detect(gray) print("I found {} face(s)".format(len(faceRects))) for (x, y, w, h) in faceRects: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Faces", frame) if cv2.waitKey(1) & 0xFF == ord("q"): break camera.release() cv2.destroyAllWindows()
from facedetector import FaceDetector import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-f", "--face", required=True, help="path to the face cascade") ap.add_argument("-i", "--image", required=True, help="path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) fd = FaceDetector(args["face"]) faceRects = fd.detect(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) print("I found {} faces(s)".format(len(faceRects))) for (x, y, w, h) in faceRects: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Faces", image) cv2.waitKey(0)
from facedetector import FaceDetector import argparse import cv2 ap = argparse.ArgumentParser() ap.add_argument("-f", "--face", required=True, help="path to where the face cascade resides") ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Load the face cascade into the face detector face_detector = FaceDetector(args["face"]) # Detect all the faces on the image face_rectangles = face_detector.detect(gray) print "I found %d face(s)" % len(face_rectangles) # Draw rectangles around the faces found on the image for (x, y, w, h) in face_rectangles: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("Faces", image) cv2.waitKey(0)
from facedetector import FaceDetector import cv2 import argparse from image_processing import imutils ap = argparse.ArgumentParser() #ap.add_argument("-f", "--face", required=True, help="path to where the face cascade resides") ap.add_argument("-v", "--video", help="path to the (optional) video file") args = vars(ap.parse_args()) fd = FaceDetector("./cascades/haarcascade_frontalface_default.xml") if not args.get("video", False): camera = cv2.VideoCapture(0) else: camera = cv2.VideoCapture(args["video"]) while True: (grabbed, frame) = camera.read() #the video file reach the end if args.get("video") and not grabbed: break frame = imutils.resize(frame, width=300) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceRects = fd.detect(frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))