spacr 0.0.82__tar.gz → 0.1.0__tar.gz
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.
- {spacr-0.0.82/spacr.egg-info → spacr-0.1.0}/PKG-INFO +1 -1
- {spacr-0.0.82 → spacr-0.1.0}/setup.py +1 -1
- {spacr-0.0.82 → spacr-0.1.0}/spacr/__init__.py +4 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/annotate_app.py +4 -0
- spacr-0.1.0/spacr/annotate_app_v2.py +511 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/core.py +254 -172
- {spacr-0.0.82 → spacr-0.1.0}/spacr/deep_spacr.py +137 -50
- {spacr-0.0.82 → spacr-0.1.0}/spacr/graph_learning.py +28 -8
- {spacr-0.0.82 → spacr-0.1.0}/spacr/io.py +227 -144
- {spacr-0.0.82 → spacr-0.1.0}/spacr/measure.py +2 -1
- spacr-0.1.0/spacr/models/cp/toxo_plaque_cyto_e25000_X1120_Y1120.CP_model +0 -0
- spacr-0.1.0/spacr/models/cp/toxo_plaque_cyto_e25000_X1120_Y1120.CP_model_settings.csv +23 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/plot.py +102 -6
- {spacr-0.0.82 → spacr-0.1.0}/spacr/sequencing.py +140 -91
- spacr-0.1.0/spacr/settings.py +477 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/timelapse.py +0 -3
- {spacr-0.0.82 → spacr-0.1.0}/spacr/utils.py +312 -275
- {spacr-0.0.82 → spacr-0.1.0/spacr.egg-info}/PKG-INFO +1 -1
- {spacr-0.0.82 → spacr-0.1.0}/spacr.egg-info/SOURCES.txt +4 -0
- {spacr-0.0.82 → spacr-0.1.0}/LICENSE +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/MANIFEST.in +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/README.rst +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/setup.cfg +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/__main__.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/chris.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_2.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_classify_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_mask_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_measure_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_sim_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/gui_utils.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/logger.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/mask_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/models/cp/toxo_pv_lumen.CP_model +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/sim.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr/version.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr.egg-info/dependency_links.txt +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr.egg-info/entry_points.txt +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr.egg-info/requires.txt +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/spacr.egg-info/top_level.txt +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_annotate_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_core.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_gui_classify_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_gui_mask_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_gui_measure_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_gui_sim_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_gui_utils.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_io.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_mask_app.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_measure.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_plot.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_sim.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_timelapse.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_train.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_umap.py +0 -0
- {spacr-0.0.82 → spacr-0.1.0}/tests/test_utils.py +0 -0
@@ -5,6 +5,7 @@ import torch
|
|
5
5
|
from . import core
|
6
6
|
from . import io
|
7
7
|
from . import utils
|
8
|
+
from . import settings
|
8
9
|
from . import plot
|
9
10
|
from . import measure
|
10
11
|
from . import sim
|
@@ -12,6 +13,7 @@ from . import sequencing
|
|
12
13
|
from . import timelapse
|
13
14
|
from . import deep_spacr
|
14
15
|
from . import annotate_app
|
16
|
+
from . import annotate_app_v2
|
15
17
|
from . import gui_utils
|
16
18
|
from . import mask_app
|
17
19
|
from . import gui_mask_app
|
@@ -24,6 +26,7 @@ __all__ = [
|
|
24
26
|
"core",
|
25
27
|
"io",
|
26
28
|
"utils",
|
29
|
+
"settings",
|
27
30
|
"plot",
|
28
31
|
"measure",
|
29
32
|
"sim",
|
@@ -31,6 +34,7 @@ __all__ = [
|
|
31
34
|
"timelapse",
|
32
35
|
"deep_spacr",
|
33
36
|
"annotate_app",
|
37
|
+
"annotate_app_v2",
|
34
38
|
"gui_utils",
|
35
39
|
"mask_app",
|
36
40
|
"gui_mask_app",
|
@@ -367,6 +367,9 @@ class ImageApp:
|
|
367
367
|
print(f'Quit application')
|
368
368
|
|
369
369
|
def annotate(src, image_type=None, channels=None, geom="1000x1100", img_size=(200, 200), rows=5, columns=5, annotation_column='annotate', normalize=False, percentiles=(1,99)):
|
370
|
+
|
371
|
+
from .io import _read_and_join_tables
|
372
|
+
|
370
373
|
"""
|
371
374
|
Annotates images in a database using a graphical user interface.
|
372
375
|
|
@@ -392,6 +395,7 @@ def annotate(src, image_type=None, channels=None, geom="1000x1100", img_size=(20
|
|
392
395
|
conn.commit()
|
393
396
|
conn.close()
|
394
397
|
|
398
|
+
|
395
399
|
root = tk.Tk()
|
396
400
|
root.geometry(geom)
|
397
401
|
app = ImageApp(root, db, src, image_type=image_type, channels=channels, image_size=img_size, grid_rows=rows, grid_cols=columns, annotation_column=annotation_column, normalize=normalize, percentiles=percentiles)
|
@@ -0,0 +1,511 @@
|
|
1
|
+
from queue import Queue
|
2
|
+
from tkinter import Label, Entry, Button
|
3
|
+
import tkinter as tk
|
4
|
+
import os, threading, time, sqlite3
|
5
|
+
import numpy as np
|
6
|
+
from PIL import Image, ImageOps
|
7
|
+
from concurrent.futures import ThreadPoolExecutor
|
8
|
+
from PIL import ImageTk
|
9
|
+
import pandas as pd
|
10
|
+
from skimage.exposure import rescale_intensity
|
11
|
+
import cv2
|
12
|
+
import matplotlib.pyplot as plt
|
13
|
+
from IPython.display import display, HTML
|
14
|
+
|
15
|
+
class ImageApp:
|
16
|
+
def __init__(self, root, db_path, src, image_type=None, channels=None, grid_rows=None, grid_cols=None, image_size=(200, 200), annotation_column='annotate', normalize=False, percentiles=(1,99), measurement=None, threshold=None):
|
17
|
+
"""
|
18
|
+
Initializes an instance of the ImageApp class.
|
19
|
+
|
20
|
+
Parameters:
|
21
|
+
- root (tkinter.Tk): The root window of the application.
|
22
|
+
- db_path (str): The path to the SQLite database.
|
23
|
+
- src (str): The source directory that should be upstream of 'data' in the paths.
|
24
|
+
- image_type (str): The type of images to display.
|
25
|
+
- channels (list): The channels to filter in the images.
|
26
|
+
- grid_rows (int): The number of rows in the image grid.
|
27
|
+
- grid_cols (int): The number of columns in the image grid.
|
28
|
+
- image_size (tuple): The size of the displayed images.
|
29
|
+
- annotation_column (str): The column name for image annotations in the database.
|
30
|
+
- normalize (bool): Whether to normalize images to their 2nd and 98th percentiles. Defaults to False.
|
31
|
+
- measurement (str): The measurement column to filter by.
|
32
|
+
- threshold (float): The threshold value for filtering the measurement column.
|
33
|
+
"""
|
34
|
+
|
35
|
+
self.root = root
|
36
|
+
self.db_path = db_path
|
37
|
+
self.src = src
|
38
|
+
self.index = 0
|
39
|
+
self.grid_rows = grid_rows
|
40
|
+
self.grid_cols = grid_cols
|
41
|
+
self.image_size = image_size
|
42
|
+
self.annotation_column = annotation_column
|
43
|
+
self.image_type = image_type
|
44
|
+
self.channels = channels
|
45
|
+
self.normalize = normalize
|
46
|
+
self.percentiles = percentiles
|
47
|
+
self.images = {}
|
48
|
+
self.pending_updates = {}
|
49
|
+
self.labels = []
|
50
|
+
self.adjusted_to_original_paths = {}
|
51
|
+
self.terminate = False
|
52
|
+
self.update_queue = Queue()
|
53
|
+
self.status_label = Label(self.root, text="", font=("Arial", 12))
|
54
|
+
self.status_label.grid(row=self.grid_rows + 1, column=0, columnspan=self.grid_cols)
|
55
|
+
self.measurement = measurement
|
56
|
+
self.threshold = threshold
|
57
|
+
|
58
|
+
self.filtered_paths_annotations = []
|
59
|
+
self.prefilter_paths_annotations()
|
60
|
+
|
61
|
+
self.db_update_thread = threading.Thread(target=self.update_database_worker)
|
62
|
+
self.db_update_thread.start()
|
63
|
+
|
64
|
+
for i in range(grid_rows * grid_cols):
|
65
|
+
label = Label(root)
|
66
|
+
label.grid(row=i // grid_cols, column=i % grid_cols)
|
67
|
+
self.labels.append(label)
|
68
|
+
|
69
|
+
def prefilter_paths_annotations(self):
|
70
|
+
"""
|
71
|
+
Pre-filters the paths and annotations based on the specified measurement and threshold.
|
72
|
+
"""
|
73
|
+
from .io import _read_and_join_tables
|
74
|
+
from .utils import is_list_of_lists
|
75
|
+
|
76
|
+
if self.measurement and self.threshold is not None:
|
77
|
+
df = _read_and_join_tables(self.db_path)
|
78
|
+
df[self.annotation_column] = None
|
79
|
+
before = len(df)
|
80
|
+
|
81
|
+
if is_list_of_lists(self.measurement):
|
82
|
+
if isinstance(self.threshold, list) or is_list_of_lists(self.threshold):
|
83
|
+
if len(self.measurement) == len(self.threshold):
|
84
|
+
for idx, var in enumerate(self.measurement):
|
85
|
+
df = df[df[var[idx]] > self.threshold[idx]]
|
86
|
+
after = len(df)
|
87
|
+
elif len(self.measurement) == len(self.threshold)*2:
|
88
|
+
th_idx = 0
|
89
|
+
for idx, var in enumerate(self.measurement):
|
90
|
+
if idx % 2 != 0:
|
91
|
+
th_idx += 1
|
92
|
+
thd = self.threshold
|
93
|
+
if isinstance(thd, list):
|
94
|
+
thd = thd[0]
|
95
|
+
df[f'threshold_measurement_{idx}'] = df[self.measurement[idx]]/df[self.measurement[idx+1]]
|
96
|
+
print(f"mean threshold_measurement_{idx}: {np.mean(df['threshold_measurement'])}")
|
97
|
+
print(f"median threshold measurement: {np.median(df[self.measurement])}")
|
98
|
+
df = df[df[f'threshold_measurement_{idx}'] > thd]
|
99
|
+
after = len(df)
|
100
|
+
elif isinstance(self.measurement, list):
|
101
|
+
df['threshold_measurement'] = df[self.measurement[0]]/df[self.measurement[1]]
|
102
|
+
print(f"mean threshold measurement: {np.mean(df['threshold_measurement'])}")
|
103
|
+
print(f"median threshold measurement: {np.median(df[self.measurement])}")
|
104
|
+
df = df[df['threshold_measurement'] > self.threshold]
|
105
|
+
after = len(df)
|
106
|
+
self.measurement = 'threshold_measurement'
|
107
|
+
print(f'Removed: {before-after} rows, retained {after}')
|
108
|
+
else:
|
109
|
+
print(f"mean threshold measurement: {np.mean(df[self.measurement])}")
|
110
|
+
print(f"median threshold measurement: {np.median(df[self.measurement])}")
|
111
|
+
before = len(df)
|
112
|
+
if isinstance(self.threshold, str):
|
113
|
+
if self.threshold == 'q1':
|
114
|
+
self.threshold = df[self.measurement].quantile(0.1)
|
115
|
+
if self.threshold == 'q2':
|
116
|
+
self.threshold = df[self.measurement].quantile(0.2)
|
117
|
+
if self.threshold == 'q3':
|
118
|
+
self.threshold = df[self.measurement].quantile(0.3)
|
119
|
+
if self.threshold == 'q4':
|
120
|
+
self.threshold = df[self.measurement].quantile(0.4)
|
121
|
+
if self.threshold == 'q5':
|
122
|
+
self.threshold = df[self.measurement].quantile(0.5)
|
123
|
+
if self.threshold == 'q6':
|
124
|
+
self.threshold = df[self.measurement].quantile(0.6)
|
125
|
+
if self.threshold == 'q7':
|
126
|
+
self.threshold = df[self.measurement].quantile(0.7)
|
127
|
+
if self.threshold == 'q8':
|
128
|
+
self.threshold = df[self.measurement].quantile(0.8)
|
129
|
+
if self.threshold == 'q9':
|
130
|
+
self.threshold = df[self.measurement].quantile(0.9)
|
131
|
+
print(f"threshold: {self.threshold}")
|
132
|
+
|
133
|
+
df = df[df[self.measurement] > self.threshold]
|
134
|
+
after = len(df)
|
135
|
+
print(f'Removed: {before-after} rows, retained {after}')
|
136
|
+
|
137
|
+
df = df.dropna(subset=['png_path'])
|
138
|
+
if self.image_type:
|
139
|
+
before = len(df)
|
140
|
+
if isinstance(self.image_type, list):
|
141
|
+
for tpe in self.image_type:
|
142
|
+
df = df[df['png_path'].str.contains(tpe)]
|
143
|
+
else:
|
144
|
+
df = df[df['png_path'].str.contains(self.image_type)]
|
145
|
+
after = len(df)
|
146
|
+
print(f'image_type: Removed: {before-after} rows, retained {after}')
|
147
|
+
|
148
|
+
self.filtered_paths_annotations = df[['png_path', self.annotation_column]].values.tolist()
|
149
|
+
else:
|
150
|
+
conn = sqlite3.connect(self.db_path)
|
151
|
+
c = conn.cursor()
|
152
|
+
if self.image_type:
|
153
|
+
c.execute(f"SELECT png_path, {self.annotation_column} FROM png_list WHERE png_path LIKE ?", (f"%{self.image_type}%",))
|
154
|
+
else:
|
155
|
+
c.execute(f"SELECT png_path, {self.annotation_column} FROM png_list")
|
156
|
+
self.filtered_paths_annotations = c.fetchall()
|
157
|
+
conn.close()
|
158
|
+
|
159
|
+
def load_images(self):
|
160
|
+
"""
|
161
|
+
Loads and displays images with annotations.
|
162
|
+
|
163
|
+
This method retrieves image paths and annotations from a pre-filtered list,
|
164
|
+
loads the images using a ThreadPoolExecutor for parallel processing,
|
165
|
+
adds colored borders to images based on their annotations,
|
166
|
+
and displays the images in the corresponding labels.
|
167
|
+
|
168
|
+
Args:
|
169
|
+
None
|
170
|
+
|
171
|
+
Returns:
|
172
|
+
None
|
173
|
+
"""
|
174
|
+
|
175
|
+
for label in self.labels:
|
176
|
+
label.config(image='')
|
177
|
+
|
178
|
+
self.images = {}
|
179
|
+
paths_annotations = self.filtered_paths_annotations[self.index:self.index + self.grid_rows * self.grid_cols]
|
180
|
+
|
181
|
+
adjusted_paths = []
|
182
|
+
for path, annotation in paths_annotations:
|
183
|
+
if not path.startswith(self.src):
|
184
|
+
parts = path.split('/data/')
|
185
|
+
if len(parts) > 1:
|
186
|
+
new_path = os.path.join(self.src, 'data', parts[1])
|
187
|
+
self.adjusted_to_original_paths[new_path] = path
|
188
|
+
adjusted_paths.append((new_path, annotation))
|
189
|
+
else:
|
190
|
+
adjusted_paths.append((path, annotation))
|
191
|
+
else:
|
192
|
+
adjusted_paths.append((path, annotation))
|
193
|
+
|
194
|
+
with ThreadPoolExecutor() as executor:
|
195
|
+
loaded_images = list(executor.map(self.load_single_image, adjusted_paths))
|
196
|
+
|
197
|
+
for i, (img, annotation) in enumerate(loaded_images):
|
198
|
+
if annotation:
|
199
|
+
border_color = 'teal' if annotation == 1 else 'red'
|
200
|
+
img = self.add_colored_border(img, border_width=5, border_color=border_color)
|
201
|
+
|
202
|
+
photo = ImageTk.PhotoImage(img)
|
203
|
+
label = self.labels[i]
|
204
|
+
self.images[label] = photo
|
205
|
+
label.config(image=photo)
|
206
|
+
|
207
|
+
path = adjusted_paths[i][0]
|
208
|
+
label.bind('<Button-1>', self.get_on_image_click(path, label, img))
|
209
|
+
label.bind('<Button-3>', self.get_on_image_click(path, label, img))
|
210
|
+
|
211
|
+
self.root.update()
|
212
|
+
|
213
|
+
def load_single_image(self, path_annotation_tuple):
|
214
|
+
"""
|
215
|
+
Loads a single image from the given path and annotation tuple.
|
216
|
+
|
217
|
+
Args:
|
218
|
+
path_annotation_tuple (tuple): A tuple containing the image path and its annotation.
|
219
|
+
|
220
|
+
Returns:
|
221
|
+
img (PIL.Image.Image): The loaded image.
|
222
|
+
annotation: The annotation associated with the image.
|
223
|
+
"""
|
224
|
+
path, annotation = path_annotation_tuple
|
225
|
+
img = Image.open(path)
|
226
|
+
img = self.normalize_image(img, self.normalize, self.percentiles)
|
227
|
+
img = img.convert('RGB')
|
228
|
+
img = self.filter_channels(img)
|
229
|
+
img = img.resize(self.image_size)
|
230
|
+
return img, annotation
|
231
|
+
|
232
|
+
@staticmethod
|
233
|
+
def normalize_image(img, normalize=False, percentiles=(1, 99)):
|
234
|
+
"""
|
235
|
+
Normalize the pixel values of an image based on the 2nd and 98th percentiles or the image min and max values,
|
236
|
+
and ensure the image is exported as 8-bit.
|
237
|
+
|
238
|
+
Parameters:
|
239
|
+
- img: PIL.Image.Image. The input image to be normalized.
|
240
|
+
- normalize: bool. Whether to normalize based on the 2nd and 98th percentiles.
|
241
|
+
- percentiles: tuple. The percentiles to use for normalization.
|
242
|
+
|
243
|
+
Returns:
|
244
|
+
- PIL.Image.Image. The normalized and 8-bit converted image.
|
245
|
+
"""
|
246
|
+
img_array = np.array(img)
|
247
|
+
|
248
|
+
if normalize:
|
249
|
+
if img_array.ndim == 2: # Grayscale image
|
250
|
+
p2, p98 = np.percentile(img_array, percentiles)
|
251
|
+
img_array = rescale_intensity(img_array, in_range=(p2, p98), out_range=(0, 255))
|
252
|
+
else: # Color image or multi-channel image
|
253
|
+
for channel in range(img_array.shape[2]):
|
254
|
+
p2, p98 = np.percentile(img_array[:, :, channel], percentiles)
|
255
|
+
img_array[:, :, channel] = rescale_intensity(img_array[:, :, channel], in_range=(p2, p98), out_range=(0, 255))
|
256
|
+
|
257
|
+
img_array = np.clip(img_array, 0, 255).astype('uint8')
|
258
|
+
|
259
|
+
return Image.fromarray(img_array)
|
260
|
+
|
261
|
+
def add_colored_border(self, img, border_width, border_color):
|
262
|
+
"""
|
263
|
+
Adds a colored border to an image.
|
264
|
+
|
265
|
+
Args:
|
266
|
+
img (PIL.Image.Image): The input image.
|
267
|
+
border_width (int): The width of the border in pixels.
|
268
|
+
border_color (str): The color of the border in RGB format.
|
269
|
+
|
270
|
+
Returns:
|
271
|
+
PIL.Image.Image: The image with the colored border.
|
272
|
+
"""
|
273
|
+
top_border = Image.new('RGB', (img.width, border_width), color=border_color)
|
274
|
+
bottom_border = Image.new('RGB', (img.width, border_width), color=border_color)
|
275
|
+
left_border = Image.new('RGB', (border_width, img.height), color=border_color)
|
276
|
+
right_border = Image.new('RGB', (border_width, img.height), color=border_color)
|
277
|
+
|
278
|
+
bordered_img = Image.new('RGB', (img.width + 2 * border_width, img.height + 2 * border_width), color='white')
|
279
|
+
bordered_img.paste(top_border, (border_width, 0))
|
280
|
+
bordered_img.paste(bottom_border, (border_width, img.height + border_width))
|
281
|
+
bordered_img.paste(left_border, (0, border_width))
|
282
|
+
bordered_img.paste(right_border, (img.width + border_width, border_width))
|
283
|
+
bordered_img.paste(img, (border_width, border_width))
|
284
|
+
|
285
|
+
return bordered_img
|
286
|
+
|
287
|
+
def filter_channels(self, img):
|
288
|
+
"""
|
289
|
+
Filters the channels of an image based on the specified channels.
|
290
|
+
|
291
|
+
Args:
|
292
|
+
img (PIL.Image.Image): The input image.
|
293
|
+
|
294
|
+
Returns:
|
295
|
+
PIL.Image.Image: The filtered image.
|
296
|
+
"""
|
297
|
+
r, g, b = img.split()
|
298
|
+
if self.channels:
|
299
|
+
if 'r' not in self.channels:
|
300
|
+
r = r.point(lambda _: 0)
|
301
|
+
if 'g' not in self.channels:
|
302
|
+
g = g.point(lambda _: 0)
|
303
|
+
if 'b' not in self.channels:
|
304
|
+
b = b.point(lambda _: 0)
|
305
|
+
|
306
|
+
if len(self.channels) == 1:
|
307
|
+
channel_img = r if 'r' in self.channels else (g if 'g' in self.channels else b)
|
308
|
+
return ImageOps.grayscale(channel_img)
|
309
|
+
|
310
|
+
return Image.merge("RGB", (r, g, b))
|
311
|
+
|
312
|
+
def get_on_image_click(self, path, label, img):
|
313
|
+
"""
|
314
|
+
Returns a callback function that handles the click event on an image.
|
315
|
+
|
316
|
+
Parameters:
|
317
|
+
path (str): The path of the image file.
|
318
|
+
label (tkinter.Label): The label widget to update with the annotated image.
|
319
|
+
img (PIL.Image.Image): The image object.
|
320
|
+
|
321
|
+
Returns:
|
322
|
+
function: The callback function for the image click event.
|
323
|
+
"""
|
324
|
+
def on_image_click(event):
|
325
|
+
new_annotation = 1 if event.num == 1 else (2 if event.num == 3 else None)
|
326
|
+
|
327
|
+
original_path = self.adjusted_to_original_paths.get(path, path)
|
328
|
+
|
329
|
+
if original_path in self.pending_updates and self.pending_updates[original_path] == new_annotation:
|
330
|
+
self.pending_updates[original_path] = None
|
331
|
+
new_annotation = None
|
332
|
+
else:
|
333
|
+
self.pending_updates[original_path] = new_annotation
|
334
|
+
|
335
|
+
print(f"Image {os.path.split(path)[1]} annotated: {new_annotation}")
|
336
|
+
|
337
|
+
img_ = img.crop((5, 5, img.width-5, img.height-5))
|
338
|
+
border_fill = 'teal' if new_annotation == 1 else ('red' if new_annotation == 2 else None)
|
339
|
+
img_ = ImageOps.expand(img_, border=5, fill=border_fill) if border_fill else img_
|
340
|
+
|
341
|
+
photo = ImageTk.PhotoImage(img_)
|
342
|
+
self.images[label] = photo
|
343
|
+
label.config(image=photo)
|
344
|
+
self.root.update()
|
345
|
+
|
346
|
+
return on_image_click
|
347
|
+
|
348
|
+
@staticmethod
|
349
|
+
def update_html(text):
|
350
|
+
display(HTML(f"""
|
351
|
+
<script>
|
352
|
+
document.getElementById('unique_id').innerHTML = '{text}';
|
353
|
+
</script>
|
354
|
+
"""))
|
355
|
+
|
356
|
+
def update_database_worker(self):
|
357
|
+
"""
|
358
|
+
Worker function that continuously updates the database with pending updates from the update queue.
|
359
|
+
It retrieves the pending updates from the queue, updates the corresponding records in the database,
|
360
|
+
and resets the text in the HTML and status label.
|
361
|
+
"""
|
362
|
+
conn = sqlite3.connect(self.db_path)
|
363
|
+
c = conn.cursor()
|
364
|
+
|
365
|
+
display(HTML("<div id='unique_id'>Initial Text</div>"))
|
366
|
+
|
367
|
+
while True:
|
368
|
+
if self.terminate:
|
369
|
+
conn.close()
|
370
|
+
break
|
371
|
+
|
372
|
+
if not self.update_queue.empty():
|
373
|
+
ImageApp.update_html("Do not exit, Updating database...")
|
374
|
+
self.status_label.config(text='Do not exit, Updating database...')
|
375
|
+
|
376
|
+
pending_updates = self.update_queue.get()
|
377
|
+
for path, new_annotation in pending_updates.items():
|
378
|
+
if new_annotation is None:
|
379
|
+
c.execute(f'UPDATE png_list SET {self.annotation_column} = NULL WHERE png_path = ?', (path,))
|
380
|
+
else:
|
381
|
+
c.execute(f'UPDATE png_list SET {self.annotation_column} = ? WHERE png_path = ?', (new_annotation, path))
|
382
|
+
conn.commit()
|
383
|
+
|
384
|
+
# Reset the text
|
385
|
+
ImageApp.update_html('')
|
386
|
+
self.status_label.config(text='')
|
387
|
+
self.root.update()
|
388
|
+
time.sleep(0.1)
|
389
|
+
|
390
|
+
def update_gui_text(self, text):
|
391
|
+
"""
|
392
|
+
Update the text of the status label in the GUI.
|
393
|
+
|
394
|
+
Args:
|
395
|
+
text (str): The new text to be displayed in the status label.
|
396
|
+
|
397
|
+
Returns:
|
398
|
+
None
|
399
|
+
"""
|
400
|
+
self.status_label.config(text=text)
|
401
|
+
self.root.update()
|
402
|
+
|
403
|
+
def next_page(self):
|
404
|
+
"""
|
405
|
+
Moves to the next page of images in the grid.
|
406
|
+
|
407
|
+
If there are pending updates in the dictionary, they are added to the update queue.
|
408
|
+
The pending updates dictionary is then cleared.
|
409
|
+
The index is incremented by the number of rows multiplied by the number of columns in the grid.
|
410
|
+
Finally, the images are loaded for the new page.
|
411
|
+
"""
|
412
|
+
if self.pending_updates: # Check if the dictionary is not empty
|
413
|
+
self.update_queue.put(self.pending_updates.copy())
|
414
|
+
self.pending_updates.clear()
|
415
|
+
self.index += self.grid_rows * self.grid_cols
|
416
|
+
self.load_images()
|
417
|
+
|
418
|
+
def previous_page(self):
|
419
|
+
"""
|
420
|
+
Move to the previous page in the grid.
|
421
|
+
|
422
|
+
If there are pending updates in the dictionary, they are added to the update queue.
|
423
|
+
The dictionary of pending updates is then cleared.
|
424
|
+
The index is decremented by the number of rows multiplied by the number of columns in the grid.
|
425
|
+
If the index becomes negative, it is set to 0.
|
426
|
+
Finally, the images are loaded for the new page.
|
427
|
+
"""
|
428
|
+
if self.pending_updates: # Check if the dictionary is not empty
|
429
|
+
self.update_queue.put(self.pending_updates.copy())
|
430
|
+
self.pending_updates.clear()
|
431
|
+
self.index -= self.grid_rows * self.grid_cols
|
432
|
+
if self.index < 0:
|
433
|
+
self.index = 0
|
434
|
+
self.load_images()
|
435
|
+
|
436
|
+
def shutdown(self):
|
437
|
+
"""
|
438
|
+
Shuts down the application.
|
439
|
+
|
440
|
+
This method sets the terminate flag to True, clears the pending updates,
|
441
|
+
updates the database, and quits the application.
|
442
|
+
|
443
|
+
"""
|
444
|
+
self.terminate = True # Set terminate first
|
445
|
+
self.update_queue.put(self.pending_updates.copy())
|
446
|
+
self.pending_updates.clear()
|
447
|
+
self.db_update_thread.join() # Join the thread to make sure database is updated
|
448
|
+
self.root.quit()
|
449
|
+
self.root.destroy()
|
450
|
+
print(f'Quit application')
|
451
|
+
|
452
|
+
def get_annotate_default_settings(settings):
|
453
|
+
|
454
|
+
settings.setdefault('image_type', 'cell_png')
|
455
|
+
settings.setdefault('channels', ['r', 'g', 'b'])
|
456
|
+
settings.setdefault('geom', "3200x2000")
|
457
|
+
settings.setdefault('img_size', (200, 200))
|
458
|
+
settings.setdefault('rows', 10)
|
459
|
+
settings.setdefault('columns', 18)
|
460
|
+
settings.setdefault('annotation_column', 'recruited_test')
|
461
|
+
settings.setdefault('normalize', False)
|
462
|
+
settings.setdefault('percentiles', (2,98))
|
463
|
+
settings.setdefault('measurement', ['cytoplasm_channel_3_mean_intensity', 'pathogen_channel_3_mean_intensity'])
|
464
|
+
settings.setdefault('threshold', 2)
|
465
|
+
|
466
|
+
return settings
|
467
|
+
|
468
|
+
def annotate(settings):
|
469
|
+
"""
|
470
|
+
Annotates images in a database using a graphical user interface.
|
471
|
+
|
472
|
+
Args:
|
473
|
+
db (str): The path to the SQLite database.
|
474
|
+
src (str): The source directory that should be upstream of 'data' in the paths.
|
475
|
+
image_type (str, optional): The type of images to load from the database. Defaults to None.
|
476
|
+
channels (str, optional): The channels of the images to load from the database. Defaults to None.
|
477
|
+
geom (str, optional): The geometry of the GUI window. Defaults to "1000x1100".
|
478
|
+
img_size (tuple, optional): The size of the images to display in the GUI. Defaults to (200, 200).
|
479
|
+
rows (int, optional): The number of rows in the image grid. Defaults to 5.
|
480
|
+
columns (int, optional): The number of columns in the image grid. Defaults to 5.
|
481
|
+
annotation_column (str, optional): The name of the annotation column in the database table. Defaults to 'annotate'.
|
482
|
+
normalize (bool, optional): Whether to normalize images to their 2nd and 98th percentiles. Defaults to False.
|
483
|
+
measurement (str, optional): The measurement column to filter by.
|
484
|
+
threshold (float, optional): The threshold value for filtering the measurement column.
|
485
|
+
"""
|
486
|
+
|
487
|
+
settings = get_annotate_default_settings(settings)
|
488
|
+
src = settings['src']
|
489
|
+
|
490
|
+
db = os.path.join(src, 'measurements/measurements.db')
|
491
|
+
conn = sqlite3.connect(db)
|
492
|
+
c = conn.cursor()
|
493
|
+
c.execute('PRAGMA table_info(png_list)')
|
494
|
+
cols = c.fetchall()
|
495
|
+
if settings['annotation_column'] not in [col[1] for col in cols]:
|
496
|
+
c.execute(f"ALTER TABLE png_list ADD COLUMN {settings['annotation_column']} integer")
|
497
|
+
conn.commit()
|
498
|
+
conn.close()
|
499
|
+
|
500
|
+
root = tk.Tk()
|
501
|
+
root.geometry(settings['geom'])
|
502
|
+
app = ImageApp(root, db, src, image_type=settings['image_type'], channels=settings['channels'], image_size=settings['img_size'], grid_rows=settings['rows'], grid_cols=settings['columns'], annotation_column=settings['annotation_column'], normalize=settings['normalize'], percentiles=settings['percentiles'], measurement=settings['measurement'], threshold=settings['threshold'])
|
503
|
+
next_button = tk.Button(root, text="Next", command=app.next_page)
|
504
|
+
next_button.grid(row=app.grid_rows, column=app.grid_cols - 1)
|
505
|
+
back_button = tk.Button(root, text="Back", command=app.previous_page)
|
506
|
+
back_button.grid(row=app.grid_rows, column=app.grid_cols - 2)
|
507
|
+
exit_button = tk.Button(root, text="Exit", command=app.shutdown)
|
508
|
+
exit_button.grid(row=app.grid_rows, column=app.grid_cols - 3)
|
509
|
+
|
510
|
+
app.load_images()
|
511
|
+
root.mainloop()
|