petergpt commited on
Commit
efae294
·
verified ·
1 Parent(s): b26217f

added logging

Browse files
Files changed (1) hide show
  1. app.py +61 -53
app.py CHANGED
@@ -11,6 +11,7 @@ import gdown
11
  import matplotlib.pyplot as plt
12
  import warnings
13
  warnings.filterwarnings("ignore")
 
14
 
15
  os.system("git clone https://github.com/xuebinqin/DIS")
16
  os.system("mv DIS/IS-Net/* .")
@@ -39,7 +40,6 @@ class GOSNormalize(object):
39
  image = normalize(image,self.mean,self.std)
40
  return image
41
 
42
-
43
  transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])])
44
 
45
  def load_image(im_path, hypar):
@@ -49,11 +49,10 @@ def load_image(im_path, hypar):
49
  shape = torch.from_numpy(np.array(im_shp))
50
  return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
51
 
 
 
52
 
53
- def build_model(hypar,device):
54
- net = hypar["model"]#GOSNETINC(3,1)
55
-
56
- # convert to half precision
57
  if(hypar["model_digit"]=="half"):
58
  net.half()
59
  for layer in net.modules():
@@ -68,7 +67,6 @@ def build_model(hypar,device):
68
  net.eval()
69
  return net
70
 
71
-
72
  def predict(net, inputs_val, shapes_val, hypar, device):
73
  '''
74
  Given an Image, predict the mask
@@ -80,74 +78,84 @@ def predict(net, inputs_val, shapes_val, hypar, device):
80
  else:
81
  inputs_val = inputs_val.type(torch.HalfTensor)
82
 
83
-
84
- inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable
85
-
86
- ds_val = net(inputs_val_v)[0] # list of 6 results
87
-
88
- pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction
89
-
90
- ## recover the prediction spatial size to the orignal image size
91
- pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear'))
92
 
93
  ma = torch.max(pred_val)
94
  mi = torch.min(pred_val)
95
- pred_val = (pred_val-mi)/(ma-mi) # max = 1
96
-
97
- if device == 'cuda': torch.cuda.empty_cache()
98
- return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need
99
-
100
- # Set Parameters
101
- hypar = {} # paramters for inferencing
102
-
103
 
104
- hypar["model_path"] ="./saved_models" ## load trained weights from this path
105
- hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights
106
- hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision
107
 
108
- ## choose floating point accuracy --
109
- hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number
 
 
 
 
110
  hypar["seed"] = 0
111
-
112
- hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution, can be configured into different size
113
-
114
- ## data augmentation parameters ---
115
- hypar["input_size"] = [1024, 1024] ## mdoel input spatial size, usually use the same value hypar["cache_size"], which means we don't further resize the images
116
- hypar["crop_size"] = [1024, 1024] ## random crop size from the input, it is usually set as smaller than hypar["cache_size"], e.g., [920,920] for data augmentation
117
-
118
  hypar["model"] = ISNetDIS()
119
 
120
- # Build Model
121
  net = build_model(hypar, device)
122
 
123
-
124
- def inference(image):
125
- image_path = image
126
-
127
- image_tensor, orig_size = load_image(image_path, hypar)
128
- mask = predict(net, image_tensor, orig_size, hypar, device)
129
-
130
- pil_mask = Image.fromarray(mask).convert('L')
131
- im_rgb = Image.open(image).convert("RGB")
132
 
133
- im_rgba = im_rgb.copy()
134
- im_rgba.putalpha(pil_mask)
135
 
136
- return [im_rgba, pil_mask]
 
 
 
 
 
 
 
 
137
 
 
 
138
 
139
  title = "Highly Accurate Dichotomous Image Segmentation"
140
- description = "This is an unofficial demo for DIS, a model that can remove the background from a given image. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below.<br>GitHub: https://github.com/xuebinqin/DIS<br>Telegram bot: https://t.me/restoration_photo_bot<br>[![](https://img.shields.io/twitter/follow/DoEvent?label=@DoEvent&style=social)](https://twitter.com/DoEvent)"
141
- article = "<div><center><img src='https://visitor-badge.glitch.me/badge?page_id=max_skobeev_dis_cmp_public' alt='visitor badge'></center></div>"
 
 
 
 
 
 
 
 
 
 
142
 
143
  interface = gr.Interface(
144
  fn=inference,
145
- inputs=gr.Image(type='filepath'),
146
- outputs=gr.Gallery(format="png"),
 
 
 
 
147
  examples=[['robot.png'], ['ship.png']],
148
  title=title,
149
  description=description,
150
  article=article,
151
  flagging_mode="never",
152
  cache_mode="lazy",
153
- ).queue().launch(show_api=True, show_error=True)
 
11
  import matplotlib.pyplot as plt
12
  import warnings
13
  warnings.filterwarnings("ignore")
14
+ import time
15
 
16
  os.system("git clone https://github.com/xuebinqin/DIS")
17
  os.system("mv DIS/IS-Net/* .")
 
40
  image = normalize(image,self.mean,self.std)
41
  return image
42
 
 
43
  transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])])
44
 
45
  def load_image(im_path, hypar):
 
49
  shape = torch.from_numpy(np.array(im_shp))
50
  return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
51
 
52
+ def build_model(hypar, device):
53
+ net = hypar["model"]
54
 
55
+ # convert to half precision if needed
 
 
 
56
  if(hypar["model_digit"]=="half"):
57
  net.half()
58
  for layer in net.modules():
 
67
  net.eval()
68
  return net
69
 
 
70
  def predict(net, inputs_val, shapes_val, hypar, device):
71
  '''
