Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GUI to select and deselect cells at extraction time.
"""
import sys
import numpy as np
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton,
QHBoxLayout, QVBoxLayout)
from PIL import Image, ImageDraw
#Import from matplotlib to use it to display the pictures and masks.
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.figure import Figure
class Extract(QWidget):
def __init__(self):
super(Extract, self).__init__()
image, mask = _test_data()
self.pc = PlotCanvas(image, mask)
self.init_UI()
self.exit_code = 0 # 0: Cancel, 1: Fluorescence, 2: Mask
def init_UI(self):
# Extract Buttons
self.extr_mask = _create_button("Extract Mask", self.do_extr_mask)
self.extr_fluo = _create_button("Extract Fluorescence", self.do_extr_fluo)
self.done = _create_button("Cancel", self.do_cancel)
extr_box = QVBoxLayout()
extr_box.addWidget(self.extr_mask)
extr_box.addWidget(self.extr_fluo)
extr_box.addWidget(self.done)
# Select Button
self.sel_mult = _create_button("Select Multiple", self.do_sel_mult)
self.sel_sngl = _create_button("Select Single", self.do_sel_sngl)
self.desel_mult = _create_button("Deselect Multiple", self.do_desel_mult)
self.desel_sngl = _create_button("Deselect Single", self.do_desel_sngl)
sel_box = QVBoxLayout()
sel_box.addWidget(self.sel_mult)
sel_box.addWidget(self.sel_sngl)
sel_box.addWidget(self.desel_mult)
sel_box.addWidget(self.desel_sngl)
# Button list
self.buttons = [self.extr_mask,
self.extr_fluo,
self.done,
self.sel_mult,
self.sel_sngl,
self.desel_mult,
self.desel_sngl]
# Buttons
buttons = QHBoxLayout()
buttons.addLayout(sel_box)
buttons.addStretch(.5)
buttons.addLayout(extr_box)
# Plot Canvas
full = QVBoxLayout()
full.addWidget(self.pc)
full.addStretch(.5)
full.addLayout(buttons)
self.setLayout(full)
self.setGeometry(300, 300, 600, 600)
self.setWindowTitle('Extracting')
self.show()
def do_extr_fluo(self):
self.exit_code = 1
self.cells = self.pc.sellist
self.close()
def do_cancel(self):
self.close()
def do_extr_mask(self):
self.exit_code = 2
self.cells = self.pc.sellist
self.close()
def do_sel_mult(self):
"""Callback for selecting multiple"""
self.pc.storemouseclicks = []
def to_connect(e):
self.pc.multiple_click(e, self.do_sel_mult_process)
self.pc.connect_id = self.pc.mpl_connect(
'button_press_event',
to_connect)
self.deactivate_all()
def do_sel_mult_process(self):
"""Process selecting multiple"""
cells = self.cells_in_polygon()
self.pc.sellist = self.pc.sellist.union(cells)
self.disconnect()
def do_desel_mult(self):
self.pc.storemouseclicks = []
"""Callback for deselecting multiple"""
def to_connect(e):
self.pc.multiple_click(e, self.do_desel_mult_process)
self.pc.connect_id = self.pc.mpl_connect(
'button_press_event',
to_connect)
self.deactivate_all()
def do_desel_mult_process(self):
"""Process deselect multiple"""
cells = self.cells_in_polygon()
self.pc.sellist = self.pc.sellist - cells
self.disconnect()
def cells_in_polygon(self):
"""Extracts cells inside of polygon specified by pc.storemouseclicks"""
img = Image.new('L', (self.pc.mask.shape), 0)
ImageDraw.Draw(img).polygon(self.pc.storemouseclicks, outline=1, fill=1)
polygon = np.array(img).astype(bool)
return set(np.unique(self.pc.mask[polygon]))
def do_sel_sngl(self):
"""Select single cell"""
def to_connect(e):
self.pc.single_click(e, self.do_sel_sngl_process)
self.pc.connect_id = self.pc.mpl_connect(
'button_press_event',
to_connect)
self.deactivate_all()
def do_sel_sngl_process(self, x, y):
"""Process selected cell"""
if x is not None:
cell = self.pc.mask[y,x]
self.pc.sellist.add(cell)
self.disconnect()
def do_desel_sngl(self):
"""Deselect single cell"""
def to_connect(e):
self.pc.single_click(e, self.do_desel_sngl_process)
self.pc.connect_id = self.pc.mpl_connect(
'button_press_event',
to_connect)
self.deactivate_all()
def do_desel_sngl_process(self, x, y):
"""Process deselected cell"""
if x is not None:
cell = self.pc.mask[y,x]
self.pc.sellist.remove(cell)
self.disconnect()
def disconnect(self):
"""Disconnects callback, updates plots, activates buttons"""
self.pc.update_plots()
self.pc.mpl_disconnect(self.pc.connect_id)
self.activate_all()
def deactivate_all(self):
for b in self.buttons:
b.setEnabled(False)
def activate_all(self):
for b in self.buttons:
b.setEnabled(True)
class PlotCanvas(FigureCanvas):
def __init__(self, image, mask, parent=None, figsize=(5,4)):
"""this class defines the canvas. It initializes a figure, which is then
used to plot our data using imshow.
"""
fig = Figure()
self.ax = fig.add_subplot(111)
super(PlotCanvas, self).__init__(fig)
self.setParent(parent)
self.image = image
self.mask = mask
self.sellist = set(np.unique(mask)) # selected cells
self.vismask = mask.copy() # mask with only selected cells
self.ax_image, self.ax_mask = self.initialize_plots(image, mask, self.ax)
self.storemouseclicks = []
self.connect_id = None
def initialize_plots(self, picture, mask, ax):
"""Creates plots at initialization"""
newcmp = _colormap(21)
ax.axis("off")
self.draw()
return (ax.imshow(picture, interpolation= 'None',
origin = 'upper', cmap = 'gray_r'),
ax.imshow((mask%10+1)*(mask != 0), origin = 'upper',
interpolation = 'None', cmap = newcmp,
vmin=0, vmax=11))
def single_click(self, event, call_after):
"""Function for single click, calls call_after afterwards with
the clicked points (or None, None) if abort click."""
if (event.button == 1
and (event.xdata != None and event.ydata != None)
and self.ax == event.inaxes):
x = int(event.xdata)
y = int(event.ydata)
call_after(x, y)
else:
call_after(None, None)
def multiple_click(self, event, call_after):
"""Function to keep track of multiple left clicks, confirmed with
a right click. After right click, the function call_after is called"""
if (event.button == 1 # left click
and (event.xdata != None and event.ydata != None)
and self.ax == event.inaxes):
newx = int(event.xdata)
newy = int(event.ydata)
self.storemouseclicks.append((newx, newy))
self.draw_click(newx, newy)
elif (event.button == 3): # right click
self.mpl_disconnect(self.connect_id)
call_after()
def draw_click(self, posx, posy):
"""
it updates the plot once the user clicks on the plot and draws a 4x4 pixel dot
at the coordinate of the click
"""
self.vismask[posy:posy+2, posx:posx+2] = 9
self.redraw_mask()
def redraw_mask(self):
"""Redraw mask with current self.vismask"""
self.ax_mask.set_data((self.vismask%10+1)*(self.vismask!=0))
self.ax.draw_artist(self.ax_image)
self.ax.draw_artist(self.ax_mask)
self.update()
self.flush_events()
def recalculate_vismask(self):
"""Recalculates vismask with current list of cells to show"""
tmp = self.mask.copy()
all_cells = set(np.unique(tmp))
to_remove = all_cells - self.sellist
for cell in to_remove:
tmp[tmp==cell] = 0
self.vismask = tmp
def update_plots(self):
"""Shows plot with currently selected cells"""
self.recalculate_vismask()
self.redraw_mask()
def _create_button(text, connect, tooltip=None):
"""Initializes button, connects with callback connect"""
button = QPushButton(text)
button.clicked.connect(connect)
button.setMaximumWidth(150)
if tooltip is not None:
button.setToolTip(tooltip)
return button
def _colormap(Ncolors=21):
"""Creates colormap for segmentation mask"""
jet = cm.get_cmap('jet', Ncolors)
cmaplist = [(0,0,0,0)]
for i in range(jet.N):
r,g,b,_ = jet(i)
cmaplist.append((r,g,b,.2))
cmap = LinearSegmentedColormap.from_list('Custom cmap', cmaplist, Ncolors)
return cmap
def _poly_to_mask(polygon, shape):
"""Converts polygon to mask"""
img = Image.new('L', shape, 0)
ImageDraw.Draw(img).polygon(polygon, outline=0, fill=1)
return np.array(img).astype(int)
def _poly_to_line(polygon, shape):
"""Converts polygon to line"""
img = Image.new('L', shape, 0)
ImageDraw.Draw(img).polygon(polygon, outline=1, fill=0)
return np.array(img).astype(int)
def _test_data():
"""Creates test data"""
im = np.zeros((100,100))
mask = np.zeros(im.shape)
poly1 = [(20,20),(30,30),(20,40),(10,30)]
poly2 = [(50,50),(60,60),(50,70),(40,60)]
mask += _poly_to_mask(poly1, im.shape)
mask += _poly_to_mask(poly2, im.shape)*2
im += _poly_to_line(poly1, im.shape)
im += _poly_to_line(poly2, im.shape)
return im, mask
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Extract()
sys.exit(app.exec_())