mlgidGUI 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. mlgidGUI/__init__.py +52 -0
  2. mlgidGUI/__main__.py +7 -0
  3. mlgidGUI/__version.py +1 -0
  4. mlgidGUI/app/__init__.py +8 -0
  5. mlgidGUI/app/actions_stack.py +1 -0
  6. mlgidGUI/app/app.py +67 -0
  7. mlgidGUI/app/cif_rois/__init__.py +0 -0
  8. mlgidGUI/app/cif_rois/cif_peaks_calculation.py +57 -0
  9. mlgidGUI/app/cif_rois/cif_simulation/__init__.py +0 -0
  10. mlgidGUI/app/cif_rois/cif_simulation/data/__init__.py +0 -0
  11. mlgidGUI/app/cif_rois/cif_simulation/data/atoms.py +15 -0
  12. mlgidGUI/app/cif_rois/cif_simulation/data/export_database.py +28 -0
  13. mlgidGUI/app/cif_rois/cif_simulation/experiment.py +57 -0
  14. mlgidGUI/app/cif_rois/cif_simulation/giwaxs_sim.py +286 -0
  15. mlgidGUI/app/cif_rois/cif_simulation/int_sim.py +105 -0
  16. mlgidGUI/app/cif_rois/cif_simulation/possible_directions.py +20 -0
  17. mlgidGUI/app/cif_rois/cif_simulation/q_sim.py +159 -0
  18. mlgidGUI/app/data_manager/__init__.py +4 -0
  19. mlgidGUI/app/data_manager/data_manager.py +164 -0
  20. mlgidGUI/app/data_manager/import_from_h5.py +68 -0
  21. mlgidGUI/app/data_manager/load_data.py +78 -0
  22. mlgidGUI/app/data_manager/pascal/__init__.py +2 -0
  23. mlgidGUI/app/data_manager/pascal/annotation_fabric.py +59 -0
  24. mlgidGUI/app/data_manager/pascal/draw_objects.py +119 -0
  25. mlgidGUI/app/data_manager/pascal/exceptions.py +6 -0
  26. mlgidGUI/app/data_manager/pascal/format_convertor.py +127 -0
  27. mlgidGUI/app/data_manager/pascal/pascal_annotation.py +85 -0
  28. mlgidGUI/app/data_manager/pascal/protocol_implementations.py +28 -0
  29. mlgidGUI/app/data_manager/pascal/protocols.py +47 -0
  30. mlgidGUI/app/data_manager/pascal/utils.py +64 -0
  31. mlgidGUI/app/data_manager/save_dataset.py +57 -0
  32. mlgidGUI/app/data_manager/save_h5.py +178 -0
  33. mlgidGUI/app/data_manager/saving_parameters.py +88 -0
  34. mlgidGUI/app/debug_tracker.py +129 -0
  35. mlgidGUI/app/edf_reader.py +135 -0
  36. mlgidGUI/app/file_manager/__init__.py +201 -0
  37. mlgidGUI/app/file_manager/config_manager.py +76 -0
  38. mlgidGUI/app/file_manager/keys.py +542 -0
  39. mlgidGUI/app/file_manager/npy_file_manager.py +17 -0
  40. mlgidGUI/app/file_manager/object_file_manager.py +77 -0
  41. mlgidGUI/app/file_manager/project_structure.py +169 -0
  42. mlgidGUI/app/file_manager/read_fits.py +76 -0
  43. mlgidGUI/app/file_manager/read_geometry.py +54 -0
  44. mlgidGUI/app/file_manager/read_images.py +31 -0
  45. mlgidGUI/app/file_manager/read_meta_roi.py +40 -0
  46. mlgidGUI/app/file_manager/read_polar_images.py +22 -0
  47. mlgidGUI/app/file_manager/read_radial_profile.py +6 -0
  48. mlgidGUI/app/file_manager/read_roi_data.py +39 -0
  49. mlgidGUI/app/fitting/__init__.py +5 -0
  50. mlgidGUI/app/fitting/background.py +92 -0
  51. mlgidGUI/app/fitting/fit.py +128 -0
  52. mlgidGUI/app/fitting/fit_holder.py +273 -0
  53. mlgidGUI/app/fitting/fit_object.py +247 -0
  54. mlgidGUI/app/fitting/functions.py +107 -0
  55. mlgidGUI/app/fitting/range_strategy.py +14 -0
  56. mlgidGUI/app/fitting/utils.py +17 -0
  57. mlgidGUI/app/geometry.py +236 -0
  58. mlgidGUI/app/geometry_holder.py +131 -0
  59. mlgidGUI/app/image_holder.py +200 -0
  60. mlgidGUI/app/image_processing.py +23 -0
  61. mlgidGUI/app/polar_image.py +96 -0
  62. mlgidGUI/app/profiles/__init__.py +5 -0
  63. mlgidGUI/app/profiles/angular_profile.py +20 -0
  64. mlgidGUI/app/profiles/basic_profile.py +169 -0
  65. mlgidGUI/app/profiles/radial_profile.py +38 -0
  66. mlgidGUI/app/read_image.py +21 -0
  67. mlgidGUI/app/rois/__init__.py +4 -0
  68. mlgidGUI/app/rois/new_roi_dict.py +670 -0
  69. mlgidGUI/app/rois/roi.py +194 -0
  70. mlgidGUI/app/rois/roi_colors.py +76 -0
  71. mlgidGUI/app/rois/roi_data.py +177 -0
  72. mlgidGUI/app/rois/roi_dict.py +466 -0
  73. mlgidGUI/app/rois/roi_meta_data.py +149 -0
  74. mlgidGUI/app/structures/__init__.py +6 -0
  75. mlgidGUI/app/structures/crystal_ring.py +19 -0
  76. mlgidGUI/app/structures/crystals_holders.py +144 -0
  77. mlgidGUI/app/structures/custom_crystal.py +45 -0
  78. mlgidGUI/app/structures/get_ring_list.py +89 -0
  79. mlgidGUI/app/transformations.py +82 -0
  80. mlgidGUI/app/update/__init__.py +3 -0
  81. mlgidGUI/app/update/check_version.py +51 -0
  82. mlgidGUI/app/update/launch_program.py +15 -0
  83. mlgidGUI/app/update/script_update.py +64 -0
  84. mlgidGUI/app/utils.py +124 -0
  85. mlgidGUI/gui/__init__.py +3 -0
  86. mlgidGUI/gui/background_tasks.py +41 -0
  87. mlgidGUI/gui/background_update.py +87 -0
  88. mlgidGUI/gui/basic_widgets/__init__.py +12 -0
  89. mlgidGUI/gui/basic_widgets/buttons.py +144 -0
  90. mlgidGUI/gui/basic_widgets/labels.py +51 -0
  91. mlgidGUI/gui/basic_widgets/mouse_events.py +119 -0
  92. mlgidGUI/gui/basic_widgets/path_line.py +162 -0
  93. mlgidGUI/gui/basic_widgets/plots_1d.py +365 -0
  94. mlgidGUI/gui/basic_widgets/plots_2d.py +224 -0
  95. mlgidGUI/gui/basic_widgets/popups.py +164 -0
  96. mlgidGUI/gui/basic_widgets/progress_bar.py +127 -0
  97. mlgidGUI/gui/basic_widgets/setup_widgets.py +138 -0
  98. mlgidGUI/gui/basic_widgets/sliders.py +616 -0
  99. mlgidGUI/gui/basic_widgets/spinner.py +65 -0
  100. mlgidGUI/gui/basic_widgets/toolbars.py +19 -0
  101. mlgidGUI/gui/debug_widgets.py +388 -0
  102. mlgidGUI/gui/dock_area.py +115 -0
  103. mlgidGUI/gui/exception_message.py +42 -0
  104. mlgidGUI/gui/fitting/__init__.py +2 -0
  105. mlgidGUI/gui/fitting/fit_widget.py +966 -0
  106. mlgidGUI/gui/fitting/inplace_fit.py +536 -0
  107. mlgidGUI/gui/fitting/selected_fit_widget.py +286 -0
  108. mlgidGUI/gui/gui_main.py +349 -0
  109. mlgidGUI/gui/image_viewer.py +323 -0
  110. mlgidGUI/gui/init_window.py +170 -0
  111. mlgidGUI/gui/load_window/__init__.py +2 -0
  112. mlgidGUI/gui/load_window/load_folder.py +61 -0
  113. mlgidGUI/gui/load_window/load_h5.py +73 -0
  114. mlgidGUI/gui/notifications.py +68 -0
  115. mlgidGUI/gui/polar_image_viewer.py +153 -0
  116. mlgidGUI/gui/profiles/__init__.py +1 -0
  117. mlgidGUI/gui/profiles/angular_profile_widget.py +62 -0
  118. mlgidGUI/gui/profiles/radial_profile_widget.py +164 -0
  119. mlgidGUI/gui/project_manager/__init__.py +17 -0
  120. mlgidGUI/gui/project_manager/cif_files_widget.py +196 -0
  121. mlgidGUI/gui/project_manager/cif_results.py +146 -0
  122. mlgidGUI/gui/project_manager/metadata_widget.py +15 -0
  123. mlgidGUI/gui/project_manager/project_viewer.py +151 -0
  124. mlgidGUI/gui/project_manager/roi_widget.py +171 -0
  125. mlgidGUI/gui/roi_widgets/__init__.py +6 -0
  126. mlgidGUI/gui/roi_widgets/abstract_roi_holder.py +189 -0
  127. mlgidGUI/gui/roi_widgets/abstract_roi_widget.py +111 -0
  128. mlgidGUI/gui/roi_widgets/cif_file_widget.py +16 -0
  129. mlgidGUI/gui/roi_widgets/cif_peak_widget.py +43 -0
  130. mlgidGUI/gui/roi_widgets/confidence_level_widget.py +105 -0
  131. mlgidGUI/gui/roi_widgets/roi_1d_widget.py +136 -0
  132. mlgidGUI/gui/roi_widgets/roi_2d_rect_widget.py +98 -0
  133. mlgidGUI/gui/roi_widgets/roi_2d_ring_widget.py +203 -0
  134. mlgidGUI/gui/roi_widgets/rois_context_menu.py +150 -0
  135. mlgidGUI/gui/roi_widgets/select_roi_color_widget.py +58 -0
  136. mlgidGUI/gui/save_window/__init__.py +152 -0
  137. mlgidGUI/gui/save_window/format_box.py +33 -0
  138. mlgidGUI/gui/save_window/num_selected_widget.py +45 -0
  139. mlgidGUI/gui/save_window/options_widgets.py +105 -0
  140. mlgidGUI/gui/save_window/save_mode_box.py +30 -0
  141. mlgidGUI/gui/save_window/select_images.py +198 -0
  142. mlgidGUI/gui/tools.py +179 -0
  143. mlgidGUI/static/__init__.py +0 -0
  144. mlgidGUI/static/icons/__init__.py +0 -0
  145. mlgidGUI/static/icons/add.png +0 -0
  146. mlgidGUI/static/icons/add_yellow.png +0 -0
  147. mlgidGUI/static/icons/angular_profile.png +0 -0
  148. mlgidGUI/static/icons/arrow.png +0 -0
  149. mlgidGUI/static/icons/baseline.png +0 -0
  150. mlgidGUI/static/icons/center.png +0 -0
  151. mlgidGUI/static/icons/confirm.png +0 -0
  152. mlgidGUI/static/icons/control_widget.png +0 -0
  153. mlgidGUI/static/icons/data.png +0 -0
  154. mlgidGUI/static/icons/delete.png +0 -0
  155. mlgidGUI/static/icons/delete_yellow.png +0 -0
  156. mlgidGUI/static/icons/error.png +0 -0
  157. mlgidGUI/static/icons/find.png +0 -0
  158. mlgidGUI/static/icons/fit.png +0 -0
  159. mlgidGUI/static/icons/fix_all.png +0 -0
  160. mlgidGUI/static/icons/flip_horizontal.png +0 -0
  161. mlgidGUI/static/icons/flip_vertical.png +0 -0
  162. mlgidGUI/static/icons/folder.png +0 -0
  163. mlgidGUI/static/icons/fromfullscreen.png +0 -0
  164. mlgidGUI/static/icons/h5_folder.png +0 -0
  165. mlgidGUI/static/icons/h5_group_folder.png +0 -0
  166. mlgidGUI/static/icons/info.png +0 -0
  167. mlgidGUI/static/icons/interpolate.png +0 -0
  168. mlgidGUI/static/icons/item.png +0 -0
  169. mlgidGUI/static/icons/properties.png +0 -0
  170. mlgidGUI/static/icons/radial_profile.png +0 -0
  171. mlgidGUI/static/icons/roi_item.png +0 -0
  172. mlgidGUI/static/icons/rotate.png +0 -0
  173. mlgidGUI/static/icons/rotate_image.png +0 -0
  174. mlgidGUI/static/icons/rotate_right.png +0 -0
  175. mlgidGUI/static/icons/setup.png +0 -0
  176. mlgidGUI/static/icons/setup_white.png +0 -0
  177. mlgidGUI/static/icons/tofullscreen.png +0 -0
  178. mlgidGUI/static/icons/unfix_all.png +0 -0
  179. mlgidGUI/static/icons/update.png +0 -0
  180. mlgidGUI/static/icons/update_suggested.png +0 -0
  181. mlgidGUI/static/icons/window_icon.png +0 -0
  182. mlgidGUI/static/icons/window_icon_256.png +0 -0
  183. mlgidGUI/utils/__init__.py +1 -0
  184. mlgidGUI/utils/project2h5.py +11 -0
  185. mlgidgui-0.4.1.dist-info/METADATA +119 -0
  186. mlgidgui-0.4.1.dist-info/RECORD +202 -0
  187. mlgidgui-0.4.1.dist-info/WHEEL +5 -0
  188. mlgidgui-0.4.1.dist-info/entry_points.txt +5 -0
  189. mlgidgui-0.4.1.dist-info/licenses/LICENSE +674 -0
  190. mlgidgui-0.4.1.dist-info/top_level.txt +4 -0
  191. tests/__init__.py +0 -0
  192. tests/conftest.py +1 -0
  193. tests/fixures/__init__.py +2 -0
  194. tests/fixures/projects.py +102 -0
  195. tests/func/__init__.py +1 -0
  196. tests/func/test_loading_state.py +21 -0
  197. tests/func/test_parse_project_data.py +23 -0
  198. tests/func/test_save.py +62 -0
  199. tests/unit/__init__.py +0 -0
  200. tests/unit/rois/__init__.py +0 -0
  201. tests/unit/rois/test_basic_operations.py +18 -0
  202. tests/unit/test_add_data.py +33 -0
