bmodel_test.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import argparse
  2. import sophon.sail as sail
  3. import cv2
  4. import os
  5. import logging
  6. import json
  7. import numpy as np
  8. class Predictor:
  9. def __init__(self):
  10. # 加载推理引擎
  11. self.net = sail.Engine(args.bmodel, args.dev_id, sail.IOMode.SYSIO)
  12. self.graph_name = self.net.get_graph_names()[0]
  13. self.input_names = self.net.get_input_names(self.graph_name)
  14. self.input_shapes = [self.net.get_input_shape(self.graph_name, name) for name in self.input_names]
  15. self.output_names = self.net.get_output_names(self.graph_name)
  16. self.output_shapes = [self.net.get_output_shape(self.graph_name, name) for name in self.output_names] # [[1, 2]]
  17. self.input_name = self.input_names[0]
  18. self.input_shape = self.input_shapes[0] # [1, 3, 256, 256]
  19. self.batch_size = self.input_shape[0]
  20. self.net_h = self.input_shape[2] # 输入图像的高
  21. self.net_w = self.input_shape[3] # 输入图像的宽
  22. # 归一化参数,采用imagenet预训练参数
  23. self.mean = [0.485, 0.456, 0.406]
  24. self.std = [0.229, 0.224, 0.225]
  25. self.print_network_info()
  26. def __call__(self, img):
  27. return self.predict(img)
  28. def print_network_info(self):
  29. info = {
  30. 'Graph Name': self.graph_name,
  31. 'Input Name': self.input_name,
  32. 'Output Names': self.output_names,
  33. 'Output Shapes': self.output_shapes,
  34. 'Input Shape': self.input_shape,
  35. 'Batch Size': self.batch_size,
  36. 'Height': self.net_h,
  37. 'Width': self.net_w,
  38. 'Mean': self.mean,
  39. 'Std': self.std
  40. }
  41. print("=" * 50)
  42. print("Network Configuration Info")
  43. print("=" * 50)
  44. for key, value in info.items():
  45. print(f"{key:<18}: {value}")
  46. print("=" * 50)
  47. def predict(self, input_img):
  48. input_data = {self.input_name: input_img}
  49. outputs = self.net.process(self.graph_name, input_data)
  50. # print('predict fun:', outputs)
  51. # print('predict fun return:', list(outputs.values())[0])
  52. return list(outputs.values())[0]
  53. def preprocess(self, img):
  54. h, w, _ = img.shape
  55. if h != 256 or w != 256:
  56. img = cv2.resize(img, (self.net_w, self.net_h))
  57. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  58. img = img.astype('float32')
  59. img = (img / 255 - self.mean) / self.std # 这一步是很有必要的
  60. # img = img / 255. # 编译过程并不会帮你做归一化,所以这里要自己做归一化,否则预测数值可能会非常不准确
  61. img = np.transpose(img, (2, 0, 1))
  62. return img
  63. def postprocess(self, outputs):
  64. outputs_exp = np.exp(outputs)
  65. # print('exp res:', outputs_exp)
  66. outputs = outputs_exp / np.sum(outputs_exp, axis=1)[:, None]
  67. # print('softmax res:', outputs)
  68. predictions = np.argmax(outputs, axis=1) # 返回最大概率的类别
  69. # print('预测结果:', predictions)
  70. return predictions
  71. def argsparser():
  72. parser = argparse.ArgumentParser(prog=__file__)
  73. parser.add_argument('--input', type=str, default='./test', help='path of input, must be image directory')
  74. parser.add_argument('--bmodel', type=str, default='./shufflenet_f32.bmodel', help='path of bmodel')
  75. parser.add_argument('--dev_id', type=int, default=0, help='tpu id')
  76. args = parser.parse_args()
  77. return args
  78. def main(args):
  79. # 加载推理引擎
  80. predictor = Predictor()
  81. # 获取图片
  82. cls = os.listdir(args.input)
  83. # cls = os.listdir('./label_data/test')
  84. filename = {}
  85. for c in cls:
  86. # filename[c] = [os.path.join('./label_data/test', p) for p in os.listdir(os.path.join('./label_data/test', c))]
  87. filename[c] = [os.path.join(args.input,c, p) for p in os.listdir(os.path.join(args.input, c))]
  88. print('find data:')
  89. for k, v in filename.items():
  90. print(f'{k}: {len(v)}')
  91. print('开始推理...')
  92. res_list=[]
  93. for k, v in filename.items():
  94. for i in v:
  95. src_img = cv2.imread(i, cv2.IMREAD_COLOR)
  96. src_img = predictor.preprocess(src_img)
  97. res = [-1]
  98. if src_img is not None:
  99. src_img = np.stack([src_img])
  100. res = predictor(src_img)
  101. res = predictor.postprocess(res)
  102. print(f'{k}: {res[0]}')
  103. res_list.append([i, k, res[0]])
  104. # 保存结果为 json
  105. res_dict = {}
  106. for path, real_value, pred_value in res_list:
  107. res_dict[path] = {'y':int(real_value), 'x':int(pred_value)}
  108. res_save_path = f'{predictor.graph_name}_prediction_result.json'
  109. with open(res_save_path, 'w') as f:
  110. json.dump(res_dict, f)
  111. print(f'保存结果为 {res_save_path} 成功!')
  112. if __name__ == '__main__':
  113. args = argsparser()
  114. main(args)