fm_vis.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import numpy as np
  15. import cv2
  16. import utils
  17. import argparse
  18. import os
  19. import sys
  20. __dir__ = os.path.dirname(os.path.abspath(__file__))
  21. sys.path.append(__dir__)
  22. sys.path.append(os.path.abspath(os.path.join(__dir__, '../../..')))
  23. import paddle
  24. from paddle.distributed import ParallelEnv
  25. from resnet import ResNet50
  26. from paddlex.ppcls.utils.save_load import load_dygraph_pretrain
  27. def parse_args():
  28. def str2bool(v):
  29. return v.lower() in ("true", "t", "1")
  30. parser = argparse.ArgumentParser()
  31. parser.add_argument("-i", "--image_file", required=True, type=str)
  32. parser.add_argument("-c", "--channel_num", type=int)
  33. parser.add_argument("-p", "--pretrained_model", type=str)
  34. parser.add_argument("--show", type=str2bool, default=False)
  35. parser.add_argument("--interpolation", type=int, default=1)
  36. parser.add_argument("--save_path", type=str, default=None)
  37. parser.add_argument("--use_gpu", type=str2bool, default=True)
  38. return parser.parse_args()
  39. def create_operators(interpolation=1):
  40. size = 224
  41. img_mean = [0.485, 0.456, 0.406]
  42. img_std = [0.229, 0.224, 0.225]
  43. img_scale = 1.0 / 255.0
  44. resize_op = utils.ResizeImage(
  45. resize_short=256, interpolation=interpolation)
  46. crop_op = utils.CropImage(size=(size, size))
  47. normalize_op = utils.NormalizeImage(
  48. scale=img_scale, mean=img_mean, std=img_std)
  49. totensor_op = utils.ToTensor()
  50. return [resize_op, crop_op, normalize_op, totensor_op]
  51. def preprocess(data, ops):
  52. for op in ops:
  53. data = op(data)
  54. return data
  55. def main():
  56. args = parse_args()
  57. operators = create_operators(args.interpolation)
  58. # assign the place
  59. place = 'gpu:{}'.format(ParallelEnv().dev_id) if args.use_gpu else 'cpu'
  60. place = paddle.set_device(place)
  61. net = ResNet50()
  62. load_dygraph_pretrain(net, args.pretrained_model)
  63. img = cv2.imread(args.image_file, cv2.IMREAD_COLOR)
  64. data = preprocess(img, operators)
  65. data = np.expand_dims(data, axis=0)
  66. data = paddle.to_tensor(data)
  67. net.eval()
  68. _, fm = net(data)
  69. assert args.channel_num >= 0 and args.channel_num <= fm.shape[
  70. 1], "the channel is out of the range, should be in {} but got {}".format(
  71. [0, fm.shape[1]], args.channel_num)
  72. fm = (np.squeeze(fm[0][args.channel_num].numpy()) * 255).astype(np.uint8)
  73. fm = cv2.resize(fm, (img.shape[1], img.shape[0]))
  74. if args.save_path is not None:
  75. print("the feature map is saved in path: {}".format(args.save_path))
  76. cv2.imwrite(args.save_path, fm)
  77. if __name__ == "__main__":
  78. main()