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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. """eval deeplabv3."""
  16. import os
  17. import argparse
  18. import numpy as np
  19. import cv2
  20. from mindspore import Tensor
  21. import mindspore.common.dtype as mstype
  22. import mindspore.nn as nn
  23. from mindspore import context
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from src.nets import net_factory
  26. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False,
  27. device_id=int(os.getenv('DEVICE_ID')))
  28. def parse_args():
  29. parser = argparse.ArgumentParser('mindspore deeplabv3 eval')
  30. # val data
  31. parser.add_argument('--data_root', type=str, default='', help='root path of val data')
  32. parser.add_argument('--data_lst', type=str, default='', help='list of val data')
  33. parser.add_argument('--batch_size', type=int, default=16, help='batch size')
  34. parser.add_argument('--crop_size', type=int, default=513, help='crop size')
  35. parser.add_argument('--image_mean', type=list, default=[103.53, 116.28, 123.675], help='image mean')
  36. parser.add_argument('--image_std', type=list, default=[57.375, 57.120, 58.395], help='image std')
  37. parser.add_argument('--scales', type=float, action='append', help='scales of evaluation')
  38. parser.add_argument('--flip', action='store_true', help='perform left-right flip')
  39. parser.add_argument('--ignore_label', type=int, default=255, help='ignore label')
  40. parser.add_argument('--num_classes', type=int, default=21, help='number of classes')
  41. # model
  42. parser.add_argument('--model', type=str, default='deeplab_v3_s16', help='select model')
  43. parser.add_argument('--freeze_bn', action='store_true', default=False, help='freeze bn')
  44. parser.add_argument('--ckpt_path', type=str, default='', help='model to evaluate')
  45. args, _ = parser.parse_known_args()
  46. return args
  47. def cal_hist(a, b, n):
  48. k = (a >= 0) & (a < n)
  49. return np.bincount(n * a[k].astype(np.int32) + b[k], minlength=n ** 2).reshape(n, n)
  50. def resize_long(img, long_size=513):
  51. h, w, _ = img.shape
  52. if h > w:
  53. new_h = long_size
  54. new_w = int(1.0 * long_size * w / h)
  55. else:
  56. new_w = long_size
  57. new_h = int(1.0 * long_size * h / w)
  58. imo = cv2.resize(img, (new_w, new_h))
  59. return imo
  60. class BuildEvalNetwork(nn.Cell):
  61. def __init__(self, network):
  62. super(BuildEvalNetwork, self).__init__()
  63. self.network = network
  64. self.softmax = nn.Softmax(axis=1)
  65. def construct(self, input_data):
  66. output = self.network(input_data)
  67. output = self.softmax(output)
  68. return output
  69. def pre_process(args, img_, crop_size=513):
  70. # resize
  71. img_ = resize_long(img_, crop_size)
  72. resize_h, resize_w, _ = img_.shape
  73. # mean, std
  74. image_mean = np.array(args.image_mean)
  75. image_std = np.array(args.image_std)
  76. img_ = (img_ - image_mean) / image_std
  77. # pad to crop_size
  78. pad_h = crop_size - img_.shape[0]
  79. pad_w = crop_size - img_.shape[1]
  80. if pad_h > 0 or pad_w > 0:
  81. img_ = cv2.copyMakeBorder(img_, 0, pad_h, 0, pad_w, cv2.BORDER_CONSTANT, value=0)
  82. # hwc to chw
  83. img_ = img_.transpose((2, 0, 1))
  84. return img_, resize_h, resize_w
  85. def eval_batch(args, eval_net, img_lst, crop_size=513, flip=True):
  86. result_lst = []
  87. batch_size = len(img_lst)
  88. batch_img = np.zeros((args.batch_size, 3, crop_size, crop_size), dtype=np.float32)
  89. resize_hw = []
  90. for l in range(batch_size):
  91. img_ = img_lst[l]
  92. img_, resize_h, resize_w = pre_process(args, img_, crop_size)
  93. batch_img[l] = img_
  94. resize_hw.append([resize_h, resize_w])
  95. batch_img = np.ascontiguousarray(batch_img)
  96. net_out = eval_net(Tensor(batch_img, mstype.float32))
  97. net_out = net_out.asnumpy()
  98. if flip:
  99. batch_img = batch_img[:, :, :, ::-1]
  100. net_out_flip = eval_net(Tensor(batch_img, mstype.float32))
  101. net_out += net_out_flip.asnumpy()[:, :, :, ::-1]
  102. for bs in range(batch_size):
  103. probs_ = net_out[bs][:, :resize_hw[bs][0], :resize_hw[bs][1]].transpose((1, 2, 0))
  104. ori_h, ori_w = img_lst[bs].shape[0], img_lst[bs].shape[1]
  105. probs_ = cv2.resize(probs_, (ori_w, ori_h))
  106. result_lst.append(probs_)
  107. return result_lst
  108. def eval_batch_scales(args, eval_net, img_lst, scales,
  109. base_crop_size=513, flip=True):
  110. sizes_ = [int((base_crop_size - 1) * sc) + 1 for sc in scales]
  111. probs_lst = eval_batch(args, eval_net, img_lst, crop_size=sizes_[0], flip=flip)
  112. print(sizes_)
  113. for crop_size_ in sizes_[1:]:
  114. probs_lst_tmp = eval_batch(args, eval_net, img_lst, crop_size=crop_size_, flip=flip)
  115. for pl, _ in enumerate(probs_lst):
  116. probs_lst[pl] += probs_lst_tmp[pl]
  117. result_msk = []
  118. for i in probs_lst:
  119. result_msk.append(i.argmax(axis=2))
  120. return result_msk
  121. def net_eval():
  122. args = parse_args()
  123. # data list
  124. with open(args.data_lst) as f:
  125. img_lst = f.readlines()
  126. # network
  127. if args.model == 'deeplab_v3_s16':
  128. network = net_factory.nets_map[args.model]('eval', args.num_classes, 16, args.freeze_bn)
  129. elif args.model == 'deeplab_v3_s8':
  130. network = net_factory.nets_map[args.model]('eval', args.num_classes, 8, args.freeze_bn)
  131. else:
  132. raise NotImplementedError('model [{:s}] not recognized'.format(args.model))
  133. eval_net = BuildEvalNetwork(network)
  134. # load model
  135. param_dict = load_checkpoint(args.ckpt_path)
  136. load_param_into_net(eval_net, param_dict)
  137. eval_net.set_train(False)
  138. # evaluate
  139. hist = np.zeros((args.num_classes, args.num_classes))
  140. batch_img_lst = []
  141. batch_msk_lst = []
  142. bi = 0
  143. image_num = 0
  144. for i, line in enumerate(img_lst):
  145. img_path, msk_path = line.strip().split(' ')
  146. img_path = os.path.join(args.data_root, img_path)
  147. msk_path = os.path.join(args.data_root, msk_path)
  148. img_ = cv2.imread(img_path)
  149. msk_ = cv2.imread(msk_path, cv2.IMREAD_GRAYSCALE)
  150. batch_img_lst.append(img_)
  151. batch_msk_lst.append(msk_)
  152. bi += 1
  153. if bi == args.batch_size:
  154. batch_res = eval_batch_scales(args, eval_net, batch_img_lst, scales=args.scales,
  155. base_crop_size=args.crop_size, flip=args.flip)
  156. for mi in range(args.batch_size):
  157. hist += cal_hist(batch_msk_lst[mi].flatten(), batch_res[mi].flatten(), args.num_classes)
  158. bi = 0
  159. batch_img_lst = []
  160. batch_msk_lst = []
  161. print('processed {} images'.format(i+1))
  162. image_num = i
  163. if bi > 0:
  164. batch_res = eval_batch_scales(args, eval_net, batch_img_lst, scales=args.scales,
  165. base_crop_size=args.crop_size, flip=args.flip)
  166. for mi in range(bi):
  167. hist += cal_hist(batch_msk_lst[mi].flatten(), batch_res[mi].flatten(), args.num_classes)
  168. print('processed {} images'.format(image_num + 1))
  169. print(hist)
  170. iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist))
  171. print('per-class IoU', iu)
  172. print('mean IoU', np.nanmean(iu))
  173. if __name__ == '__main__':
  174. net_eval()