Example #1
0
def __find_eyes(img):
    coords = []
    face_cascade = CascadeClassifier(
        bin_path + '/Resources/Classifiers/haarcascade_frontalface.xml')
    eye_cascade = CascadeClassifier(
        bin_path + '/Resources/Classifiers/haarcascade_eye.xml')
    gray = array(img.convert("L"))

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        roi_gray = gray[y:y + h, x:x + w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex, ey, ew, eh) in eyes:
            coords.append((x + ex + ew / 2, y + ey + eh / 2))
    return coords
    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 __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 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 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()
Example #6
0
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)
Example #7
0
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
Example #8
0
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)
Example #9
0
 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
Example #10
0
    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
Example #11
0
 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)
Example #12
0
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)
Example #13
0
    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)
Example #14
0
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
Example #15
0
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 main():

    classifier1 = CascadeClassifier('haarcascade_frontalface_default.xml')
    classifier2 = CascadeClassifier('lbpcascade_frontalface.xml')

    video_capture = cv2.VideoCapture(0)

    while True:
        # Capture frame-by-frame
        start = time.time()
        ret, frame = video_capture.read()

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces1, p, confidence1 = classifier1.detectMultiScale3(
            gray, scaleFactor=1.05, minNeighbors=8, outputRejectLevels=True)

        # Draw a Green rectangle around the faces identified by HAAR_Cascade
        for (x, y, w, h), conf1 in zip(faces1, confidence1):
            if conf1 > 1:
                rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        faces2, q, confidence2 = classifier2.detectMultiScale3(
            gray, scaleFactor=1.05, minNeighbors=8, outputRejectLevels=True)

        # Draw a Blue rectangle around the faces identified by LBP
        for (x, y, w, h), conf2 in zip(faces2, confidence2):
            if conf2 > 1:
                rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        end = time.time()
        print('time taken to execute one frame ', end - start)

    video_capture.release()
    cv2.destroyAllWindows()
Example #17
0
    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)
Example #18
0
 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')
Example #19
0
 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]
Example #20
0
    def __init__(self,
                 path_to_face_points,
                 path_to_hc_model,
                 scale=1,
                 minNeighbors=5):

        # load_weigths face detector model
        self.detector = CascadeClassifier(
            str(path_to_hc_model)).detectMultiScale

        # parameters for face detector model
        self.scale = scale
        self.minNeighbors = minNeighbors

        # load_weigths face landmarks detector model
        self.predictor = shape_predictor(str(path_to_face_points))
Example #21
0
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()
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()
Example #23
0
    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)
Example #24
0
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
Example #25
0
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()
Example #26
0
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
Example #27
0
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
Example #28
0
 def __init__(self):
     # create classifier to determine what a face is
     self.face_cascade = CascadeClassifier(
         "../data/haarcascades/haarcascade_frontalface_default.xml")
     self.trackers = []  # object tracker for each face
     self.tracking_count = 0
Example #29
0
import cv2
from cv2 import CascadeClassifier
from cv2 import imread
from cv2 import rectangle
from cv2 import imshow
from cv2 import waitKey
from cv2 import destroyAllWindows
#print(cv2.__version__)

#Cargamos un modelo pre-entrenado para reconocimiento facial y creamos un modelo en cascada con el
classifier = CascadeClassifier('haarcascade_frontalface_default.xml')

#cargamos una foto de prueba
pixels = imread('image/foto grupal.jpg')

#realizamos el reconocimiento facial. 1.1 significa ampliar la foto un 10% y 3 indica el nivel de fiabilidad de la deteccion
bboxes = classifier.detectMultiScale(pixels, 1.1, 3)
#representamos los cuadros delimitadores de los rostros detectados
for box in bboxes:
    print(box)
    # para mostrar la imagen original con los cuadros delimitadores dibujados encima haremos lo siguiente:
    # extraemos cada propiedad del resultado (x e y de la esquina inferior izq del cuadro delimitador y su altura y anchura)
    x, y, width, height = box
    x2, y2 = x + width, y + height
    # dibujamos un rectangulo sobre los pixels
    rectangle(pixels, (x, y), (x2, y2), (0, 0, 255), 1)

#imprimimos la imagen con la deteccion y la mantenamos abierta hasta que el usuario pulse una tecla
#mostramos la imagen
imshow('face detection', pixels)
#mantenemos la ventana abierta hasta que se pulse una tecla
def detect_human_face():

    # 得到user目录下的所有文件名称,即各个好友头像
    pics = listdir('image')

    # 使用人脸的头像个数
    count_face_image = 0

    # 存储使用人脸的头像的文件名
    list_name_face_image = []

    # 加载人脸识别模型
    face_cascade = CascadeClassifier(
        'model/haarcascade_frontalface_default.xml')

    for index, file_name in enumerate(pics):
        print(u'正在进行人脸识别,进度%d/%d,请耐心等待……' % (index + 1, len(pics)))
        # 读取图片
        img = imread('image/' + file_name)

        # 检测图片是否读取成功,失败则跳过
        if img is None:
            continue

        # 对图片进行灰度处理
        gray = cvtColor(img, COLOR_BGR2GRAY)
        # 进行实际的人脸检测,传递参数是scaleFactor和minNeighbor,分别表示人脸检测过程中每次迭代时图
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        if (len(faces) > 0):
            count_face_image += 1
            list_name_face_image.append(file_name)

    print(u'使用人脸的头像%d/%d' % (count_face_image, len(pics)))

    # 开始拼接使用人脸的头像
    pics = list_name_face_image
    numPic = len(pics)
    eachsize = int(math.sqrt(float(640 * 640) /
                             numPic))  # 先圈定每个正方形小头像的边长,如果嫌小可以加大
    numrow = int(640 / eachsize)
    numcol = int(numPic / numrow)  # 向下取整
    toImage = Image.new('RGB',
                        (eachsize * numrow, eachsize * numcol))  # 先生成头像集模板

    x = 0  # 小头像拼接时的左上角横坐标
    y = 0  # 小头像拼接时的左上角纵坐标

    for index, i in enumerate(pics):

        print(u'正在拼接使用人脸的微信好友头像数据,进度%d/%d,请耐心等待……' % (index + 1, len(pics)))
        try:
            # 打开图片
            img = Image.open('image/' + i)
        except IOError:
            print(u'Error: 没有找到文件或读取文件失败')
        else:
            # 缩小图片
            img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
            # 拼接图片
            toImage.paste(img, (x * eachsize, y * eachsize))
            x += 1
            if x == numrow:
                x = 0
                y += 1

    toImage.save('data/使用人脸的拼接' + ".jpg")

    # 生成一个网页
    with open('data/使用人脸的微信好友头像拼接图.html', 'w', encoding='utf-8') as f:
        data = '''
            <!DOCTYPE html>
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
                  <meta charset="utf-8" /> 
                  <title>使用人脸的微信好友头像拼接图</title> 
            </head>
            <body>
                <p><font size=4px><strong>描述内容</strong></font></p>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <img src="使用人脸的拼接.jpg" />
            </body>
            </html>
        '''

        data = data.replace(
            '描述内容', '在{}个好友中,有{}个好友使用真实的人脸作为头像'.format(len(friends),
                                                       count_face_image))
        f.write(data)