18 from typing
import Any, Optional, List, Set, Dict
19 from pathlib
import Path
28 from ..base_converter
import BaseConverter
29 from ...annotation
import CoretexImageAnnotation, CoretexSegmentationInstance, BBox
32 class CityScapeConverter(BaseConverter):
34 def __init__(self, datasetName: str, projectId: int, datasetPath: str) ->
None:
35 super().__init__(datasetName, projectId, datasetPath)
37 self.__baseImagePath = os.path.join(datasetPath,
"leftImg8bit_trainvaltest",
"leftImg8bit")
38 self.__baseAnnotationsPaths = [
39 os.path.join(datasetPath,
"gtFine_trainvaltest",
"gtFine",
"train"),
40 os.path.join(datasetPath,
"gtFine_trainvaltest",
"gtFine",
"val")
43 self.__imagePaths: List[str] = []
44 self.__imagePaths.extend(glob.glob(f
"{self.__baseImagePath}/train/*/*.png"))
45 self.__imagePaths.extend(glob.glob(f
"{self.__baseImagePath}/val/*/*.png"))
47 def __annotationPathFor(self, imagePath: str) -> str:
49 annotationName = os.path.sep.join(Path(imagePath).parts[-2:])
52 annotationName = annotationName.replace(
"leftImg8bit.png",
"gtFine_polygons.json")
54 for annotationsPath
in self.__baseAnnotationsPaths:
55 annotationPath = os.path.join(annotationsPath, annotationName)
57 if os.path.exists(annotationPath):
62 def _dataSource(self) -> List[str]:
63 return self.__imagePaths
65 def _extractLabels(self) -> Set[str]:
66 labels: Set[str] = set()
68 for imagePath
in self.__imagePaths:
69 annotationPath = self.__annotationPathFor(imagePath)
71 with open(annotationPath, mode=
"r")
as annotationFile:
72 annotationData: Dict[str, Any] = json.load(annotationFile)
74 for obj
in annotationData[
"objects"]:
75 labels.add(obj[
"label"])
79 def __extractInstance(self, obj: Dict[str, Any]) -> Optional[CoretexSegmentationInstance]:
82 coretexClass = self._dataset.classByName(label)
83 if coretexClass
is None:
84 logging.getLogger(
"coretexpylib").info(f
">> [Coretex] Class: ({label}) is not a part of dataset")
87 polygon = np.array(obj[
"polygon"]).flatten().tolist()
89 return CoretexSegmentationInstance.create(
90 coretexClass.classIds[0],
91 BBox.fromPoly(polygon),
95 def __extractImageAnnotation(self, imagePath: str, annotationData: Dict[str, Any]) ->
None:
96 imageName = Path(imagePath).stem
97 width = annotationData[
"imgWidth"]
98 height = annotationData[
"imgHeight"]
100 coretexAnnotation = CoretexImageAnnotation.create(imageName, width, height, [])
102 for obj
in annotationData[
"objects"]:
103 instance = self.__extractInstance(obj)
107 coretexAnnotation.instances.append(instance)
109 self._saveImageAnnotationPair(imagePath, coretexAnnotation)
111 def _extractSingleAnnotation(self, imagePath: str) ->
None:
112 annotationPath = self.__annotationPathFor(imagePath)
114 with open(annotationPath, mode=
"r")
as annotationFile:
115 annotationData: Dict[str, Any] = json.load(annotationFile)
116 self.__extractImageAnnotation(imagePath, annotationData)