OriLib commited on
Commit
4cb2cd7
1 Parent(s): 77a5409

Upload example_inference.py

Browse files
Files changed (1) hide show
  1. example_inference.py +56 -0
example_inference.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ from skimage import io
4
+ import cv2
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torchvision.transforms.functional import normalize
8
+ from briarmbg import BriaRMBG
9
+
10
+
11
+ def example_inference():
12
+
13
+ input_size=[1024,1024]
14
+ net=BriaRMBG()
15
+
16
+ model_path = "./model.pth"
17
+ im_path = "./example_image.jpg"
18
+ result_path = "."
19
+
20
+ if torch.cuda.is_available():
21
+ net.load_state_dict(torch.load(model_path))
22
+ net=net.cuda()
23
+ else:
24
+ net.load_state_dict(torch.load(model_path,map_location="cpu"))
25
+ net.eval()
26
+
27
+ # prepare input
28
+ im = io.imread(im_path)
29
+ if len(im.shape) < 3:
30
+ im = im[:, :, np.newaxis]
31
+ im_size=im.shape[0:2]
32
+ im_tensor = torch.tensor(im, dtype=torch.float32).permute(2,0,1)
33
+ im_tensor = F.interpolate(torch.unsqueeze(im_tensor,0), size=input_size, mode='bilinear').type(torch.uint8)
34
+ image = torch.divide(im_tensor,255.0)
35
+ image = normalize(image,[0.5,0.5,0.5],[1.0,1.0,1.0])
36
+
37
+ if torch.cuda.is_available():
38
+ image=image.cuda()
39
+
40
+ #inference
41
+ result=net(image)
42
+
43
+ # post process
44
+ result = torch.squeeze(F.interpolate(result[0][0], size=im_size, mode='bilinear') ,0)
45
+ ma = torch.max(result)
46
+ mi = torch.min(result)
47
+ result = (result-mi)/(ma-mi)
48
+
49
+ # save result
50
+ im_name=im_path.split('/')[-1].split('.')[0]
51
+ im_array = (result*255).permute(1,2,0).cpu().data.numpy().astype(np.uint8)
52
+ cv2.imwrite(os.path.join(result_path, im_name+".png"), im_array)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ example_inference()