mediaportal commited on
Commit
9a44f00
Β·
verified Β·
1 Parent(s): be006dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -33
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
- # Force Keras 2 logic to prevent 'recursion depth' and 'quantization' errors
 
3
  os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
 
5
  import gradio as gr
@@ -11,83 +12,82 @@ from PIL import Image
11
  from huggingface_hub import hf_hub_download
12
 
13
  # --- CONFIGURATION ---
14
- # Replace with your actual Repo ID for the Road Segmentation Space
15
- REPO_ID = "mediaportal/Braintumor-MRI-detection" # Update this to your road repo if different
16
  MODEL_FILENAME = "trained_model_33_cpu.h5"
17
 
 
18
  hf_token = os.getenv("HF_TOKEN")
19
  model = None
20
 
21
  def load_model():
22
  global model
23
  try:
24
- # Download the .h5 file
25
  path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, token=hf_token)
26
 
27
- # Load the model using the Classic Keras engine
28
- # compile=False is critical because segmentation models often use custom Dice/IoU losses
 
29
  model = keras.models.load_model(path, compile=False)
30
- return "βœ… Segmentation Model Ready"
31
  except Exception as e:
32
  return f"❌ Error: {str(e)}"
33
 
34
- def segment_road(img):
35
  if model is None:
36
  return None
37
 
38
- # 1. Store original dimensions to resize the mask back later
39
  h, w = img.shape[:2]
40
 
41
- # 2. Preprocessing: Resize to 256x256 (standard for BDD100K CPU-optimized models)
42
- img_resized = cv2.resize(img, (256, 256))
 
 
 
43
  img_array = img_resized.astype('float32') / 255.0
44
  img_array = np.expand_dims(img_array, axis=0)
45
 
46
- # 3. Predict the Road Mask
47
  prediction = model.predict(img_array)[0]
48
 
49
- # 4. Post-processing
50
- # The model outputs probabilities. We threshold at 0.5 to get a binary mask.
51
  mask = (prediction > 0.5).astype(np.uint8) * 255
52
-
53
- # If the mask has a channel dimension (256, 256, 1), remove it
54
  if len(mask.shape) == 3:
55
  mask = np.squeeze(mask, axis=-1)
56
 
57
- # Resize the binary mask back to the original image size
58
  mask_full = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
59
 
60
- # 5. Create the Visual Overlay (Transparent Green)
 
61
  overlay = img.copy()
62
- # Apply green color (BGR: 0, 255, 0) where the mask is positive
63
- overlay[mask_full > 0] = [0, 255, 0]
64
 
65
- # Blend the original image with the green overlay
66
- # 0.6 is original visibility, 0.4 is mask visibility
67
- combined = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
68
 
69
- return combined
70
 
71
  # --- GRADIO INTERFACE ---
72
-
73
-
74
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
75
- gr.Markdown("# πŸš— BDD100K Road Surface Segmentation")
76
- gr.Markdown("Upload a dashboard camera image to highlight the drivable road area.")
77
 
78
  status = gr.Markdown("⏳ Initializing system...")
79
 
80
  with gr.Row():
81
- input_img = gr.Image(label="Original Image", type="numpy")
82
- output_img = gr.Image(label="Segmented Result (Green Overlay)")
83
 
84
  btn = gr.Button("Analyze Road", variant="primary")
85
 
86
- # Load model on startup
87
  demo.load(load_model, outputs=status)
88
 
89
- # Trigger segmentation on button click
90
- btn.click(fn=segment_road, inputs=input_img, outputs=output_img)
91
 
92
  if __name__ == "__main__":
93
  demo.queue().launch()
 
1
  import os
2
+ # Force Keras 2 logic to prevent the 'recursion depth' and 'quantization' errors
3
+ # common when loading Kaggle-trained .h5 files in new environments.
4
  os.environ["TF_USE_LEGACY_KERAS"] = "1"
5
 
6
  import gradio as gr
 
12
  from huggingface_hub import hf_hub_download
13
 
14
  # --- CONFIGURATION ---
15
+ REPO_ID = "mediaportal/Roadsegmentation"
 
16
  MODEL_FILENAME = "trained_model_33_cpu.h5"
17
 
18
+ # If your repo is PRIVATE, add your token to Space Secrets as 'HF_TOKEN'
19
  hf_token = os.getenv("HF_TOKEN")
20
  model = None
21
 
22
  def load_model():
23
  global model
24
  try:
25
+ # Download the model file
26
  path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, token=hf_token)
27
 
28
+ # Load using the Classic Keras engine
29
+ # compile=False is required because segmentation models often use
30
+ # custom Loss functions (like IoU or Dice) that are hard to reload.
31
  model = keras.models.load_model(path, compile=False)
32
+ return "βœ… Road Segmentation Model Loaded"
33
  except Exception as e:
34
  return f"❌ Error: {str(e)}"
35
 
36
+ def predict_segmentation(img):
37
  if model is None:
38
  return None
39
 
40
+ # 1. Store original dimensions
41
  h, w = img.shape[:2]
42
 
43
+ # 2. Preprocessing
44
+ # BDD100K segmentation models typically use 256x256 or 512x512.
45
+ # We resize to 256x256 based on common CPU-optimized configurations.
46
+ input_size = (256, 256)
47
+ img_resized = cv2.resize(img, input_size)
48
  img_array = img_resized.astype('float32') / 255.0
49
  img_array = np.expand_dims(img_array, axis=0)
50
 
51
+ # 3. Predict the Mask
52
  prediction = model.predict(img_array)[0]
53
 
54
+ # 4. Process the Mask
55
+ # The output is a probability map. Threshold at 0.5 to get binary road/not-road.
56
  mask = (prediction > 0.5).astype(np.uint8) * 255
 
 
57
  if len(mask.shape) == 3:
58
  mask = np.squeeze(mask, axis=-1)
59
 
60
+ # Resize mask back to original image size
61
  mask_full = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
62
 
63
+ # 5. Create the Green Overlay
64
+ # We create a green version of the original image
65
  overlay = img.copy()
66
+ overlay[mask_full > 0] = [0, 255, 0] # Apply green color (RGB)
 
67
 
68
+ # Blend original and green overlay (0.6 original + 0.4 green)
69
+ output = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
 
70
 
71
+ return output
72
 
73
  # --- GRADIO INTERFACE ---
 
 
74
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
75
+ gr.Markdown("# πŸš— ADAS: Road Surface Segmentation")
76
+ gr.Markdown("Upload a dashboard camera image to visualize the drivable road area detection.")
77
 
78
  status = gr.Markdown("⏳ Initializing system...")
79
 
80
  with gr.Row():
81
+ input_img = gr.Image(label="Original View", type="numpy")
82
+ output_img = gr.Image(label="Detected Road (Green Overlay)")
83
 
84
  btn = gr.Button("Analyze Road", variant="primary")
85
 
86
+ # Automatically load model on start
87
  demo.load(load_model, outputs=status)
88
 
89
+ # Connect button to prediction
90
+ btn.click(fn=predict_segmentation, inputs=input_img, outputs=output_img)
91
 
92
  if __name__ == "__main__":
93
  demo.queue().launch()