Imadsarvm commited on
Commit
6d9249b
·
1 Parent(s): 02b4dab

Upload dis.py

Browse files
Files changed (1) hide show
  1. dis.py +225 -0
dis.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """DIS.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1MI9utM7GJbz0w_zw1GJNU-ay15SzZHIN
8
+
9
+ # Clone official repo
10
+ """
11
+
12
+ # Commented out IPython magic to ensure Python compatibility.
13
+ ! git clone https://github.com/xuebinqin/DIS
14
+
15
+ # %cd ./DIS/IS-Net
16
+
17
+ !pip install gdown
18
+
19
+ !mkdir ./saved_models
20
+
21
+ """# Imports"""
22
+
23
+ import numpy as np
24
+ from PIL import Image
25
+ import torch
26
+ from torch.autograd import Variable
27
+ from torchvision import transforms
28
+ import torch.nn.functional as F
29
+ import gdown
30
+ import os
31
+
32
+ import requests
33
+ import matplotlib.pyplot as plt
34
+ from io import BytesIO
35
+
36
+ # project imports
37
+ from data_loader_cache import normalize, im_reader, im_preprocess
38
+ from models import *
39
+
40
+ """# Helpers"""
41
+
42
+ drive_link = "https://drive.google.com/uc?id=1XHIzgTzY5BQHw140EDIgwIb53K659ENH"
43
+
44
+ # Specify the local path and filename
45
+ local_path = "/content/DIS/IS-Net/saved_models/isnet.pth"
46
+
47
+ # Download the file
48
+ gdown.download(drive_link, local_path, quiet=False)
49
+
50
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
51
+
52
+ # Download official weights
53
+
54
+
55
+
56
+ class GOSNormalize(object):
57
+ '''
58
+ Normalize the Image using torch.transforms
59
+ '''
60
+ def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]):
61
+ self.mean = mean
62
+ self.std = std
63
+
64
+ def __call__(self,image):
65
+ image = normalize(image,self.mean,self.std)
66
+ return image
67
+
68
+
69
+ transform = transforms.Compose([GOSNormalize([0.5,0.5,0.5],[1.0,1.0,1.0])])
70
+
71
+ def load_image(im_path, hypar):
72
+ if im_path.startswith("http"):
73
+ im_path = BytesIO(requests.get(im_path).content)
74
+
75
+ im = im_reader(im_path)
76
+ im, im_shp = im_preprocess(im, hypar["cache_size"])
77
+ im = torch.divide(im,255.0)
78
+ shape = torch.from_numpy(np.array(im_shp))
79
+ return transform(im).unsqueeze(0), shape.unsqueeze(0) # make a batch of image, shape
80
+
81
+
82
+ def build_model(hypar,device):
83
+ net = hypar["model"]#GOSNETINC(3,1)
84
+
85
+ # convert to half precision
86
+ if(hypar["model_digit"]=="half"):
87
+ net.half()
88
+ for layer in net.modules():
89
+ if isinstance(layer, nn.BatchNorm2d):
90
+ layer.float()
91
+
92
+ net.to(device)
93
+
94
+ if(hypar["restore_model"]!=""):
95
+ net.load_state_dict(torch.load(hypar["model_path"]+"/"+hypar["restore_model"],map_location=device))
96
+ net.to(device)
97
+ net.eval()
98
+ return net
99
+
100
+
101
+ def predict(net, inputs_val, shapes_val, hypar, device):
102
+ '''
103
+ Given an Image, predict the mask
104
+ '''
105
+ net.eval()
106
+
107
+ if(hypar["model_digit"]=="full"):
108
+ inputs_val = inputs_val.type(torch.FloatTensor)
109
+ else:
110
+ inputs_val = inputs_val.type(torch.HalfTensor)
111
+
112
+
113
+ inputs_val_v = Variable(inputs_val, requires_grad=False).to(device) # wrap inputs in Variable
114
+
115
+ ds_val = net(inputs_val_v)[0] # list of 6 results
116
+
117
+ pred_val = ds_val[0][0,:,:,:] # B x 1 x H x W # we want the first one which is the most accurate prediction
118
+
119
+ ## recover the prediction spatial size to the orignal image size
120
+ pred_val = torch.squeeze(F.upsample(torch.unsqueeze(pred_val,0),(shapes_val[0][0],shapes_val[0][1]),mode='bilinear'))
121
+
122
+ ma = torch.max(pred_val)
123
+ mi = torch.min(pred_val)
124
+ pred_val = (pred_val-mi)/(ma-mi) # max = 1
125
+
126
+ if device == 'cuda': torch.cuda.empty_cache()
127
+ return (pred_val.detach().cpu().numpy()*255).astype(np.uint8) # it is the mask we need
128
+
129
+ """# Set Parameters"""
130
+
131
+ hypar = {} # paramters for inferencing
132
+
133
+
134
+ hypar["model_path"] ="./saved_models" ## load trained weights from this path
135
+ hypar["restore_model"] = "isnet.pth" ## name of the to-be-loaded weights
136
+ hypar["interm_sup"] = False ## indicate if activate intermediate feature supervision
137
+
138
+ ## choose floating point accuracy --
139
+ hypar["model_digit"] = "full" ## indicates "half" or "full" accuracy of float number
140
+ hypar["seed"] = 0
141
+
142
+ hypar["cache_size"] = [1024, 1024] ## cached input spatial resolution, can be configured into different size
143
+
144
+ ## data augmentation parameters ---
145
+ 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
146
+ 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
147
+
148
+ hypar["model"] = ISNetDIS()
149
+
150
+ """# Build Model"""
151
+
152
+ net = build_model(hypar, device)
153
+
154
+ """# Predict Mask"""
155
+
156
+ gsheetid = "1n9kk7IHyBzkw5e08wpjjt-Ry5aE_thqGrJ97rMeN-K4"
157
+ sheet_name = "sarvm"
158
+
159
+ gsheet_url = "https://docs.google.com/spreadsheets/d/{}/gviz/tq?tqx=out:csv&sheet={}".format(gsheetid, sheet_name)
160
+
161
+ gsheet_url
162
+
163
+ import pandas as pd
164
+ df = pd.read_csv(gsheet_url)
165
+
166
+ image_path = df.iloc[-1]['Image']
167
+
168
+ drive_link = image_path
169
+
170
+ # Specify the local path and filename
171
+ local_path = "/content/DIS/IS-Net/saved_models/input2.jpg"
172
+
173
+ # Download the file
174
+ gdown.download(drive_link, local_path, quiet=False)
175
+
176
+ from google.colab.patches import cv2_imshow
177
+ from PIL import Image
178
+ image_path = "/content/DIS/IS-Net/saved_models/input2.jpg"
179
+ # image_bytes = BytesIO(requests.get(image_path).content)
180
+ # print(image_bytes)
181
+ image_tensor, orig_size = load_image(image_path, hypar)
182
+ mask = predict(net,image_tensor,orig_size, hypar, device)
183
+ image = Image.open(image_path)
184
+
185
+ f, ax = plt.subplots(1,2, figsize = (35,20))
186
+
187
+ # ax[0].imshow(np.array(Image.open(image_bytes))) # Original image
188
+ # cv2_imshow(image_path)
189
+
190
+ ax[0].imshow(mask, cmap = 'gray') # retouched image
191
+
192
+ # ax[0].set_title("Original Image")
193
+ ax[0].set_title("Mask")
194
+
195
+ plt.show()
196
+
197
+ import cv2
198
+ image = cv2.imread(image_path)
199
+ h, w , _ = image.shape
200
+ # print(h)
201
+ # print(w)
202
+ # print(_)
203
+ # print(image)
204
+ h, w , _ = image.shape
205
+ # print(h)
206
+ # print(w)
207
+ # print(_)
208
+ # new_image = np.zeros_like(image)
209
+ # new_image[mask] = image[mask]
210
+ new_image = cv2.bitwise_and(image, image, mask=mask)
211
+ transparent_bg = np.zeros((new_image.shape[0],new_image.shape[1], new_image.shape[2]+1) , dtype=np.uint8)
212
+
213
+ # Apply the mask to the transparent background
214
+ transparent_bg[:, :, :3] = new_image
215
+
216
+ # Set the alpha channel using the mask
217
+ transparent_bg[:, :, 3] = mask
218
+
219
+ # Save the new image with a transparent background
220
+ output_path = "/content/output.png"
221
+ cv2.imwrite(output_path, transparent_bg)
222
+ # Save the new image
223
+ # output_path = "/content/output.jpg"
224
+ # cv2.imwrite(output_path, new_image)
225
+