| from fastapi import FastAPI, UploadFile, File |
| import cv2 |
| import numpy as np |
| import uvicorn |
| from io import BytesIO |
| from PIL import Image |
|
|
| app = FastAPI() |
|
|
| def find_diff(bg_img, target_img): |
| |
| bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY) |
| target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY) |
| |
| |
| res = cv2.matchTemplate(bg_gray, target_gray, cv2.TM_CCOEFF_NORMED) |
| _, _, _, max_loc = cv2.minMaxLoc(res) |
| |
| |
| return max_loc[0] |
|
|
| @app.post("/solve") |
| async def solve(background: UploadFile = File(...), target: UploadFile = File(...)): |
| try: |
| |
| bg_bytes = await background.read() |
| bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR) |
| |
| |
| target_bytes = await target.read() |
| target_img = cv2.imdecode(np.frombuffer(target_bytes, np.uint8), cv2.IMREAD_COLOR) |
| |
| |
| distance = find_diff(bg_img, target_img) |
| |
| return {"status": "success", "distance": int(distance)} |
| except Exception as e: |
| return {"status": "error", "message": str(e)} |
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |