姓名:{{ name }}
年龄:{{ age }}
人脸评分:{{ beauty }}
性别:{{ gender }}
脸型:{{ face_shape }}
Back PS:在代码的修改中发现一些小bug,例如现实的姓名是包含.JPG,因此前面需要把数据进行split切割保持数据的合适性! Q:我希望Result.html 右侧可以看到上传的照片 import os from flask import Flask, render_template, request, url_for from face import analyze_face # 假设您已经在 face.py 中定义了这个函数 app = Flask(__name__) # 定义存储上传图片的文件夹 UPLOAD_FOLDER = 'uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': # 获取上传的图片文件对象 image_file = request.files['image'] # 保存图片到上传文件夹 filename = os.path.join(app.config['UPLOAD_FOLDER'], image_file.filename) image_file.save(filename) # 获取图片的 URL image_url = url_for('static', filename=os.path.join('uploads', image_file.filename)) # 进行人脸分析 image_data = image_file.read() face_features = analyze_face(image_data) # 提取分析结果并显示,同时传递图片的 URL age = face_features['age'] beauty = face_features['beauty'] gender = face_features['gender']['type'] face_shape = face_features['face_shape']['type'] return render_template('result.html', age=age, beauty=beauty, gender=gender, face_shape=face_shape, image_url=image_url) return render_template('index.html') if __name__ == '__main__': app.run(debug=True) 问题集1: 不要多次读取文件:在代码中,读取了 image_file 的内容到 image_data 变量,然后又保存了 image_file。在文件对象被读取后,文件指针会移动到文件的末尾,所以如果再次尝试读取或保存,将不会得到任何数据。因此可以在保存文件之后重新打开它来读取数据! @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': # 获取上传的图片文件 image_file = request.files['image'] file_name = image_file.filename.split('.')[0] # 保存图片到static/uploads文件夹 filename = os.path.join(app.config['UPLOAD_FOLDER'], image_file.filename) image_file.save(filename) # 如果之后需要读取文件内容,可以这样做: with open(filename, 'rb') as f: image_data = f.read() # 使用url_for生成图片的URL image_url = url_for('static', filename=os.path.join('uploads', image_file.filename)) # 调用analyze_face函数分析人脸 face_features = analyze_face(image_data) # 提取分析结果并显示 name = file_name age = face_features['age'] beauty = face_features['beauty'] gender = face_features['gender']['type'] face_shape = face_features['face_shape']['type'] return render_template('result.html', name=name, age=age, beauty=beauty, gender=gender, face_shape=face_shape, image_url=image_url) return render_template('index.html') Q:我感觉UI界面太丑了,加一个框架开发可行吗 安装Bootstrap UI库 pip install Flask Flask-Bootstrap {% extends "base.html" %} {% block page_content %}- 姓名: {{ name }}
- 年龄: {{ age }}
- 颜值(满分100): {{ beauty }}
- 性别: {{ gender }}
- 脸型: {{ face_shape }}