adpro commited on
Commit
b3652fb
·
verified ·
1 Parent(s): c30ce2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -46
app.py CHANGED
@@ -1,51 +1,40 @@
1
- from fastapi import FastAPI, UploadFile, File, Response
2
- import cv2
3
  import numpy as np
4
- import torch
5
- import torchvision.transforms as T
6
  from PIL import Image
7
- import io
 
8
 
9
  app = FastAPI()
10
 
11
- # Load AI Model MiDaS
12
- midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small")
13
- midas.eval()
14
- transform = T.Compose([
15
- T.Resize((256, 256)),
16
- T.ToTensor(),
17
- T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
18
- ])
19
-
20
- @app.post("/upload/")
21
- async def upload_image(file: UploadFile = File(...)):
22
- try:
23
- image_bytes = await file.read()
24
- print(f"📷 Ảnh nhận được ({len(image_bytes)} bytes)")
25
-
26
- image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
27
- print("✅ Ảnh mở thành công!")
28
- image = image.transpose(Image.FLIP_TOP_BOTTOM)
29
- image = image.transpose(Image.FLIP_LEFT_RIGHT)
30
- # Chuyển đổi ảnh sang tensor
31
- img_tensor = transform(image).unsqueeze(0)
32
- with torch.no_grad():
33
- depth_map = midas(img_tensor).squeeze().cpu().numpy()
34
-
35
- # Chuẩn hóa depth map
36
- depth_map = cv2.normalize(depth_map, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
37
- depth_resized = cv2.resize(depth_map, (160, 120))
38
-
39
- # hóa ảnh thành JPEG
40
- _, buffer = cv2.imencode(".jpg", depth_resized)
41
- print("✅ Depth Map đã được tạo!")
42
-
43
- return Response(content=buffer.tobytes(), media_type="image/jpeg") # 🟢 Trả ảnh trực tiếp
44
-
45
- except Exception as e:
46
- print("❌ Lỗi xử lý ảnh:", str(e))
47
- return {"error": str(e)}
48
-
49
- if __name__ == "__main__":
50
- import uvicorn
51
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import io
 
2
  import numpy as np
3
+ import cv2
4
+ from fastapi import FastAPI, File, UploadFile
5
  from PIL import Image
6
+ import torch
7
+ import torch.nn.functional as F
8
 
9
  app = FastAPI()
10
 
11
+ @app.post("/analyze_path/")
12
+ async def analyze_path(file: UploadFile = File(...)):
13
+ image_bytes = await file.read()
14
+ image = Image.open(io.BytesIO(image_bytes)).convert("L") # Convert to grayscale
15
+ depth_map = np.array(image)
16
+
17
+ # 🟢 Tìm đường đi bằng phẳng (vùng độ sâu ổn định)
18
+ command = detect_path(depth_map)
19
+
20
+ return {"command": command}
21
+
22
+ def detect_path(depth_map):
23
+ h, w = depth_map.shape
24
+ center_x = w // 2 # Điểm giữa ảnh
25
+ scan_y = h - 20 # Quét dòng gần cuối ảnh
26
+
27
+ left_region = np.mean(depth_map[scan_y, :center_x])
28
+ right_region = np.mean(depth_map[scan_y, center_x:])
29
+ center_region = np.mean(depth_map[scan_y, center_x - 20:center_x + 20])
30
+
31
+ # 🟢 Logic điều hướng dựa vào độ sâu
32
+ if center_region > 200: # Đường trước mặt rộng và không có vật cản
33
+ return "forward"
34
+ elif left_region > right_region: # Phía trái trống hơn
35
+ return "left"
36
+ elif right_region > left_region: # Phía phải trống hơn
37
+ return "right"
38
+ else:
39
+ return "backward" # Nếu tất cả đều bị cản, lùi lại
40
+