【问题标题】:How to call instance variable form another class and file如何从另一个类和文件中调用实例变量
【发布时间】:2019-08-08 10:05:00
【问题描述】:

我有一个问题,我有 4 个文件 app.pyface.pycamera.pydb。 pyface.py 文件中,我有一个变量调用 known_encoding_faces。如果我将打印代码放入我的 face.py 并运行 app.py,结果将显示在我的命令提示符中。

我的问题是如何在我的 camera.py 中使用 known_encoding_faces 变量?我的预期结果是,当我运行 app.py 并打开网络摄像头时,命令提示符将显示打印的 known_encoding_faces 输出。我相信如果这项工作意味着这个 known_encoding_faces 变量可以被 camera.py 文件成功使用。

我在这里附上我的代码。希望有人可以帮助我解决这个问题。

app.py

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)


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')

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

@app.route('/')
def index():
    return render_template('index.html')

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

face.py

import face_recognition
from os import path
import cv2
import face_recognition



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
        self.load_all()

    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 = self.db.select('SELECT faces.id, 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]
            }

            self.faces.append(face)

            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)
            self.known_encoding_faces.append(face_image_encoding)
            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

camera.py

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 = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # 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', image)
        return jpeg.tobytes()

【问题讨论】:

  • 可以导入变量,不行吗?
  • @Nishant 不起作用:(我尝试了几天但失败了..也许你可以告诉我如何做。我可以尝试编辑我的代码
  • 只需正确查看您的变量名称即可。在 face.py 文件中声明的 known_encoding_faces 列表我看不到其中的 known_face_encoding 变量。
  • @VaradarajuG 我已经在我的 face.py 文件 self.known_encoding_faces = [] 中声明了。我相信它是实例变量
  • @VaradarajuG 感谢您的努力先生.. 也感谢您的建议:)

标签: python python-3.x instance-variables


【解决方案1】:

known_encoding_facesFace 对象的成员。这意味着它本身并不存在 - 作为证据,请注意您仅引用 self.known_encoding_faces 而不仅仅是 known_encoding_faces。您需要初始化一些 Face 对象,然后才能使用它。此外,您似乎需要在所述对象上调用load_all 才能正确初始化它。你需要的最少的东西是这样的:

from face import Face

aface = Face(app) #You would need an app here
aface.load_all()
known_encoding_faces = aface.known_encoding_faces

如果您希望无论对象创建如何都存在,那么您需要重新考虑您的设计,并将其从课堂中移除。

如果您希望从主脚本中调用它,您可以要求这个变量来初始化您的相机:

VideoCamera(app.face.known_encoding_faces) #Called from main script

camera.py:

class VideoCamera(object):
    def __init__(self,known_face_encodings):
        self.known_encoding_faces = known_face_encodings
        self.video = cv2.VideoCapture(0)

在本课程中,您现在可以使用self.known_encoding_faces

【讨论】:

  • 感谢您的建议。目前我已经放了这段代码但不起作用..我几乎相信了。正如您所提到的,我可能知道如何获取应用程序以便可以执行我的 aface.face(app) 吗?我应该把它放在我的 app.py 的什么地方?
  • @iszzulikhwan91 看第二个例子。更改VideoCamera 以在其init 方法中获取此列表,然后当您在app.py 中创建VideoCamera 时,只需发送已初始化的app.face.known_encoding_faces
  • 非常感谢@kabanus。代码运行良好。非常感谢先生,我们的努力。对此,我真的非常感激。先生,我很想知道您提供的第一个解决方案。如果我想使用它。我需要放入 app.py 吗?
  • @iszzulikhwan91 您需要在camera.py 中使用它,因为这是您想要使用它的地方。但是你需要初始化appFace。我不确定这在您的上下文中是否有意义,因为在您初始化VideoCamera 时它们已经存在于app.py 中。您必须在camera 中创建appFace,我认为这没有意义。这就是为什么我会使用第二种解决方案 -
  • 你提到我必须初始化和应用程序和人脸。我以前尝试过这种方法,但它显示错误。这就是为什么我有兴趣知道。就我而言,如何初始化应用程序。我需要再次声明这个 app = Flask(name) 吗?
猜你喜欢
  • 2020-04-14
  • 2018-07-25
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2011-07-26
  • 2022-01-27
  • 2014-11-19
相关资源
最近更新 更多