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.1 kB

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