将所有文件保存在for循环中,而不仅仅是由for循环处理的最终文件

时间:2020-08-21 14:01:44

标签: python flask

我正在从图像中裁剪脸部并将其保存到带有时间戳的目录中以创建唯一的文件名。我遇到的问题是唯一保存的面孔是在for循环中处理的最终面孔。

在图像中找到了5张脸,但只保存了最后一张被裁剪的脸。

我确定我如何处理for循环和保存事件存在问题,但是,到目前为止,我似乎无法解决此问题。

@app.route("/CropFace", methods=["GET", "POST"])
def crop_face():
    if 'image' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['image']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER_CROP'], filename))
        # print('upload_image filename: ' + filename)
        flash('Face(s) Successfully Uploaded')
        # Crop faces using face_recognition
        uploaded_file = os.path.join(app.config['UPLOAD_FOLDER_CROP'], filename)
        crop_image = face_recognition.load_image_file(str(uploaded_file))
        face_locations = face_recognition.face_locations(crop_image)
        flash("Found {} face(s) in this Event Image".format(len(face_locations)))

# THIS IS THE SECTION I NEED TO RESOLVE THE SAVE ISSUE IN

        for face_location in face_locations:
            # Print the location of each face in this image
            top, right, bottom, left = face_location
            # You can access the actual face itself like this:
            face_image = crop_image[top:bottom, left:right]
            saved_face = Image.fromarray(face_image)
            timestr = time.strftime("%Y%m%d-%H%M%S")
            static_save = saved_face.save("static/nametag/" + timestr + ".jpg")

        flash(" Face Crop Successful, Awaiting NameTag.")
        return render_template('cropface.html', filename=filename)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)
    return render_template("cropface.html")

enter image description here

enter image description here

找到5张脸,但仅保存1张。

1 个答案:

答案 0 :(得分:0)

我不确定这是否是解决此问题的正确方法,但对我有用。

只需添加:

time.sleep(2)

在for循环结束时,为循环提供一个暂停,以保存每张面孔。

enter image description here