text: import glob
  import os
  from collections import OrderedDict
  
  import numpy as np
  from detectron2.evaluation.cityscapes_evaluation import CityscapesEvaluator
  from detectron2.utils import comm
  from detectron2.utils.file_io import PathManager
  from PIL import Image
  
  __all__ = ["CityscapesSemSegEvaluator"]
  
  
  class CityscapesSemSegEvaluator(CityscapesEvaluator):
      """
      Evaluate semantic segmentation results on cityscapes dataset using cityscapes API.
  
      Note:
          * It does not work in multi-machine distributed training.
          * It contains a synchronization, therefore has to be used on all ranks.
          * Only the main process runs evaluation.
  
      Based on the detectron2 CityscapesSemSegEvaluator
      (See https://github.com/facebookresearch/detectron2/blob/main/detectron2/evaluation/cityscapes_evaluation.py),  # noqa
      but uses ignoreInEval from the dataset metadata to ignore categories during eval, i.e. ego_car.
      """
  
      def process(self, inputs, outputs):
          for _input, output in zip(inputs, outputs):
              file_name = _input["file_name"]
              basename = os.path.splitext(os.path.basename(file_name))[0]
              pred_filename = os.path.join(self._temp_dir, basename + "_pred.png")
  
              output = output["sem_seg"].argmax(dim=0).to(self._cpu_device).numpy()
              pred = np.zeros(output.shape, dtype=np.uint8)
              for cat in self._metadata.categories:
                  if cat["ignoreInEval"]:
                      continue
                  pred[output == cat["trainId"]] = cat["id"]
              Image.fromarray(pred).save(pred_filename)
  
      def evaluate(self):
          comm.synchronize()
          if comm.get_rank() > 0:
              return
          # Load the Cityscapes eval script *after* setting the required env var,
          # since the script reads CITYSCAPES_DATASET into global variables at load time.
          import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as cityscapes_eval
  
          self._logger.info("Evaluating results under {} ...".format(self._temp_dir))
  
          # set some global states in cityscapes evaluation API, before evaluating
          cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir)
          cityscapes_eval.args.predictionWalk = None
          cityscapes_eval.args.JSONOutput = False
          cityscapes_eval.args.colorized = False
  
          # These lines are adopted from
          # https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalPixelLevelSemanticLabeling.py  # noqa
          gt_dir = PathManager.get_local_path(self._metadata.gt_dir)
          groundTruthImgList = glob.glob(os.path.join(gt_dir, "*", "*_gtFine_labelIds.png"))
          assert len(
              groundTruthImgList
          ), "Cannot find any ground truth images to use for evaluation. Searched for: {}".format(
              cityscapes_eval.args.groundTruthSearch
          )
          predictionImgList = []
          for gt in groundTruthImgList:
              predictionImgList.append(cityscapes_eval.getPrediction(cityscapes_eval.args, gt))
          results = cityscapes_eval.evaluateImgLists(
              predictionImgList, groundTruthImgList, cityscapes_eval.args
          )
          ret = OrderedDict()
          ret["sem_seg"] = {
              "IoU": 100.0 * results["averageScoreClasses"],
              "iIoU": 100.0 * results["averageScoreInstClasses"],
              "IoU_sup": 100.0 * results["averageScoreCategories"],
              "iIoU_sup": 100.0 * results["averageScoreInstCategories"],
          }
          self._working_dir.cleanup()
          return ret
  