前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
</head>
<body>
<h1>Image Upload</h1>
<input type="file" id="imageInput">
<button onclick="uploadImage()">Upload</button>
<script>
function uploadImage() {
const imageInput = document.getElementById('imageInput');
const file = imageInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const imageBase64 = event.target.result;
const data = {
image: imageBase64,
direction: 0
};
fetch('http://127.0.0.0:5000/slot_count', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error('Error:', error);
});
};
reader.readAsDataURL(file);
}
}
</script>
</body>
</html>
Python后端代码
import base64
from gevent import pywsgi
from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import cv2
import traceback
app = Flask(__name__)
CORS(app, resources=r'/*') # 跨域
app.config['JSON_AS_ASCII'] = False # 返回显示中文
@app.route('/', methods=['GET'])
def verify_connect():
return jsonify({'code': 200, 'msg': 'success', 'data': ["connection successful"]})
@app.route('/slot_count', methods=['POST'])
def predict():
ret = []
try:
data = request.json
direction = data['direction']
print(direction)
base64_image = data['image']
image_data = base64.b64decode(base64_image.split(',')[-1])
image = cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR)
print(image.shape)
cv2.imshow('img', image)
cv2.waitKey()
code = 200
msg = "success"
except ValueError as ve:
traceback.print_exc()
code = 400
msg = str(ve)
except Exception as e:
traceback.print_exc()
code = 500
msg = str(e)
result = {'code': code, 'msg': msg, 'data': ret}
return jsonify(result)
if __name__ == '__main__':
app.run('0.0.0.0', 5000, debug=True)
# server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
# server.serve_forever()