示例#1
0
    def __init__(self, show=False, model=None, folder=None, save_model=None):
        self.show = show
        self.frtool = FaceExtractor()
        self.fr_recog = FaceIdentify(show)

        if model is not None:
            self.fr_recog.load(model)
        elif folder is not None:
            self.fr_recog.train(folder, save_model)
        else:
            print('ERROR')
            exit()
示例#2
0
class FaceIdentify:
    def __init__(self, show):
        self.frtool = FaceExtractor()
        self.show = show

    def load(self, model_file):
        try:
            feature = np.load(filename)
            print('Model have {} samples'.format(feature.shape[0]))
            self.model = feature

        except IOError:
            print('Wrong numpy format in file {}'.format(filename))
            exit()

    def identify(self, feature):
        dist = np.linalg.norm(self.model - feature, axis=1)
        return np.mean(dist)

    def train(self, folder, save_model):
        filenames = os.listdir(folder)

        features = list()
        project_root = os.getcwd()
        print('Get {} files'.format(len(filenames)))
        for filename in filenames:
            filepath = os.path.join(project_root, folder, filename)

            img = cv2.imread(filepath)
            if img is not None:
                feature = self.frtool.extract_feature(img, self.show)
                if feature is not None:
                    features.append(feature)
                else:
                    print('Cannot found face in {}'.format(filepath))
            else:
                print('Cannot read file {}'.format(filepath))

        if len(features) == 0:
            print('Cannot extract any feature from folder {}'.format(folder))
        else:
            features = np.array(features)
            num_samples = features.shape[0]
            print('Get {} samples'.format(num_samples))
            if save_model is None:
                np.save('model', features)
                print('Save to model.npy')
            else:
                np.save(save_model, features)
                print('save to {}'.format(save_model))
            self.model = features
示例#3
0
class Identify:
    @classmethod
    def load_from_model(cls, filename, show):
        if not os.path.isfile(filename):
            print('Wrong file path {}'.format(filename))
            exit()
        else:
            return cls(model=filename)

    @classmethod
    def train_from_folder(cls, folder, save_model, show):
        if not os.path.isdir(folder):
            print('Wrong folder path {}'.format(folder))
            exit()
        else:
            return cls(folder=folder, save_model=save_model, show=show)

    def __init__(self, show=False, model=None, folder=None, save_model=None):
        self.show = show
        self.frtool = FaceExtractor()
        self.fr_recog = FaceIdentify(show)

        if model is not None:
            self.fr_recog.load(model)
        elif folder is not None:
            self.fr_recog.train(folder, save_model)
        else:
            print('ERROR')
            exit()

    def predict_image(self, filename):
        if len(filename) == 0:
            return 
        elif not os.path.isfile(filename):
            print('Cannot found test file {}'.format(filename))
            return

        img = cv2.imread(filename)

        feature = self.frtool.extract_feature(img, self.show)
        if feature is None:
            print('Cannot found face in {}'.format(filename))
        else:
            dist = self.fr_recog.identify(feature)
            print(dist)

    def predict_from_stream(self, web_cam_idx):
        if web_cam_idx == -1:
            return

        cam = cv2.VideoCapture(web_cam_idx)

        if not cam.isOpened:
            print('Cannot load cam stream')
        else:
            is_open = True
            ret, frame = cam.read()

            while ret and is_open:
                ret, frame = cam.read()
                feature = self.frtool.extract_feature(frame, show=False)

                flip_frame = cv2.flip(frame, 1)
                if feature is None:
                    is_open = show_image(flip_frame, text='No Face', is_block=False)
                else:
                    avg_dist = self.fr_recog.identify(feature)
                    # print(dist)
                    text = 'Similarity: {:.5f}'.format(avg_dist)
                    is_open = show_image(flip_frame, text=text, is_block=False)
示例#4
0
 def __init__(self):
     self.frtool = FaceExtractor()
