midas / app.py
adpro's picture
Update app.py
b3652fb verified
raw
history blame
1.34 kB
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