de3sec commited on
Commit
7ba936e
·
1 Parent(s): 1489559

Upload bg-api.py

Browse files
Files changed (1) hide show
  1. bg-api.py +120 -0
bg-api.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ import numpy as np
5
+ import cv2
6
+ import uuid
7
+ import os
8
+
9
+ from model import U2NET
10
+ from torch.autograd import Variable
11
+ from skimage import io, transform
12
+ from PIL import Image
13
+
14
+
15
+ from fastapi import FastAPI, File, UploadFile
16
+ from fastapi.responses import JSONResponse
17
+ app = FastAPI()
18
+
19
+
20
+ # Get The Current Directory
21
+ currentDir = os.path.dirname(__file__)
22
+
23
+ # Functions:
24
+ # Save Results
25
+
26
+
27
+ def save_output(image_name, output_name, pred, d_dir, type):
28
+ predict = pred
29
+ predict = predict.squeeze()
30
+ predict_np = predict.cpu().data.numpy()
31
+ im = Image.fromarray(predict_np*255).convert('RGB')
32
+ image = io.imread(image_name)
33
+ imo = im.resize((image.shape[1], image.shape[0]))
34
+ pb_np = np.array(imo)
35
+ if type == 'image':
36
+ # Make and apply mask
37
+ mask = pb_np[:, :, 0]
38
+ mask = np.expand_dims(mask, axis=2)
39
+ imo = np.concatenate((image, mask), axis=2)
40
+ imo = Image.fromarray(imo, 'RGBA')
41
+
42
+ imo.save(d_dir+output_name)
43
+ # Remove Background From Image (Generate Mask, and Final Results)
44
+
45
+
46
+ @app.get("/removeBG/")
47
+ async def removeBG(image_file: str):
48
+
49
+ # ------- Load Trained Model --------
50
+ print("---Loading Model---")
51
+ model_name = 'u2net'
52
+ model_dir = os.path.join(currentDir, 'saved_models',
53
+ model_name, model_name + '.pth')
54
+ net = U2NET(3, 1)
55
+ if torch.cuda.is_available():
56
+ net.load_state_dict(torch.load(model_dir))
57
+ net.cuda()
58
+ else:
59
+ net.load_state_dict(torch.load(model_dir, map_location='cpu'))
60
+ # ------- Load Trained Model --------
61
+
62
+ inputs_dir = os.path.join(currentDir, 'static/inputs/')
63
+ results_dir = os.path.join(currentDir, 'static/results/')
64
+ masks_dir = os.path.join(currentDir, 'static/masks/')
65
+
66
+ # convert string of image data to uint8
67
+ with open(image_file, "rb") as image:
68
+ f = image.read()
69
+ img = bytearray(f)
70
+
71
+ nparr = np.frombuffer(img, np.uint8)
72
+
73
+ if len(nparr) == 0:
74
+ return '---Empty image---'
75
+
76
+ # decode image
77
+ try:
78
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
79
+ except:
80
+ # build a response dict to send back to client
81
+ return "---Empty image---"
82
+
83
+ # save image to inputs
84
+ unique_filename = str(uuid.uuid4())
85
+ cv2.imwrite(inputs_dir+unique_filename+'.jpg', img)
86
+
87
+ # processing
88
+ image = transform.resize(img, (320, 320), mode='constant')
89
+
90
+ tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
91
+
92
+ tmpImg[:, :, 0] = (image[:, :, 0]-0.485)/0.229
93
+ tmpImg[:, :, 1] = (image[:, :, 1]-0.456)/0.224
94
+ tmpImg[:, :, 2] = (image[:, :, 2]-0.406)/0.225
95
+
96
+ tmpImg = tmpImg.transpose((2, 0, 1))
97
+ tmpImg = np.expand_dims(tmpImg, 0)
98
+ image = torch.from_numpy(tmpImg)
99
+
100
+ image = image.type(torch.FloatTensor)
101
+ image = Variable(image)
102
+
103
+ d1, d2, d3, d4, d5, d6, d7 = net(image)
104
+ pred = d1[:, 0, :, :]
105
+ ma = torch.max(pred)
106
+ mi = torch.min(pred)
107
+ dn = (pred-mi)/(ma-mi)
108
+ pred = dn
109
+
110
+ save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
111
+ '.png', pred, results_dir, 'image')
112
+ save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
113
+ '.png', pred, masks_dir, 'mask')
114
+ return "---Success---"
115
+
116
+
117
+ #print("---Removing Background...")
118
+ # ------- Call The removeBg Function --------
119
+ # imgPath = "1.jpg" # Change this to your image path
120
+ # print(removeBg(imgPath))