-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathimage.py
More file actions
490 lines (374 loc) · 14.8 KB
/
image.py
File metadata and controls
490 lines (374 loc) · 14.8 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
from typing import *
from math import ceil
from itertools import product
import weakref
import numpy as np
import pygfx
from ..utils import quick_min_max
from ._base import Graphic, Interaction
from .selectors import LinearSelector, LinearRegionSelector
from ._features import (
ImageCmapFeature,
ImageDataFeature,
HeatmapDataFeature,
HeatmapCmapFeature,
to_gpu_supported_dtype,
)
class _AddSelectorsMixin:
def add_linear_selector(
self, selection: int = None, padding: float = None, **kwargs
) -> LinearSelector:
"""
Adds a :class:`.LinearSelector`.
Parameters
----------
selection: int, optional
initial position of the selector
padding: float, optional
pad the length of the selector
kwargs:
passed to :class:`.LinearSelector`
Returns
-------
LinearSelector
"""
# default padding is 15% the height or width of the image
if "axis" in kwargs.keys():
axis = kwargs["axis"]
else:
axis = "x"
(
bounds_init,
limits,
size,
origin,
axis,
end_points,
) = self._get_linear_selector_init_args(padding, **kwargs)
if selection is None:
selection = limits[0]
if selection < limits[0] or selection > limits[1]:
raise ValueError(
f"the passed selection: {selection} is beyond the limits: {limits}"
)
selector = LinearSelector(
selection=selection,
limits=limits,
end_points=end_points,
parent=weakref.proxy(self),
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
selector.position_z = self.position_z + 1
return weakref.proxy(selector)
def add_linear_region_selector(
self, padding: float = None, **kwargs
) -> LinearRegionSelector:
"""
Add a :class:`.LinearRegionSelector`.
Parameters
----------
padding: float, optional
Extends the linear selector along the y-axis to make it easier to interact with.
kwargs: optional
passed to ``LinearRegionSelector``
Returns
-------
LinearRegionSelector
linear selection graphic
"""
(
bounds_init,
limits,
size,
origin,
axis,
end_points,
) = self._get_linear_selector_init_args(padding, **kwargs)
# create selector
selector = LinearRegionSelector(
bounds=bounds_init,
limits=limits,
size=size,
origin=origin,
parent=weakref.proxy(self),
fill_color=(0, 0, 0.35, 0.2),
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
# so that it is above this graphic
selector.position_z = self.position_z + 3
# PlotArea manages this for garbage collection etc. just like all other Graphics
# so we should only work with a proxy on the user-end
return weakref.proxy(selector)
# TODO: this method is a bit of a mess, can refactor later
def _get_linear_selector_init_args(self, padding: float, **kwargs):
# computes initial bounds, limits, size and origin of linear selectors
data = self.data()
if "axis" in kwargs.keys():
axis = kwargs["axis"]
else:
axis = "x"
if padding is None:
if axis == "x":
# based on number of rows
padding = int(data.shape[0] * 0.15)
elif axis == "y":
# based on number of columns
padding = int(data.shape[1] * 0.15)
if axis == "x":
offset = self.position_x
# x limits, number of columns
limits = (offset, data.shape[1] - 1)
# size is number of rows + padding
# used by LinearRegionSelector but not LinearSelector
size = data.shape[0] + padding
# initial position of the selector
# center row
position_y = data.shape[0] / 2
# need y offset too for this
origin = (limits[0] - offset, position_y + self.position_y)
# endpoints of the data range
# used by linear selector but not linear region
# padding, n_rows + padding
end_points = (0 - padding, data.shape[0] + padding)
else:
offset = self.position_y
# y limits
limits = (offset, data.shape[0] - 1)
# width + padding
# used by LinearRegionSelector but not LinearSelector
size = data.shape[1] + padding
# initial position of the selector
position_x = data.shape[1] / 2
# need x offset too for this
origin = (position_x + self.position_x, limits[0] - offset)
# endpoints of the data range
# used by linear selector but not linear region
end_points = (0 - padding, data.shape[1] + padding)
# initial bounds are 20% of the limits range
# used by LinearRegionSelector but not LinearSelector
bounds_init = (limits[0], int(np.ptp(limits) * 0.2) + offset)
return bounds_init, limits, size, origin, axis, end_points
def _add_plot_area_hook(self, plot_area):
self._plot_area = plot_area
class ImageGraphic(Graphic, Interaction, _AddSelectorsMixin):
feature_events = {"data", "cmap", "present"}
def __init__(
self,
data: Any,
vmin: int = None,
vmax: int = None,
cmap: str = "plasma",
filter: str = "nearest",
isolated_buffer: bool = True,
*args,
**kwargs,
):
"""
Create an Image Graphic
Parameters
----------
data: array-like
array-like, usually numpy.ndarray, must support ``memoryview()``
Tensorflow Tensors also work **probably**, but not thoroughly tested
| shape must be ``[x_dim, y_dim]`` or ``[x_dim, y_dim, rgb]``
vmin: int, optional
minimum value for color scaling, calculated from data if not provided
vmax: int, optional
maximum value for color scaling, calculated from data if not provided
cmap: str, optional, default "plasma"
colormap to use to display the image data, ignored if data is RGB
filter: str, optional, default "nearest"
interpolation filter, one of "nearest" or "linear"
isolated_buffer: bool, default True
If True, initialize a buffer with the same shape as the input data and then
set the data, useful if the data arrays are ready-only such as memmaps.
If False, the input array is itself used as the buffer.
args:
additional arguments passed to Graphic
kwargs:
additional keyword arguments passed to Graphic
Features
--------
**data**: :class:`.ImageDataFeature`
Manages the data buffer displayed in the ImageGraphic
**cmap**: :class:`.ImageCmapFeature`
Manages the colormap
**present**: :class:`.PresentFeature`
Control the presence of the Graphic in the scene
"""
super().__init__(*args, **kwargs)
data = to_gpu_supported_dtype(data)
# TODO: we need to organize and do this better
if isolated_buffer:
# initialize a buffer with the same shape as the input data
# we do not directly use the input data array as the buffer
# because if the input array is a read-only type, such as
# numpy memmaps, we would not be able to change the image data
buffer_init = np.zeros(shape=data.shape, dtype=data.dtype)
else:
buffer_init = data
if (vmin is None) or (vmax is None):
vmin, vmax = quick_min_max(data)
texture = pygfx.Texture(buffer_init, dim=2)
geometry = pygfx.Geometry(grid=texture)
self.cmap = ImageCmapFeature(self, cmap)
# if data is RGB or RGBA
if data.ndim > 2:
material = pygfx.ImageBasicMaterial(
clim=(vmin, vmax), map_interpolation=filter, pick_write=True
)
# if data is just 2D without color information, use colormap LUT
else:
material = pygfx.ImageBasicMaterial(
clim=(vmin, vmax),
map=self.cmap(),
map_interpolation=filter,
pick_write=True,
)
world_object = pygfx.Image(geometry, material)
self._set_world_object(world_object)
self.cmap.vmin = vmin
self.cmap.vmax = vmax
self.data = ImageDataFeature(self, data)
# TODO: we need to organize and do this better
if isolated_buffer:
# if the buffer was initialized with zeros
# set it with the actual data
self.data = data
def set_feature(self, feature: str, new_data: Any, indices: Any):
pass
def reset_feature(self, feature: str):
pass
class _ImageTile(pygfx.Image):
"""
Similar to pygfx.Image, only difference is that it contains a few properties to keep track of
row chunk index, column chunk index
"""
def _wgpu_get_pick_info(self, pick_value):
pick_info = super()._wgpu_get_pick_info(pick_value)
# add row chunk and col chunk index to pick_info dict
return {
**pick_info,
"row_chunk_index": self.row_chunk_index,
"col_chunk_index": self.col_chunk_index,
}
@property
def row_chunk_index(self) -> int:
return self._row_chunk_index
@row_chunk_index.setter
def row_chunk_index(self, index: int):
self._row_chunk_index = index
@property
def col_chunk_index(self) -> int:
return self._col_chunk_index
@col_chunk_index.setter
def col_chunk_index(self, index: int):
self._col_chunk_index = index
class HeatmapGraphic(Graphic, Interaction, _AddSelectorsMixin):
feature_events = {"data", "cmap", "present"}
def __init__(
self,
data: Any,
vmin: int = None,
vmax: int = None,
cmap: str = "plasma",
filter: str = "nearest",
chunk_size: int = 8192,
isolated_buffer: bool = True,
*args,
**kwargs,
):
"""
Create an Image Graphic
Parameters
----------
data: array-like
array-like, usually numpy.ndarray, must support ``memoryview()``
Tensorflow Tensors also work **probably**, but not thoroughly tested
| shape must be ``[x_dim, y_dim]``
vmin: int, optional
minimum value for color scaling, calculated from data if not provided
vmax: int, optional
maximum value for color scaling, calculated from data if not provided
cmap: str, optional, default "plasma"
colormap to use to display the data
filter: str, optional, default "nearest"
interpolation filter, one of "nearest" or "linear"
chunk_size: int, default 8192, max 8192
chunk size for each tile used to make up the heatmap texture
isolated_buffer: bool, default True
If True, initialize a buffer with the same shape as the input data and then
set the data, useful if the data arrays are ready-only such as memmaps.
If False, the input array is itself used as the buffer.
args:
additional arguments passed to Graphic
kwargs:
additional keyword arguments passed to Graphic
Features
--------
**data**: :class:`.HeatmapDataFeature`
Manages the data buffer displayed in the HeatmapGraphic
**cmap**: :class:`.HeatmapCmapFeature`
Manages the colormap
**present**: :class:`.PresentFeature`
Control the presence of the Graphic in the scene
"""
super().__init__(*args, **kwargs)
if chunk_size > 8192:
raise ValueError("Maximum chunk size is 8192")
data = to_gpu_supported_dtype(data)
# TODO: we need to organize and do this better
if isolated_buffer:
# initialize a buffer with the same shape as the input data
# we do not directly use the input data array as the buffer
# because if the input array is a read-only type, such as
# numpy memmaps, we would not be able to change the image data
buffer_init = np.zeros(shape=data.shape, dtype=data.dtype)
else:
buffer_init = data
row_chunks = range(ceil(data.shape[0] / chunk_size))
col_chunks = range(ceil(data.shape[1] / chunk_size))
chunks = list(product(row_chunks, col_chunks))
# chunks is the index position of each chunk
start_ixs = [list(map(lambda c: c * chunk_size, chunk)) for chunk in chunks]
stop_ixs = [list(map(lambda c: c + chunk_size, chunk)) for chunk in start_ixs]
world_object = pygfx.Group()
self._set_world_object(world_object)
if (vmin is None) or (vmax is None):
vmin, vmax = quick_min_max(data)
self.cmap = HeatmapCmapFeature(self, cmap)
self._material = pygfx.ImageBasicMaterial(
clim=(vmin, vmax),
map=self.cmap(),
map_interpolation=filter,
pick_write=True,
)
for start, stop, chunk in zip(start_ixs, stop_ixs, chunks):
row_start, col_start = start
row_stop, col_stop = stop
# x and y positions of the Tile in world space coordinates
y_pos, x_pos = row_start, col_start
texture = pygfx.Texture(
buffer_init[row_start:row_stop, col_start:col_stop], dim=2
)
geometry = pygfx.Geometry(grid=texture)
# material = pygfx.ImageBasicMaterial(clim=(0, 1), map=self.cmap())
img = _ImageTile(geometry, self._material)
# row and column chunk index for this Tile
img.row_chunk_index = chunk[0]
img.col_chunk_index = chunk[1]
img.world.x = x_pos
img.world.y = y_pos
self.world_object.add(img)
self.data = HeatmapDataFeature(self, buffer_init)
# TODO: we need to organize and do this better
if isolated_buffer:
# if the buffer was initialized with zeros
# set it with the actual data
self.data = data
def set_feature(self, feature: str, new_data: Any, indices: Any):
pass
def reset_feature(self, feature: str):
pass