Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

infer.py 6.4 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
  1. import argparse
  2. import torch
  3. from torch import nn
  4. from torchvision import transforms
  5. from PIL import Image
  6. import os
  7. import sys
  8. import pathlib
  9. import numpy as np
  10. import cv2
  11. import importlib
  12. import ssl
  13. from datasets import utils as ds_utils
  14. from runners import utils as rn_utils
  15. from external.Graphonomy import wrapper
  16. import face_alignment
  17. class InferenceWrapper(nn.Module):
  18. @staticmethod
  19. def get_args(args_dict):
  20. # Read and parse args of the module being loaded
  21. args_path = pathlib.Path(args_dict['project_dir']) / 'runs' / args_dict['experiment_name'] / 'args.txt'
  22. parser = argparse.ArgumentParser(conflict_handler='resolve')
  23. parser.add = parser.add_argument
  24. with open(args_path, 'rt') as args_file:
  25. lines = args_file.readlines()
  26. for line in lines:
  27. k, v, v_type = rn_utils.parse_args_line(line)
  28. parser.add('--%s' % k, type=v_type, default=v)
  29. args, _ = parser.parse_known_args()
  30. # Add args from args_dict that overwrite the default ones
  31. for k, v in args_dict.items():
  32. setattr(args, k, v)
  33. args.world_size = args.num_gpus
  34. return args
  35. def __init__(self, args_dict):
  36. super(InferenceWrapper, self).__init__()
  37. # Get a config for the network
  38. self.args = self.get_args(args_dict)
  39. self.to_tensor = transforms.ToTensor()
  40. # Load the model
  41. self.runner = importlib.import_module(f'runners.{self.args.runner_name}').RunnerWrapper(self.args, training=False)
  42. self.runner.eval()
  43. # Load pretrained weights
  44. checkpoints_dir = pathlib.Path(self.args.project_dir) / 'runs' / self.args.experiment_name / 'checkpoints'
  45. # Load pre-trained weights
  46. init_networks = rn_utils.parse_str_to_list(self.args.init_networks) if self.args.init_networks else {}
  47. networks_to_train = self.runner.nets_names_to_train
  48. if self.args.init_which_epoch != 'none' and self.args.init_experiment_dir:
  49. for net_name in init_networks:
  50. self.runner.nets[net_name].load_state_dict(torch.load(
  51. pathlib.Path(self.args.init_experiment_dir)
  52. / 'checkpoints'
  53. / f'{self.args.init_which_epoch}_{net_name}.pth',
  54. map_location='cpu'))
  55. for net_name in networks_to_train:
  56. if net_name not in init_networks and net_name in self.runner.nets.keys():
  57. self.runner.nets[net_name].load_state_dict(torch.load(
  58. checkpoints_dir
  59. / f'{self.args.which_epoch}_{net_name}.pth',
  60. map_location='cpu'))
  61. # Remove spectral norm to improve the performance
  62. self.runner.apply(rn_utils.remove_spectral_norm)
  63. # Stickman/facemasks drawer
  64. self.fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=True)
  65. self.net_seg = wrapper.SegmentationWrapper(self.args)
  66. if self.args.num_gpus > 0:
  67. self.cuda()
  68. def change_args(self, args_dict):
  69. self.args = self.get_args(args_dict)
  70. def preprocess_data(self, input_imgs, crop_data=True):
  71. imgs = []
  72. poses = []
  73. stickmen = []
  74. if len(input_imgs.shape) == 3:
  75. input_imgs = input_imgs[None]
  76. N = 1
  77. else:
  78. N = input_imgs.shape[0]
  79. for i in range(N):
  80. pose = self.fa.get_landmarks(input_imgs[i])[0]
  81. center = ((pose.min(0) + pose.max(0)) / 2).round().astype(int)
  82. size = int(max(pose[:, 0].max() - pose[:, 0].min(), pose[:, 1].max() - pose[:, 1].min()))
  83. center[1] -= size // 6
  84. if input_imgs is None:
  85. # Crop poses
  86. if crop_data:
  87. s = size * 2
  88. pose -= center - size
  89. else:
  90. # Crop images and poses
  91. img = Image.fromarray(input_imgs[i])
  92. if crop_data:
  93. img = img.crop((center[0]-size, center[1]-size, center[0]+size, center[1]+size))
  94. s = img.size[0]
  95. pose -= center - size
  96. img = img.resize((self.args.image_size, self.args.image_size), Image.BICUBIC)
  97. imgs.append((self.to_tensor(img) - 0.5) * 2)
  98. if crop_data:
  99. pose = pose / float(s)
  100. poses.append(torch.from_numpy((pose - 0.5) * 2).view(-1))
  101. poses = torch.stack(poses, 0)[None]
  102. if self.args.output_stickmen:
  103. stickmen = ds_utils.draw_stickmen(self.args, poses[0])
  104. stickmen = stickmen[None]
  105. if input_imgs is not None:
  106. imgs = torch.stack(imgs, 0)[None]
  107. if self.args.num_gpus > 0:
  108. poses = poses.cuda()
  109. if input_imgs is not None:
  110. imgs = imgs.cuda()
  111. if self.args.output_stickmen:
  112. stickmen = stickmen.cuda()
  113. segs = None
  114. if hasattr(self, 'net_seg') and not isinstance(imgs, list):
  115. segs = self.net_seg(imgs)[None]
  116. return poses, imgs, segs, stickmen
  117. def forward(self, data_dict, crop_data=True, no_grad=True):
  118. if 'target_imgs' not in data_dict.keys():
  119. data_dict['target_imgs'] = None
  120. # Inference without finetuning
  121. (source_poses,
  122. source_imgs,
  123. source_segs,
  124. source_stickmen) = self.preprocess_data(data_dict['source_imgs'], crop_data)
  125. (target_poses,
  126. target_imgs,
  127. target_segs,
  128. target_stickmen) = self.preprocess_data(data_dict['target_imgs'], crop_data)
  129. data_dict = {
  130. 'source_imgs': source_imgs,
  131. 'source_poses': source_poses,
  132. 'target_poses': target_poses}
  133. if len(target_imgs):
  134. data_dict['target_imgs'] = target_imgs
  135. if source_segs is not None:
  136. data_dict['source_segs'] = source_segs
  137. if target_segs is not None:
  138. data_dict['target_segs'] = target_segs
  139. if source_stickmen is not None:
  140. data_dict['source_stickmen'] = source_stickmen
  141. if target_stickmen is not None:
  142. data_dict['target_stickmen'] = target_stickmen
  143. if no_grad:
  144. with torch.no_grad():
  145. self.runner(data_dict)
  146. else:
  147. self.runner(data_dict)
  148. return self.runner.data_dict
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...