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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from transformers import SegformerForSemanticSegmentation
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# 1. SETUP & MODEL LOADING
|
| 11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
+
|
| 13 |
+
model = SegformerForSemanticSegmentation.from_pretrained(
|
| 14 |
+
"nvidia/mit-b2",
|
| 15 |
+
num_labels=4,
|
| 16 |
+
id2label={0: "Soil", 1: "Bedrock", 2: "Sand", 3: "Big Rock"},
|
| 17 |
+
label2id={"Soil": 0, "Bedrock": 1, "Sand": 2, "Big Rock": 3},
|
| 18 |
+
ignore_mismatched_sizes=True
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Load your Stirling weights (Must be in the same folder as app.py)
|
| 22 |
+
try:
|
| 23 |
+
checkpoint = torch.load('SegFormer_B2_Final_Stirling_3456526.pth', map_location=device)
|
| 24 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
| 25 |
+
print("Model Weights Loaded Successfully")
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"⚠️ Weights missing or error: {e}. Running with base weights.")
|
| 28 |
+
|
| 29 |
+
model.to(device).eval()
|
| 30 |
+
|
| 31 |
+
# 2. COLOR MAP (Brightened for visibility)
|
| 32 |
+
COLOR_MAP = {
|
| 33 |
+
0: [0, 255, 0], # Soil (Neon Green) - UPDATED
|
| 34 |
+
1: [0, 0, 255], # Bedrock (Electric Blue) - UPDATED
|
| 35 |
+
2: [255, 215, 0], # Sand (Yellow)
|
| 36 |
+
3: [255, 0, 0], # Big Rock (Red)
|
| 37 |
+
-1: [0, 0, 0]
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
def apply_mask_safe(preds, folder, img_path, suffix, w, h):
|
| 41 |
+
"""
|
| 42 |
+
Finds the mask by searching for the 9-digit SCLK ID inside the folder,
|
| 43 |
+
ignoring 'EDR', 'NLA', or other naming variations.
|
| 44 |
+
"""
|
| 45 |
+
filename = os.path.basename(img_path)
|
| 46 |
+
|
| 47 |
+
# 1. Extract the 9-digit numeric ID (SCLK)
|
| 48 |
+
# Example: NLA_601686301EDR... -> 601686301
|
| 49 |
+
import re
|
| 50 |
+
match = re.search(r'\d{9}', filename)
|
| 51 |
+
if not match:
|
| 52 |
+
print(f"❌ Could not find a 9-digit ID in {filename}")
|
| 53 |
+
return preds
|
| 54 |
+
|
| 55 |
+
seq_id = match.group(0)
|
| 56 |
+
print(f"DEBUG: Searching for ID {seq_id} in {folder}...")
|
| 57 |
+
|
| 58 |
+
# 2. Search the folder for a file containing this ID and the suffix (mxy/rng)
|
| 59 |
+
target_file = None
|
| 60 |
+
if os.path.exists(folder):
|
| 61 |
+
for f in os.listdir(folder):
|
| 62 |
+
# Check if the 9-digit ID is in the filename AND it's a .png
|
| 63 |
+
if seq_id in f and f.lower().endswith('.png'):
|
| 64 |
+
# Also check if it matches the specific suffix if needed
|
| 65 |
+
if suffix in f.lower():
|
| 66 |
+
target_file = f
|
| 67 |
+
break
|
| 68 |
+
|
| 69 |
+
# 3. Apply if found
|
| 70 |
+
if target_file:
|
| 71 |
+
path = os.path.join(folder, target_file)
|
| 72 |
+
mask = Image.open(path).convert('L').resize((w, h), Image.NEAREST)
|
| 73 |
+
mask_np = np.array(mask)
|
| 74 |
+
preds[mask_np > 0] = -1
|
| 75 |
+
print(f"✅ SUCCESS: Applied mask from {target_file}")
|
| 76 |
+
else:
|
| 77 |
+
print(f"❌ FAIL: No mask for ID {seq_id} found in {folder}")
|
| 78 |
+
|
| 79 |
+
return preds
|
| 80 |
+
|
| 81 |
+
def segment_mars(img_path):
|
| 82 |
+
if not img_path: return None
|
| 83 |
+
|
| 84 |
+
# 1. Load Image
|
| 85 |
+
raw_img = Image.open(img_path).convert('RGB')
|
| 86 |
+
orig_w, orig_h = raw_img.size
|
| 87 |
+
|
| 88 |
+
# 2. Inference (SegFormer)
|
| 89 |
+
preprocess = transforms.Compose([
|
| 90 |
+
transforms.Resize((256, 256)),
|
| 91 |
+
transforms.ToTensor(),
|
| 92 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 93 |
+
])
|
| 94 |
+
input_tensor = preprocess(raw_img).unsqueeze(0).to(device)
|
| 95 |
+
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
outputs = model(pixel_values=input_tensor)
|
| 98 |
+
logits = F.interpolate(outputs.logits, size=(orig_h, orig_w), mode='bilinear')
|
| 99 |
+
probs = F.softmax(logits, dim=1)
|
| 100 |
+
confidences, preds = torch.max(probs, dim=1)
|
| 101 |
+
preds = preds.squeeze().cpu().numpy()
|
| 102 |
+
|
| 103 |
+
# 3. DIRECT FILENAME SWAP (EDR -> MXY / EDR -> RNG)
|
| 104 |
+
filename = os.path.basename(img_path)
|
| 105 |
+
|
| 106 |
+
# Generate mask names by replacing 'EDR' with 'MXY' or 'RNG'
|
| 107 |
+
# and changing extension to .png
|
| 108 |
+
mxy_filename = filename.replace("EDR", "MXY").replace(".JPG", ".png").replace(".jpg", ".png")
|
| 109 |
+
rng_filename = filename.replace("EDR", "RNG").replace(".JPG", ".png").replace(".jpg", ".png")
|
| 110 |
+
|
| 111 |
+
mxy_path = os.path.join("stirling_masks_bundle", "rover_mxy", mxy_filename)
|
| 112 |
+
rng_path = os.path.join("stirling_masks_bundle", "range_rng", rng_filename)
|
| 113 |
+
|
| 114 |
+
# Apply MXY Mask
|
| 115 |
+
if os.path.exists(mxy_path):
|
| 116 |
+
mxy = Image.open(mxy_path).convert('L').resize((orig_w, orig_h), Image.NEAREST)
|
| 117 |
+
preds[np.array(mxy) > 0] = -1
|
| 118 |
+
|
| 119 |
+
else:
|
| 120 |
+
print(f"❌ MXY Not Found: {mxy_path}")
|
| 121 |
+
|
| 122 |
+
# Apply RNG Mask
|
| 123 |
+
if os.path.exists(rng_path):
|
| 124 |
+
rng = Image.open(rng_path).convert('L').resize((orig_w, orig_h), Image.NEAREST)
|
| 125 |
+
preds[np.array(rng) > 0] = -1
|
| 126 |
+
else:
|
| 127 |
+
print(f"❌ RNG Not Found: {rng_path}")
|
| 128 |
+
|
| 129 |
+
# 4. OVERLAY
|
| 130 |
+
mask_rgb = np.zeros((orig_h, orig_w, 3), dtype=np.uint8)
|
| 131 |
+
for cls_id, color in COLOR_MAP.items():
|
| 132 |
+
mask_rgb[preds == cls_id] = color
|
| 133 |
+
|
| 134 |
+
overlay = (np.array(raw_img) * 0.5 + mask_rgb * 0.5).astype(np.uint8)
|
| 135 |
+
return Image.fromarray(overlay)
|
| 136 |
+
|
| 137 |
+
# 3. CUSTOM HTML LEGEND
|
| 138 |
+
legend_html = """
|
| 139 |
+
<div style="display: flex; justify-content: center; gap: 20px; font-weight: bold; margin-bottom: 10px;">
|
| 140 |
+
<div style="display: flex; align-items: center; gap: 5px;">
|
| 141 |
+
<div style="width: 20px; height: 20px; background-color: rgb(0, 255, 0); border: 1px solid white;"></div> <span>Soil</span>
|
| 142 |
+
</div>
|
| 143 |
+
<div style="display: flex; align-items: center; gap: 5px;">
|
| 144 |
+
<div style="width: 20px; height: 20px; background-color: rgb(0, 0, 255); border: 1px solid white;"></div> <span>Bedrock</span>
|
| 145 |
+
</div>
|
| 146 |
+
<div style="display: flex; align-items: center; gap: 5px;">
|
| 147 |
+
<div style="width: 20px; height: 20px; background-color: rgb(255, 215, 0); border: 1px solid white;"></div> <span>Sand</span>
|
| 148 |
+
</div>
|
| 149 |
+
<div style="display: flex; align-items: center; gap: 5px;">
|
| 150 |
+
<div style="width: 20px; height: 20px; background-color: rgb(255, 0, 0); border: 1px solid white;"></div> <span>Big Rock</span>
|
| 151 |
+
</div>
|
| 152 |
+
<div style="display: flex; align-items: center; gap: 5px;">
|
| 153 |
+
<div style="width: 20px; height: 20px; background-color: rgb(0, 0, 0); border: 1px solid white;"></div> <span>Rover / Background Mask</span>
|
| 154 |
+
</div>
|
| 155 |
+
</div>
|
| 156 |
+
"""
|
| 157 |
+
# 3. GRADIO INTERFACE
|
| 158 |
+
with gr.Blocks() as demo:
|
| 159 |
+
gr.Markdown(f"## NASA AI4Mars Expert Fused Classifier")
|
| 160 |
+
gr.HTML(legend_html)
|
| 161 |
+
with gr.Row():
|
| 162 |
+
img_input = gr.Image(type="filepath", label="Input Martian Image",interactive=False)
|
| 163 |
+
img_output = gr.Image(type="pil", label="Fused Ground Truth Prediction")
|
| 164 |
+
|
| 165 |
+
btn = gr.Button("Execute Data Fusion Segmentation")
|
| 166 |
+
btn.click(segment_mars, inputs=img_input, outputs=img_output)
|
| 167 |
+
|
| 168 |
+
gr.Examples(
|
| 169 |
+
examples=[
|
| 170 |
+
["NLA_601686301EDR_F0732112NCAM00353M1.JPG"],
|
| 171 |
+
["NLB_436292094EDR_F0211028NCAM00257M1.JPG"],
|
| 172 |
+
["NLB_486005519EDR_F0481570NCAM07813M1.JPG"],
|
| 173 |
+
["NLB_519658137EDR_F0550000NCAM00654M1.JPG"],
|
| 174 |
+
["NLB_541230242EDR_F0611140NCAM07753M1.JPG"],
|
| 175 |
+
["NLB_621571338EDR_F0763002NCAM00207M1.JPG"]
|
| 176 |
+
],
|
| 177 |
+
inputs=img_input
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
demo.launch(share=True)
|