This time, we will create an image recognition application that uses Vue.js for the front end and Flask for the back end. For the time being, this time we will implement the image upload function.
The environment was built in the above environment. See the links below for instructions and details.
Vue The following code explains the details.
Home.vue
//Upload image to server
onUploadImage () {
var params = new FormData()
params.append('image', this.uploadedImage)
//I am posting the data converted to FormData using Axios to Flask.
axios.post(`${API_URL}/classification`, params).then(function (response) {
console.log(response)
})
Flask
The following code explains the details.
app.py
@app.route('/classification', methods=['POST'])
def uploadImage():
if request.method == 'POST':
base64_png = request.form['image']
code = base64.b64decode(base64_png.split(',')[1])
image_decoded = Image.open(BytesIO(code))
image_decoded.save(Path(app.config['UPLOAD_FOLDER']) / 'image.png')
return make_response(jsonify({'result': 'success'}))
else:
return make_response(jsonify({'result': 'invalid method'}), 400)
Vue
Home.vue
<template>
<div>
<div class="imgContent">
<div class="imagePreview">
<img :src="uploadedImage" style="width:100%;" />
</div>
<input type="file" class="file_input" name="photo" @change="onFileChange" accept="image/*" />
<button @click='onUploadImage'>Please judge the image ...</button>
</div>
</div>
</template>
<script>
import axios from 'axios'
const API_URL = 'http://127.0.0.1:5000'
export default {
data () {
return {
uploadedImage: ''
}
},
methods: {
//Reflect the selected image
onFileChange (e) {
let files = e.target.files || e.dataTransfer.files
this.createImage(files[0])
},
//View uploaded image
createImage (file) {
let reader = new FileReader()
reader.onload = (e) => {
this.uploadedImage = e.target.result
}
reader.readAsDataURL(file)
},
//Upload image to server
onUploadImage () {
var params = new FormData()
params.append('image', this.uploadedImage)
//I am posting the data converted to FormData using Axios to Flask.
axios.post(`${API_URL}/classification`, params).then(function (response) {
console.log(response)
})
}
}
}
</script>
Flask
--CORS allows resources to be shared by different origins (protocols, domains, ports). --CORS is required if you have different web applications. --Japanese is supported by app.config ['JSON_AS_ASCII'] = False.
app.py
# render_template: Specify the template to refer to
#jsonify: json output
from flask import Flask, render_template, jsonify, request, make_response
#CORS: Library for Ajax communication
from flask_restful import Api, Resource
from flask_cors import CORS
from random import *
from PIL import Image
from pathlib import Path
from io import BytesIO
import base64
# static_folder: Specify the path of the static file built with vue
# template_folder: index built with vue.Specify html path
app = Flask(__name__, static_folder = "./../frontend/dist/static", template_folder="./../frontend/dist")
#Japanese
app.config['JSON_AS_ASCII'] = False
#CORS=Terms for secure communication with Ajax
api = Api(app)
CORS(app)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#Index when receiving any request.See html
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
return render_template("index.html")
@app.route('/classification', methods=['POST'])
def uploadImage():
if request.method == 'POST':
base64_png = request.form['image']
code = base64.b64decode(base64_png.split(',')[1])
image_decoded = Image.open(BytesIO(code))
image_decoded.save(Path(app.config['UPLOAD_FOLDER']) / 'image.png')
return make_response(jsonify({'result': 'success'}))
else:
return make_response(jsonify({'result': 'invalid method'}), 400)
# app.run(host, port): Start flask server by specifying host and port
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Like this
https://developer.mozilla.org/ja/docs/Web/HTTP/CORS POST image, face detection, draw on face with canvas
Recommended Posts