evaluate.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (c) 2021, NVIDIA CORPORATION. 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 glob
  15. import os
  16. from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
  17. import nibabel
  18. import numpy as np
  19. from tqdm import tqdm
  20. parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
  21. parser.add_argument("--preds", type=str, required=True, help="Path to predictions")
  22. parser.add_argument("--lbls", type=str, required=True, help="Path to labels")
  23. def get_stats(pred, targ, class_idx):
  24. tp_ = np.logical_and(pred == class_idx, targ == class_idx).sum()
  25. fn_ = np.logical_and(pred != class_idx, targ == class_idx).sum()
  26. fp_ = np.logical_and(pred == class_idx, targ != class_idx).sum()
  27. return tp_, fn_, fp_
  28. if __name__ == "__main__":
  29. args = parser.parse_args()
  30. y_pred = sorted(glob.glob(os.path.join(args.preds, "*.npy")))
  31. y_true = [os.path.join(args.lbls, os.path.basename(pred).replace("npy", "nii.gz")) for pred in y_pred]
  32. assert len(y_pred) > 0
  33. n_class = np.load(y_pred[0]).shape[0] - 1
  34. dice = [[] for _ in range(n_class)]
  35. for pr, lb in tqdm(zip(y_pred, y_true), total=len(y_pred)):
  36. prd = np.transpose(np.argmax(np.load(pr), axis=0), (2, 1, 0))
  37. lbl = nibabel.load(lb).get_fdata().astype(np.uint8)
  38. for i in range(1, n_class + 1):
  39. counts = np.count_nonzero(lbl == i) + np.count_nonzero(prd == i)
  40. if counts == 0: # no foreground class
  41. dice[i - 1].append(1)
  42. else:
  43. tp, fn, fp = get_stats(prd, lbl, i)
  44. denum = 2 * tp + fp + fn
  45. dice[i - 1].append(2 * tp / denum if denum != 0 else 0)
  46. dice_score = np.mean(np.array(dice), axis=-1)
  47. dice_cls = " ".join([f"L{i+1} {round(dice_score[i], 4)}" for i, dice in enumerate(dice_score)])
  48. print(f"mean dice: {round(np.mean(dice_score), 4)} - {dice_cls}")