让用户上传图像,我需要显示上传的图像以及该人的姓名

时间:2018-03-26 10:03:47

标签: python html flask

import sys
from flask import Flask, request, render_template, jsonify, make_response
#import pyexcel as pe
import csv
import cv2
app = Flask(__name__)
@app.route('/send', methods=['GET', 'POST'])

def send():
        if request.method == 'POST':
                postdata = request.form
                file_name = postdata['filename']
                print("file name: ====================== {}".format(file_name))
                file = str(file_name)
                path = ".\\static\\" + file
        return render_template('/send.html')


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

upload.py文件和我的send.html代码是

    <html>

<form action = "/send" method = "POST">
<meta name="viewport" content="width=device-width, initial-scale=1">

</body>
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
    <span>Upload</span>
    <input id="uploadBtn" type="file" class="upload" />
</div>
<script>
document.getElementById("uploadBtn").onchange = function () {
    document.getElementById("uploadFile").value = this.value;
    var filename=(document.getElementById("uploadBtn").value)
    document.write("You have chosen"+filename)


};
</script>
</form>
</html>

我的final.py

用于识别面孔并显示我训练过的人的姓名

import cv2
import os
import numpy as np
import glob
subjects = ["", "shah rukh", "Ram","Aishwarya","Kavya","Vaishnavi","Rajamouli","Nani","Mahesh Babu","Samantha"]
def detect_face(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face_cascade = cv2.CascadeClassifier('D:/lbpcascade_frontalface.xml')
    eye_cascade = cv2.CascadeClassifier('D:/haarcascade_eye.xml')
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
    if (len(faces) == 0):
        return None, None   
    (x, y, w, h) = faces[0]
    return gray[y:y+w, x:x+h], faces[0]
def prepare_training_data(data_folder_path):
    dirs = os.listdir(data_folder_path)
    faces = []
    labels = []
    for dir_name in dirs:
        if not dir_name.startswith("s"):
            continue;
        label = int(dir_name.replace("s", ""))
        subject_dir_path = data_folder_path + "/" + dir_name
        subject_images_names = os.listdir(subject_dir_path)
        for image_name in subject_images_names:
            if image_name.startswith("."):
                continue;
            image_path = subject_dir_path + "/" + image_name
            image = cv2.imread(image_path)
            cv2.imshow("Training on image...", cv2.resize(image, (400, 500)))
            cv2.waitKey(100)
            face, rect = detect_face(image)
            if face is not None:
                faces.append(face)
                labels.append(label)

    cv2.destroyAllWindows()
    cv2.waitKey(1)
    cv2.destroyAllWindows()
    return faces, labels
print("Preparing data...")
faces, labels = prepare_training_data("D://training-data/")
print("Data prepared")
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.train(faces, np.array(labels))
def draw_rectangle(img, rect):
    (x, y, w, h) = rect
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
def draw_text(img, text, x, y):
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
def predict(test_img):
    img = test_img.copy()
    face, rect = detect_face(img)
    label, confidence = face_recognizer.predict(face)
    label_text = subjects[label]
    draw_rectangle(img, rect)
    draw_text(img, label_text, rect[0], rect[1]-5)

    return img

print("Predicting images...")

img_path=glob.glob("D://test-data/*.jpg")
z=1
for i in img_path:
    predicted_img1 = predict(cv2.imread(i))
    cv2.imshow(subjects[z], cv2.resize(predicted_img1, (400, 500)))
    z=z+1
print("Prediction complete")
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()

我可以获取upload.py中使用的file_name并在final.py中使用它。当一个人选择一个文件(在这种情况下是一个图像)并点击上传按钮,然后我需要在我的final.py中训练的html中显示那个人的名字。

请帮帮我。谢谢。

1 个答案:

答案 0 :(得分:1)

几个月前我有同样的问题,这是答案:

出于安全原因,您永远无法从用户获取系统路径。 浏览器不允许这样做。

您只能获取具有图像名称,高度,宽度等的Image对象。

所以你可以做的是

  • 从用户那里获取图片,
  • 将其存储在文件夹名称&#34;静态&#34;,
  • 生成静态路径,以便稍后在您的应用中使用它。 (&#34; path / to / static / folder&#34; +&#34; image_name.jpg&#34;)

这是你完成这项工作的唯一方法。

检查一下:

@app.route('/home2', methods=['POST', 'GET'])
def home2():
    if request.method == 'POST':
        postdata = request.form
        file_name = postdata['filename']
        print("file name: ====================== {}".format(file_name))
        file = str(file_name)
        path = ".\\static\\" + file

确保表单中的html元素名称为&#34; filename&#34;