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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import gradio as gr
|
6 |
+
import segmentation_models_pytorch as smp
|
7 |
+
from PIL import Image
|
8 |
+
from glob import glob
|
9 |
+
from pipeline.ImgOutlier import detect_outliers
|
10 |
+
from pipeline.normalization import align_images
|
11 |
+
|
12 |
+
# 检测是否在Hugging Face环境中运行
|
13 |
+
HF_SPACE = os.environ.get('SPACE_ID') is not None
|
14 |
+
|
15 |
+
# 尝试导入上传模块,如果不在HF环境中才需要
|
16 |
+
if not HF_SPACE:
|
17 |
+
try:
|
18 |
+
from uploader.do_spaces import upload_mask
|
19 |
+
except ImportError:
|
20 |
+
def upload_mask(image, prefix=""):
|
21 |
+
return "上传模块未加载"
|
22 |
+
|
23 |
+
# Global Configuration
|
24 |
+
MODEL_PATHS = {
|
25 |
+
"Metal Marcy": "models/MM_best_model.pth",
|
26 |
+
"Silhouette Jaenette": "models/SJ_best_model.pth"
|
27 |
+
}
|
28 |
+
|
29 |
+
REFERENCE_VECTOR_PATHS = {
|
30 |
+
"Metal Marcy": "models/MM_mean.npy",
|
31 |
+
"Silhouette Jaenette": "models/SJ_mean.npy"
|
32 |
+
}
|
33 |
+
|
34 |
+
REFERENCE_IMAGE_DIRS = {
|
35 |
+
"Metal Marcy": "reference_images/MM",
|
36 |
+
"Silhouette Jaenette": "reference_images/SJ"
|
37 |
+
}
|
38 |
+
|
39 |
+
# Category names and color mapping
|
40 |
+
CLASSES = ['background', 'cobbles', 'drysand', 'plant', 'sky', 'water', 'wetsand']
|
41 |
+
COLORS = [
|
42 |
+
[0, 0, 0], # background - black
|
43 |
+
[139, 137, 137], # cobbles - dark gray
|
44 |
+
[255, 228, 181], # drysand - light yellow
|
45 |
+
[0, 128, 0], # plant - green
|
46 |
+
[135, 206, 235], # sky - sky blue
|
47 |
+
[0, 0, 255], # water - blue
|
48 |
+
[194, 178, 128] # wetsand - sand brown
|
49 |
+
]
|
50 |
+
|
51 |
+
# Load model function
|
52 |
+
def load_model(model_path, device="cuda"):
|
53 |
+
try:
|
54 |
+
# 如果在HF环境中,默认使用CPU
|
55 |
+
if HF_SPACE:
|
56 |
+
device = "cpu" # HF Space可能没有GPU
|
57 |
+
|
58 |
+
model = smp.create_model(
|
59 |
+
"DeepLabV3Plus",
|
60 |
+
encoder_name="efficientnet-b6",
|
61 |
+
in_channels=3,
|
62 |
+
classes=len(CLASSES),
|
63 |
+
encoder_weights=None
|
64 |
+
)
|
65 |
+
state_dict = torch.load(model_path, map_location=device)
|
66 |
+
if all(k.startswith('model.') for k in state_dict.keys()):
|
67 |
+
state_dict = {k[6:]: v for k, v in state_dict.items()}
|
68 |
+
model.load_state_dict(state_dict)
|
69 |
+
model.to(device)
|
70 |
+
model.eval()
|
71 |
+
print(f"Model load success: {model_path}")
|
72 |
+
return model
|
73 |
+
except Exception as e:
|
74 |
+
print(f"Model load fail: {e}")
|
75 |
+
return None
|
76 |
+
|
77 |
+
# Load reference vector
|
78 |
+
def load_reference_vector(vector_path):
|
79 |
+
try:
|
80 |
+
ref_vector = np.load(vector_path)
|
81 |
+
print(f"reference vector load success: {vector_path}")
|
82 |
+
return ref_vector
|
83 |
+
except Exception as e:
|
84 |
+
print(f"reference vector load {vector_path}: {e}")
|
85 |
+
return []
|
86 |
+
|
87 |
+
# Load reference image
|
88 |
+
def load_reference_images(ref_dir):
|
89 |
+
try:
|
90 |
+
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp']
|
91 |
+
image_files = []
|
92 |
+
for ext in image_extensions:
|
93 |
+
image_files.extend(glob(os.path.join(ref_dir, ext)))
|
94 |
+
image_files.sort()
|
95 |
+
reference_images = []
|
96 |
+
for file in image_files[:4]:
|
97 |
+
img = cv2.imread(file)
|
98 |
+
if img is not None:
|
99 |
+
reference_images.append(img)
|
100 |
+
print(f"from {ref_dir} load {len(reference_images)} images")
|
101 |
+
return reference_images
|
102 |
+
except Exception as e:
|
103 |
+
print(f"load image failed {ref_dir}: {e}")
|
104 |
+
return []
|
105 |
+
|
106 |
+
# Preprocess the image
|
107 |
+
def preprocess_image(image):
|
108 |
+
if image.shape[2] == 4:
|
109 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
|
110 |
+
orig_h, orig_w = image.shape[:2]
|
111 |
+
image_resized = cv2.resize(image, (1024, 1024))
|
112 |
+
image_norm = image_resized.astype(np.float32) / 255.0
|
113 |
+
mean = np.array([0.485, 0.456, 0.406])
|
114 |
+
std = np.array([0.229, 0.224, 0.225])
|
115 |
+
image_norm = (image_norm - mean) / std
|
116 |
+
image_tensor = torch.from_numpy(image_norm.transpose(2, 0, 1)).float().unsqueeze(0)
|
117 |
+
return image_tensor, orig_h, orig_w
|
118 |
+
|
119 |
+
# Generate segmentation map and visualization
|
120 |
+
def generate_segmentation_map(prediction, orig_h, orig_w):
|
121 |
+
mask = prediction.argmax(1).squeeze().cpu().numpy().astype(np.uint8)
|
122 |
+
mask_resized = cv2.resize(mask, (orig_w, orig_h), interpolation=cv2.INTER_NEAREST)
|
123 |
+
kernel = np.ones((5, 5), np.uint8)
|
124 |
+
processed_mask = mask_resized.copy()
|
125 |
+
for idx in range(1, len(CLASSES)):
|
126 |
+
class_mask = (mask_resized == idx).astype(np.uint8)
|
127 |
+
dilated_mask = cv2.dilate(class_mask, kernel, iterations=2)
|
128 |
+
dilated_effect = dilated_mask & (mask_resized == 0)
|
129 |
+
processed_mask[dilated_effect > 0] = idx
|
130 |
+
segmentation_map = np.zeros((orig_h, orig_w, 3), dtype=np.uint8)
|
131 |
+
for idx, color in enumerate(COLORS):
|
132 |
+
segmentation_map[processed_mask == idx] = color
|
133 |
+
return segmentation_map
|
134 |
+
|
135 |
+
# Analysis result HTML
|
136 |
+
def create_analysis_result(mask):
|
137 |
+
total_pixels = mask.size
|
138 |
+
percentages = {cls: round((np.sum(mask == i) / total_pixels) * 100, 1)
|
139 |
+
for i, cls in enumerate(CLASSES)}
|
140 |
+
ordered = ['sky', 'cobbles', 'plant', 'drysand', 'wetsand', 'water']
|
141 |
+
result = "<div style='font-size:18px;font-weight:bold;'>"
|
142 |
+
result += " | ".join(f"{cls}: {percentages.get(cls,0)}%" for cls in ordered)
|
143 |
+
result += "</div>"
|
144 |
+
return result
|
145 |
+
|
146 |
+
# Merge and overlay
|
147 |
+
def create_overlay(image, segmentation_map, alpha=0.5):
|
148 |
+
if image.shape[:2] != segmentation_map.shape[:2]:
|
149 |
+
segmentation_map = cv2.resize(segmentation_map, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST)
|
150 |
+
return cv2.addWeighted(image, 1-alpha, segmentation_map, alpha, 0)
|
151 |
+
|
152 |
+
# Perform segmentation
|
153 |
+
def perform_segmentation(model, image_bgr):
|
154 |
+
device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
|
155 |
+
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
156 |
+
image_tensor, orig_h, orig_w = preprocess_image(image_rgb)
|
157 |
+
with torch.no_grad():
|
158 |
+
prediction = model(image_tensor.to(device))
|
159 |
+
seg_map = generate_segmentation_map(prediction, orig_h, orig_w) # RGB
|
160 |
+
overlay = create_overlay(image_rgb, seg_map)
|
161 |
+
mask = prediction.argmax(1).squeeze().cpu().numpy()
|
162 |
+
analysis = create_analysis_result(mask)
|
163 |
+
return seg_map, overlay, analysis
|
164 |
+
|
165 |
+
# Single image processing
|
166 |
+
def process_coastal_image(location, input_image):
|
167 |
+
if input_image is None:
|
168 |
+
return None, None, "请上传一张图片", "未检测", None
|
169 |
+
|
170 |
+
device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
|
171 |
+
model = load_model(MODEL_PATHS[location], device)
|
172 |
+
|
173 |
+
if model is None:
|
174 |
+
return None, None, f"错误:无法加载模型", "未检测", None
|
175 |
+
|
176 |
+
ref_vector = load_reference_vector(REFERENCE_VECTOR_PATHS[location]) if os.path.exists(REFERENCE_VECTOR_PATHS[location]) else []
|
177 |
+
ref_images = load_reference_images(REFERENCE_IMAGE_DIRS[location])
|
178 |
+
|
179 |
+
outlier_status = "未检测"
|
180 |
+
is_outlier = False
|
181 |
+
image_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
|
182 |
+
|
183 |
+
if len(ref_vector) > 0:
|
184 |
+
filtered, _ = detect_outliers(ref_images, [image_bgr], ref_vector)
|
185 |
+
is_outlier = len(filtered) == 0
|
186 |
+
else:
|
187 |
+
filtered, _ = detect_outliers(ref_images, [image_bgr])
|
188 |
+
is_outlier = len(filtered) == 0
|
189 |
+
|
190 |
+
outlier_status = "异常检测: <span style='color:red;font-weight:bold'>未通过</span>" if is_outlier else "异常检测: <span style='color:green;font-weight:bold'>通过</span>"
|
191 |
+
seg_map, overlay, analysis = perform_segmentation(model, image_bgr)
|
192 |
+
|
193 |
+
# 在HF环境中不上传,只返回本地结果
|
194 |
+
url = "本地存储"
|
195 |
+
if not HF_SPACE:
|
196 |
+
try:
|
197 |
+
url = upload_mask(Image.fromarray(seg_map), prefix=location.replace(' ', '_'))
|
198 |
+
except Exception as e:
|
199 |
+
print(f"Upload failed: {e}")
|
200 |
+
url = "上传错误"
|
201 |
+
|
202 |
+
if is_outlier:
|
203 |
+
analysis = "<div style='color:red;font-weight:bold;margin-bottom:10px'>警告:图像未通过异常检测,结果可能不准确!</div>" + analysis
|
204 |
+
|
205 |
+
return seg_map, overlay, analysis, outlier_status, url
|
206 |
+
|
207 |
+
# Spacial Alignment
|
208 |
+
def process_with_alignment(location, reference_image, input_image):
|
209 |
+
if reference_image is None or input_image is None:
|
210 |
+
return None, None, None, None, "请上传参考图像和需要分析的图像", "未处理", None
|
211 |
+
|
212 |
+
device = "cuda" if torch.cuda.is_available() and not HF_SPACE else "cpu"
|
213 |
+
model = load_model(MODEL_PATHS[location], device)
|
214 |
+
|
215 |
+
if model is None:
|
216 |
+
return None, None, None, None, "错误:无法加载模型", "未处理", None
|
217 |
+
|
218 |
+
ref_bgr = cv2.cvtColor(np.array(reference_image), cv2.COLOR_RGB2BGR)
|
219 |
+
tgt_bgr = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
|
220 |
+
|
221 |
+
aligned, _ = align_images([ref_bgr, tgt_bgr], [np.zeros_like(ref_bgr), np.zeros_like(tgt_bgr)])
|
222 |
+
aligned_tgt_bgr = aligned[1]
|
223 |
+
|
224 |
+
seg_map, overlay, analysis = perform_segmentation(model, aligned_tgt_bgr)
|
225 |
+
|
226 |
+
# 在HF环境中不上传,只返回本地结果
|
227 |
+
url = "本地存储"
|
228 |
+
if not HF_SPACE:
|
229 |
+
try:
|
230 |
+
url = upload_mask(Image.fromarray(seg_map), prefix="aligned_" + location.replace(' ', '_'))
|
231 |
+
except Exception as e:
|
232 |
+
print(f"Upload failed: {e}")
|
233 |
+
url = "上传错误"
|
234 |
+
|
235 |
+
status = "空间对齐: <span style='color:green;font-weight:bold'>完成</span>"
|
236 |
+
ref_rgb = cv2.cvtColor(ref_bgr, cv2.COLOR_BGR2RGB)
|
237 |
+
aligned_tgt_rgb = cv2.cvtColor(aligned_tgt_bgr, cv2.COLOR_BGR2RGB)
|
238 |
+
|
239 |
+
return ref_rgb, aligned_tgt_rgb, seg_map, overlay, analysis, status, url
|
240 |
+
|
241 |
+
# Create the Gradio interface
|
242 |
+
def create_interface():
|
243 |
+
scale = 0.5
|
244 |
+
disp_w, disp_h = int(1365*scale), int(1024*scale)
|
245 |
+
with gr.Blocks(title="海岸侵蚀分析系统") as demo:
|
246 |
+
gr.Markdown("""# 海岸侵蚀分析系统
|
247 |
+
|
248 |
+
上传海岸照片进行分析,包括分割和空间对齐功能。""")
|
249 |
+
with gr.Tabs():
|
250 |
+
with gr.TabItem("单张图像分割"):
|
251 |
+
with gr.Row():
|
252 |
+
loc1 = gr.Radio(list(MODEL_PATHS.keys()), label="选择模型", value=list(MODEL_PATHS.keys())[0])
|
253 |
+
with gr.Row():
|
254 |
+
inp = gr.Image(label="输入图像", type="numpy", image_mode="RGB")
|
255 |
+
seg = gr.Image(label="分割图像", type="numpy", width=disp_w, height=disp_h)
|
256 |
+
ovl = gr.Image(label="叠加图像", type="numpy", width=disp_w, height=disp_h)
|
257 |
+
with gr.Row():
|
258 |
+
btn1 = gr.Button("执行分割")
|
259 |
+
url1 = gr.Text(label="分割图URL")
|
260 |
+
status1 = gr.HTML(label="异常检测状态")
|
261 |
+
res1 = gr.HTML(label="分析结果")
|
262 |
+
btn1.click(fn=process_coastal_image,inputs=[loc1, inp],outputs=[seg, ovl, res1, status1, url1])
|
263 |
+
|
264 |
+
with gr.TabItem("空间对齐分割"):
|
265 |
+
with gr.Row():
|
266 |
+
loc2 = gr.Radio(list(MODEL_PATHS.keys()), label="选择模型", value=list(MODEL_PATHS.keys())[0])
|
267 |
+
with gr.Row():
|
268 |
+
ref_img = gr.Image(label="参考图像", type="numpy", image_mode="RGB")
|
269 |
+
tgt_img = gr.Image(label="待分析图像", type="numpy", image_mode="RGB")
|
270 |
+
with gr.Row():
|
271 |
+
btn2 = gr.Button("执行空间对齐分割")
|
272 |
+
with gr.Row():
|
273 |
+
orig = gr.Image(label="原始图像", type="numpy", width=disp_w, height=disp_h)
|
274 |
+
aligned = gr.Image(label="对齐后图像", type="numpy", width=disp_w, height=disp_h)
|
275 |
+
with gr.Row():
|
276 |
+
seg2 = gr.Image(label="分割图像", type="numpy", width=disp_w, height=disp_h)
|
277 |
+
ovl2 = gr.Image(label="叠加图像", type="numpy", width=disp_w, height=disp_h)
|
278 |
+
url2 = gr.Text(label="分割图URL")
|
279 |
+
status2 = gr.HTML(label="空间对齐状态")
|
280 |
+
res2 = gr.HTML(label="分析结果")
|
281 |
+
btn2.click(fn=process_with_alignment, inputs=[loc2, ref_img, tgt_img], outputs=[orig, aligned, seg2, ovl2, res2, status2, url2])
|
282 |
+
return demo
|
283 |
+
|
284 |
+
if __name__ == "__main__":
|
285 |
+
for path in ["models", "reference_images/MM", "reference_images/SJ"]:
|
286 |
+
os.makedirs(path, exist_ok=True)
|
287 |
+
for p in MODEL_PATHS.values():
|
288 |
+
if not os.path.exists(p):
|
289 |
+
print(f"警告:模型文件 {p} 不存在!")
|
290 |
+
demo = create_interface()
|
291 |
+
# 在HF环境中使用适当的启动配置
|
292 |
+
if HF_SPACE:
|
293 |
+
demo.launch()
|
294 |
+
else:
|
295 |
+
demo.launch(share=True)
|