| from fastapi import FastAPI, UploadFile, File |
| import cv2 |
| import numpy as np |
| import uvicorn |
|
|
| app = FastAPI() |
|
|
| def get_distance(bg_img, target_img): |
| |
| bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY) |
| target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY) |
| |
| |
| bg_edge = cv2.Canny(bg_gray, 100, 200) |
| target_edge = cv2.Canny(target_gray, 100, 200) |
| |
| |
| res = cv2.matchTemplate(bg_edge, target_edge, 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() |
| target_bytes = await target.read() |
| |
| bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR) |
| target_img = cv2.imdecode(np.frombuffer(target_bytes, np.uint8), cv2.IMREAD_COLOR) |
| |
| |
| distance = get_distance(bg_img, target_img) |
| |
| return { |
| "status": "success", |
| "distance": int(distance), |
| "info": "Edge detection applied for maximum accuracy" |
| } |
| except Exception as e: |
| return {"status": "error", "message": str(e)} |
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|