Call instance variable from another class


Hye Guys, I would like to ask a question regarding python. Basiclly I have two class Face and VideoCamera . In my class Face I have one variable call self.known_encoding_faces()

My question is how can i get the variable self.known_encoding_faces and this variable can be used by class of VIdeoCamera`

from flask import Flask, Response, json, render_template
from werkzeug.utils import secure_filename
from flask import request
from os import path, getcwd
import time
from face import Face
from db import Database
app = Flask(__name__)
import cv2
from camera import VideoCamera

app.config['file_allowed'] = ['image/png', 'image/jpeg']
app.config['train_img'] = path.join(getcwd(), 'train_img')
app.db = Database()
app.face = Face(app)
#print (app.face) = VideoCamera(app)

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

def index():
    return render_template('index.html')

def success_handle(output, status=200, mimetype='application/json'):
    return Response(output, status=status, mimetype=mimetype)

def error_handle(error_message, status=500, mimetype='application/json'):
    return Response(json.dumps({"error": {"message": error_message}}), status=status, mimetype=mimetype)

def get_user_by_id(user_id):
    user = {}
    results =
        'SELECT,, users.created,, faces.user_id, faces.filename,faces.created FROM users LEFT JOIN faces ON faces.user_id = WHERE = ?',
    index = 0
    for row in results:
        face = {
            "id": row[3],
            "user_id": row[4],
            "filename": row[5],
            "created" : row[6],
        if index == 0:
            user = {
                "id": row[0],
                "name": row[1],
                "created": row[2],
                "faces" : [],
        if 3 in row:
        index = index + 1
    if 'id' in user:
        return user
    return None

def delete_user_by_id(user_id):
    app.db.delete('DELETE FROM users WHERE = ?', [user_id])
    # also delete all faces with user id
    app.db.delete('DELETE FROM faces WHERE faces.user_id = ?', [user_id])

#def hello():
#    return "Welcome to machine learning model APIs!"

def train():
    output=json.dumps({"success": True})

    if 'file' not in request.files:
        print("Face Image Is Required")
        return error_handle("face Image is required")
        print("File Request", request.files)
        file = request.files['file']
        if file.mimetype not in app.config['file_allowed']:
            print("file extension is not allowed")
            error_handle("we are only allow upload file with .png , *.jpg")
            name = request.form['name']
            print("information of that face", name)
            print("File is allowed and will be saved in ", app.config['train_img'])
            filename = secure_filename(file.filename)
            training_image = path.join(app.config['train_img'], 'trained')
  , filename))

            # # save to our sqlite database.db
            created = int(time.time())
            user_id = app.db.insert('INSERT INTO users (name,created) values(?,?)', [name,created])
            if user_id:
                print("user data already save", name, user_id)
                face_id = app.db.insert('INSERT INTO faces (user_id,filename,created) values (?,?,?)', [user_id, filename, created])
                if face_id:
                    print("cool face has been saved")
                    face_data = {"id": face_id, "filename": filename, "created": created}
                    return_output = json.dumps({"id": user_id, "name": name, "face": [face_data]})
                    return success_handle(return_output)
                    print("an error saving image")
                    return error_handle("an error saving image")
                print("Something happen")
                return error_handle("An error inserting new user")
        print("Request Is Contain Image")

    return success_handle(output)

# route for user profile
@app.route('/api/users/<int:user_id>', methods=['GET', 'DELETE'])
def user_profile(user_id):
    if request.method == 'GET':
        user = get_user_by_id(user_id)
        if user:
            return success_handle(json.dumps(user),200)
            return error_handle("user not found",404)

    if request.method == 'DELETE':
        return success_handle(json.dumps({"deleted":True}))
@app.route('/api/recognize', methods=['POST'])
def recognize():
    if 'file' not in request.files:
        return error_handle("Image is required")
        file = request.files['file']
        #file extension validation
        if file.mimetype not in app.config['file_allowed']:
            return error_handle("File extension is not allowed")

            filename = secure_filename(file.filename)
            unknown_storage = path.join(app.config["train_img"], 'unknown')
            file_path = path.join(unknown_storage, filename)

            user_id = app.face.recognize(filename)
            if user_id:
                user = get_user_by_id(user_id)
                message = {"message": "Hey we found {0} matched with your face image".format(user["name"]),"user": user}
                return success_handle(json.dumps(message))

                return error_handle("Sorry we can not found any people matched with your face image, try another image")

    return success_handle(json.dumps({"filename to compare is": filename}))

    import face_recognition
    from os import path
    import cv2

    class Face:
        def __init__(self, app):
            self.train_img = app.config["train_img"]
            self.db = app.db
            self.faces = []
           self.face_user_keys = {}
           self.known_encoding_faces = []  # faces data for recognition

    def load_user_by_index_key(self, index_key=0):

        key_str = str(index_key)

        if key_str in self.face_user_keys:
            return self.face_user_keys[key_str]

        return None

    def load_train_file_by_name(self,name):
        trained_train_img = path.join(self.train_img, 'trained')
        return path.join(trained_train_img, name)

    def load_unknown_file_by_name(self,name):
        unknown_img = path.join(self.train_img, 'unknown')
        return path.join(unknown_img, name)

    def load_all(self):
        results ='SELECT, faces.user_id, faces.filename, faces.created FROM faces')
        for row in results:

            user_id = row[1]
            filename = row[2]

            face = {
                "id": row[0],
                "user_id": user_id,
                "filename": filename,
                "created": row[3]


            face_image = face_recognition.load_image_file(self.load_train_file_by_name(filename))
            face_image_encoding = face_recognition.face_encodings(face_image)[0]
            index_key = len(self.known_encoding_faces)
            index_key_string = str(index_key)
            self.face_user_keys['{0}'.format(index_key_string)] = user_id

    def recognize(self,unknown_filename):
        unknown_image = face_recognition.load_image_file(self.load_unknown_file_by_name(unknown_filename))
        unknown_encoding_image =  face_recognition.face_encodings(unknown_image)[0]

        results = face_recognition.compare_faces(self.known_encoding_faces, unknown_encoding_image);

        print("results", results)

        index_key = 0
        for matched in results:

            if matched:
                # so we found this user with index key and find him
                user_id = self.load_user_by_index_key(index_key)

                return user_id

            index_key = index_key + 1
        return None

    import face_recognition
    from os import path
    import cv2
    from db import Database
    from face import Face


    class VideoCamera(object):
        def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video_capture = cv2.VideoCapture(0)
        self.face_locations = []
        self.face_encodings = []
        self.face_names = []
        self.process_this_frame = True
        # If you decide to use video.mp4, you must have this file in the folder
        # as the
        # = cv2.VideoCapture('video.mp4')

    def __del__(self):

    def get_frame(self):
        success, frame =
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        if self.process_this_frame:
        # Find all the faces and face encodings in the current frame of video
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
        # Grab a single frame of video
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()