【问题标题】:How to access variable from a function in python如何从python中的函数访问变量
【发布时间】:2021-12-09 08:00:11
【问题描述】:

我正在开发一个使用人脸识别登录的网站数字银行。我创建了一个名为 gen_frame() 的函数,其中我使用了名为“name”的变量。我想在函数外部使用这个变量,以便我可以使用路由在 HTML 页面上显示它。我使用了flask框架。

这是我的 app.py 文件

# Initialize some variables
face_locations = []
face_encodings = []
face_names  = []
process_this_frame = True


def gen_frames():  
    while True:
        success, frame = camera.read()  # read the camera frame
        if not success:
            break
        else:
            # Resize frame of video to 1/4 size for faster face recognition processing
            small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
            # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
            rgb_small_frame = small_frame[:, :, ::-1]

            # Only process every other frame of video to save time
           
            # 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)
            face_names = []
            for face_encoding in face_encodings:
                # See if the face is a match for the known face(s)
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"
                # Or instead, use the known face with the smallest distance to the new face
                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]
                face_names.append(name)
            
            # Display the results
            for (top, right, bottom, left), name in zip(face_locations, face_names):
                # Scale back up face locations since the frame we detected in was scaled to 1/4 size
                top *= 4
                right *= 4
                bottom *= 4
                left *= 4

                # Draw a box around the face
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)

                # Draw a label with a name below the face
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

data = name
@app.route('/')
def index():
    return render_template('Index.html',data = data) 

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

if __name__=='__main__':
    app.run(debug=True)

我创建了数据变量 数据 = 名称

并使用路由将数据发送到html

@app.route('/')
    def index():
        return render_template('Index.html',data = data) 

这是我的 HTMl 文件代码 sn-p

<div class="container">
        <div class="row justify-content-center">

            <div class="col-sm-3"  style="margin-top: 20px;box-shadow: 9px 9px 27px 2px hsl(250, 66%, 55%); border-radius: 70px; margin-right: 50px; text-align: center;">
                <h4 style="text-align: center; color:hsl(250, 69%, 61%);" >Name: 
                <p>{{data}}</p>
                </h4>
            </div>
        </div>
    </div>

【问题讨论】:

  • 也许使用global关键字
  • 已使用但无法正常工作。我也尝试创建函数属性但不工作
  • 我认为您没有正确跟踪每个变量的每个值的分配,例如,如果您将名称分配给数据,您将在数据中获得名称的“当前”值在执行的那一刻,如果通过调用 gen_frames 更改了“name”,则变量“data”将不会更新,因此您应该在 index() 函数中使用“name”,并让两个函数都将 name 声明为全局,但是注意全局变量只对模块是全局的,所以如果你将代码拆分到多个文件或使用多处理,你将不会得到你期望的值。
  • 能否请您注释掉您解释的代码sn-p

标签: python html function flask routes


【解决方案1】:

尝试将变量全局放在函数的开头:

全局变量名

【讨论】:

  • 显示错误
  • 这里我给你举个例子:def foo(): global name name = "Example"
【解决方案2】:

在程序中创建全局变量的最快方法是在顶部创建变量。

# Initialize some variables
...
name = ''

这不是最佳实践,当您在访问/video_feed 的多个客户端/浏览器上使用该程序时,名称的引用将使用相同的内存实例。正如 Ahmed Mohamed AEK 在评论中提到的那样,有时,您不会得到预期的结果。

如果您创建图像处理页面以触发 API,并使用该触发器发送名称会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2022-12-05
    • 2018-07-16
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多