Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- bg_removersarvm.py +162 -0
- isnet.pth +3 -0
bg_removersarvm.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""bg_removersarvm.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/17ZfqfkhZV5xSwXdHblThSQM_Yna-0J22
|
8 |
+
"""
|
9 |
+
|
10 |
+
import cv2
|
11 |
+
import gradio as gr
|
12 |
+
import os
|
13 |
+
from PIL import Image
|
14 |
+
import numpy as np
|
15 |
+
import torch
|
16 |
+
from torch.autograd import Variable
|
17 |
+
from torchvision import transforms
|
18 |
+
import torch.nn.functional as F
|
19 |
+
import gdown
|
20 |
+
import matplotlib.pyplot as plt
|
21 |
+
import warnings
|
22 |
+
warnings.filterwarnings("ignore")
|
23 |
+
|
24 |
+
os.system("git clone https://github.com/xuebinqin/DIS")
|
25 |
+
os.system("mv DIS/IS-Net/* .")
|
26 |
+
|
27 |
+
# project imports
|
28 |
+
from data_loader_cache import normalize, im_reader, im_preprocess
|
29 |
+
from models import *
|
30 |
+
|
31 |
+
#Helpers
|
32 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
33 |
+
|
34 |
+
# Download official weights
|
35 |
+
if not os.path.exists("saved_models"):
|
36 |
+
os.mkdir("saved_models")
|
37 |
+
os.system("mv isnet.pth saved_models/")
|
38 |
+
|
39 |
+
class GOSNormalize(object):
|
40 |
+
'''
|
41 |
+
Normalize the Image using torch.transforms
|
42 |
+
'''
|
43 |
+
def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]):
|
44 |
+
self.mean = mean
|
45 |
+
self.std = std
|
46 |
+
|
47 |
+
def __call__(self,image):
|
48 |
+
image = normalize(image,self.mean,self.std)
|
49 |
+
return image
|
50 |
+
|
51 |
+
|
52 |
+
transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])])
|
53 |
+
|
54 |
+
def load_image(im_path, hypar):
|
55 |
+
im = im_reader(im_path)
|
56 |
+
im, im_shp = im_preprocess(im, hypar["cache_size"])
|
57 |
+
im = torch.divide(im,255.0)
|
58 |
+
shape = torch.from_numpy(np.array(im_shp))
|
59 |
+
return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
|
60 |
+
|
61 |
+
|
62 |
+
def build_model(hypar,device):
|
63 |
+
net = hypar["model"]#GOSNETINC(3,1)
|
64 |
+
|
65 |
+
# convert to half precision
|
66 |
+
if(hypar["model_digit"]=="half"):
|
67 |
+
net.half()
|
68 |
+
for layer in net.modules():
|
69 |
+
if isinstance(layer, nn.BatchNorm2d):
|
70 |
+
layer.float()
|
71 |
+
|
72 |
+
net.to(device)
|
73 |
+
|
74 |
+
if(hypar["restore_model"]!=""):
|
75 |
+
net.load_state_dict(torch.load(hypar["model_path"]+"/"+hypar["restore_model"], map_location=device))
|
76 |
+
net.to(device)
|
77 |
+
net.eval()
|
78 |
+
return net
|
79 |
+
|
80 |
+
|
81 |
+
def predict(net, inputs_val, shapes_val, hypar, device):
|
82 |
+
'''
|
83 |
+
Given an Image, predict the mask
|
84 |
+
'''
|
85 |
+
net.eval()
|
86 |
+
|
87 |
+
if(hypar["model_digit"]=="full"):
|
88 |
+
inputs_val = inputs_val.type(torch.FloatTensor)
|
89 |
+
else:
|
90 |
+
inputs_val = inputs_val.type(torch.HalfTensor)
|
91 |
+
|
92 |
+
|
93 |
+
inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable
|
94 |
+
|
95 |
+
ds_val = net(inputs_val_v)[0] # list of 6 results
|
96 |
+
|
97 |
+
pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction
|
98 |
+
|
99 |
+
## recover the prediction spatial size to the orignal image size
|
100 |
+
pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear'))
|
101 |
+
|
102 |
+
ma = torch.max(pred_val)
|
103 |
+
mi = torch.min(pred_val)
|
104 |
+
pred_val = (pred_val-mi)/(ma-mi) # max = 1
|
105 |
+
|
106 |
+
if device == 'cuda': torch.cuda.empty_cache()
|
107 |
+
return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need
|
108 |
+
|
109 |
+
# Set Parameters
|
110 |
+
hypar = {} # paramters for inferencing
|
111 |
+
|
112 |
+
|
113 |
+
hypar["model_path"] ="./saved_models" ## load trained weights from this path
|
114 |
+
hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights
|
115 |
+
hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision
|
116 |
+
|
117 |
+
## choose floating point accuracy --
|
118 |
+
hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number
|
119 |
+
hypar["seed"] = 0
|
120 |
+
|
121 |
+
hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution, can be configured into different size
|
122 |
+
|
123 |
+
## data augmentation parameters ---
|
124 |
+
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
|
125 |
+
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
|
126 |
+
|
127 |
+
hypar["model"] = ISNetDIS()
|
128 |
+
|
129 |
+
# Build Model
|
130 |
+
net = build_model(hypar, device)
|
131 |
+
|
132 |
+
|
133 |
+
def inference(image):
|
134 |
+
image_path = image
|
135 |
+
|
136 |
+
image_tensor, orig_size = load_image(image_path, hypar)
|
137 |
+
mask = predict(net, image_tensor, orig_size, hypar, device)
|
138 |
+
|
139 |
+
pil_mask = Image.fromarray(mask).convert('L')
|
140 |
+
im_rgb = Image.open(image).convert("RGB")
|
141 |
+
|
142 |
+
im_rgba = im_rgb.copy()
|
143 |
+
im_rgba.putalpha(pil_mask)
|
144 |
+
|
145 |
+
return [im_rgba, pil_mask]
|
146 |
+
|
147 |
+
|
148 |
+
title = "Bg remover"
|
149 |
+
description = "Bg remover for sarvm catalog"
|
150 |
+
article = "<div><center><img src='https://visitor-badge.glitch.me/badge?page_id=max_skobeev_dis_cmp_public' alt='visitor badge'></center></div>"
|
151 |
+
|
152 |
+
interface = gr.Interface(
|
153 |
+
fn=inference,
|
154 |
+
inputs=gr.Image(type='filepath'),
|
155 |
+
outputs=["image", "image"],
|
156 |
+
examples=[['robot.png'], ['ship.png']],
|
157 |
+
title=title,
|
158 |
+
description=description,
|
159 |
+
article=article,
|
160 |
+
allow_flagging='never',
|
161 |
+
cache_examples=False,
|
162 |
+
).queue().launch(show_error=True)
|
isnet.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e1aafea58f0b55d0c35077e0ceade6ba1ba2bce372fd4f8f77215391f3fac13
|
3 |
+
size 176579397
|