Ss / app.py.bak
Forgets's picture
Rename app.py to app.py.bak
297ca32 verified
raw
history blame
1.32 kB
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):
# Robah ka grayscale
bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
# Template Matching
res = cv2.matchTemplate(bg_gray, target_gray, cv2.TM_CCOEFF_NORMED)
_, _, _, max_loc = cv2.minMaxLoc(res)
# max_loc[0] nyaeta koordinat X (jarak geser)
return max_loc[0]
@app.post("/solve")
async def solve(background: UploadFile = File(...), target: UploadFile = File(...)):
try:
# Baca gambar background
bg_bytes = await background.read()
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
# Baca gambar target (potongan puzzle)
target_bytes = await target.read()
target_img = cv2.imdecode(np.frombuffer(target_bytes, np.uint8), cv2.IMREAD_COLOR)
# Cari jarak
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)