Slicing and Iteration

PIMS objects are like lists or numpy arrays that lazily load and “stream” data like Python generators. Unlike Python generators, they can be sliced and indexed, and they have a length. But unlike lists or arrays, the underlying data is only accessed one element at a time.

Accessing Individual Images

Images can be randomly accessed with standard Python slicing syntax. The built-in PIMS readers all enable random access, even if the underlying file format does not support it natively, as with video files.

In [1]: images[0]  # first image
Out[1]: 
Frame([[ 39,  25, 187, ..., 127, 172,  74],
       [200, 154,  23, ...,  55, 183, 202],
       [ 44, 114, 137, ..., 153,  37, 217],
       ...,
       [ 12, 152, 198, ...,  69, 113,  65],
       [218, 116, 148, ..., 131, 248, 149],
       [200,  36, 211, ..., 168, 211, 248]], dtype=uint8)

In [2]: images[-5]  # fifth from the end
Out[2]: 
Frame([[ 20, 146,  18, ...,  73, 131,  74],
       [241,  71,  87, ..., 178,  44, 212],
       [ 95, 215, 162, ..., 173,  59, 238],
       ...,
       [108,  20,  14, ..., 217, 124, 202],
       [209,  61,  37, ...,  87,  29, 171],
       [183, 187, 205, ..., 181, 152, 104]], dtype=uint8)

Iteration

The images are iterable. Data is loaded one image at a time, conserving memory.

In [3]: import numpy as np

In [4]: for image in images:
   ...:     np.sum(image)  # do something
   ...: 

Slices – and Slices of Slices

Slicing images returns another lazy-loading object that is also iterable and sliceable.

In [5]: subsection = images[:5]  # the first five images

In [6]: len(images)
Out[6]: 9

In [7]: len(subsection)
Out[7]: 5

In [8]: for image in subsection:
   ...:     np.sum(image)  # do something
   ...: 

In [9]: subsubsection = subsection[::2]  # every other of the first five images

You can creates slices of slices of slices to any depth.

Fancy Indexing

Numpy-like “fancy indexing” is supported. As above, the examples below create more sliceable, iterable objects.

In [10]: subsection2 = images[[0, 3, 7]]

In [11]: mask = [True, False, False, False, False, True, False, False, False, False]

In [12]: subsection3 = images[mask]

Slicing in Space

It’s easy to make a sequence with all images cropped using the pims.process.crop pipeline, or to make a sequence with any sort of slicing by creating a new pipeline. See the doc:pipelines documentation for details.