客户端摄像头实时视频流推送至AWS远程Flask服务器的实现方案
核心实现架构
- 拆分原有逻辑的硬件依赖:AWS远程服务器无物理摄像头,原代码中直接调用
cv2.VideoCapture(0)采图的逻辑无法在服务器端运行,需要将采图模块从服务端剥离,部署在连接实体摄像头的本地设备上。 - 全流程无人工交互:本地采图进程后台持续运行,无需打开Web页面、无用户交互触发,自动将采集到的图像帧传输到AWS上的Flask接口;Flask服务端接收到帧后执行人脸识别、绘制标注框,将处理后的图像流自动返回给本地端完成展示,完全匹配自动运行的要求。
- 复用现有核心算法:直接沿用你已经写好的人脸识别匹配逻辑,不需要适配参考开源项目中“客户端发起请求后再上传画面”的交互模式。
代码改造方案
AWS端Flask服务改造
替换原服务端直接读取本地摄像头的逻辑,改为接收本地端推送的图像帧,处理后返回标注结果,核心代码结构如下:
from flask import Flask, Response, request import cv2 import numpy as np import face_recognition import os import time app = Flask(__name__) # 初始化人脸库逻辑和原代码保持一致 known_person = [] known_face_encodings = [] for file in os.listdir("profiles"): try: known_person.append(file.replace(".jpg", "")) file_path = os.path.join("profiles/", file) known_image = face_recognition.load_image_file(file_path) known_face_encodings.append(face_recognition.face_encodings(known_image)[0]) except Exception as e: pass # 全局帧缓存,替代原来的本地摄像头读取 latest_frame = None process_this_frame = True @app.route('/upload_frame', methods=['POST']) def upload_frame(): """接收本地端推送的图像帧""" global latest_frame frame_data = request.data nparr = np.frombuffer(frame_data, np.uint8) latest_frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) return "ok" def gen_processed_stream(): """处理接收到的帧,生成标注后的连续流""" global latest_frame, process_this_frame while True: if latest_frame is None: time.sleep(0.1) continue image = latest_frame.copy() small_frame = cv2.resize(image, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] face_locations = [] face_encodings = [] face_names = [] if process_this_frame: face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" 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_person[best_match_index] face_names.append(name) process_this_frame = not process_this_frame # 绘制标注框和姓名 for (top, right, bottom, left), name in zip(face_locations, face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(image, (left, top), (right, bottom), (255, 255, 255), 2) cv2.rectangle(image, (left, bottom - 35), (right, bottom), (255, 255, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(image, name, (left + 10, bottom - 10), font, 1.0, (0, 0, 0), 1) ret, jpeg = cv2.imencode('.jpg', image) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n') time.sleep(0.05) @app.route('/processed_feed') def processed_feed(): return Response(gen_processed_stream(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=False, threaded=True)
本地端自动采图推流脚本
部署在连接实体摄像头的设备上,后台持续运行,不需要打开任何Web页面,同时支持拉取AWS端处理后的标注流本地展示:
import cv2 import requests import time # 配置AWS上的Flask服务地址 AWS_SERVER_IP = "<你的AWS公网IP>" UPLOAD_URL = f"http://{AWS_SERVER_IP}:5000/upload_frame" PROCESSED_STREAM_URL = f"http://{AWS_SERVER_IP}:5000/processed_feed" # 初始化本地摄像头 camera = cv2.VideoCapture(0) # 初始化拉取AWS处理流的客户端 processed_capture = cv2.VideoCapture(PROCESSED_STREAM_URL) while True: # 持续采集本地图像并上传 success, frame = camera.read() if success: _, jpeg = cv2.imencode('.jpg', frame) try: requests.post(UPLOAD_URL, data=jpeg.tobytes(), timeout=2) except Exception as e: pass # 持续拉取处理后的帧本地展示 show_ret, show_frame = processed_capture.read() if show_ret: cv2.imshow("AWS人脸识别结果", show_frame) # 按q退出 if cv2.waitKey(1) == ord('q'): break time.sleep(0.03) camera.release() processed_capture.release() cv2.destroyAllWindows()
原代码问题修正
- 原
camera.py中process_this_frame是get_frame方法内的局部变量,每次调用都会被重置为True,完全无法实现隔帧处理降低算力消耗的效果,改造后改为全局变量维护状态。 - 原代码中
face_names列表每次处理帧时不会清空,会持续累积历史帧的识别结果,导致标注框和姓名错位,改造后每次处理帧时重新初始化列表。 - 原代码中用全局变量
name_gui存储识别结果,多目标识别时所有标注位置都会显示最后识别到的人名,改造后按人脸位置匹配对应姓名做标注。
AWS部署配套配置
- 安全组开放Flask服务的5000端口,允许本地摄像头所在设备的IP发起访问
- 服务器端安装全部依赖:
flask、opencv-python、face_recognition、numpy - 上传人脸库文件到服务器端的
profiles目录,确保路径配置和代码一致 - 生产环境不要开启
debug=True,避免服务崩溃,可使用gunicorn做多进程部署提升稳定性
内容的提问来源于stack exchange,提问作者Agung Banar
相关产品推荐
相关产品推荐

