1
|
|
|
from niprov.dependencies import Dependencies |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
class Camera(object): |
5
|
|
|
|
6
|
|
|
def __init__(self, dependencies): |
7
|
|
|
self.film = dependencies.getPictureCache() |
8
|
|
|
self.libs = dependencies.getLibraries() |
9
|
|
|
|
10
|
|
|
def saveSnapshot(self, data, for_): |
11
|
|
|
"""Plot an overview of the image and store it. |
12
|
|
|
|
13
|
|
|
Uses :class:`.PictureCache` as service that provides a file-like |
14
|
|
|
handle to save the plotted picture to. |
15
|
|
|
Calls takeSnapshot() to do the actual plotting. |
16
|
|
|
|
17
|
|
|
Args: |
18
|
|
|
data (numpy.ndarray): Array of 2, 3 or 4 dimensions with image data. |
19
|
|
|
""" |
20
|
|
|
newPicture = self.film.new() |
21
|
|
|
success = self.takeSnapshot(data, on=newPicture) |
22
|
|
|
if success: |
23
|
|
|
self.film.keep(newPicture, for_) |
24
|
|
|
|
25
|
|
|
def takeSnapshot(self, data, on): |
26
|
|
|
"""Plot an overview of the image using matplotlib.pyplot. |
27
|
|
|
|
28
|
|
|
Args: |
29
|
|
|
data (numpy.ndarray): Array of 2, 3 or 4 dimensions with image data. |
30
|
|
|
on (str or file-like object): Where to save figure to. |
31
|
|
|
""" |
32
|
|
|
tookSnapshot = False |
33
|
|
|
if not self.libs.hasDependency('pyplot'): |
34
|
|
|
return tookSnapshot |
35
|
|
|
plt = self.libs.pyplot |
36
|
|
|
interactiveModeWasOn = plt.isinteractive() |
37
|
|
|
if interactiveModeWasOn: |
38
|
|
|
# Turn off interactive mode since we don't want to open windows |
39
|
|
|
# while attempting to plot snapshots. |
40
|
|
|
plt.ioff() |
41
|
|
|
|
42
|
|
|
try: |
43
|
|
|
ndims = len(data.shape) |
44
|
|
|
sliceOrder = [1, 0, 2] |
45
|
|
|
fig, axs = plt.subplots(nrows=1, ncols=ndims, figsize=(8, 3), dpi=100) |
46
|
|
|
for d in range(ndims): |
47
|
|
|
slicing = [slice(None)]*ndims |
48
|
|
|
slicing[sliceOrder[d]] = int(data.shape[d]/2) |
49
|
|
|
axs[d].matshow(data[slicing].T, origin='lower', |
50
|
|
|
cmap = plt.get_cmap('gray'), vmin = 0, vmax = data.max()) |
51
|
|
|
axs[d].locator_params(nbins=3) |
52
|
|
|
axs[d].tick_params(axis='both', which='major', labelsize=8) |
53
|
|
|
plt.tight_layout() |
54
|
|
|
plt.savefig(on) |
55
|
|
|
tookSnapshot = True |
56
|
|
|
except Exception as e: |
57
|
|
|
pass |
58
|
|
|
finally: |
59
|
|
|
if interactiveModeWasOn: |
60
|
|
|
## Turn interactive mode back on. |
61
|
|
|
plt.ion() |
62
|
|
|
return tookSnapshot |
63
|
|
|
|