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([[155, 127, 164, ..., 108, 247, 185],
[248, 148, 187, ..., 113, 50, 103],
[224, 212, 133, ..., 169, 114, 71],
...,
[127, 77, 12, ..., 125, 243, 18],
[158, 74, 239, ..., 225, 146, 121],
[174, 97, 120, ..., 143, 70, 68]], dtype=uint8)
In [2]: images[-5] # fifth from the end
Out[2]:
Frame([[146, 177, 85, ..., 226, 125, 180],
[129, 61, 4, ..., 40, 43, 168],
[132, 228, 212, ..., 26, 161, 61],
...,
[ 53, 169, 69, ..., 141, 35, 16],
[ 75, 183, 193, ..., 115, 5, 115],
[152, 153, 216, ..., 227, 72, 83]], 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.