File size: 1,553 Bytes
192052a
d98d85d
 
 
 
 
 
9289a22
 
d98d85d
 
 
9289a22
 
 
 
 
 
d98d85d
 
9289a22
05b0eb3
d98d85d
 
05b0eb3
d98d85d
05b0eb3
 
9289a22
 
05b0eb3
 
9289a22
 
05b0eb3
9289a22
 
 
 
 
d98d85d
 
 
 
9289a22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)