keysun89 commited on
Commit
fa8b1b9
·
verified ·
1 Parent(s): 517c099

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -34
app.py CHANGED
@@ -25,42 +25,16 @@ transform = transforms.Compose([
25
  ])
26
 
27
  def predict(image):
28
- # Preprocess
29
  orig_w, orig_h = image.size
30
- img = transform(image).unsqueeze(0) # shape [1,3,H,W] (float tensor)
31
-
32
  with torch.no_grad():
33
- pred = model(img) # shape: [1,C,H,W] where C>=1
34
-
35
- pred = pred.cpu() # move to cpu for numpy ops
36
-
37
- # If single-channel output (binary segmentation)
38
- if pred.shape[1] == 1:
39
- # Use sigmoid -> probability map -> binary mask
40
- prob = torch.sigmoid(pred) # [1,1,H,W]
41
- prob_np = prob.squeeze(0).squeeze(0).numpy() # [H,W]
42
- # optional: threshold (0.5) to binary mask
43
- mask = (prob_np >= 0.5).astype(np.uint8) * 255
44
-
45
- mask_img = Image.fromarray(mask).resize((orig_w, orig_h), Image.NEAREST)
46
- return mask_img.convert("L") # grayscale
47
-
48
- # If multi-channel output (C-class segmentation)
49
- else:
50
- # Convert logits to class map with argmax
51
- class_map = pred.argmax(dim=1).squeeze(0).numpy().astype(np.uint8) # [H,W], values 0..C-1
52
-
53
- # If you want a greyscale visualization: scale classes into 0..255
54
- if pred.shape[1] <= 256:
55
- # map class indices -> greyscale values (simple linear mapping)
56
- vis = (class_map.astype(np.float32) / (pred.shape[1]-1) * 255.0).astype(np.uint8)
57
- mask_img = Image.fromarray(vis).resize((orig_w, orig_h), Image.NEAREST)
58
- return mask_img.convert("L")
59
- else:
60
- # If >256 classes (rare), just return raw indices scaled modulo 256
61
- vis = (class_map % 256).astype(np.uint8)
62
- mask_img = Image.fromarray(vis).resize((orig_w, orig_h), Image.NEAREST)
63
- return mask_img.convert("L")
64
 
65
 
66
  # Gradio interface
 
25
  ])
26
 
27
  def predict(image):
 
28
  orig_w, orig_h = image.size
29
+ img = transform(image).unsqueeze(0).float()
 
30
  with torch.no_grad():
31
+ pred = model(img) # [1,7,H,W]
32
+ # convert to class map
33
+ class_map = pred.argmax(dim=1).squeeze(0).cpu().numpy().astype(np.uint8) # H,W
34
+ # if you want a binary crack mask from classes (treat class 0 as background)
35
+ binary_mask = (class_map != 0).astype(np.uint8) * 255
36
+ # return grayscale mask (or return class_map visual)
37
+ return Image.fromarray(binary_mask).resize((orig_w, orig_h), Image.NEAREST).convert("L")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
 
40
  # Gradio interface