davideuler mcrlc commited on
Commit
044675f
·
0 Parent(s):

Duplicate from mcrlc/background-replacer

Browse files

Co-authored-by: Michael Ehrlich <[email protected]>

Files changed (6) hide show
  1. .gitattributes +31 -0
  2. README.md +14 -0
  3. app.py +168 -0
  4. requirements.txt +8 -0
  5. robot.png +0 -0
  6. ship.png +0 -0
.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Background Replacer :)
3
+ emoji: 🔥 🌠 🏰
4
+ colorFrom: yellow
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.15.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: mcrlc/background-replacer
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import gradio as gr
3
+ import os
4
+ from PIL import Image
5
+ import numpy as np
6
+ import torch
7
+ from torch.autograd import Variable
8
+ from torchvision import transforms
9
+ import torch.nn.functional as F
10
+ 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/* .")
17
+
18
+ # project imports
19
+ from data_loader_cache import normalize, im_reader, im_preprocess
20
+ from models import *
21
+
22
+ #Helpers
23
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
24
+
25
+ # Download official weights
26
+ if not os.path.exists("saved_models"):
27
+ os.mkdir("saved_models")
28
+ # MODEL_PATH_URL = "https://drive.google.com/uc?id=1KyMpRjewZdyYfxHPYcd-ZbanIXtin0Sn" # IS-Net
29
+ MODEL_PATH_URL = "https://drive.google.com/uc?id=1nV57qKuy--d5u1yvkng9aXW1KS4sOpOi" # IS-Net General Use
30
+ gdown.download(MODEL_PATH_URL, "saved_models/isnet.pth", use_cookies=False)
31
+
32
+ class GOSNormalize(object):
33
+ '''
34
+ Normalize the Image using torch.transforms
35
+ '''
36
+ def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]):
37
+ self.mean = mean
38
+ self.std = std
39
+
40
+ def __call__(self,image):
41
+ image = normalize(image,self.mean,self.std)
42
+ return image
43
+
44
+
45
+ transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])])
46
+
47
+ def load_image(im_path, hypar):
48
+ im = im_reader(im_path)
49
+ im, im_shp = im_preprocess(im, hypar["cache_size"])
50
+ im = torch.divide(im,255.0)
51
+ shape = torch.from_numpy(np.array(im_shp))
52
+ return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
53
+
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):
63
+ layer.float()
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
+
74
+ def predict(net, inputs_val, shapes_val, hypar, device):
75
+ '''
76
+ Given an Image, predict the mask
77
+ '''
78
+ net.eval()
79
+
80
+ if(hypar["model_digit"]=="full"):
81
+ inputs_val = inputs_val.type(torch.FloatTensor)
82
+ else:
83
+ inputs_val = inputs_val.type(torch.HalfTensor)
84
+
85
+
86
+ inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable
87
+
88
+ ds_val = net(inputs_val_v)[0] # list of 6 results
89
+
90
+ pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction
91
+
92
+ ## recover the prediction spatial size to the orignal image size
93
+ pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear'))
94
+
95
+ ma = torch.max(pred_val)
96
+ mi = torch.min(pred_val)
97
+ pred_val = (pred_val-mi)/(ma-mi) # max = 1
98
+
99
+ if device == 'cuda': torch.cuda.empty_cache()
100
+ return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need
101
+
102
+ # Set Parameters
103
+ hypar = {} # paramters for inferencing
104
+
105
+
106
+ hypar["model_path"] ="./saved_models" ## load trained weights from this path
107
+ hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights
108
+ hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision
109
+
110
+ ## choose floating point accuracy --
111
+ hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number
112
+ hypar["seed"] = 0
113
+
114
+ hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution, can be configured into different size
115
+
116
+ ## data augmentation parameters ---
117
+ 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
118
+ 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
119
+
120
+ hypar["model"] = ISNetDIS()
121
+
122
+ # Build Model
123
+ net = build_model(hypar, device)
124
+
125
+
126
+ def inference(image: Image):
127
+ image_path = image
128
+
129
+ image_tensor, orig_size = load_image(image_path, hypar)
130
+ mask = predict(net, image_tensor, orig_size, hypar, device)
131
+
132
+ pil_mask = Image.fromarray(mask).convert('L')
133
+ im_rgb = Image.open(image).convert("RGB")
134
+
135
+ im_rgba = im_rgb.copy()
136
+ im_rgba.putalpha(pil_mask)
137
+
138
+ # Apply Background
139
+ bg_color = 0xFF9AC400
140
+ w = im_rgba.size[0]
141
+ h = im_rgba.size[1]
142
+ im_colored = Image.new("RGBA", (w,h), bg_color)
143
+ im_colored.alpha_composite(im_rgba)
144
+
145
+ return [im_colored, im_rgba]
146
+
147
+
148
+ title = "Background Replacer :)"
149
+ description = "Based on 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)"
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=[
155
+ gr.Image(type='filepath', label="Image")
156
+ ],
157
+ outputs=[
158
+ gr.Image(label="Full Background"),
159
+ gr.Image(label="Transparent Background")
160
+ ],
161
+ examples=[['robot.png'], ['ship.png']],
162
+ title=title,
163
+ description=description,
164
+ article=article,
165
+ allow_flagging='never',
166
+ theme="default",
167
+ cache_examples=True,
168
+ ).launch(enable_queue=True, debug=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ requests
4
+ gdown
5
+ matplotlib
6
+ opencv-python
7
+ Pillow==8.0.0
8
+ scikit-image==0.15.0
robot.png ADDED
ship.png ADDED