File size: 1,339 Bytes
b3652fb
02cc722
b3652fb
 
02cc722
b3652fb
 
02cc722
 
 
b3652fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import numpy as np
import cv2
from fastapi import FastAPI, File, UploadFile
from PIL import Image
import torch
import torch.nn.functional as F

app = FastAPI()

@app.post("/analyze_path/")
async def analyze_path(file: UploadFile = File(...)):
    image_bytes = await file.read()
    image = Image.open(io.BytesIO(image_bytes)).convert("L")  # Convert to grayscale
    depth_map = np.array(image)

    # 🟢 Tìm đường đi bằng phẳng (vùng có độ sâu ổn định)
    command = detect_path(depth_map)

    return {"command": command}

def detect_path(depth_map):
    h, w = depth_map.shape
    center_x = w // 2  # Điểm giữa ảnh
    scan_y = h - 20  # Quét dòng gần cuối ảnh

    left_region = np.mean(depth_map[scan_y, :center_x])
    right_region = np.mean(depth_map[scan_y, center_x:])
    center_region = np.mean(depth_map[scan_y, center_x - 20:center_x + 20])

    # 🟢 Logic điều hướng dựa vào độ sâu
    if center_region > 200:  # Đường trước mặt rộng và không có vật cản
        return "forward"
    elif left_region > right_region:  # Phía trái trống hơn
        return "left"
    elif right_region > left_region:  # Phía phải trống hơn
        return "right"
    else:
        return "backward"  # Nếu tất cả đều bị cản, lùi lại