@@ -0,0 +1,119 @@
1
+ import hashlib
2
+ import logging
3
+ import random
4
+ from functools import lru_cache
5
+ from pathlib import Path
6
+
7
+
8
+ import PIL.ImageFont
9
+ from PIL import Image, ImageDraw
10
+ from transliterate import translit
11
+
12
+ from .protocols import BndBox, PascalAnnotation
13
+ from .protocols import PascalObject as PascalObjectProtocol
14
+
15
+ random.seed(32)
16
+
17
+ n_colors = 100
18
+ RAND_COLORS = [
19
+ (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))
20
+ for _ in range(n_colors)
21
+ ]
22
+
23
+
24
+ @lru_cache
25
+ def get_name_hash(name: str) -> int:
26
+ """
27
+ https://stackoverflow.com/questions/16008670/how-to-hash-a-string-into-8-digits
28
+ """
29
+ return abs(int(hashlib.sha1(name.encode("utf-8")).hexdigest(), 16) % n_colors)
30
+
31
+
32
+ def is_relative_coords(box: BndBox) -> bool:
33
+ return any(c < 1 for c in [box.xmin, box.ymin, box.xmax, box.ymax])
34
+
35
+
36
+ def _get_rect_coords(text_coord, d):
37
+ x0 = text_coord[0] - d if text_coord[0] - 1 >= 0 else text_coord[0]
38
+ y0 = text_coord[1] - d if text_coord[1] - 1 >= 0 else text_coord[1]
39
+ x1 = text_coord[2] + d
40
+ y1 = text_coord[3] + d
41
+ return x0, y0, x1, y1
42
+
43
+
44
+ class DrawObjectsMixin(PascalAnnotation):
45
+ """
46
+ Draw objects
47
+ """
48
+
49
+ _font_path = str(Path(__file__).parent / "fonts/arialmt.ttf")
50
+
51
+ def draw_boxes(
52
+ self,
53
+ image: Image.Image,
54
+ width: int = 5,
55
+ color: [[int, int, int]] = None,
56
+ fontsize: int = 10,
57
+ font_path: str = None,
58
+ language_code: [str] = None,
59
+ ) -> Image.Image:
60
+ """
61
+ Draw bounding boxes and obj names
62
+
63
+ Parameters
64
+ ----------
65
+ image: Pillow image
66
+ width: The line width, in pixels
67
+ color: bounding box color
68
+ fontsize: requested font size, in pixels
69
+ font_path: path to font
70
+ language_code: str language code if transliteration needs
71
+
72
+ Returns
73
+ -------
74
+ Copy of image with rendered boxes
75
+ """
76
+ img_copy = image.copy()
77
+ img_width = img_copy.width
78
+ img_height = img_copy.height
79
+ img_draw = ImageDraw.Draw(img_copy)
80
+ set_color = color is None
81
+ if font_path is not None:
82
+ font = PIL.ImageFont.truetype(font_path, size=fontsize)
83
+ else:
84
+ font = PIL.ImageFont.truetype(self._font_path, size=fontsize)
85
+ for obj in self.objects:
86
+ if not isinstance(obj, PascalObjectProtocol):
87
+ logging.warning("Annotation has object which is not PascalObject")
88
+ continue
89
+ if set_color:
90
+ hash_id = get_name_hash(str(obj.name))
91
+ color = RAND_COLORS[hash_id]
92
+ # draw rectangle
93
+ if is_relative_coords(obj.bndbox):
94
+ p1 = (
95
+ float(obj.bndbox.xmin * img_width),
96
+ float(obj.bndbox.ymin * img_height),
97
+ )
98
+ p2 = (
99
+ float(obj.bndbox.xmax * img_width),
100
+ float(obj.bndbox.ymax * img_height),
101
+ )
102
+ else:
103
+ p1 = (float(obj.bndbox.xmin), float(obj.bndbox.ymin))
104
+ p2 = (float(obj.bndbox.xmax), float(obj.bndbox.ymax))
105
+ img_draw.rectangle((p1, p2), outline=color, width=width)
106
+ # draw text
107
+ text_coord = (
108
+ float(p1[0] + width + 1),
109
+ float(p1[1] + width + 1),
110
+ )
111
+ if language_code is not None:
112
+ obj_name = str(translit(obj.name, language_code, reversed=True))
113
+ else:
114
+ obj_name = str(obj.name)
115
+ text_box = img_draw.textbbox(text_coord, obj_name, font=font)
116
+ rect_coords = _get_rect_coords(text_box, width // 2)
117
+ img_draw.rectangle(rect_coords, fill=(32, 32, 28))
118
+ img_draw.text(text_coord, obj_name, align="left", font=font)
119
+ return img_copy
@@ -0,0 +1,6 @@
1
+ class ParseException(Exception):
2
+ pass
3
+
4
+
5
+ class InconsistentAnnotation(Exception):
6
+ pass
@@ -0,0 +1,127 @@
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import List, Union
4
+
5
+ from PIL import Image
6
+
7
+ from .exceptions import InconsistentAnnotation
8
+ from .protocols import PascalAnnotation, PascalObject, Size
9
+ from .utils import _is_primitive, base64img
10
+
11
+
12
+ def get_shapes(obj_data) -> List[dict]:
13
+ if len(obj_data) == 0:
14
+ return []
15
+ shapes = []
16
+ for obj in obj_data:
17
+ if not isinstance(obj, PascalObject):
18
+ logging.warning("Annotation has object which is not PascalObject")
19
+ continue
20
+ label = obj.name
21
+ points = [
22
+ [obj.bndbox.xmin, obj.bndbox.ymin],
23
+ [obj.bndbox.xmax, obj.bndbox.ymin],
24
+ [obj.bndbox.xmax, obj.bndbox.ymax],
25
+ [obj.bndbox.xmin, obj.bndbox.ymax],
26
+ ]
27
+ obj_flags = {}
28
+ for k, v in obj.__dict__.items():
29
+ if _is_primitive(v) and k != "name":
30
+ obj_flags[k] = v
31
+ if isinstance(v, list):
32
+ shapes.extend(get_shapes(v))
33
+ shape = dict(
34
+ label=label,
35
+ points=points,
36
+ group_id=None,
37
+ shape_type="polygon",
38
+ flags=obj_flags,
39
+ )
40
+ shapes.append(shape)
41
+ return shapes
42
+
43
+
44
+ class FormatConvertorMixin(PascalAnnotation):
45
+ def to_yolo(self, labels_map: dict, precision: int = 3) -> str:
46
+ """
47
+ Convert annotation to yolo format str
48
+ Annotation object must have size attribute, which contains fields: width, height
49
+
50
+ Parameters
51
+ ----------
52
+ labels_map: dict of label ids
53
+ {"person": 0, "cat": 1, "dog": 2}
54
+ precision: int, coord precision
55
+
56
+ Returns
57
+ -------
58
+ Yolo format annotation str
59
+ """
60
+ if not isinstance(self.size, Size):
61
+ raise InconsistentAnnotation(
62
+ "Incorrect size. Size must have width and height attributes"
63
+ )
64
+
65
+ objects = []
66
+ for obj in self:
67
+ if not isinstance(obj, PascalObject):
68
+ logging.warning("Annotation has object which is not PascalObject")
69
+ continue
70
+ try:
71
+ label = labels_map[obj.name]
72
+ except KeyError:
73
+ logging.warning(f"No label {obj.name} in label map. Skip object")
74
+ continue
75
+ dx = float(obj.bndbox.xmax - obj.bndbox.xmin)
76
+ dy = float(obj.bndbox.ymax - obj.bndbox.ymin)
77
+ x = obj.bndbox.xmin + dx * 0.5
78
+ y = obj.bndbox.ymin + dy * 0.5
79
+ dx /= self.size.width
80
+ dy /= self.size.height
81
+ x /= self.size.width
82
+ y /= self.size.height
83
+ s = f"{label} {x:.{precision}f} {y:.{precision}f} {dx:.{precision}f} {dy:.{precision}f}"
84
+ objects.append(s)
85
+ return "\n".join(objects)
86
+
87
+ def to_labelme(
88
+ self,
89
+ img_path: Union[str, Path] = None,
90
+ save_img_data: bool = False,
91
+ label_me_version: str = "5.3.0",
92
+ ) -> dict:
93
+ """
94
+ Convert annotation to labelme format
95
+
96
+ Parameters
97
+ ----------
98
+ img_path: path to image
99
+ save_img_data: if true store encoded image in output dict
100
+ label_me_version: version of labelme app
101
+
102
+ Returns
103
+ -------
104
+ labelme annotation dict which can be saved as json
105
+ """
106
+ if save_img_data:
107
+ img_path = Path(img_path)
108
+ if not img_path.exists():
109
+ raise FileNotFoundError(f"No such file: {img_path}")
110
+
111
+ encoded_string = None
112
+ if save_img_data:
113
+ img = Image.open(img_path)
114
+ encoded_string = base64img(img, img_path.suffix)
115
+
116
+ shapes = get_shapes(self.objects)
117
+
118
+ res = dict(
119
+ version=label_me_version,
120
+ flags={},
121
+ shapes=shapes,
122
+ imagePath=str(img_path),
123
+ imageData=encoded_string,
124
+ imageHeight=self.size.height,
125
+ imageWidth=self.size.width,
126
+ )
127
+ return res
@@ -0,0 +1,85 @@
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import List, Optional, Union
4
+
5
+ from xmlobj.xmlmapping import XMLMixin
6
+
7
+ from .draw_objects import DrawObjectsMixin
8
+ from .exceptions import InconsistentAnnotation
9
+ from .format_convertor import FormatConvertorMixin
10
+ from .protocol_implementations import BndBox, Object, Size
11
+
12
+
13
+ class Annotation(DrawObjectsMixin, XMLMixin, FormatConvertorMixin):
14
+ def __init__(self, filename: Union[Path, str], objects: List[Object], size: Size):
15
+ self.filename = filename
16
+ self.objects = objects
17
+ self.size = size
18
+
19
+
20
+ def annotation_from_yolo(
21
+ ann_path: Union[str, Path],
22
+ img_w: int = 1,
23
+ img_h: int = 1,
24
+ label_map: Optional[dict] = None,
25
+ precision: int = 4,
26
+ ) -> Annotation:
27
+ """
28
+ Get annotation object from yolo ann file
29
+
30
+ Parameters
31
+ ----------
32
+ ann_path: path to yolo annotation
33
+ img_w: image width, px
34
+ img_h: image height, px
35
+ label_map: dict of labels and correspond ids, example:
36
+ label_map = {0: "person", 1: "dog"}
37
+ precision: coordinates precision
38
+ Returns
39
+ -------
40
+ PascalAnnotation object
41
+ """
42
+ objects = []
43
+ has_label_map = label_map is not None
44
+ if img_w <= 1 or img_h <= 1:
45
+ logging.warning(
46
+ "Relative coordinates! Cannot work with labelimg or other tools. Please, set correct image size"
47
+ )
48
+ with open(ann_path, "r") as f:
49
+ lines = f.readlines()
50
+ for line in lines:
51
+ vals = line.split(" ")
52
+ class_id = int(vals[0])
53
+ x = float(vals[1])
54
+ y = float(vals[2])
55
+ dx = float(vals[3]) * 0.5
56
+ dy = float(vals[4]) * 0.5
57
+ x1 = x - dx
58
+ x2 = x + dx
59
+ y1 = y - dy
60
+ y2 = y + dy
61
+
62
+ x1 *= img_w
63
+ x2 *= img_w
64
+ y1 *= img_h
65
+ y2 *= img_h
66
+ if has_label_map:
67
+ try:
68
+ name = label_map[class_id]
69
+ except KeyError:
70
+ name = str(class_id)
71
+ logging.warning(f"No id {class_id} in label map")
72
+ else:
73
+ name = str(class_id)
74
+ box = BndBox(
75
+ round(x1, precision),
76
+ round(y1, precision),
77
+ round(x2, precision),
78
+ round(y2, precision),
79
+ )
80
+ pobj = Object(name, box)
81
+ objects.append(pobj)
82
+ ann = Annotation(Path(ann_path).stem, objects, Size(img_w, img_h))
83
+ if not isinstance(ann, Annotation):
84
+ raise InconsistentAnnotation(f"Cannot make annotation from file: {ann_path}")
85
+ return ann
@@ -0,0 +1,28 @@
1
+ from dataclasses import dataclass
2
+ from typing import Union
3
+
4
+ from xmlobj.xmlmapping import XMLMixin
5
+
6
+ from .protocols import BndBox as BndBoxProtocol
7
+ from .protocols import PascalObject as PascalObjectProtocol
8
+ from .protocols import Size as SizeProtocol
9
+
10
+
11
+ @dataclass
12
+ class BndBox(BndBoxProtocol, XMLMixin):
13
+ xmin: Union[float, int]
14
+ ymin: Union[float, int]
15
+ xmax: Union[float, int]
16
+ ymax: Union[float, int]
17
+
18
+
19
+ @dataclass
20
+ class Object(PascalObjectProtocol, XMLMixin):
21
+ name: str
22
+ bndbox: BndBox
23
+
24
+
25
+ @dataclass
26
+ class Size(SizeProtocol, XMLMixin):
27
+ width: Union[float, int]
28
+ height: Union[float, int]
@@ -0,0 +1,47 @@
1
+ from typing import List, Optional, Union
2
+
3
+ from typing_extensions import Protocol, runtime_checkable
4
+
5
+
6
+ @runtime_checkable
7
+ class BndBox(Protocol):
8
+ xmin: Union[float, int]
9
+ ymin: Union[float, int]
10
+ xmax: Union[float, int]
11
+ ymax: Union[float, int]
12
+
13
+
14
+ @runtime_checkable
15
+ class PascalObject(Protocol):
16
+ name: str
17
+ bndbox: BndBox
18
+
19
+
20
+ @runtime_checkable
21
+ class Size(Protocol):
22
+ width: Union[float, int]
23
+ height: Union[float, int]
24
+
25
+
26
+ @runtime_checkable
27
+ class PascalAnnotation(Protocol):
28
+ objects: List[PascalObject] = []
29
+ size: Optional[Size] = None
30
+ filename: Optional[str] = None
31
+
32
+ def __len__(self):
33
+ return len(self.objects)
34
+
35
+ def __getitem__(self, item):
36
+ return self.objects[item]
37
+
38
+ def filter_objects(self, names: List):
39
+ """Filter objects by names"""
40
+ ind = []
41
+ for i, obj in enumerate(self.objects):
42
+ if obj.name not in names:
43
+ ind.append(i)
44
+ if len(ind) == 0:
45
+ self.objects = list()
46
+ elif len(ind) < len(self.objects):
47
+ self.objects = [self.objects[i] for i in ind]
@@ -0,0 +1,64 @@
1
+ import base64
2
+ import xml.etree.ElementTree as xml
3
+ from io import BytesIO
4
+ from pathlib import Path
5
+ from typing import Union
6
+
7
+ from PIL import Image
8
+ from xmlobj import XMLMixin
9
+
10
+
11
+ def _is_primitive(obj):
12
+ """
13
+ https://stackoverflow.com/questions/6391694/how-to-check-if-a-variables-type-is-primitive
14
+ """
15
+ return not hasattr(obj, "__dict__") and not isinstance(obj, list)
16
+
17
+
18
+ def base64img(img: Image.Image, img_suffix: str) -> str:
19
+ """
20
+ Convert image to base64
21
+ """
22
+ buffered = BytesIO()
23
+ if img_suffix in [".JPG", ".jpg", ".JPEG", ".jpeg"]:
24
+ format_ = "JPEG"
25
+ elif img_suffix in [".PNG", ".png"]:
26
+ format_ = "PNG"
27
+ else:
28
+ format_ = "PNG"
29
+ img.save(buffered, format=format_)
30
+ buffered.seek(0)
31
+ img_byte = buffered.getvalue()
32
+ encoded_string = base64.b64encode(img_byte).decode("utf-8")
33
+ return encoded_string
34
+
35
+
36
+ def save_xml(output: Union[str, Path], xml_obj):
37
+ """
38
+ Save object to output file
39
+ """
40
+ tree = xml.ElementTree(xml_obj)
41
+ xml.indent(tree, space=" ", level=0)
42
+ with open(output, "w") as out:
43
+ tree.write(out, encoding="unicode", method="xml")
44
+
45
+
46
+ def _set_attr(box, obj_type, clip_zero: bool = True):
47
+ for attr_name, attr_val in box.__dict__.items():
48
+ attr_val = obj_type(attr_val)
49
+ if clip_zero:
50
+ attr_val = obj_type(max(0, attr_val))
51
+ setattr(box, attr_name, attr_val)
52
+ return box
53
+
54
+
55
+ def _check_bnd_box(box: XMLMixin, clip_zero: bool = True):
56
+ attr_types = [type(attr) for attr in box.__dict__.values()]
57
+ if all(attr is int or attr is float for attr in attr_types):
58
+ return box
59
+ if any(attr is float for attr in attr_types):
60
+ val_type = float
61
+ else:
62
+ val_type = int
63
+ box = _set_attr(box, val_type, clip_zero)
64
+ return box
@@ -0,0 +1,57 @@
1
+ from .saving_parameters import SavingParameters
2
+ from .pascal.protocol_implementations import BndBox, Object, Size
3
+ from .pascal.pascal_annotation import Annotation
4
+ from .save_h5 import _get_boxes_n_labels
5
+ from ..file_manager import ImageKey
6
+ from .load_data import ImageData, ImageDataFlags, load_image_data
7
+ import xml.etree.ElementTree as xml
8
+ from tifffile import imwrite
9
+
10
+
11
+ def pretty_xml(current, parent=None, index=-1, depth=0):
12
+ for i, node in enumerate(current):
13
+ pretty_xml(node, current, i, depth + 1)
14
+ if parent is not None:
15
+ if index == 0:
16
+ parent.text = '\n' + ('\t' * depth)
17
+ else:
18
+ parent[index - 1].tail = '\n' + ('\t' * depth)
19
+ if index == len(parent) - 1:
20
+ current.tail = '\n' + ('\t' * (depth - 1))
21
+
22
+
23
+
24
+ def save_for_object_detection(fm, image_holder, params: SavingParameters):
25
+ output_folder = params.path / 'pascal-voc'
26
+ output_folder.mkdir(parents=True, exist_ok=True)
27
+
28
+ count: int = 0
29
+
30
+ for _, image_keys in params.selected_images.items():
31
+ for image_key in image_keys:
32
+ if _save_image_for_object_detection(fm, image_holder, image_key, str(count), output_folder):
33
+ count += 1
34
+
35
+ return True
36
+
37
+
38
+ def _save_image_for_object_detection(fm, image_holder, image_key: ImageKey, name: str, output_folder) -> bool:
39
+ image_data: ImageData = load_image_data(fm, image_holder,
40
+ image_key, flags=ImageDataFlags.POLAR_IMAGE | ImageDataFlags.GEOMETRY | ImageDataFlags.ROI_DATA)
41
+
42
+ if image_data.polar_image is None or image_data.roi_data is None or image_data.geometry is None:
43
+ return False
44
+
45
+ boxes, labels = _get_boxes_n_labels(image_data.roi_data.to_array(), image_data.geometry)
46
+
47
+ obj = [Object(str(key),
48
+ BndBox((round(box[0]), 4),(round(box[1]), 4), (round(box[2]), 4), (round(box[3]), 4),))
49
+ for key, box in enumerate(boxes)]
50
+
51
+ filename = str(image_holder.current_key)
52
+ imwrite((output_folder / (filename + '.tiff')) , image_data.polar_image)
53
+
54
+ ann = Annotation(filename + '.tiff', obj, Size(image_data.polar_image.shape[1],image_data.polar_image.shape[0])).to_xml()
55
+ tree = xml.ElementTree(ann)
56
+ pretty_xml(tree.getroot())
57
+ tree.write((output_folder / (filename + '.xml')))