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 6.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright 2020 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. devid = int(os.getenv('DEVICE_ID'))
  30. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=True, device_id=devid)
  31. def inclass_likehood(ims_info, types='cos'):
  32. '''Inclass likehood.'''
  33. obj_feas = {}
  34. likehoods = []
  35. for name, _, fea in ims_info:
  36. if re.split('_\\d\\d\\d\\d', name)[0] not in obj_feas:
  37. obj_feas[re.split('_\\d\\d\\d\\d', name)[0]] = []
  38. obj_feas[re.split('_\\d\\d\\d\\d', name)[0]].append(fea) # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  39. for _, feas in tqdm(obj_feas.items()):
  40. feas = np.array(feas)
  41. if types == 'cos':
  42. likehood_mat = np.dot(feas, np.transpose(feas)).tolist()
  43. for row in likehood_mat:
  44. likehoods += row
  45. else:
  46. for fea in feas.tolist():
  47. likehoods += np.sum(-(fea - feas) ** 2, axis=1).tolist()
  48. likehoods = np.array(likehoods)
  49. return likehoods
  50. def btclass_likehood(ims_info, types='cos'):
  51. '''Btclass likehood.'''
  52. likehoods = []
  53. count = 0
  54. for name1, _, fea1 in tqdm(ims_info):
  55. count += 1
  56. # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  57. frame_id1, _ = re.split('_\\d\\d\\d\\d', name1)[0], name1.split('_')[-1]
  58. fea1 = np.array(fea1)
  59. for name2, _, fea2 in ims_info:
  60. # pylint: "_\d\d\d\d" -> "_\\d\\d\\d\\d"
  61. frame_id2, _ = re.split('_\\d\\d\\d\\d', name2)[0], name2.split('_')[-1]
  62. if frame_id1 == frame_id2:
  63. continue
  64. fea2 = np.array(fea2)
  65. if types == 'cos':
  66. likehoods.append(np.sum(fea1 * fea2))
  67. else:
  68. likehoods.append(np.sum(-(fea1 - fea2) ** 2))
  69. likehoods = np.array(likehoods)
  70. return likehoods
  71. def tar_at_far(inlikehoods, btlikehoods):
  72. test_point = [0.5, 0.3, 0.1, 0.01, 0.001, 0.0001, 0.00001]
  73. tar_far = []
  74. for point in test_point:
  75. thre = btlikehoods[int(btlikehoods.size * point)]
  76. n_ta = np.sum(inlikehoods > thre)
  77. tar_far.append((point, float(n_ta) / inlikehoods.size, thre))
  78. return tar_far
  79. def load_images(paths, batch_size=128):
  80. '''Load images.'''
  81. ll = []
  82. resize = V.Resize((96, 64))
  83. transform = T.Compose([
  84. V.ToTensor(),
  85. V.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
  86. for i, _ in enumerate(paths):
  87. im = Image.open(paths[i])
  88. im = resize(im)
  89. img = np.array(im)
  90. ts = transform(img)
  91. ll.append(ts[0])
  92. if len(ll) == batch_size:
  93. yield np.stack(ll, axis=0)
  94. ll.clear()
  95. if ll:
  96. yield np.stack(ll, axis=0)
  97. def main(args):
  98. model_path = args.pretrained
  99. result_file = model_path.replace('.ckpt', '.txt')
  100. if os.path.exists(result_file):
  101. os.remove(result_file)
  102. with open(result_file, 'a+') as result_fw:
  103. result_fw.write(model_path + '\n')
  104. network = SphereNet(num_layers=12, feature_dim=128, shape=(96, 64))
  105. if os.path.isfile(model_path):
  106. param_dict = load_checkpoint(model_path)
  107. param_dict_new = {}
  108. for key, values in param_dict.items():
  109. if key.startswith('moments.'):
  110. continue
  111. elif key.startswith('model.'):
  112. param_dict_new[key[6:]] = values
  113. else:
  114. param_dict_new[key] = values
  115. load_param_into_net(network, param_dict_new)
  116. print('-----------------------load model success-----------------------')
  117. else:
  118. print('-----------------------load model failed -----------------------')
  119. network.add_flags_recursive(fp16=True)
  120. network.set_train(False)
  121. root_path = args.eval_dir
  122. root_file_list = os.listdir(root_path)
  123. ims_info = []
  124. for sub_path in root_file_list:
  125. for im_path in os.listdir(os.path.join(root_path, sub_path)):
  126. ims_info.append((im_path.split('.')[0], os.path.join(root_path, sub_path, im_path)))
  127. paths = [path for name, path in ims_info]
  128. names = [name for name, path in ims_info]
  129. print("exact feature...")
  130. l_t = []
  131. for batch in load_images(paths):
  132. batch = batch.astype(np.float32)
  133. batch = Tensor(batch)
  134. fea = network(batch)
  135. l_t.append(fea.asnumpy().astype(np.float16))
  136. feas = np.concatenate(l_t, axis=0)
  137. ims_info = list(zip(names, paths, feas.tolist()))
  138. print("exact inclass likehood...")
  139. inlikehoods = inclass_likehood(ims_info)
  140. inlikehoods[::-1].sort()
  141. print("exact btclass likehood...")
  142. btlikehoods = btclass_likehood(ims_info)
  143. btlikehoods[::-1].sort()
  144. tar_far = tar_at_far(inlikehoods, btlikehoods)
  145. for far, tar, thre in tar_far:
  146. print('---{}: {}@{}'.format(far, tar, thre))
  147. for far, tar, thre in tar_far:
  148. result_fw.write('{}: {}@{} \n'.format(far, tar, thre))
  149. if __name__ == "__main__":
  150. parser = argparse.ArgumentParser(description='reid test')
  151. parser.add_argument('--pretrained', type=str, default='', help='pretrained model to load')
  152. parser.add_argument('--eval_dir', type=str, default='', help='eval image dir, e.g. /home/test')
  153. arg = parser.parse_args()
  154. print(arg)
  155. main(arg)