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

3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. """YoloV5 eval."""
  16. import os
  17. import time
  18. import numpy as np
  19. import mindspore as ms
  20. from src.yolo import YOLOV5
  21. from src.logger import get_logger
  22. from src.util import DetectionEngine
  23. from src.yolo_dataset import create_yolo_dataset
  24. from model_utils.config import config
  25. # only useful for huawei cloud modelarts
  26. from model_utils.moxing_adapter import moxing_wrapper, modelarts_pre_process
  27. def eval_preprocess():
  28. config.data_root = os.path.join(config.data_dir, 'dataset/inference')
  29. config.ann_file = os.path.join(config.data_dir, 'coco/annotations.json')
  30. device_id = int(os.getenv('DEVICE_ID', '0'))
  31. ms.set_context(mode=ms.GRAPH_MODE, device_target=config.device_target, device_id=device_id)
  32. # logger module is managed by config, it is used in other function. e.x. config.logger.info("xxx")
  33. config.logger = get_logger(config.output_dir, device_id)
  34. def load_parameters(network, filename):
  35. config.logger.info("yolov5 pretrained network model: %s", filename)
  36. param_dict = ms.load_checkpoint(filename)
  37. param_dict_new = {}
  38. for key, values in param_dict.items():
  39. if key.startswith('moments.'):
  40. continue
  41. elif key.startswith('yolo_network.'):
  42. param_dict_new[key[13:]] = values
  43. else:
  44. param_dict_new[key] = values
  45. ms.load_param_into_net(network, param_dict_new)
  46. config.logger.info('load_model %s success', filename)
  47. @moxing_wrapper(pre_process=modelarts_pre_process, pre_args=[config])
  48. def run_eval():
  49. eval_preprocess()
  50. start_time = time.time()
  51. config.logger.info('Creating Network....')
  52. dict_version = {'yolov5s': 0, 'yolov5m': 1, 'yolov5l': 2, 'yolov5x': 3}
  53. network = YOLOV5(is_training=False, version=dict_version[config.yolov5_version])
  54. if os.path.isfile(config.pretrained):
  55. load_parameters(network, config.pretrained)
  56. else:
  57. raise FileNotFoundError(f"{config.pretrained} is not a filename.")
  58. ds = create_yolo_dataset(config.data_root, config.ann_file, is_training=False, batch_size=config.per_batch_size,
  59. device_num=1, rank=0, shuffle=False, config=config)
  60. config.logger.info('testing shape : %s', config.test_img_shape)
  61. config.logger.info('total %d images to eval', ds.get_dataset_size() * config.per_batch_size)
  62. network.set_train(False)
  63. # init detection engine
  64. detection = DetectionEngine(config, config.test_ignore_threshold)
  65. input_shape = ms.Tensor(tuple(config.test_img_shape), ms.float32)
  66. config.logger.info('Start inference....')
  67. for index, data in enumerate(ds.create_dict_iterator(output_numpy=True, num_epochs=1)):
  68. image = data["image"]
  69. # adapt network shape of input data
  70. image = np.concatenate((image[..., ::2, ::2], image[..., 1::2, ::2],
  71. image[..., ::2, 1::2], image[..., 1::2, 1::2]), axis=1)
  72. image = ms.Tensor(image)
  73. image_shape_ = data["image_shape"]
  74. image_id_ = data["img_id"]
  75. output_big, output_me, output_small = network(image, input_shape)
  76. output_big = output_big.asnumpy()
  77. output_me = output_me.asnumpy()
  78. output_small = output_small.asnumpy()
  79. detection.detect([output_small, output_me, output_big], config.per_batch_size, image_shape_, image_id_)
  80. if index % 50 == 0:
  81. config.logger.info('Processing... {:.2f}% '.format(index / ds.get_dataset_size() * 100))
  82. config.logger.info('Calculating mAP...')
  83. detection.do_nms_for_results()
  84. result_file_path = detection.write_result()
  85. config.logger.info('result file path: %s', result_file_path)
  86. eval_result = detection.get_eval_result()
  87. cost_time = time.time() - start_time
  88. eval_log_string = '\n=============coco eval result=========\n' + eval_result
  89. config.logger.info(eval_log_string)
  90. config.logger.info('testing cost time %.2f h', cost_time / 3600.)
  91. if __name__ == "__main__":
  92. run_eval()

随着人工智能和大数据的发展,任一方面对自动化工具有着一定的需求,在当下疫情防控期间,使用mindspore来实现yolo模型来进行目标检测及语义分割,对视频或图片都可以进行口罩佩戴检测和行人社交距离检测,来对公共场所的疫情防控来实行自动化管理。