Completed
Push — master ( 6d0d49...6d6a7d )
by Jasper
02:25 queued 57s
created

Camera.takeSnapshot()   B

Complexity

Conditions 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
c 2
b 0
f 0
dl 0
loc 27
rs 8.5806
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
        if not self.libs.hasDependency('pyplot'):
33
            return False
34
        plt = self.libs.pyplot
35
36
        try:
37
            ndims = len(data.shape)
38
            sliceOrder = [1, 0, 2]
39
            fig, axs = plt.subplots(nrows=1, ncols=ndims, figsize=(8, 3), dpi=100)
40
            for d in range(ndims):
41
                slicing = [slice(None)]*ndims
42
                slicing[sliceOrder[d]] = int(data.shape[d]/2)
43
                axs[d].matshow(data[slicing].T, origin='lower', 
44
                    cmap = plt.get_cmap('gray'), vmin = 0, vmax = data.max())
45
                axs[d].locator_params(nbins=3)
46
                axs[d].tick_params(axis='both', which='major', labelsize=8)
47
            plt.tight_layout()
48
            plt.savefig(on)
49
        except Exception as e:
50
            return False
51
        return True
52