mat2json.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import json
  4. import time
  5. from scipy.io import loadmat
  6. def parse_args():
  7. parser = argparse.ArgumentParser(
  8. description='Converting the predicted .mat file to .json file.')
  9. parser.add_argument('pred_mat_file', help='input prediction mat file.')
  10. parser.add_argument(
  11. 'gt_json_file',
  12. help='input ground-truth json file to get the image name. '
  13. 'Default: "data/mpii/mpii_val.json" ')
  14. parser.add_argument('output_json_file', help='output converted json file.')
  15. args = parser.parse_args()
  16. return args
  17. def save_json(list_file, path):
  18. with open(path, 'w') as f:
  19. json.dump(list_file, f, indent=4)
  20. return 0
  21. def convert_mat(pred_mat_file, gt_json_file, output_json_file):
  22. res = loadmat(pred_mat_file)
  23. preds = res['preds']
  24. N = preds.shape[0]
  25. with open(gt_json_file) as anno_file:
  26. anno = json.load(anno_file)
  27. assert len(anno) == N
  28. instance = {}
  29. for pred, ann in zip(preds, anno):
  30. ann.pop('joints_vis')
  31. ann['joints'] = pred.tolist()
  32. instance['annotations'] = anno
  33. instance['info'] = {}
  34. instance['info']['description'] = 'Converted MPII prediction.'
  35. instance['info']['year'] = time.strftime('%Y', time.localtime())
  36. instance['info']['date_created'] = time.strftime('%Y/%m/%d',
  37. time.localtime())
  38. save_json(instance, output_json_file)
  39. def main():
  40. args = parse_args()
  41. convert_mat(args.pred_mat_file, args.gt_json_file, args.output_json_file)
  42. if __name__ == '__main__':
  43. main()