code: def main():
      args = parse_args()
      load_result = args.load_result
      num_gpus = args.gpus
  
      if not load_result:
          index = args.index
          model = PoseEstimationInferenceModel(
              model_prefix=args.model_prefix,
              gpu_id=index,
              image_width=args.image_width,
              image_height=args.image_height,
              threshold=0.05,
          )
  
          for dataset_name in args.val_annotations:
              gt_file = DATASET_INFO[dataset_name]["ann_file"]
              img_dir = DATASET_INFO[dataset_name]["img_dir"]
  
              val_imgs = json.load(open(gt_file))["images"]
              start_index = (len(val_imgs) // num_gpus + 1) * index
              end_index = (len(val_imgs) // num_gpus + 1) * (index + 1)
  
              coco_results = []
              count = 0
              for img_name in tqdm(val_imgs[start_index:end_index]):
                  # Test on image, change from BGR channel to RGB channel
                  raw_image = cv2.imread(
                      os.path.join(img_dir, img_name["file_name"])
                  )
                  # raw_image = np.array(Image.open(os.path.join(img_dir, img_name["file_name"])))[:, :, ::-1]
                  # raw_image = raw_image[:, :, ::-1]
                  image = {"image": raw_image, "transform_info": None}
  
                  result = model.process([image])
                  # print(result)
                  # viusalize(image, result[0], output_path=img_name['file_name'])
                  # count += 1
                  # if count == 5:
                  #     raise
                  # raise
                  for bbox, cat_id, score, kpt in zip(
                      result[0]["bboxes"],
                      result[0]["class_ids"],
                      result[0]["scores"],
                      result[0]["keypoints"],
                  ):
                      coco_results.append(
                          {
                              "image_id": img_name["id"],
                              "category_id": int(cat_id + 1),
                              "keypoints": kpt.flatten()
                              .astype(float)
                              .tolist(),
                              "bbox": bbox.flatten()
                              .astype(float)
                              .tolist(),
                              "score": float(score[0]),
                          }
                      )
  
              os.makedirs(
                  os.path.join(args.export_dir, dataset_name),
                  exist_ok=True,
              )
              with open(
                  os.path.join(
                      args.export_dir,
                      dataset_name,
                      "{}_end2endtest.json".format(index),
                  ),
                  "w",
              ) as f:
                  json.dump(coco_results, f)
      else:
          for dataset_name in args.val_annotations:
              gt_file = DATASET_INFO[dataset_name]["ann_file"]
  
              # Aggregate All end2end test result and filter low confidence person detections
              if not os.path.exists(
                  os.path.join(args.export_dir, dataset_name)
              ):
                  print(
                      "Please run distribute_test.sh first to save prediction results!"
                  )
                  return
  
              res_figure = os.path.join(
                  args.export_dir, dataset_name, "PRCurve.png"
              )
              res_file = os.path.join(
                  args.export_dir, dataset_name, "final_res.json"
              )
              if not os.path.exists(res_file):
                  final_res = []
                  for index in range(num_gpus):
                      final_res.extend(
                          json.load(
                              open(
                                  os.path.join(
                                      args.export_dir,
                                      dataset_name,
                                      "{}_end2endtest.json".format(
                                          index
                                      ),
                                  ),
                                  "r",
                              )
                          )
                      )
                  with open(res_file, "w") as f:
                      json.dump(final_res, f)
  
              # COCO based evaluation
              from pycocotools.coco import COCO
              from pycocotools.cocoeval import COCOeval
  
              coco_gt = COCO(gt_file)
              coco_dt = coco_gt.loadRes(res_file)
              coco_eval = COCOeval(coco_gt, coco_dt, "keypoints")
              coco_eval.evaluate()
              coco_eval.accumulate()
              coco_eval.summarize()
  
              # Per category evaluation PR Curve
              IoU_lo_thresh = 0.5
              ind_lo = _get_thr_ind(coco_eval, IoU_lo_thresh)
  
              num_class = args.num_classes
              precision = coco_eval.eval["precision"][
                  ind_lo, :, :num_class, 0, 0
              ]
              mAP = np.mean(precision[precision > -1])
              print(
                  "mAP @ OKS={:.2f} : {:.4f}".format(IoU_lo_thresh, mAP)
              )
  
              recall = np.linspace(
                  0.0,
                  1.00,
                  int(np.round((1.00 - 0.0) / 0.01)) + 1,
                  endpoint=True,
              )
              color = [("b-", "person")]
  
              for cls_ind in range(num_class):
                  mAP = coco_eval.eval["precision"][:, :, cls_ind, 0, 0]
                  mAP = np.mean(mAP[mAP > -1])
                  if not np.isnan(mAP):
                      print(
                          "Class {} mAP @ OKS=0.5:0.95 : {:.4f}".format(
                              cls_ind, mAP
                          )
                      )
                  prec = precision[:, cls_ind]
                  ap = np.mean(prec[prec > -1])
                  if not np.isnan(ap):
                      print("Class {}: {:.4f}".format(cls_ind, ap))
                      plt.plot(
                          recall,
                          prec,
                          color[cls_ind][0],
                          label=color[cls_ind][1],
                      )
  
              plt.xlabel("recall")
              plt.ylabel("precision")
              plt.legend()
              plt.xlim(0, 1.0)
              plt.ylim(0, 1.01)
              plt.savefig(res_figure)
  
file_path: gluon-cv/scripts/pose/directpose/tvm_evaluation/evaluate_pose.py
imports: import json
  import numpy
  import os
  from pose_model import PoseEstimationInferenceModel
  import cv2
  from PIL import Image
  from tqdm import tqdm
  import matplotlib
  import matplotlib.pyplot
label_desc: Use image node_id 5 for calling a global function with example usage: main() without return types