advancedskrald/web.py

52 lines
1.4 KiB
Python
Raw Permalink Normal View History

2019-04-25 14:00:04 +00:00
import base64
import cv2
import numpy as np
from flask import Flask, jsonify, request
from main import find_occupied_squares
from runner import find_homography, warp_board
from tensor_classifier import predict_board
2019-05-18 15:12:35 +00:00
from time import time
2019-04-25 14:00:04 +00:00
app = Flask(__name__)
@app.route("/", methods=["POST"])
def process():
2019-05-18 15:12:35 +00:00
print("Received request")
2019-04-25 14:00:04 +00:00
data = request.get_json(force=True)
decoded = base64.b64decode(data["img"])
img_array = np.frombuffer(decoded, dtype=np.uint8)
camera_img = cv2.imdecode(img_array, flags=cv2.COLOR_BGR2RGB)
camera_img = cv2.cvtColor(camera_img, cv2.COLOR_BGR2RGB)
# def do_everything:
2019-05-18 15:12:35 +00:00
start = time()
print("Finding keypoints")
homography = find_homography(camera_img, debug=True)
print("Computing homography")
2019-04-25 14:00:04 +00:00
warped_board = warp_board(camera_img, homography)
2019-05-18 15:12:35 +00:00
print("Warping board")
cv2.imwrite("warped.png", warped_board)
print("Removing empty squares")
2019-04-25 14:00:04 +00:00
occupied_squares = find_occupied_squares(warped_board)
2019-05-18 15:12:35 +00:00
print("Predicting board state")
2019-04-25 14:00:04 +00:00
board = predict_board(occupied_squares)
2019-05-18 15:12:35 +00:00
print(f"The request took {round(time() - start, 3)} seconds")
print("Returning board state")
2019-04-25 14:00:04 +00:00
# Finally, output for unity to read
return jsonify({
"homography": homography.tolist(),
"board": board.to_array,
2019-05-18 15:12:35 +00:00
})
2019-04-25 14:00:04 +00:00
def main():
app.run(host='0.0.0.0', debug=True)
if __name__ == '__main__':
main()