You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

eval.py 7.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Face Recognition eval."""
  16. import os
  17. import re
  18. import warnings
  19. import argparse
  20. import numpy as np
  21. from PIL import Image
  22. from tqdm import tqdm
  23. import mindspore.dataset.vision.py_transforms as V
  24. import mindspore.dataset.transforms.py_transforms as T
  25. from mindspore import context, Tensor
  26. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  27. from src.reid import SphereNet
  28. warnings.filterwarnings('ignore')
  29. def inclass_likehood(ims_info, types='cos'):
  30. '''Inclass likehood.'''
  31. obj_feas = {}
  32. likehoods = []
  33. for name, _, fea in ims_info:
  34. if re.split('_\\d\\d\\d\\d', name)[0] not in obj_feas:
  35. obj_feas[re.split('_\\d\\d\\d\\d', name)[0]] = []
  36. obj_feas[re.split('_\\d\\d\\d\\d', name)[0]].append(fea) # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  37. for _, feas in tqdm(obj_feas.items()):
  38. feas = np.array(feas)
  39. if types == 'cos':
  40. likehood_mat = np.dot(feas, np.transpose(feas)).tolist()
  41. for row in likehood_mat:
  42. likehoods += row
  43. else:
  44. for fea in feas.tolist():
  45. likehoods += np.sum(-(fea - feas) ** 2, axis=1).tolist()
  46. likehoods = np.array(likehoods)
  47. return likehoods
  48. def btclass_likehood(ims_info, types='cos'):
  49. '''Btclass likehood.'''
  50. likehoods = []
  51. count = 0
  52. for name1, _, fea1 in tqdm(ims_info):
  53. count += 1
  54. # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  55. frame_id1, _ = re.split('_\\d\\d\\d\\d', name1)[0], name1.split('_')[-1]
  56. fea1 = np.array(fea1)
  57. for name2, _, fea2 in ims_info:
  58. # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  59. frame_id2, _ = re.split('_\\d\\d\\d\\d', name2)[0], name2.split('_')[-1]
  60. if frame_id1 == frame_id2:
  61. continue
  62. fea2 = np.array(fea2)
  63. if types == 'cos':
  64. likehoods.append(np.sum(fea1 * fea2))
  65. else:
  66. likehoods.append(np.sum(-(fea1 - fea2) ** 2))
  67. likehoods = np.array(likehoods)
  68. return likehoods
  69. def tar_at_far(inlikehoods, btlikehoods):
  70. test_point = [0.5, 0.3, 0.1, 0.01, 0.001, 0.0001, 0.00001]
  71. tar_far = []
  72. for point in test_point:
  73. thre = btlikehoods[int(btlikehoods.size * point)]
  74. n_ta = np.sum(inlikehoods > thre)
  75. tar_far.append((point, float(n_ta) / inlikehoods.size, thre))
  76. return tar_far
  77. def load_images(paths, batch_size=128):
  78. '''Load images.'''
  79. ll = []
  80. resize = V.Resize((96, 64))
  81. transform = T.Compose([
  82. V.ToTensor(),
  83. V.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
  84. for i, _ in enumerate(paths):
  85. im = Image.open(paths[i])
  86. im = resize(im)
  87. img = np.array(im)
  88. ts = transform(img)
  89. ll.append(ts[0])
  90. if len(ll) == batch_size:
  91. yield np.stack(ll, axis=0)
  92. ll.clear()
  93. if ll:
  94. yield np.stack(ll, axis=0)
  95. def main(args):
  96. model_path = args.pretrained
  97. result_file = model_path.replace('.ckpt', '.txt')
  98. if os.path.exists(result_file):
  99. os.remove(result_file)
  100. with open(result_file, 'a+') as result_fw:
  101. result_fw.write(model_path + '\n')
  102. network = SphereNet(num_layers=12, feature_dim=128, shape=(96, 64))
  103. if os.path.isfile(model_path):
  104. param_dict = load_checkpoint(model_path)
  105. param_dict_new = {}
  106. for key, values in param_dict.items():
  107. if key.startswith('moments.'):
  108. continue
  109. elif key.startswith('model.'):
  110. param_dict_new[key[6:]] = values
  111. else:
  112. param_dict_new[key] = values
  113. load_param_into_net(network, param_dict_new)
  114. print('-----------------------load model success-----------------------')
  115. else:
  116. print('-----------------------load model failed -----------------------')
  117. if args.device_target == 'CPU':
  118. network.add_flags_recursive(fp32=True)
  119. else:
  120. network.add_flags_recursive(fp16=True)
  121. network.set_train(False)
  122. root_path = args.eval_dir
  123. root_file_list = os.listdir(root_path)
  124. ims_info = []
  125. for sub_path in root_file_list:
  126. for im_path in os.listdir(os.path.join(root_path, sub_path)):
  127. ims_info.append((im_path.split('.')[0], os.path.join(root_path, sub_path, im_path)))
  128. paths = [path for name, path in ims_info]
  129. names = [name for name, path in ims_info]
  130. print("exact feature...")
  131. l_t = []
  132. for batch in load_images(paths):
  133. batch = batch.astype(np.float32)
  134. batch = Tensor(batch)
  135. fea = network(batch)
  136. l_t.append(fea.asnumpy().astype(np.float16))
  137. feas = np.concatenate(l_t, axis=0)
  138. ims_info = list(zip(names, paths, feas.tolist()))
  139. print("exact inclass likehood...")
  140. inlikehoods = inclass_likehood(ims_info)
  141. inlikehoods[::-1].sort()
  142. print("exact btclass likehood...")
  143. btlikehoods = btclass_likehood(ims_info)
  144. btlikehoods[::-1].sort()
  145. tar_far = tar_at_far(inlikehoods, btlikehoods)
  146. for far, tar, thre in tar_far:
  147. print('---{}: {}@{}'.format(far, tar, thre))
  148. for far, tar, thre in tar_far:
  149. result_fw.write('{}: {}@{} \n'.format(far, tar, thre))
  150. if __name__ == "__main__":
  151. parser = argparse.ArgumentParser(description='reid test')
  152. parser.add_argument('--pretrained', type=str, default='', help='pretrained model to load')
  153. parser.add_argument('--eval_dir', type=str, default='', help='eval image dir, e.g. /home/test')
  154. parser.add_argument('--device_target', type=str, choices=['Ascend', 'GPU', 'CPU'], default='Ascend',
  155. help='device_target')
  156. arg = parser.parse_args()
  157. context.set_context(mode=context.GRAPH_MODE, device_target=arg.device_target, save_graphs=False)
  158. if arg.device_target == 'Ascend':
  159. devid = int(os.getenv('DEVICE_ID'))
  160. context.set_context(device_id=devid)
  161. print(arg)
  162. main(arg)