예제 #1
0
    def train(self, image, name):
        bbs = self._face_detector.detect(image, False)

        trained_list = []
        for face in bbs:
            self._log.debug("Face found in training")
            phash, rep = self._face_eigener.eigenValue(face.img)
            identity = self._toIdentity(name)
            if identity is None:
                people_list = self._face_db.distinct_search(
                                            ['name', 'class_id'], 'class_id')

                identity = len(people_list) - 1
                add_new_person(self, identity, name)

            face_img = os.path.join(
                    self._trained_face_dir, "{}_{}.jpg".format(name, phash))
            Image.fromarray(face.img).save(face_img)
            #content = [str(x) for x in face.img.flatten()]
            record = faceapi.FaceInfo(
                            phash, name, rep, face_img, identity)
            self._face_db.addList([record])
            trained_list.append(record)
            # content = [str(x) for x in face.img.flatten()]
        #self._face_classifier.updateDB()
        return trained_list
예제 #2
0
    def predict(self, image):
        if self._svm is None:
            self._log.warn("self._svm is None")
            return None
        elif len(self._db_dict) == 0:
            self._log.warn("self._db_dict == 0")
            return None

        if isinstance(image, basestring):
            pil_img = Image.open(image)
            np_img = np.asarray(pil_img)
            #self._log.debug("PIL image: {}".format(str(pil_img)))
        elif isinstance(image, Image.Image):
            pil_img = image
            np_img = np.asarray(image)
        elif isinstance(image, np.ndarray):
            np_img = image
            pil_img = Image.fromarray(image)
        else:
            raise exceptions.LibError("Unknow image type")

        resultRecord = None
        phash = str(imagehash.phash(pil_img))
        if phash in self._db_dict:
            hit = self._db_dict[phash]
        else:
            rep = openfaceutils.neural_net.forward(np_img)
            pred = self._svm.predict(rep)
            #self._log.info("pred {}".format(pred))
            #self._log.info("df {}".format(self._svm.decision_function(rep)))
            class_id = pred[0]
            if _USE_PREDICTIVE:
                ##self._log.info("prob {}".format(self._svm.predict_proba(rep)))

                probability = max(self._svm.predict_proba(rep)[0])
                self._log.info("prob {} {}".format(
                    probability, np.argmax(self._svm.predict_proba(rep))))
                if probability <= _PROB_THRESH:
                    self._log.info("prob too low")
                    class_id = -1
            db_list = self._face_db.search('class_id', class_id, 1)
            #self._log.debug("result({}): {}".format(len(db_list), db_list))
            try:
                hit = db_list[0]
            except IndexError:
                hit = {
                    'name': 'Unknown',
                    'eigen': '',
                    'img_path': '',
                    'class_id': class_id
                }

        resultRecord = faceapi.FaceInfo(phash, hit['name'], hit['eigen'],
                                        hit['img_path'], hit['class_id'])

        return resultRecord
예제 #3
0
 def faceList(self):
     list = []
     for info in self._face_db.dbList():
         face_info = faceapi.FaceInfo(
             info['hash'].encode('ascii', 'ignore'), info['name'],
             [float(x) for x in info['eigen'].split(',')],
             info['src_hash'].encode('ascii', 'ignore'),
             info['face_img'].encode('ascii', 'ignore'), info['class_id'])
         list.append(face_info)
     return list
예제 #4
0
    def predict(self, image):
        if self._svm is None:
            self._log.warn("self._svm is None")
            return None
        elif len(self._db_dict) == 0:
            self._log.warn("self._db_dict == 0")
            return None

        if isinstance(image, basestring):
            pil_img = Image.open(image)
            np_img = np.asarray(pil_img)
            self._log.debug("PIL image: {}".format(str(pil_img)))
        elif isinstance(image, Image.Image):
            pil_img = image
            np_img = np.asarray(image)
        elif isinstance(image, np.ndarray):
            np_img = image
            pil_img = Image.fromarray(image)
        else:
            raise exceptions.LibError("Unknow image type")

        resultRecord = None
        phash = str(imagehash.phash(pil_img))
        if phash in self._db_dict:
            hit = self._db_dict[phash]
            hit_p = 0.95
            self._log.debug('match with hash: {}'.format(hit['name']))
        else:
            rep = openfaceutils.neural_net.forward(np_img)
            # predict_ret = self._svm.predict(rep)
            predict_p = self._svm.predict_proba(rep)[0]
            hit_p = max(predict_p)
            # if hit_p < (2.0/len(predict_p)):
            #     # probability of hit < average * 2
            #     return None
            # class_id = predict_p.index(hit_p)
            class_id = np.argmax(predict_p)
            self._log.info("svm({}, {}):\n{}".format(
                class_id, predict_p.max(), predict_p))
            db_list = self._face_db.search('class_id', class_id, 1)
            self._log.debug("result({}): {}".format(len(db_list), db_list))
            hit = db_list[0]

        resultRecord = faceapi.FaceInfo(
            phash,
            hit['name'],
            hit['eigen'],
            'src_img_no_need',
            hit['face_img'],
            hit['class_id'])
        resultRecord.scroe = hit_p
        self._face_db.Mark_Attendance(hit['name'])
        return resultRecord
