visualize.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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 os
  15. import cv2
  16. import copy
  17. import os.path as osp
  18. import numpy as np
  19. from .core.explanation import Explanation
  20. def visualize(img_file,
  21. model,
  22. explanation_type='lime',
  23. num_samples=3000,
  24. batch_size=50,
  25. save_dir='./'):
  26. model.arrange_transforms(
  27. transforms=model.test_transforms, mode='test')
  28. tmp_transforms = copy.deepcopy(model.test_transforms)
  29. tmp_transforms.transforms = tmp_transforms.transforms[:-2]
  30. img = tmp_transforms(img_file)[0]
  31. img = np.around(img).astype('uint8')
  32. img = np.expand_dims(img, axis=0)
  33. explaier = None
  34. if explanation_type == 'lime':
  35. explaier = get_lime_explaier(img, model, num_samples=num_samples, batch_size=batch_size)
  36. else:
  37. raise Exception('The {} explanantion method is not supported yet!'.format(explanation_type))
  38. img_name = osp.splitext(osp.split(img_file)[-1])[0]
  39. explaier.explain(img, save_dir=save_dir)
  40. def get_lime_explaier(img, model, num_samples=3000, batch_size=50):
  41. def predict_func(image):
  42. image = image.astype('float32')
  43. model.test_transforms.transforms = model.test_transforms.transforms[-2:]
  44. out = model.explanation_predict(image)
  45. return out[0]
  46. explaier = Explanation('lime',
  47. predict_func,
  48. num_samples=num_samples,
  49. batch_size=batch_size)
  50. return explaier