Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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.
|
| 28 |
if not os.path.exists("saved_models/isnet.pth"):
|
| 29 |
-
os.
|
|
|
|
| 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 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 54 |
-
|
| 55 |
-
def build_model(hypar,device):
|
| 56 |
-
net = hypar["model"]#GOSNETINC(3,1)
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
| 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
|
| 68 |
-
net.load_state_dict(torch.load(hypar["model_path"]
|
| 69 |
-
|
| 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
|
| 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)
|
| 85 |
-
ds_val = net(inputs_val_v)[0]
|
| 86 |
|
| 87 |
-
pred_val = ds_val[0][0
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
| 92 |
ma = torch.max(pred_val)
|
| 93 |
mi = torch.min(pred_val)
|
| 94 |
-
pred_val = (pred_val-mi)/(ma-mi)
|
| 95 |
|
| 96 |
-
if device == 'cuda':
|
| 97 |
-
|
|
|
|
| 98 |
|
| 99 |
# Set Parameters
|
| 100 |
-
hypar = {
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
| 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=
|
|
|
|
|
|
|
| 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)
|