soiz1 commited on
Commit
b90811d
·
verified ·
1 Parent(s): d50aa15

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -48
app.py CHANGED
@@ -1,12 +1,11 @@
1
- import cv2
2
  import os
3
- from PIL import Image
4
  import numpy as np
5
  import torch
6
  from torch.autograd import Variable
7
  from torchvision import transforms
8
  import torch.nn.functional as F
9
  from flask import Flask, request, jsonify, render_template, send_from_directory
 
10
  import warnings
11
  warnings.filterwarnings("ignore")
12
 
@@ -24,39 +23,48 @@ device = 'cuda' if torch.cuda.is_available() else 'cpu'
24
 
25
  # Download official weights if not exists
26
  if not os.path.exists("saved_models"):
27
- os.mkdir("saved_models")
28
  if not os.path.exists("saved_models/isnet.pth"):
29
- os.system("mv isnet.pth saved_models/")
 
30
 
31
  class GOSNormalize(object):
32
- '''
33
- Normalize the Image using torch.transforms
34
- '''
35
- def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]):
36
  self.mean = mean
37
  self.std = std
38
 
39
- def __call__(self,image):
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):
46
  im = im_reader(im_path)
47
- # Convert to RGB if image has alpha channel
48
- if im.mode == 'RGBA':
49
- im = im.convert('RGB')
 
 
 
 
 
 
 
 
 
 
 
 
50
  im, im_shp = im_preprocess(im, hypar["cache_size"])
51
- im = torch.divide(im,255.0)
52
  shape = torch.from_numpy(np.array(im_shp))
53
- return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
54
-
55
- def build_model(hypar,device):
56
- net = hypar["model"]#GOSNETINC(3,1)
57
 
58
- # convert to half precision
59
- if(hypar["model_digit"]=="half"):
 
 
60
  net.half()
61
  for layer in net.modules():
62
  if isinstance(layer, nn.BatchNorm2d):
@@ -64,49 +72,48 @@ def build_model(hypar,device):
64
 
65
  net.to(device)
66
 
67
- if(hypar["restore_model"]!=""):
68
- net.load_state_dict(torch.load(hypar["model_path"]+"/"+hypar["restore_model"], map_location=device))
69
- net.to(device)
70
- net.eval()
71
  return net
72
 
73
  def predict(net, inputs_val, shapes_val, hypar, device):
74
- '''
75
- Given an Image, predict the mask
76
- '''
77
  net.eval()
78
 
79
- if(hypar["model_digit"]=="full"):
80
  inputs_val = inputs_val.type(torch.FloatTensor)
81
  else:
82
  inputs_val = inputs_val.type(torch.HalfTensor)
83
 
84
- inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable
85
- ds_val = net(inputs_val_v)[0] # list of 6 results
86
 
87
- pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction
88
 
89
- ## recover the prediction spatial size to the orignal image size
90
- pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear'))
91
 
92
  ma = torch.max(pred_val)
93
  mi = torch.min(pred_val)
94
- pred_val = (pred_val-mi)/(ma-mi) # max = 1
95
 
96
- if device == 'cuda': torch.cuda.empty_cache()
97
- return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need
 
98
 
99
  # Set Parameters
100
- hypar = {} # paramters for inferencing
101
- hypar["model_path"] ="./saved_models" ## load trained weights from this path
102
- hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights
103
- hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision
104
- hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number
105
- hypar["seed"] = 0
106
- hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution
107
- hypar["input_size"] = [1024, 1024] ## model input spatial size
108
- hypar["crop_size"] = [1024, 1024] ## random crop size from the input
109
- hypar["model"] = ISNetDIS()
 
110
 
111
  # Build Model
112
  net = build_model(hypar, device)
@@ -171,4 +178,4 @@ def serve_upload(filename):
171
  return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
172
 
173
  if __name__ == '__main__':
174
- app.run(host='0.0.0.0', port=7860, debug=True)
 
 
1
  import os
 
2
  import numpy as np
3
  import torch
4
  from torch.autograd import Variable
5
  from torchvision import transforms
6
  import torch.nn.functional as F
7
  from flask import Flask, request, jsonify, render_template, send_from_directory
