18 from typing
import Any, Final, Optional, List, Dict, Set
25 from ..base_converter
import BaseConverter
26 from ...annotation
import CoretexImageAnnotation, CoretexSegmentationInstance, BBox
29 class _CocoImageAnnotationData:
31 def __init__(self, data: Dict[str, Any], imageInfo: Dict[str, Any]) ->
None:
33 self.imageInfo = imageInfo
36 class COCOConverter(BaseConverter):
38 def __init__(self, datasetName: str, projectId: int, datasetPath: str) ->
None:
39 super().__init__(datasetName, projectId, datasetPath)
41 self.__imagesPath: Final = os.path.join(datasetPath,
"images")
43 annotationsPath = os.path.join(datasetPath,
"annotations")
44 self.__fileNames: Final = glob.glob(os.path.join(annotationsPath,
"*.json"))
46 def _dataSource(self) -> List[_CocoImageAnnotationData]:
47 fullAnnotationData: List[_CocoImageAnnotationData] = []
49 for fileName
in self.__fileNames:
50 with open(fileName)
as jsonFile:
51 data = json.load(jsonFile)
53 fullAnnotationData.extend([
54 _CocoImageAnnotationData(data, imageInfo)
55 for imageInfo
in data[
"images"]
58 return fullAnnotationData
60 def _extractLabels(self) -> Set[str]:
61 labels: Set[str] = set()
63 for fileName
in self.__fileNames:
64 with open(fileName)
as jsonFile:
65 data = json.load(jsonFile)
67 for category
in data[
"categories"]:
68 labels.add(category[
"name"])
72 def __extractInstance(
74 categories: List[Dict[str, Any]],
75 annotation: Dict[str, Any]
76 ) -> Optional[CoretexSegmentationInstance]:
78 label: Optional[str] =
None
80 for category
in categories:
81 if category[
"id"] == annotation[
"category_id"]:
82 label = category[
"name"]
85 logging.getLogger(
"coretexpylib").info(f
">> [Coretex] Invalid class: {label}")
88 coretexClass = self._dataset.classByName(label)
89 if coretexClass
is None:
90 logging.getLogger(
"coretexpylib").info(f
">> [Coretex] Class: ({label}) is not a part of dataset")
93 bbox = BBox(*(annotation[
"bbox"]))
95 if "segmentation" in annotation:
96 segmentation = annotation[
"segmentation"]
102 return CoretexSegmentationInstance.create(
103 coretexClass.classIds[0],
108 def _extractSingleAnnotation(self, annotationData: _CocoImageAnnotationData) ->
None:
109 imageName = annotationData.imageInfo[
"file_name"]
110 width = annotationData.imageInfo[
"width"]
111 height = annotationData.imageInfo[
"height"]
113 imagePath = os.path.join(self.__imagesPath, imageName)
114 if not os.path.exists(imagePath):
117 coretexAnnotation = CoretexImageAnnotation.create(imageName, width, height, [])
119 for annotation
in annotationData.data[
"annotations"]:
120 if annotation[
"image_id"] != annotationData.imageInfo[
"id"]:
123 instance = self.__extractInstance(annotationData.data[
"categories"], annotation)
127 coretexAnnotation.instances.append(instance)
129 self._saveImageAnnotationPair(imagePath, coretexAnnotation)