-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy path_image.py
More file actions
326 lines (250 loc) · 9.48 KB
/
_image.py
File metadata and controls
326 lines (250 loc) · 9.48 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
from itertools import product
from math import ceil
import numpy as np
import pygfx
from ._base import GraphicFeature, GraphicFeatureEvent, block_reentrance
from ...utils import (
make_colors,
get_cmap_texture,
)
class TextureArray(GraphicFeature):
"""
Manages an array of Textures representing chunks of an image.
Creates multiple pygfx.Texture objects based on the GPU's max texture dimension limit.
"""
event_info_spec = [
{
"dict key": "key",
"type": "slice, index, numpy-like fancy index",
"description": "key at which image data was sliced/fancy indexed",
},
{
"dict key": "value",
"type": "np.ndarray | float",
"description": "new data values",
},
]
def __init__(self, data, isolated_buffer: bool = True, property_name: str = "data"):
super().__init__(property_name=property_name)
data = self._fix_data(data)
shared = pygfx.renderers.wgpu.get_shared()
self._texture_limit_2d = shared.device.limits["max-texture-dimension-2d"]
if isolated_buffer:
# useful if data is read-only, example: memmaps
self._value = np.zeros(data.shape, dtype=data.dtype)
self.value[:] = data[:]
else:
# user's input array is used as the buffer
self._value = data
# data start indices for each Texture
self._row_indices = np.arange(
0,
ceil(self.value.shape[0] / self._texture_limit_2d) * self._texture_limit_2d,
self._texture_limit_2d,
)
self._col_indices = np.arange(
0,
ceil(self.value.shape[1] / self._texture_limit_2d) * self._texture_limit_2d,
self._texture_limit_2d,
)
# buffer will be an array of textures
self._buffer: np.ndarray[pygfx.Texture] = np.empty(
shape=(self.row_indices.size, self.col_indices.size), dtype=object
)
self._iter = None
# iterate through each chunk of passed `data`
# create a pygfx.Texture from this chunk
for _, buffer_index, data_slice in self:
texture = pygfx.Texture(self.value[data_slice], dim=2)
self.buffer[buffer_index] = texture
@property
def value(self) -> np.ndarray:
return self._value
def set_value(self, graphic, value):
self[:] = value
@property
def buffer(self) -> np.ndarray[pygfx.Texture]:
return self._buffer
@property
def row_indices(self) -> np.ndarray:
"""
row indices that are used to chunk the big data array
into individual Textures on the GPU
"""
return self._row_indices
@property
def col_indices(self) -> np.ndarray:
"""
column indices that are used to chunk the big data array
into individual Textures on the GPU
"""
return self._col_indices
def _fix_data(self, data):
if data.ndim not in (2, 3):
raise ValueError(
"image data must be 2D with or without an RGB(A) dimension, i.e. "
"it must be of shape [rows, cols], [rows, cols, 3] or [rows, cols, 4]"
)
# let's just cast to float32 always
return data.astype(np.float32)
def __iter__(self):
self._iter = product(enumerate(self.row_indices), enumerate(self.col_indices))
return self
def __next__(self) -> tuple[pygfx.Texture, tuple[int, int], tuple[slice, slice]]:
"""
Iterate through each Texture within the texture array
Returns
-------
Texture, tuple[int, int], tuple[slice, slice]
| Texture: pygfx.Texture
| tuple[int, int]: chunk index, i.e corresponding index of ``self.buffer`` array
| tuple[slice, slice]: data slice of big array in this chunk and Texture
"""
(chunk_row, data_row_start), (chunk_col, data_col_start) = next(self._iter)
# indices for to self.buffer for this chunk
chunk_index = (chunk_row, chunk_col)
# stop indices of big data array for this chunk
row_stop = min(self.value.shape[0], data_row_start + self._texture_limit_2d)
col_stop = min(self.value.shape[1], data_col_start + self._texture_limit_2d)
# row and column slices that slice the data for this chunk from the big data array
data_slice = (slice(data_row_start, row_stop), slice(data_col_start, col_stop))
# texture for this chunk
texture = self.buffer[chunk_index]
return texture, chunk_index, data_slice
def __getitem__(self, item):
return self.value[item]
@block_reentrance
def __setitem__(self, key, value):
self.value[key] = value
for texture in self.buffer.ravel():
texture.update_range((0, 0, 0), texture.size)
event = GraphicFeatureEvent(
self._property_name, info={"key": key, "value": value}
)
self._call_event_handlers(event)
def __len__(self):
return self.buffer.size
class ImageVmin(GraphicFeature):
"""lower contrast limit"""
event_info_spec = [
{
"dict key": "value",
"type": "float",
"description": "new vmin value",
},
]
def __init__(self, value: float, property_name: str = "vmin"):
self._value = value
super().__init__(property_name=property_name)
@property
def value(self) -> float:
return self._value
@block_reentrance
def set_value(self, graphic, value: float):
vmax = graphic._material.clim[1]
graphic._material.clim = (value, vmax)
self._value = value
event = GraphicFeatureEvent(type=self._property_name, info={"value": value})
self._call_event_handlers(event)
class ImageVmax(GraphicFeature):
"""upper contrast limit"""
event_info_spec = [
{
"dict key": "value",
"type": "float",
"description": "new vmax value",
},
]
def __init__(self, value: float, property_name: str = "vmax"):
self._value = value
super().__init__(property_name=property_name)
@property
def value(self) -> float:
return self._value
@block_reentrance
def set_value(self, graphic, value: float):
vmin = graphic._material.clim[0]
graphic._material.clim = (vmin, value)
self._value = value
event = GraphicFeatureEvent(type=self._property_name, info={"value": value})
self._call_event_handlers(event)
class ImageCmap(GraphicFeature):
"""colormap for texture"""
event_info_spec = [
{
"dict key": "value",
"type": "str",
"description": "new cmap name",
},
]
def __init__(self, value: str, property_name: str = "cmap"):
self._value = value
self.texture = get_cmap_texture(value)
super().__init__(property_name=property_name)
@property
def value(self) -> str:
return self._value
@block_reentrance
def set_value(self, graphic, value: str):
new_colors = make_colors(256, value)
graphic._material.map.texture.data[:] = new_colors
graphic._material.map.texture.update_range((0, 0, 0), size=(256, 1, 1))
self._value = value
event = GraphicFeatureEvent(type=self._property_name, info={"value": value})
self._call_event_handlers(event)
class ImageInterpolation(GraphicFeature):
"""Image interpolation method"""
event_info_spec = [
{
"dict key": "value",
"type": "str",
"description": "new interpolation method, nearest | linear",
},
]
def __init__(self, value: str, property_name: str = "interpolation"):
self._validate(value)
self._value = value
super().__init__(property_name=property_name)
def _validate(self, value):
if value not in ["nearest", "linear"]:
raise ValueError("`interpolation` must be one of 'nearest' or 'linear'")
@property
def value(self) -> str:
return self._value
@block_reentrance
def set_value(self, graphic, value: str):
self._validate(value)
graphic._material.interpolation = value
self._value = value
event = GraphicFeatureEvent(type="interpolation", info={"value": value})
self._call_event_handlers(event)
class ImageCmapInterpolation(GraphicFeature):
"""Image cmap interpolation method"""
event_info_spec = [
{
"dict key": "value",
"type": "str",
"description": "new cmap interpolatio method, nearest | linear",
},
]
def __init__(self, value: str, property_name: str = "cmap_interpolation"):
self._validate(value)
self._value = value
super().__init__(property_name=property_name)
def _validate(self, value):
if value not in ["nearest", "linear"]:
raise ValueError(
"`cmap_interpolation` must be one of 'nearest' or 'linear'"
)
@property
def value(self) -> str:
return self._value
@block_reentrance
def set_value(self, graphic, value: str):
self._validate(value)
# common material for all image tiles
graphic._material.map.min_filter = value
graphic._material.map.mag_filter = value
self._value = value
event = GraphicFeatureEvent(type=self._property_name, info={"value": value})
self._call_event_handlers(event)