예제 #5
0
    def train(self, img):
        if self._training_id == -1:
            self._log.error('[ERROR] Call start_train first, please.')
            return False

        add_face_list = []
        # for img in image_list:
        self._log.debug("training img: {}".format(img))
        pil_img = self._toPilImg(img)
        src_hash = str(imagehash.phash(pil_img, hash_size=16))
        db_list = self._face_db.search('src_hash', '\'{}\''.format(src_hash),
                                       1)

        if len(db_list) > 0:
            self._log.debug('trained image, skip it')
            F = open("detected.txt", "w")
            print('name')
            return False

        # start to train the faces in the image
        t = time.time()
        bbs = self._face_detector.detect(img)
        t = time.time() - t
        self._log.debug("face detection done({})".format(t))
        t = time.time()

        record = None
        for face in bbs:
            # every single face in a image
            phash, rep = self._face_eigener.eigenValue(face.img)

            save_dir = os.path.join(self._trained_face_dir,
                                    self._trainint_name)

            face_img = os.path.join(save_dir, "{}.jpg".format(phash))
            Image.fromarray(face.img).save(face_img)

            record = faceapi.FaceInfo(phash, self._trainint_name, rep,
                                      src_hash, face_img, self._training_id)

            add_face_list.append(record)
            if self._trainint_cb is not None:
                self._trainint_cb(face.area, face.landmarks)

        t = time.time() - t
        self._log.debug("training img done({})".format(t))

        self._face_db.addList(add_face_list)
        return record
예제 #6
0
    def trainDir(self, dir_path):
        if not os.path.isdir(dir_path):
            self._log.error('Not a dir, do nothing.\n({})'.format(dir_path))
            return

        trian_names = next(os.walk(dir_path))[1]
        for name in trian_names:
            path = os.path.join(dir_path, name)
            self._log.debug("Going to train: {}".format(path))

            # check if this person exist
            db_names = self._face_db.distinct_search(
                                        ['name', 'class_id'], 'class_id')
            self._log.debug("db_names: {}".format(db_names))
            check_ret = [
                        (name_dic['name'], name_dic['class_id'])
                        for name_dic in db_names
                        if name_dic['name'] == name]

            self._log.debug("check_ret: {}".format(check_ret))
            class_id = len(db_names)
            if len(check_ret) > 0:
                class_id = (check_ret[0])[1]

            tp = time.time()
            self._log.info(
                    "train >>>>> name: {}, svm id: {}".format(name, class_id))

            exts = ("*.png", "*.PNG", "*.jpg", "*.jpeg", "*.JPG", "*.JPEG")
            train_imgs = []
            for ext in exts:
                train_imgs.extend(glob.glob(os.path.join(path, ext)))

            # # print "train imgs: {}".format(train_imgs)
            for img in train_imgs:
                self._log.debug("training img: {}".format(img))
                # one training image for a person
                t = time.time()
                bbs = self._face_detector.detect(img, False)
                t = time.time() - t
                self._log.debug("face detection done({})".format(t))
                t = time.time()
                for face in bbs:
                    # every single face in a image
                    phash, rep = self._face_eigener.eigenValue(face.img)

                    face_img = os.path.join(
                                        self._trained_face_dir,
                                        "{}_{}.jpg".format(name, phash))

                    Image.fromarray(face.img).save(face_img)
                    #content = [str(x) for x in alignedFace.flatten()]
                    record = faceapi.FaceInfo(
                                phash, name, rep, face_img, class_id)
                    self._face_db.addList([record])
                t = time.time() - t
                self._log.debug("face training done({})".format(t))

            tp = time.time() - tp
            self._log.info(
                "<<<({}) end name: {}, svm id: {}".format(tp, name, class_id))

        self._face_classifier.updateDB()