def __enter__(self): if self.haar_file is None: self.haar_file = streamsx.ec.get_application_directory( ) + "/etc/haarcascade_frontalface_default.xml" if self.haar_cascade_face is None: self.haar_cascade_face = CascadeClassifier(self.haar_file) return self
def main(): image_list = [ file for file in os.listdir('Dataset') if file.endswith('.jpg') ] image_list.sort() # load the pre-trained model classifier = CascadeClassifier('haarcascade_frontalface_default.xml') j = 0 for i in image_list[:10]: j = j + 1 # load the photograph pixels = imread('Dataset/' + i) # perform face detection bboxes, p, q = classifier.detectMultiScale3(pixels, scaleFactor=1.05, minNeighbors=8, outputRejectLevels=True) # print bounding box for each detected face #print('Number of faces detected in '+i+' : '+str(len(bboxes))) for box, conf in zip(bboxes, q): if conf > 1: # extract x, y, width, height = box x2, y2 = x + width, y + height # draw a rectangle over the pixels rectangle(pixels, (x, y), (x2, y2), (0, 0, 255), 2) imwrite('Output/Face_Detection_Haar' + str(j) + str(i), pixels)
def __call__(self, _tuple): """ The processing Args: _tuple: process the image_string f9eld Returns: faces_regions added to tuple None on failure """ if self.haar_file is None: self.haar_file = streamsx.ec.get_application_directory( ) + "/etc/haarcascade_frontalface_default.xml" if self.haar_cascade_face is None: self.haar_cascade_face = CascadeClassifier(self.haar_file) bio = io.BytesIO(base64.b64decode(_tuple['image_string'])) img_raw = self.bts_to_img(bio.read()) if img_raw is None: img_url = _tuple['img_desc'][0]['img'] logging.getLogger(__name__).warning( "Fail bts_to_img() on url: {}".format(img_url)) return None print("Size of image to process : ", img_raw.shape) img_rgb = self.convertToRGB(img_raw) face_rects = self.haar_cascade_face.detectMultiScale(img_rgb, scaleFactor=1.2, minNeighbors=5) if len(face_rects) is 0: return None _tuple['face_regions'] = face_rects.tolist() return _tuple
def face_detection(self) -> bool: """Detects faces by converting it to grayscale and neighbor match method. Returns: bool: A boolean value if not a face was detected. """ cascade = CascadeClassifier(data.haarcascades + "haarcascade_frontalface_default.xml") for _ in range(20): ignore, image = self.validation_video.read( ) # reads video from web cam scale = cvtColor( image, COLOR_BGR2GRAY) # convert the captured image to grayscale scale_factor = 1.1 # specify how much the image size is reduced at each image scale min_neighbors = 5 # specify how many neighbors each candidate rectangle should have to retain it faces = cascade.detectMultiScale( scale, scale_factor, min_neighbors) # faces are listed as tuple here # This is a hacky way to solve the problem. The problem when using "if faces:": # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() # When used either of the suggestion: # AttributeError: 'tuple' object has no attribute 'any' / 'all' # But happens only when the value is true so ¯\_(ツ)_/¯ try: if faces: pass except ValueError: imwrite('cv2_open.jpg', image) self.validation_video.release() return True
def main(): image_list = [ file for file in os.listdir('Dataset') if file.endswith('.jpg') ] image_list.sort() # load the pre-trained model classifier = CascadeClassifier('lbpcascade_frontalface.xml') j = 0 for i in image_list[:10]: j = j + 1 # load the photograph pixels = imread('Dataset/' + i) # perform face detection bboxes = classifier.detectMultiScale(pixels) # print bounding box for each detected face #print('Number of faces detected in '+i+' : '+str(len(bboxes))) for box in bboxes: # extract x, y, width, height = box x2, y2 = x + width, y + height # draw a rectangle over the pixels rectangle(pixels, (x, y), (x2, y2), (0, 0, 255), 2) imwrite('Output/Face_Detection_LBP' + str(i), pixels)
def cropFace(img): # load the photograph # pixels = img pixels = img # load the pre-trained model classifier = CascadeClassifier( 'face_detect/haarcascade_frontalface_default.xml') # perform face detection bboxes = classifier.detectMultiScale(pixels) if len(bboxes) == 0: print("ERROR: No faces found.") # extract x, y, width, height = bboxes[0] x2, y2 = x + width, y + height BUFFER = int(width * 0.25) # show the image image = pixels[max(y - BUFFER, 0):min(y2 + BUFFER, pixels.shape[0]), max(x - BUFFER, 0):min(x2 + BUFFER, pixels.shape[1])] # imshow('hehe', image) # waitKey(0) return image
def detect_face_cv2_webcam(): cap = VideoCapture(0) classifier = CascadeClassifier('haarcascade_frontalface_default.xml') # Check if the webcam is opened correctly if not cap.isOpened(): raise IOError("Cannot open webcam") while True: ret, frame = cap.read() frame = flip(frame, 1) gray = cvtColor(frame, COLOR_BGR2GRAY) faces = classifier.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), # flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) for (x, y, w, h) in faces: rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) imshow("Video", frame) if waitKey(1) == ord('q'): break cap.release() destroyAllWindows()
def crop(self, input_image, output_filename=None, to_gray=False): image = asarray(input_image) img_height, img_width = image.shape[:2] minface = int(sqrt(img_height ** 2 + img_width ** 2) / self.minface) # create the haar cascade face_cascade = CascadeClassifier(self.casc_path) # detect faces in the image faces = face_cascade.detectMultiScale( cvtColor(image, COLOR_BGR2GRAY), scaleFactor=1.1, minNeighbors=5, minSize=(minface, minface), flags=CASCADE_FIND_BIGGEST_OBJECT | CASCADE_DO_ROUGH_SEARCH, ) # handle no faces if len(faces) == 0: return None # make padding from biggest face found x, y, w, h = faces[-1] pos = self._crop_positions(img_height, img_width, x, y, w, h,) # actual cropping image = image[pos[0]: pos[1], pos[2]: pos[3]] # resize image = resize(image, (self.width, self.height), interpolation=INTER_AREA) if output_filename: if to_gray: Image.fromarray(image).convert("L").save(output_filename) else: cv2.imwrite(output_filename, image) return image
def __init__( self, cascadeXMLFilePath: str = './resources/face_detectors/facedetect_haarcascade_frontalface_default.xml', postProcessCallback=None): super().__init__(postProcessCallback=postProcessCallback) # check if file exists open(cascadeXMLFilePath, 'r').close() self.face_cascade = CascadeClassifier(cascadeXMLFilePath)
async def Start(self) -> None: self.face_cascade = CascadeClassifier(f"Files/{Settings.cascade}") if (not self.cap): self.cap = VideoCapture(Settings.capIndex) self.cap.set(3, Settings.resolution[0]) self.cap.set(4, Settings.resolution[1]) if (Settings.port): if (self.serialArduino): self.serialArduino.close() self.serialArduino = serial.Serial(port=Settings.port, baudrate=Settings.speed)
def start(q, postURLe): global embeddedDB global postURL postURL = postURLe embedUpdateTimeout = 0 fetchEmbedded() detector = CascadeClassifier("haarcascade_frontalface_default.xml") prevName = None while True: time.sleep(0.1) if (not (q.empty())): if (embedUpdateTimeout == 6): #fetchEmbedded() embedUpdateTimeout = 0 frame = imutils.resize(q.get(), width=500) frame = cvtColor(frame, COLOR_BGR2RGB) frameGray = cvtColor(frame, COLOR_BGR2GRAY) rects = detector.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=CASCADE_SCALE_IMAGE) boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects] sendBoxes = [(x, y, x + w, y + h) for (x, y, w, h) in rects] encodings = face_recognition.face_encodings(frame, boxes) names = [] for encoding in encodings: matches = face_recognition.compare_faces( embeddedDB["encodings"], encoding, tolerance=0.48) name = "Unknown" if True in matches: matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} for i in matchedIdxs: name = embeddedDB["names"][i] counts[name] = counts.get(name, 0) + 1 name = max(counts, key=counts.get) names.append(name) if (len(names) > 0): if (prevName == names[0]): eventLogger.eventLogger(frame, sendBoxes[0], names[0], postURL) if (names[0] != "Unknown"): print("Recognized: " + names[0]) lockCtrl.unlock() else: print("Unrecognized stranger!") prevName = names[0] else: eventLogger.eventLogger(frame, None, None, postURL) embedUpdateTimeout += 1
def __init__(self, file_path=None): """Init Haar Cascade Classifier Create classifier instance with given XML file. Download XML from the web if the file does not exist. Args: file_path: the path for cascade classifier XML file """ if not file_path: file_path = FaceDetector.get_abs_path() if not exists(file_path): FaceDetector.download_haarcascade_xml(file_path) self.ccc = CascadeClassifier(file_path)
def __init__(self, fl, lock, fps=None): # Reference to lock > I'm not sure if I am doing this correctly self.lock = lock # Reference to the FrameLoop object (instance) self.fl_ref = fl # The target fps self.target_fps = fps if fps else fl.fps # The current frame of the FrameLoop self.frame = None # The current frame of the FrameLoop (.jpg encoded) self.encodedFrame = None # Classifier reference self.face_cascade = CascadeClassifier(data.haarcascades + 'haarcascade_frontalface_default.xml')
def crop_face(img): """ Given an image with a single face, crop the face out and return it. :param img: :return: """ # get face classifier face_cascade = CascadeClassifier( "../data/haarcascades/haarcascade_frontalface_default.xml") # detect all faces detected = face_cascade.detectMultiScale(img, 1.2, 5) # get first face detected (probably the largest one) (x, y, w, h) = detected[0] # return cropped image return img[y:y + w, x:x + h]
def main(): if(len(sys.argv)!=4): print("Wrong number of arguments.") print(" Usage: ./bin/pre_annotate.py <file.txt> <image_dir> <output_dir>") sys.exit(0) localizer = bob.ip.flandmark.Flandmark() files = open(sys.argv[1]).readlines() if os.environ.has_key('SGE_TASK_ID'): pos = int(os.environ['SGE_TASK_ID']) - 1 if pos >= len(files): raise RuntimeError, "Grid request for job %d on a setup with %d jobs" % \ (pos, len(files)) files = [files[pos]] for o in files: filename = os.path.join(sys.argv[2], o.rstrip("\n")) output_filename = os.path.join(sys.argv[3], o.rstrip("\n")+".pos") img = bob.io.base.load(filename) if(len(img.shape)==3): img = bob.ip.color.rgb_to_gray(img) cc = CascadeClassifier('./pre_annotation/data/haarcascade_frontalface_alt2.xml') face_bbxs = cc.detectMultiScale(img, 1.3, 4, 0, (20, 20)) if(len(face_bbxs)>0): key_temp = localizer.locate(img, face_bbxs[0][1], face_bbxs[0][0], face_bbxs[0][2], face_bbxs[0][3]) if(key_temp is not None): R_eye = [ (key_temp[1,0] + key_temp[5,0])/2, (key_temp[1,1] + key_temp[5,1])/2 ] L_eye = [ (key_temp[2,0] + key_temp[6,0])/2, (key_temp[2,1] + key_temp[6,1])/2 ] keypoints = [int(L_eye[1]), int(L_eye[0]), int(R_eye[1]), int(R_eye[0])] else: keypoints = [100,100,100,200] else: keypoints = [100,100,100,200] print("{0}: {1}".format(filename,str(keypoints))) bob.io.base.create_directories_safe(os.path.dirname(output_filename)) annotations = "L R\n0 {0} {1} {2} {3}".format(str(keypoints[0]), str(keypoints[1]), str(keypoints[2]), str(keypoints[3])) open(output_filename,'w').write(annotations)
def start(self, vid_path): self.tracker = BarbellTracker('') self.s3_dao.download_file_from_s3(config.S3_BUCKET, vid_path, self.vid_location) # Create the classifier to detect the barbell classifier = CascadeClassifier(config.CLASSIFIER_LOCATION) # Load the video into the tracker self.tracker.load_video(self.vid_location) # Get the FPS of the video fps = self.tracker.get_video_fps() # Apply the classifier to the video frame, pos, cm_multiplier = self.tracker.detect_barbell_pos(classifier) # Track the detected objcet throughout the video dist_list = self.tracker.track(frame, pos) # Add results to the DB Session = sessionmaker(bind=self.db_eng) db_session = Session() video = db_session.query(Video).filter_by(s3_path=vid_path).first() # Update the video to add attributes determined by the tracker video.fps = fps video.cm_multiplier = cm_multiplier dist_ctr = 1 for distance in dist_list: bar_distance = BarDistance(video.vid, dist_ctr, distance) db_session.add(bar_distance) dist_ctr += 1 db_session.commit()
class FaceExtractorCascadePipe(FaceExtractorPipe): def __init__( self, cascadeXMLFilePath: str = './resources/face_detectors/facedetect_haarcascade_frontalface_default.xml', postProcessCallback=None): super().__init__(postProcessCallback=postProcessCallback) # check if file exists open(cascadeXMLFilePath, 'r').close() self.face_cascade = CascadeClassifier(cascadeXMLFilePath) def getFaceBB(self, image: Image_Type, passThrough: PushPipe.PassThrough) -> Image_Type: gray = cvtColor(image, COLOR_RGB2GRAY) faces = self.face_cascade.detectMultiScale(gray, 1.3, 5) if (len(faces) > 0): # get largest face largest = (0, 0, 0, 0) for (x, y, w, h) in faces: if (largest[-1] * largest[-2] < w * h): largest = (x, y, w, h) (x, y, w, h) = largest rect = BoundingBox_twopoint(x, y, x + w, y + h) return rect else: # no faces found, won't push forward self.setErrored("No face found.") return image
def opencv_detect(image): """Detects a face using OpenCV's cascade detector Returns a list of arrays containing (x, y, width, height) for each detected face. """ from cv2 import CascadeClassifier cc = CascadeClassifier(F('haarcascade_frontalface_alt.xml')) return cc.detectMultiScale( image, 1.3, #scaleFactor (at each time the image is re-scaled) 4, #minNeighbors (around candidate to be retained) 0, #flags (normally, should be set to zero) (20,20), #(minSize, maxSize) (of detected objects on that scale) )
def extract_face_opencv(f_cascade: cv2.CascadeClassifier, image: np.ndarray, scale_factor=1.1, size=-1, padding_ratio=0.5) \ -> List[np.ndarray]: gray = cv2.cvtColor(image.copy(), cv2.COLOR_RGB2GRAY) # let's detect multiscale (some images may be closer to camera than others) images bboxes = f_cascade.detectMultiScale(gray, scaleFactor=scale_factor, minNeighbors=5) res = [] for (x, y, w, h) in bboxes: bbox = [x, y, x + w, y + h] width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] bbox = [ int(bbox[0] - width * padding_ratio // 2), int(bbox[1] - height * padding_ratio // 2), int(bbox[2] + width * padding_ratio // 2), int(bbox[3] + height * padding_ratio // 2) ] width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] padding_width_face = (height - width if height > width else 0) // 2 padding_height_face = (width - height if width > height else 0) // 2 bbox = [ bbox[0] - padding_width_face, bbox[1] - padding_height_face, bbox[2] + padding_width_face, bbox[3] + padding_height_face ] left_shift = abs(bbox[0]) if bbox[0] < 0 else 0 right_shift = bbox[2] - image.shape[1] if bbox[2] > image.shape[ 1] else 0 top_shift = abs(bbox[1]) if bbox[1] < 0 else 0 bottom_shift = bbox[3] - image.shape[0] if bbox[3] > image.shape[ 0] else 0 bbox[0] += left_shift bbox[0] -= right_shift bbox[1] += top_shift bbox[1] -= bottom_shift bbox[2] += left_shift bbox[2] -= right_shift bbox[3] += top_shift bbox[3] -= bottom_shift face = image[bbox[1]:bbox[3], bbox[0]:bbox[2], :] if size == -1 else \ cv2.resize(image[bbox[1]:bbox[3], bbox[0]:bbox[2], :], (size, size)) res.append(face) return res
def opencv_detect(image): """ Detects a face using OpenCV's cascade detector Returns a list of arrays containing (x, y, width, height) for each detected face. """ from cv2 import CascadeClassifier cc = CascadeClassifier('./bob/prepare_eyes_annotations/util/data/haarcascade_frontalface_alt.xml') faces = cc.detectMultiScale( image, 1.3, #scaleFactor (at each time the image is re-scaled) 4, #minNeighbors (around candidate to be retained) 0, #flags (normally, should be set to zero) (20,20), #(minSize, maxSize) (of detected objects on that scale) ) if(len(faces) == 0): faces = [[0,0,image.shape[0],image.shape[1]]] return faces
def classify(model, cascade_classifier_path_xml, transformations=None): cap = cv2.VideoCapture(0) face_cascade = CascadeClassifier(cascade_classifier_path_xml) while True: ret, img_bgr = cap.read() gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 2) for (x, y, w, h) in faces: w += 20 h += 20 r = max(w, h) / 2 centerx = x + w / 2 centery = y + h / 2 nx = int(centerx - r) ny = int(centery - r) nr = int(r * 2) faceimg_bgr = img_bgr[ny:ny + nr, nx:nx + nr] predimg = transformations(faceimg_bgr) predimg = np.expand_dims(predimg.numpy(), axis=0) outputs = model(torch.Tensor(predimg)) _, prediction = torch.max(outputs.data, 1) prediction = prediction.item() if prediction == 1: img_bgr = cv2.rectangle(img_bgr, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(img_bgr, 'No Mask', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2) elif prediction == 0: img_bgr = cv2.rectangle(img_bgr, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(img_bgr, 'Mask', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.namedWindow("img_1") cv2.imshow('img_1', img_bgr) k = cv2.waitKey(30) & 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
class GenericFaceDetection(object): def __init__(self, fl, lock, fps=None): # Reference to lock > I'm not sure if I am doing this correctly self.lock = lock # Reference to the FrameLoop object (instance) self.fl_ref = fl # The target fps self.target_fps = fps if fps else fl.fps # The current frame of the FrameLoop self.frame = None # The current frame of the FrameLoop (.jpg encoded) self.encodedFrame = None # Classifier reference self.face_cascade = CascadeClassifier(data.haarcascades + 'haarcascade_frontalface_default.xml') def detect_generic_face(self): while True: # Grab the lock with self.lock: # Make a copy of the frame loop's current frame self.frame = self.fl_ref.frame.copy() # Try to detect faces in the current faces = self.face_cascade.detectMultiScale(self.frame, 1.35, 5) # Draw the rectangle around each face for (x, y, w, h) in faces: rectangle(self.frame, (x, y), (x+w, y+h), (255, 0, 0), 2) # Sleep until the time for the next frame sleep(1/self.target_fps) def encoding_generator(self): while True: # Grab the lock with self.lock: # Encode the frame into the `encodedImage` variable (flag, self.encodedImage) = imencode(".jpg", self.frame) # Check if encoding was successful if flag: yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(self.encodedImage) + b'\r\n') # Else just skip else: print("Error encoding to .jpg ~(detect_generic_face)") continue def start(self): # Run the generic face detection in another thread self.t = Thread(target=self.detect_generic_face) self.t.daemon = True self.t.start()
def main(): cascade = CascadeClassifier('cascades/haarcascade_frontalface_default.xml') model = load_model('my_models/my_model_small.h5') image_BGR, image_gray = load_image('test_images/test_image_1.jpg') faces = detect_cascade(image_gray, cascade, scaleFactor=4) facialFeatures = detect_facial_features(image_gray, faces, model) image_BGR = add_sunglasses(image_BGR, faces, facialFeatures) imwrite('output.jpg', image_BGR)
def detect_face_cv2(img): # load the photograph pixels = imread(img) # load the pre-trained model classifier = CascadeClassifier('haarcascade_frontalface_default.xml') # perform face detection bboxes = classifier.detectMultiScale(pixels, scaleFactor=1.05, minNeighbors=8 ) # print bounding box for each detected face for box in bboxes: x, y, width, height = box x2, y2 = x + width, y + height rectangle(pixels, (x, y), (x2, y2), (0, 0, 255), 1) imshow("face detection", pixels) waitKey(0) destroyAllWindows()
def __init__(self, cascade_object=None, scale_factor=2.5, min_neighbors=5): """Create a Cascade Scanner Parameters ---------- cascade_object : str | ClassifierObject a model used for object detection scale_factor : float the scale with which the image will be resized min_neighbors : int a parameter needed for the object detection """ self.scale_factor = scale_factor self.min_neighbors = min_neighbors if cascade_object is not None: if cascade_object is not str: self.cascade_object = cascade_object else: self.cascade_object = CascadeClassifier(cascade_object)
def extract_faces(classifier: cv2.CascadeClassifier, image: array) -> Iterator[array]: """ 画像から顔を検出して、顔の部分を切り取った画像をyieldする。 """ # 顔検出を高速化するため、画像をグレースケールに変換する。 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 顔を検出する。 faces = classifier.detectMultiScale(gray_image) # 検出した顔のリストについて反復処理する。 for x, y, w, h in faces: yield image[y:y + h, x:x + w] # 顔の部分だけを切り取った画像をyieldする。
def face_detection(path): # Create the haar cascade faceCascade = CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Read the image image = cv2.imread(path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) return len(faces), image
def camera_prediction(model): frequency = 0.02 # minutes instant = -1 faceCascade = CascadeClassifier('haarcascade_frontalface_alt.xml') capture = VideoCapture(0) while True: ret, frame = capture.read() image = copy.deepcopy(frame) gray = cvtColor(frame, COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(image_width, image_height), flags=CASCADE_SCALE_IMAGE) captured_face = None for (x, y, w, h) in faces: rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) captured_face = gray[y:y + h, x:x + w] imshow('Face detector', frame) if captured_face is not None: captured_face = resize(captured_face, (image_width, image_height)) instant = classify_emotion(model, captured_face, instant, frequency) captured_face = None if waitKey(1) & 0xFF == ord('q'): break video_capture.release() destroyAllWindows()
def opencv_detect(image): """ Detects a face using OpenCV's cascade detector Returns a list of arrays containing (x, y, width, height) for each detected face. """ from cv2 import CascadeClassifier cc = CascadeClassifier( './bob/prepare_eyes_annotations/util/data/haarcascade_frontalface_alt.xml' ) faces = cc.detectMultiScale( image, 1.3, #scaleFactor (at each time the image is re-scaled) 4, #minNeighbors (around candidate to be retained) 0, #flags (normally, should be set to zero) (20, 20), #(minSize, maxSize) (of detected objects on that scale) ) if (len(faces) == 0): faces = [[0, 0, image.shape[0], image.shape[1]]] return faces
def init_face_classifier(): """ Load the Cascade Classifier and initialize it with the weights from the Haar Cascade Classifier. """ print('\n\nLoading the Cascade Classifier') # try: facec = CascadeClassifier('models/haarcascade_frontalface_default.xml') print('Cascade Classifier Loaded Successfully') # except: # print('ERROR: Could not Load the Cascade Classifier') # sys.exit(1) return facec
def cropFace(img_path): img = cv2.imread(img_path) # load the photograph # pixels = img pixels = img # load the pre-trained model classifier = CascadeClassifier('haarcascade_frontalface_default.xml') # perform face detection bboxes = classifier.detectMultiScale(pixels) if len(bboxes) == 0: print("ERROR: No faces found.") return None # extract x, y, width, height = bboxes[0] x2, y2 = x + width, y + height BUFFER = int(width * 0.25) images = [] # show the image for i in range(len(bboxes)): x, y, width, height = bboxes[i] x2, y2 = x + width, y + height images.append( pixels[max(y - BUFFER, 0):min(y2 + BUFFER, pixels.shape[0]), max(x - BUFFER, 0):min(x2 + BUFFER, pixels.shape[1])]) # imshow('hehe', images[i]) # waitKey(0) images[i] = cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB) return images
def detect_face_opencv_haar(face_cascade: cv2.CascadeClassifier, frame: numpy.ndarray, i_w: int, in_height=300): """ Take haar_cascade and frame (img), search faces in the frame, select face with size 'iw' :param face_cascade: haarCascade obj :param frame: image for face detecting :param i_w: out img size :param in_height: default height for template img for haarDetector algorithm :return: out img (cut to iw) """ iw_h = i_w >> 1 # half of img width frame_open_cv_haar = frame.copy() frame_height = frame_open_cv_haar.shape[0] frame_width = frame_open_cv_haar.shape[1] in_width = int((frame_width / frame_height) * in_height) frame_open_cv_haar_small = cv2.resize(frame_open_cv_haar, (in_width, in_height)) faces = face_cascade.detectMultiScale( cv2.cvtColor(frame_open_cv_haar_small, cv2.COLOR_BGR2GRAY)) # choose the first face, find center of rect if not list(faces): # if no face detected select the middle of the picture roi = get_roi(int(frame_width / 2), int(frame_height / 2), frame_width, frame_height, iw_h) out_small_image = frame_open_cv_haar[roi[1] - iw_h:roi[1] + iw_h - 1, roi[0] - iw_h:roi[0] + iw_h - 1].copy() else: # faces are detected, select one of them x_center = int( (faces[0][0] + faces[0][2] / 2) * (frame_width / in_width)) y_center = int( (faces[0][1] + faces[0][3] / 2) * (frame_height / in_height)) roi = get_roi(x_center, y_center, frame_width, frame_height, iw_h) out_small_image = frame_open_cv_haar[roi[1] - iw_h:roi[1] + iw_h - 1, roi[0] - iw_h:roi[0] + iw_h - 1].copy() # logger.debug(VisualRecord("Haar face detector " + str(datetime.datetime.utcnow()), # [frame_open_cv_haar, out_small_image], "bla bla", fmt="png")) return out_small_image
class FaceDetector: def __init__(self, faceCascadePath): self.faceCascade = CascadeClassifier(faceCascadePath) def track_faces(self, image): rects = [] face_rects = self.faceCascade.detectMultiScale( image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) for (fX, fY, fH, fW) in face_rects: rects.append((fX, fY, fX + fW, fY + fH)) return (face_rects, rects)
from shapely.geometry import Polygon from shapely.geometry import box from time import time import sys from GroundTruthMasks import fix_path try: cascade_xml_path = sys.argv[1] test_annotation_dir = sys.argv[2] except: print "USAGE: python Accuracy cascade_xml_path test_annotation_dir" exit() try: #Open up the cascade classifier cascade = CascadeClassifier(cascade_xml_path) except: print "Error reading cascade xml" exit() #Get the file paths to read from detector_output_files = directory_paths(test_annotation_dir) #Open all the files and read the JSON annotation_files = batch_open_deserialise(detector_output_files) #For each of the hand marked test files for annotation_file in annotation_files: #Read the image corresponding to the annotation img = imread(fix_path(annotation_file['imagePath']))
import md5 import os import random import sys import time import urllib import pylab import numpy from cv2.cv import * from cv2 import CascadeClassifier, waitKey, imread, imshow, cvtColor, equalizeHist, rectangle, Sobel, GaussianBlur face_cascade_name = "haarcascade_frontalface_alt.xml"; eyes_cascade_name = "haarcascade_eye.xml"; face_cascade = CascadeClassifier(face_cascade_name) eyes_cascade = CascadeClassifier(eyes_cascade_name) image = imread("jaxons_class_crop.jpg") colour_image = image image = cvtColor(image, CV_BGR2GRAY) image = equalizeHist(image) objects = face_cascade.detectMultiScale(image, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, (30, 30)) for x, y, w, h in objects: rectangle(image, (x, y), (x+w, y+h), (255, 255, 255)) face_image = image[y:y+h,x:x+w] imshow("Image", image)