18 from typing
import Any, Optional, List, Set, Dict
27 from ..base_converter
import BaseConverter
28 from ...annotation
import CoretexSegmentationInstance, CoretexImageAnnotation, BBox
31 class CreateMLConverter(BaseConverter):
33 def __init__(self, datasetName: str, projectId: int, datasetPath: str) ->
None:
34 super().__init__(datasetName, projectId, datasetPath)
36 self.__imagesPath = os.path.join(datasetPath,
"images")
38 annotations = os.path.join(datasetPath,
"annotations")
39 self.__fileNames = glob.glob(os.path.join(annotations,
"*.json"))
41 def _dataSource(self) -> List[str]:
42 return self.__fileNames
44 def _extractLabels(self) -> Set[str]:
45 labels: Set[str] = set()
47 for fileName
in self.__fileNames:
48 with open(fileName)
as jsonFile:
49 data = json.load(jsonFile)[0]
51 for annotation
in data[
"annotations"]:
52 labels.add(annotation[
"label"])
56 def __extractBBox(self, bbox: Dict[str, int]) -> BBox:
58 bbox[
"x"] - bbox[
"width"] // 2,
59 bbox[
"y"] - bbox[
"height"] // 2,
64 def __extractInstance(self, annotation: Dict[str, Any]) -> Optional[CoretexSegmentationInstance]:
65 label = annotation[
"label"]
67 coretexClass = self._dataset.classByName(label)
68 if coretexClass
is None:
69 logging.getLogger(
"coretexpylib").info(f
">> [Coretex] Class: ({label}) is not a part of dataset")
72 bbox = self.__extractBBox(annotation[
"coordinates"])
73 return CoretexSegmentationInstance.create(coretexClass.classIds[0], bbox, [bbox.polygon])
75 def __extractImageAnnotation(self, imageAnnotation: Dict[str, Any]) ->
None:
76 imageName = imageAnnotation[
"image"]
77 image = Image.open(f
"{self.__imagesPath}/{imageName}")
79 coretexAnnotation = CoretexImageAnnotation.create(imageName, image.width, image.height, [])
81 for annotation
in imageAnnotation[
"annotations"]:
82 instance = self.__extractInstance(annotation)
86 coretexAnnotation.instances.append(instance)
88 self._saveImageAnnotationPair(os.path.join(self.__imagesPath, imageName), coretexAnnotation)
90 def _extractSingleAnnotation(self, fileName: str) ->
None:
91 with open(fileName)
as jsonFile:
92 data = json.load(jsonFile)[0]
94 self.__extractImageAnnotation(data)