from fastapi import FastAPI, UploadFile, File import cv2 import numpy as np import uvicorn app = FastAPI() def get_distance(bg_img, target_img): # 1. Preprocessing: Ubah ke Gray dan Blur untuk ngilangin noise bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY) target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY) # 2. Canny Edge Detection: Ini kuncinya! Kita cari garis tepi bg_edge = cv2.Canny(bg_gray, 100, 200) target_edge = cv2.Canny(target_gray, 100, 200) # 3. Template Matching pada hasil Edge Detection res = cv2.matchTemplate(bg_edge, target_edge, cv2.TM_CCOEFF_NORMED) _, _, _, max_loc = cv2.minMaxLoc(res) # max_loc[0] adalah koordinat X terbaik 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) # Eksekusi pencarian jarak 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)