lazylabel-gui 1.0.0__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.
@@ -0,0 +1,10 @@
1
+ from PyQt6.QtWidgets import QTableWidgetItem
2
+
3
+
4
+ class NumericTableWidgetItem(QTableWidgetItem):
5
+ def __lt__(self, other):
6
+ # Override the default less-than operator for sorting
7
+ try:
8
+ return int(self.text()) < int(other.text())
9
+ except (ValueError, TypeError):
10
+ return super().__lt__(other)
@@ -0,0 +1,51 @@
1
+ from PyQt6.QtCore import Qt, QRectF
2
+ from PyQt6.QtGui import QPixmap
3
+ from PyQt6.QtWidgets import QGraphicsView, QGraphicsScene, QGraphicsPixmapItem
4
+
5
+
6
+ class PhotoViewer(QGraphicsView):
7
+ def __init__(self, parent=None):
8
+ super().__init__(parent)
9
+ self._scene = QGraphicsScene(self)
10
+ self._pixmap_item = QGraphicsPixmapItem()
11
+ self._scene.addItem(self._pixmap_item)
12
+ self.setScene(self._scene)
13
+
14
+ self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
15
+ self.setResizeAnchor(QGraphicsView.ViewportAnchor.AnchorViewCenter)
16
+ self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
17
+ self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
18
+ self.setDragMode(QGraphicsView.DragMode.NoDrag)
19
+
20
+ def fitInView(self, scale=True):
21
+ rect = QRectF(self._pixmap_item.pixmap().rect())
22
+ if not rect.isNull():
23
+ self.setSceneRect(rect)
24
+ unity = self.transform().mapRect(QRectF(0, 0, 1, 1))
25
+ self.scale(1 / unity.width(), 1 / unity.height())
26
+ viewrect = self.viewport().rect()
27
+ scenerect = self.transform().mapRect(rect)
28
+ factor = min(
29
+ viewrect.width() / scenerect.width(),
30
+ viewrect.height() / scenerect.height(),
31
+ )
32
+ self.scale(factor, factor)
33
+
34
+ def set_photo(self, pixmap):
35
+ if pixmap and not pixmap.isNull():
36
+ self._pixmap_item.setPixmap(pixmap)
37
+ self.fitInView()
38
+ else:
39
+ self._pixmap_item.setPixmap(QPixmap())
40
+
41
+ def resizeEvent(self, event):
42
+ self.fitInView()
43
+ super().resizeEvent(event)
44
+
45
+ def wheelEvent(self, event):
46
+ if not self._pixmap_item.pixmap().isNull():
47
+ if event.angleDelta().y() > 0:
48
+ factor = 1.25
49
+ else:
50
+ factor = 0.8
51
+ self.scale(factor, factor)
@@ -0,0 +1,58 @@
1
+ from PyQt6.QtWidgets import QTableWidget, QAbstractItemView
2
+ from PyQt6.QtCore import Qt
3
+
4
+
5
+ class ReorderableClassTable(QTableWidget):
6
+ def __init__(self, *args, **kwargs):
7
+ super().__init__(*args, **kwargs)
8
+ self.setDragEnabled(True)
9
+ self.setAcceptDrops(True)
10
+ self.setDropIndicatorShown(True)
11
+ self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
12
+ self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
13
+ self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
14
+ self.scroll_margin = 40
15
+
16
+ def dragMoveEvent(self, event):
17
+ pos = event.position().toPoint()
18
+ rect = self.viewport().rect()
19
+
20
+ if pos.y() < rect.top() + self.scroll_margin:
21
+ self.verticalScrollBar().setValue(self.verticalScrollBar().value() - 1)
22
+ elif pos.y() > rect.bottom() - self.scroll_margin:
23
+ self.verticalScrollBar().setValue(self.verticalScrollBar().value() + 1)
24
+
25
+ super().dragMoveEvent(event)
26
+
27
+ def dropEvent(self, event):
28
+ if not event.isAccepted() and event.source() == self:
29
+ drop_row = self.rowAt(event.position().toPoint().y())
30
+ if drop_row < 0:
31
+ drop_row = self.rowCount()
32
+
33
+ selected_rows = sorted(
34
+ list({index.row() for index in self.selectedIndexes()}), reverse=True
35
+ )
36
+
37
+ dragged_items = []
38
+ for row in selected_rows:
39
+ # Take the item from the row and keep its data
40
+ item = self.takeItem(row, 0)
41
+ dragged_items.insert(0, item)
42
+ # Then remove the row itself
43
+ self.removeRow(row)
44
+
45
+ # Adjust drop row if it was shifted by the removal
46
+ for row in selected_rows:
47
+ if row < drop_row:
48
+ drop_row -= 1
49
+
50
+ # Insert items at the new location
51
+ for item in dragged_items:
52
+ self.insertRow(drop_row)
53
+ self.setItem(drop_row, 0, item)
54
+ self.selectRow(drop_row)
55
+ drop_row += 1
56
+
57
+ event.accept()
58
+ super().dropEvent(event)
lazylabel/sam_model.py ADDED
@@ -0,0 +1,70 @@
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ import requests
6
+ from tqdm import tqdm
7
+ from segment_anything import sam_model_registry, SamPredictor
8
+
9
+
10
+ def download_model(url, download_path):
11
+ """Downloads file with a progress bar."""
12
+ print(
13
+ f"SAM model not found. Downloading from Meta's GitHub repository to: {download_path}"
14
+ )
15
+ response = requests.get(url, stream=True)
16
+ response.raise_for_status()
17
+ total_size_in_bytes = int(response.headers.get("content-length", 0))
18
+ block_size = 1024 # 1 Kibibyte
19
+
20
+ progress_bar = tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
21
+ with open(download_path, "wb") as file:
22
+ for data in response.iter_content(block_size):
23
+ progress_bar.update(len(data))
24
+ file.write(data)
25
+ progress_bar.close()
26
+
27
+ if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
28
+ print("ERROR, something went wrong during download")
29
+
30
+
31
+ class SamModel:
32
+ def __init__(self, model_type, model_filename="sam_vit_h_4b8939.pth"):
33
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
34
+
35
+ # Define model URL and local cache path
36
+ model_url = f"https://dl.fbaipublicfiles.com/segment_anything/{model_filename}"
37
+ cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "lazylabel")
38
+ os.makedirs(cache_dir, exist_ok=True)
39
+ model_path = os.path.join(cache_dir, model_filename)
40
+
41
+ # Download the model if it doesn't exist
42
+ if not os.path.exists(model_path):
43
+ download_model(model_url, model_path)
44
+
45
+ print(f"Loading SAM model from {model_path}...")
46
+ self.model = sam_model_registry[model_type](checkpoint=model_path).to(
47
+ self.device
48
+ )
49
+ self.predictor = SamPredictor(self.model)
50
+ self.image = None
51
+ print("SAM model loaded successfully.")
52
+
53
+ def set_image(self, image_path):
54
+ self.image = cv2.imread(image_path)
55
+ self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
56
+ self.predictor.set_image(self.image)
57
+
58
+ def predict(self, positive_points, negative_points):
59
+ if not positive_points:
60
+ return None
61
+
62
+ points = np.array(positive_points + negative_points)
63
+ labels = np.array([1] * len(positive_points) + [0] * len(negative_points))
64
+
65
+ masks, _, _ = self.predictor.predict(
66
+ point_coords=points,
67
+ point_labels=labels,
68
+ multimask_output=False,
69
+ )
70
+ return masks[0]
lazylabel/utils.py ADDED
@@ -0,0 +1,12 @@
1
+ import numpy as np
2
+ from PyQt6.QtGui import QImage, QPixmap
3
+
4
+
5
+ def mask_to_pixmap(mask, color):
6
+ colored_mask = np.zeros((mask.shape[0], mask.shape[1], 4), dtype=np.uint8)
7
+ colored_mask[mask, :3] = color
8
+ colored_mask[mask, 3] = 150 # Alpha channel for transparency
9
+ image = QImage(
10
+ colored_mask.data, mask.shape[1], mask.shape[0], QImage.Format.Format_RGBA8888
11
+ )
12
+ return QPixmap.fromImage(image)
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: lazylabel-gui
3
+ Version: 1.0.0
4
+ Summary: An image segmentation GUI for generating mask tensors.
5
+ Author-email: "Deniz N. Cakan" <deniz.n.cakan@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Deniz N. Cakan
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/dnzckn/lazylabel
29
+ Project-URL: Bug Tracker, https://github.com/dnzckn/lazylabel/issues
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: License :: OSI Approved :: MIT License
32
+ Classifier: Operating System :: OS Independent
33
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
34
+ Classifier: Environment :: X11 Applications :: Qt
35
+ Requires-Python: >=3.10
36
+ Description-Content-Type: text/markdown
37
+ License-File: LICENSE
38
+ Requires-Dist: PyQt6>=6.9.0
39
+ Requires-Dist: pyqtdarktheme==2.1.0
40
+ Requires-Dist: torch>=2.7.1
41
+ Requires-Dist: torchvision>=0.22.1
42
+ Requires-Dist: segment-anything==1.0
43
+ Requires-Dist: numpy>=2.3.0
44
+ Requires-Dist: opencv-python>=4.11.0.86
45
+ Requires-Dist: scipy>=1.15.3
46
+ Requires-Dist: requests>=2.32.4
47
+ Requires-Dist: tqdm>=4.67.1
48
+ Dynamic: license-file
49
+
50
+ # <img src="https://raw.githubusercontent.com/dnzckn/LazyLabel/main/src/lazylabel/demo_pictures/logo2.png" alt="LazyLabel Logo" style="height:60px; vertical-align:middle;" /> <img src="https://raw.githubusercontent.com/dnzckn/LazyLabel/main/src/lazylabel/demo_pictures/logo_black.png" alt="LazyLabel Cursive" style="height:60px; vertical-align:middle;" />
51
+ LazyLabel is an intuitive, AI-assisted image segmentation tool. It uses Meta's Segment Anything Model (SAM) for quick, precise mask generation, alongside advanced polygon editing for fine-tuned control. Outputs are saved in a clean, one-hot encoded format for easy machine learning integration.
52
+
53
+ Inspired by [LabelMe](https://github.com/wkentaro/labelme?tab=readme-ov-file#installation) and [Segment-Anything-UI](https://github.com/branislavhesko/segment-anything-ui/tree/main).
54
+
55
+ ![LazyLabel Screenshot](https://raw.githubusercontent.com/dnzckn/LazyLabel/main/src/lazylabel/demo_pictures/gui.PNG)
56
+
57
+ ---
58
+
59
+ ## ✨ Core Features
60
+
61
+ * **AI-Powered Segmentation**: Generate masks with simple left-click (positive) and right-click (negative) interactions.
62
+ * **Vector Polygon Tool**: Full control to draw, edit, and reshape polygons. Drag vertices or move entire shapes.
63
+ * **Advanced Class Management**: Assign multiple segments to a single class ID for organized labeling.
64
+ * **Intuitive Editing & Refinement**: Select, merge, and re-order segments.
65
+ * **Interactive UI**: Color-coded segments, sortable lists, and hover highlighting.
66
+ * **Smart I/O**: Loads existing `.npz` masks; saves work as clean, one-hot encoded outputs.
67
+
68
+ ---
69
+
70
+ ## 🚀 Getting Started
71
+
72
+ ### Prerequisites
73
+ Ensure you have **Python 3.10** or newer.
74
+
75
+ ### Installation
76
+
77
+ #### For Users (via PyPI)
78
+ 1. Install LazyLabel directly:
79
+ ```bash
80
+ pip install lazylabel-gui
81
+ ```
82
+ 2. Run the application:
83
+ ```bash
84
+ lazylabel-gui
85
+ ```
86
+
87
+ #### For Developers (from Source)
88
+ 1. Clone the repository:
89
+ ```bash
90
+ git clone [https://github.com/dnzckn/LazyLabel.git](https://github.com/dnzckn/LazyLabel.git)
91
+ cd LazyLabel
92
+ ```
93
+ 2. Install in editable mode, which links the installed package to your source directory:
94
+ ```bash
95
+ pip install -e .
96
+ ```
97
+ 3. Run the application:
98
+ ```bash
99
+ lazylabel-gui
100
+ ```
101
+
102
+ **Note**: On the first run, the application will automatically download the SAM model checkpoint (~2.5 GB) from Meta's repository to a local cache. This is a one-time download.
103
+
104
+ ---
105
+
106
+ ## ⌨️ Controls & Keybinds
107
+
108
+ ### Modes
109
+ | Key | Action |
110
+ |---|---|
111
+ | `1` | Enter **Point Mode** (for AI segmentation). |
112
+ | `2` | Enter **Polygon Drawing Mode**. |
113
+ | `E` | Toggle **Selection Mode** to select existing segments. |
114
+ | `R` | Enter **Edit Mode** for selected polygons (drag shape or vertices). |
115
+ | `Q` | Toggle **Pan Mode** (click and drag the image). |
116
+
117
+ ### Actions
118
+ | Key(s) | Action |
119
+ |---|---|
120
+ | `L-Click` | Add positive point (Point Mode) or polygon vertex. |
121
+ | `R-Click` | Add negative point (Point Mode). |
122
+ | `Ctrl + Z` | Undo last point. |
123
+ | `Spacebar` | Finalize and save current AI segment. |
124
+ | `Enter` | **Save final mask for the current image to a `.npz` file.** |
125
+ | `M` | **Merge** selected segments into a single class. |
126
+ | `V` / `Delete` / `Backspace`| **Delete** selected segments. |
127
+ | `C` | Clear temporary points/vertices. |
128
+ | `W/A/S/D` | Pan image. |
129
+ | `Scroll Wheel` | Zoom-in or -out. |
130
+
131
+ ---
132
+
133
+ ## 📦 Output Format
134
+
135
+ LazyLabel saves your work as a compressed NumPy array (`.npz`) with the same name as your image file.
136
+
137
+ The file contains a single data key, `'mask'`, holding a **one-hot encoded tensor** with the shape `(H, W, C)`:
138
+ * `H`: Image height.
139
+ * `W`: Image width.
140
+ * `C`: Total unique classes.
141
+
142
+ Each channel is a binary mask for a class, combining all assigned segments into a clean, ML-ready output.
143
+
144
+ ---
145
+
146
+ ## ☕ Support LazyLabel
147
+ [If you found LazyLabel helpful, consider supporting the project!](https://buymeacoffee.com/dnzckn)
@@ -0,0 +1,16 @@
1
+ lazylabel/controls.py,sha256=YCTm8hQMgk4GFrr7b8p5p8PX3IQi9NoWZV1EFYEhDI8,4125
2
+ lazylabel/custom_file_system_model.py,sha256=QwqlHKrvBZbpKLXhUdBbJMbdImp7j6MnI8JCs7yKOlw,1996
3
+ lazylabel/editable_vertex.py,sha256=lw_MmDmgkiPZbouIb6DkqIEJZhG32AJ2T2TUt0P3rWk,1040
4
+ lazylabel/hoverable_polygon_item.py,sha256=-0l8C8PfsXtJGqvZZ2qtizxHmFwO8RCwz5UfjKpDvzY,775
5
+ lazylabel/main.py,sha256=mJxZcy8mXXs7F7GD9BKyo0oGOHUu5HXSP1uDdsGNUno,35234
6
+ lazylabel/numeric_table_widget_item.py,sha256=ZnwaUvCeOGEX504DfbLHWKMKVMt5zSjdQkPjPCuYCcY,346
7
+ lazylabel/photo_viewer.py,sha256=qZ6t9RO0TOXQuoLr6ASVy6sgSIcVFPwyNRnjkK5MIHc,1993
8
+ lazylabel/reorderable_class_table.py,sha256=9BctudGTrb6dTV8_7IpQ5lMM0D-5unuQbLVk3Yu49xQ,2242
9
+ lazylabel/sam_model.py,sha256=9NB51Xq1P5dIxZMBdttwwRlszlJR3U5HRs83QsPLxNE,2595
10
+ lazylabel/utils.py,sha256=a2n2f4NehzSjS8-UwbOioYTSO_lWe1uYjzDdOIEJloE,435
11
+ lazylabel_gui-1.0.0.dist-info/licenses/LICENSE,sha256=kSDEIgrWAPd1u2UFGGpC9X71dhzrlzBFs8hbDlENnGE,1092
12
+ lazylabel_gui-1.0.0.dist-info/METADATA,sha256=WmK28eQsDWHa8lXwZn6594bIGCFVUNWKP4IkZvQmXBE,6287
13
+ lazylabel_gui-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
+ lazylabel_gui-1.0.0.dist-info/entry_points.txt,sha256=Hd0WwEG9OPTa_ziYjiD0aRh7R6Fupt-wdQ3sspdc1mM,54
15
+ lazylabel_gui-1.0.0.dist-info/top_level.txt,sha256=YN4uIyrpDBq1wiJaBuZLDipIzyZY0jqJOmmXiPIOUkU,10
16
+ lazylabel_gui-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lazylabel-gui = lazylabel.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Deniz N. Cakan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ lazylabel