72
  Given an Image, predict the mask
 
78
  else:
79
  inputs_val = inputs_val.type(torch.HalfTensor)
80
 
81
+ inputs_val_v = Variable(inputs_val, requires_grad=False).to(device)
82
+ ds_val = net(inputs_val_v)[0]
83
+ pred_val = ds_val[0][0,:,:,:]
84
+ pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),
85
+ (shapes_val[0][0],shapes_val[0][1]),
86
+ mode='bilinear'))
 
 
 
87
 
88
  ma = torch.max(pred_val)
89
  mi = torch.min(pred_val)
90
+ pred_val = (pred_val-mi)/(ma-mi) # normalize to 0~1
 
 
 
 
 
 
 
91
 
92
+ if device == 'cuda':
93
+ torch.cuda.empty_cache()
94
+ return (pred_val.detach().cpu().numpy()*255).astype(np.uint8)
95
 
96
+ # Set Parameters
97
+ hypar = {}
98
+ hypar["model_path"] ="./saved_models"
99
+ hypar["restore_model"] = "isnet.pth"
100
+ hypar["interm_sup"] = False
101
+ hypar["model_digit"] = "full"
102
  hypar["seed"] = 0
103
+ hypar["cache_size"] = [1024, 1024]
104
+ hypar["input_size"] = [1024, 1024]
105
+ hypar["crop_size"] = [1024, 1024]
 
 
 
 
106
  hypar["model"] = ISNetDIS()
107
 
108
+ # Build Model
109
  net = build_model(hypar, device)
110
 
111
+ def inference(image, logs):
112
+ start_time = time.time()
113
+
114
+ image_tensor, orig_size = load_image(image, hypar)
115
+ mask = predict(net, image_tensor, orig_size, hypar, device)
 
 
 
 
116
 
117
+ pil_mask = Image.fromarray(mask).convert('L')
118
+ im_rgb = Image.open(image).convert("RGB")
119
 
120
+ im_rgba = im_rgb.copy()
121
+ im_rgba.putalpha(pil_mask)
122
+
123
+ end_time = time.time()
124
+ elapsed = round(end_time - start_time, 2)
125
+
126
+ # Update and return logs
127
+ logs = logs or ""
128
+ logs += f"Processed in {elapsed} seconds.\n"
129
 
130
+ # Return (gallery output), the logs state, and the logs display
131
+ return [im_rgba, pil_mask], logs, logs
132
 
133
  title = "Highly Accurate Dichotomous Image Segmentation"
134
+ description = (
135
+ "This is an unofficial demo for DIS, a model that can remove the background from a given image. "
136
+ "To use it, simply upload your image, or click one of the examples to load them. "
137
+ "Read more at the links below.<br>"
138
+ "GitHub: https://github.com/xuebinqin/DIS<br>"
139
+ "Telegram bot: https://t.me/restoration_photo_bot<br>"
140
+ "[![](https://img.shields.io/twitter/follow/DoEvent?label=@DoEvent&style=social)](https://twitter.com/DoEvent)"
141
+ )
142
+ article = (
143
+ "<div><center><img src='https://visitor-badge.glitch.me/badge?page_id=max_skobeev_dis_cmp_public' "
144
+ "alt='visitor badge'></center></div>"
145
+ )
146
 
147
  interface = gr.Interface(
148
  fn=inference,
149
+ inputs=[gr.Image(type='filepath'), gr.State()],
150
+ outputs=[
151
+ gr.Gallery(format="png"),
152
+ gr.State(),
153
+ gr.Textbox(label="Logs", lines=6)
154
+ ],
155
  examples=[['robot.png'], ['ship.png']],
156
  title=title,
157
  description=description,
158
  article=article,
159
  flagging_mode="never",
160
  cache_mode="lazy",
161
+ ).queue().launch(show_api=True, show_error=True)