8
+ from PIL import Image
9
  import warnings
10
  warnings.filterwarnings("ignore")
11
 
 
23
 
24
  # Download official weights if not exists
25
  if not os.path.exists("saved_models"):
26
+ os.makedirs("saved_models", exist_ok=True)
27
  if not os.path.exists("saved_models/isnet.pth"):
28
+ if os.path.exists("isnet.pth"):
29
+ os.rename("isnet.pth", "saved_models/isnet.pth")
30
 
31
  class GOSNormalize(object):
32
+ def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
 
 
 
33
  self.mean = mean
34
  self.std = std
35
 
36
+ def __call__(self, image):
37
+ image = normalize(image, self.mean, self.std)
38
  return image
39
 
40
+ transform = transforms.Compose([GOSNormalize([0.5, 0.5, 0.5], [1.0, 1.0, 1.0])])
41
 
42
  def load_image(im_path, hypar):
43
  im = im_reader(im_path)
44
+
45
+ # Convert numpy array to PIL Image if needed
46
+ if isinstance(im, np.ndarray):
47
+ if im.ndim == 3 and im.shape[2] == 4: # RGBA image
48
+ im = Image.fromarray(im).convert('RGB')
49
+ elif im.ndim == 3: # RGB image
50
+ im = Image.fromarray(im)
51
+ elif im.ndim == 2: # Grayscale image
52
+ im = Image.fromarray(im).convert('RGB')
53
+
54
+ # If it's already PIL Image, check mode
55
+ elif hasattr(im, 'mode'):
56
+ if im.mode == 'RGBA':
57
+ im = im.convert('RGB')
58
+
59
  im, im_shp = im_preprocess(im, hypar["cache_size"])
60
+ im = torch.divide(im, 255.0)
61
  shape = torch.from_numpy(np.array(im_shp))
62
+ return transform(im).unsqueeze(0), shape.unsqueeze(0)
 
 
 
63
 
64
+ def build_model(hypar, device):
65
+ net = hypar["model"]
66
+
67
+ if hypar["model_digit"] == "half":
68
  net.half()
69
  for layer in net.modules():
70
  if isinstance(layer, nn.BatchNorm2d):
 
72
 
73
  net.to(device)
74
 
75
+ if hypar["restore_model"] != "":
76
+ net.load_state_dict(torch.load(os.path.join(hypar["model_path"], hypar["restore_model"]),
77
+ map_location=device))
78
+ net.eval()
79
  return net
80
 
81
  def predict(net, inputs_val, shapes_val, hypar, device):
 
 
 
82
  net.eval()
83
 
84
+ if hypar["model_digit"] == "full":
85
  inputs_val = inputs_val.type(torch.FloatTensor)
86
  else:
87
  inputs_val = inputs_val.type(torch.HalfTensor)
88
 
89
+ inputs_val_v = Variable(inputs_val, requires_grad=False).to(device)
90
+ ds_val = net(inputs_val_v)[0]
91
 
92
+ pred_val = ds_val[0][0, :, :, :]
93
 
94
+ pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val, 0),
95
+ (shapes_val[0][0], shapes_val[0][1]), mode='bilinear'))
96
 
97
  ma = torch.max(pred_val)
98
  mi = torch.min(pred_val)
99
+ pred_val = (pred_val - mi) / (ma - mi)
100
 
101
+ if device == 'cuda':
102
+ torch.cuda.empty_cache()
103
+ return (pred_val.detach().cpu().numpy() * 255).astype(np.uint8)
104
 
105
  # Set Parameters
106
+ hypar = {
107
+ "model_path": "./saved_models",
108
+ "restore_model": "isnet.pth",
109
+ "interm_sup": False,
110
+ "model_digit": "full",
111
+ "seed": 0,
112
+ "cache_size": [1024, 1024],
113
+ "input_size": [1024, 1024],
114
+ "crop_size": [1024, 1024],
115
+ "model": ISNetDIS()
116
+ }
117
 
118
  # Build Model
119
  net = build_model(hypar, device)
 
178
  return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
179
 
180
  if __name__ == '__main__':
181
+ app.run(host='0.0.0.0', port=5000, debug=True)