示例#5
0
class FaceClassifier:
    def __init__(self):
        self.frtool = FaceExtractor()

    def recog(self, feature):
        if len(feature.shape) == 1:
            feature = feature.reshape(1, -1)
        return self.model.predict(feature)

    def recog_proba(self, feature):
        if len(feature.shape) == 1:
            feature = feature.reshape(1, -1)
        proba = self.model.predict_proba(feature)
        identified = self.model.classes_[np.argmax(proba)]

        return identified, proba

    def load(self, model_file):
        try:
            self.model = pickle.load(open(model_file, 'rb'))
        except pickle.UnpicklingError as e:
            print('Wrong pickle file {}'.format(model_file))

    def train(self, root, save_model):
        subfolders = {
            folder: os.path.join(root, folder)
            for folder in os.listdir(root)
        }

        users_encoding = dict()
        for _id, folder in subfolders.items():
            if not os.path.isdir(folder):
                print('Not folder, skip {}'.format(folder))
            else:
                print('Doing {}'.format(folder))
                files = [
                    os.path.join(folder, _file) for _file in os.listdir(folder)
                ]

                user_encoding = list()
                for _file in filter(os.path.isfile, files):
                    img = cv2.imread(_file)
                    if img is not None:
                        feature = self.frtool.extract_feature(img)
                        if feature is not None:
                            user_encoding.append(feature)

                if len(user_encoding):
                    users_encoding[_id] = user_encoding
                print('Finish {}'.format(folder))

        X = np.concatenate(list(users_encoding.values()))
        Y = np.array(
            list(_id for _id, encodings in users_encoding.items()
                 for loop in range(len(encodings))))

        clf = KNeighborsClassifier(algorithm='ball_tree')
        clf.fit(X, Y)

        self.model = clf

        pickle.dump(clf, open(save_model, 'wb'))
示例#6
0
 def __init__(self, show):
     self.frtool = FaceExtractor()
     self.show = show
示例#7
0
class Classifier:
    @classmethod
    def load_from_model(cls, filename, show):
        if not os.path.isfile(filename):
            print('Wrong model file path {}'.format(filename))
            exit()
        else:
            return cls(model=filename, show=show)

    @classmethod
    def train_from_folder(cls, root, save_model, show):
        return cls(folder=root, save_model=save_model, show=show)

    def __init__(self, show=False, model=None, folder=None, save_model=None):
        self.show = show
        self.frtool = FaceExtractor()
        self.fr_recog = FaceClassifier()

        if model is not None:
            self.fr_recog.load(model)

        elif folder is not None:
            self.fr_recog.train(folder, save_model)
        else:
            print('ERROR')
            exit()

    def predict_image(self, filename):
        if len(filename) == 0:
            return
        elif not os.path.isfile(filename):
            print('Cannot found test file {}'.format(filename))
            return

        img = cv2.imread(filename)

        feature = self.frtool.extract_feature(img, self.show)
        if feature is None:
            print('Cannot found face in {}'.format(filename))
        else:
            result = self.fr_recog.recog_proba(feature)
            # dist = self.fr_recog.identify(feature)
            print(result)
            # dist = np.linalg.norm(self.features-feature, axis=1)
            # print(np.mean(dist))

    def predict_from_stream(self, web_cam_idx):
        if web_cam_idx == -1:
            return

        cam = cv2.VideoCapture(web_cam_idx)

        if not cam.isOpened:
            print('Cannot load cam stream')
        else:
            is_open = True
            ret, frame = cam.read()

            while ret and is_open:
                ret, frame = cam.read()
                feature = self.frtool.extract_feature(frame, show=False)

                flip_frame = cv2.flip(frame, 1)
                if feature is None:
                    is_open = show_image(flip_frame,
                                         text='No Face',
                                         is_block=False)
                else:
                    user, proba = self.fr_recog.recog_proba(feature)
                    # print(user, proba)
                    # avg_dist = self.fr_recog.recog(feature)
                    # print(dist)
                    # text = 'Similarity: {:.5f}'.format(avg_dist)
                    text = 'User: {}-{}'.format(user, np.max(proba))
                    is_open = show_image(flip_frame, text=text, is_block=False)