pulse2percept.stimuli.images
ImageStimulus,
LogoBVL,
LogoUCSB,
SnellenChart
Classes
|
A stimulus made from an image, where each pixel gets assigned to an electrode, and grayscale values in the range [0, 255] get converted to activation values in the range [0, 1]. |
|
Bionic Vision Lab (BVL) logo |
|
UCSB logo |
|
Snellen chart |
- class pulse2percept.stimuli.images.ImageStimulus(source, resize=None, as_gray=False, electrodes=None, metadata=None, compress=False)[source]
A stimulus made from an image, where each pixel gets assigned to an electrode, and grayscale values in the range [0, 255] get converted to activation values in the range [0, 1].
See also
Basic Concepts > Electrical Stimuli <topics-stimuli>
Added in version 0.7.
- Parameters:
source (str) – Path to image file. Supported image types include JPG, PNG, and TIF; and are inferred from the file ending. Use
VideoStimulusfor GIFs.resize ((height, width) or None, optional) – Shape of the resized image. If one of the dimensions is set to -1, its value will be inferred by keeping a constant aspect ratio.
as_gray (bool, optional) – Flag whether to convert the image to grayscale. A four-channel image is interpreted as RGBA (e.g., a PNG), and the alpha channel will be blended with the color black.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image: a letter for the row, a number for the column, and a suffix for the color channel (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the (resized) image.
metadata (dict, optional) – Additional stimulus metadata can be stored in a dictionary.
compress (bool, optional) – If True, will remove pixels with 0 grayscale value.
- apply(func, *args, electrodes=None, **kwargs)[source]
Apply a function to the image
Changed in version 0.10.0:
funcmay now change the shape of the image, andelectrodescan name the result.- Parameters:
func (function) – The function to apply to the image. Must accept a 2D or 3D image and return a 2D or 3D image. The returned image need not have the same shape as the original; see
electrodes.args (*) – Additional positional arguments passed to the function
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, the original names are carried over whenever
funcleaves the shape of the image alone, and the result is named after its place in the new image otherwise (e.g. forskimage.transform.resize). SeeElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the returned image.
**kwargs – Additional keyword arguments passed to the function
- Returns:
stim – A copy of the stimulus object with the new image
- Return type:
ImageStimulus
- invert()[source]
Invert the gray levels of the image
- Returns:
stim – A copy of the stimulus object with all grayscale values inverted in the range [0, 1].
- Return type:
ImageStimulus
- rgb2gray(electrodes=None)[source]
Convert the image to grayscale
- Parameters:
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
- Returns:
stim – A copy of the stimulus object with all RGB values converted to grayscale in the range [0, 1].
- Return type:
ImageStimulus
Notes
A four-channel image is interpreted as RGBA (e.g., a PNG), and the alpha channel will be blended with the color black.
- resize(shape, electrodes=None, **kwargs)[source]
Resize the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
shape ((rows, cols)) – Shape of the resized image
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
**kwargs – Additional keyword arguments passed to skimage.transform.resize, such as
order=0for nearest-neighbor interpolation (which keeps a binary image binary).
- Returns:
stim – A copy of the stimulus object containing the resized image
- Return type:
ImageStimulus
- crop(idx_rect=None, left=0, right=0, top=0, bottom=0, electrodes=None)[source]
Crop the image
This method maps a rectangle (defined by two corners) from the image to a rectangle of the given size. Alternatively, this method can be used to crop a number of columns either from the left or the right of the image, or a number of rows either from the top or the bottom.
Added in version 0.8.
- Parameters:
idx_rect (4-tuple (y0, x0, y1, x1)) – Image indices of the top-left corner
[y0, x0]and bottom-right corner[y1, x1](exclusive) of the rectangle to crop.left (int) – Number of columns to crop from the left
right (int) – Number of columns to crop from the right
top (int) – Number of rows to crop from the top
bottom (int) – Number of rows to crop from the bottom
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the cropped image.
- Returns:
stim – A copy of the stimulus object containing the cropped image
- Return type:
ImageStimulus
- trim(tol=0, electrodes=None)[source]
Remove any black border around the image
Added in version 0.7.
- Parameters:
tol (float) – Any pixels with gray levels > tol will be trimmed.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the trimmed image.
- Returns:
stim – A copy of the stimulus object with trimmed borders.
- Return type:
ImageStimulus
- threshold(thresh, **kwargs)[source]
Threshold the image
- Parameters:
If a float in [0,1] is provided, pixels whose grayscale value is above said threshold will be white, others black.
A number of additional methods are supported:
’mean’: Threshold image based on the mean of grayscale values.
- ’minimum’: Threshold image based on the minimum method, where
the histogram of the input image is computed and smoothed until there are only two maxima.
- ’local’: Threshold image based on `local pixel neighborhood`_.
Requires
block_size: odd number of pixels in the neighborhood.
’otsu’: `Otsu's method`_
- ’isodata’: `ISODATA method`_, also known as the Ridler-Calvard
method or intermeans.
neighborhood (.. _local pixel)
method (.. _ISODATA)
method
- Returns:
stim – A copy of the stimulus object with two gray levels 0.0 and 1.0
- Return type:
ImageStimulus
- rotate(angle, mode='constant', electrodes=None, **kwargs)[source]
Rotate the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
angle (float) – Angle by which to rotate the image (degrees). Positive: counter-clockwise, negative: clockwise
mode (str, optional) – How to fill in the corners the rotation leaves empty; see skimage.transform.rotate.
electrodes (int, string or list thereof; optional) – Optionally, you can provide your own electrode names. If none are given, each pixel keeps the name it had before the rotation, unless
resize=Truegrew the canvas, in which case the enlarged image is named after its own pixel grid. SeeElectrodeNames.**kwargs – Additional keyword arguments passed to skimage.transform.rotate, such as
order,cval, orresize=Trueto grow the image so that it contains every rotated pixel.
- Returns:
stim – A copy of the stimulus object containing the rotated image
- Return type:
ImageStimulus
- shift(shift_cols, shift_rows)[source]
Shift the image foreground
This function shifts the center of mass (CoM) of the image by the specified number of rows and columns.
- Parameters:
- Returns:
stim – A copy of the stimulus object containing the shifted image
- Return type:
ImageStimulus
- center(loc=None)[source]
Center the image foreground
This function shifts the center of mass (CoM) to the image center.
- Parameters:
loc ((col, row), optional) – The pixel location at which to center the CoM. By default, shifts the CoM to the image center.
- Returns:
stim – A copy of the stimulus object containing the centered image
- Return type:
ImageStimulus
- scale(scaling_factor)[source]
Scale the image foreground
This function scales the image foreground (excluding black pixels) by a factor.
- Parameters:
scaling_factor (float) – Factory by which to scale the image
- Returns:
stim – A copy of the stimulus object containing the scaled image
- Return type:
ImageStimulus
- filter(filt, **kwargs)[source]
Filter the image
- Parameters:
filt (str) –
Image filter. Additional parameters can be passed as keyword arguments. The following filters are supported:
’sobel’: Edge filter the image using the `Sobel filter`_.
’scharr’: Edge filter the image using the `Scharr filter`_.
’canny’: Edge filter the image using the `Canny algorithm`_. You can also specify
sigma,low_threshold,high_threshold,mask, anduse_quantiles.’median’: Return local median of the image.
**kwargs – Additional parameters passed to the filter
filter (.. _Scharr)
filter
algorithm (.. _Canny)
- Returns:
stim – A copy of the stimulus object with the filtered image
- Return type:
ImageStimulus
- encode(amp_range=(0, 50), freq=20, implant=None, **kwargs)[source]
Encode the image using amplitude modulation
Encodes the image as a train of biphasic pulses, where the gray level of a pixel sets the amplitude of its pulses.
This is a shorthand for
AmplitudeEncoder; use that directly for the full set of options.Changed in version 0.10.0: Gray levels now map onto
amp_rangeabsolutely rather than being stretched to fill it (passstretch=Truefor the old behavior), the image receives a pulse train rather than a single pulse, andimplantencodes at electrode rather than pixel resolution.- Parameters:
amp_range ((min_amp, max_amp), optional) – Range of pulse amplitudes (uA). A gray level of 0 maps onto
min_amp, a gray level of 1 ontomax_amp.freq (float, optional) – Pulse train frequency (Hz). The image is treated as a single frame lasting 500 ms unless
frame_dursays otherwise.implant (
ProsthesisSystem, optional) – If given, the image is first sampled at the implant’s electrode locations, so that the pulse trains are built at electrode rather than pixel resolution.**kwargs – Additional arguments passed to
AmplitudeEncoder.
- Returns:
stim – Encoded stimulus
- Return type:
- plot(ax=None, **kwargs)[source]
Plot the stimulus
- Parameters:
ax (matplotlib.axes.Axes or list thereof; optional, default: None) – A Matplotlib Axes object or a list thereof (one per electrode to plot). If None, a new Axes object will be created.
- Returns:
ax – Returns the axes with the plot on it
- Return type:
matplotlib.axes.Axes
- save(fname, vmin=0, vmax=None)[source]
Save the stimulus as an image
- Parameters:
fname (str) – The name of the image file to be created. Image type will be inferred from the file extension.
- append(other)[source]
Append another stimulus
This method appends another stimulus (with matching electrodes) in time. The combined stimulus duration will be the sum of the two individual stimuli.
Added in version 0.7.
- property data
Stimulus data container A 2-D NumPy array that contains the stimulus data, where the rows denote electrodes and the columns denote points in time.
- property dt
Sampling time step (ms)
Defines the duration of the signal edge transitions.
Added in version 0.7.
- property duration
Stimulus duration (ms)
- property electrodes
Electrode names A list of electrode names, corresponding to the rows in the data container.
- property is_charge_balanced
Flag indicating whether the stimulus is charge-balanced
A stimulus with a time component is considered charge-balanced if its net current is smaller than 10 pico Amps. For the whole stimulus to be charge-balanced, every electrode must be charge-balanced as well.
Returns None if the stimulus is not a current at all: the gray levels of an
ImageStimulusintegrate to a number like any others, but that number is not a charge and asking whether it is zero answers nothing. Note that this is “not applicable”, not “unbalanced” – it issafe_modethat turns the question into an error, since a safety system genuinely cannot do its job on a stimulus that is not electrical.Changed in version 0.10.0: Returns None for a stimulus that is not measured in units of current (was: integrated the values anyway).
- property is_compressed
Flag indicating whether the stimulus has been compressed
Read-only: the flag is maintained by
compress. Assigning to it raises anAttributeError.
- property quantity
The stimulus data, with its unit attached
Added in version 0.10.0.
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA >>> Stimulus([500, 1000] * uA).quantity [[ 500.] [1000.]] uA
- remove(electrodes)[source]
Remove electrode(s)
Removes the stimulus of a certain electrode or list of electrodes.
Added in version 0.8.
- property shape
Data container shape
- property time
Time steps A list of time steps, corresponding to the columns in the data container.
- property time_quantity
The stimulus time axis with its unit attached, or None
Added in version 0.10.0.
- property time_unit
The unit
timeis expressed in (milliseconds)Added in version 0.10.0.
- times(unit=None)[source]
The stimulus time axis, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the time axis in. If None,timeis returned as it is stored (milliseconds).- Returns:
times – An ordinary NumPy array, or None if the stimulus has no time component.
- Return type:
np.ndarray or None
- property unit
The unit
datais expressed inMicroamps for an electrical stimulus, dimensionless for the gray levels of an
ImageStimulusorVideoStimulus.Read-only. The canonical storage unit is fixed so that models, safety checks and Cython kernels can rely on it; ask for another unit with
values().Added in version 0.10.0.
- values(unit=None)[source]
The stimulus data, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the data in. Must be compatible withunit. If None, the stimulus’ own unit is used anddatais returned as it is stored.- Returns:
values – An ordinary NumPy array, never a
Quantity. This is the boundary a numerical implementation should take its data across.- Return type:
np.ndarray
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA, mA >>> Stimulus([500, 1000] * uA).values(mA) array([[0.5], [1. ]], dtype=float32)
- class pulse2percept.stimuli.images.SnellenChart(resize=None, show_annotations=True, row=None, electrodes=None, metadata=None)[source]
Snellen chart
Load the 1348x840 Snellen chart commonly used to measure visual acuity.
Added in version 0.7.
- Parameters:
resize ((height, width) or None, optional) – A tuple specifying the desired height and the width of the image stimulus.
show_annotations ({True, False}, optional) – If True, show the full Snellen chart including annotations of the rows and corresponding acuity measures.
row (None, optional) – Select a single row (between 1 and 11) from the Snellen chart. For example, row 1 corresponds to 20/200, row 2 to 20/100.
electrodes (int, string or list thereof; optional, default: None) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image: a letter for the row, a number for the column, and a suffix for the color channel (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the (resized) image.
metadata (dict, optional, default: None) – Additional stimulus metadata can be stored in a dictionary.
- append(other)[source]
Append another stimulus
This method appends another stimulus (with matching electrodes) in time. The combined stimulus duration will be the sum of the two individual stimuli.
Added in version 0.7.
- apply(func, *args, electrodes=None, **kwargs)[source]
Apply a function to the image
Changed in version 0.10.0:
funcmay now change the shape of the image, andelectrodescan name the result.- Parameters:
func (function) – The function to apply to the image. Must accept a 2D or 3D image and return a 2D or 3D image. The returned image need not have the same shape as the original; see
electrodes.args (*) – Additional positional arguments passed to the function
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, the original names are carried over whenever
funcleaves the shape of the image alone, and the result is named after its place in the new image otherwise (e.g. forskimage.transform.resize). SeeElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the returned image.
**kwargs – Additional keyword arguments passed to the function
- Returns:
stim – A copy of the stimulus object with the new image
- Return type:
ImageStimulus
- center(loc=None)[source]
Center the image foreground
This function shifts the center of mass (CoM) to the image center.
- Parameters:
loc ((col, row), optional) – The pixel location at which to center the CoM. By default, shifts the CoM to the image center.
- Returns:
stim – A copy of the stimulus object containing the centered image
- Return type:
ImageStimulus
- crop(idx_rect=None, left=0, right=0, top=0, bottom=0, electrodes=None)[source]
Crop the image
This method maps a rectangle (defined by two corners) from the image to a rectangle of the given size. Alternatively, this method can be used to crop a number of columns either from the left or the right of the image, or a number of rows either from the top or the bottom.
Added in version 0.8.
- Parameters:
idx_rect (4-tuple (y0, x0, y1, x1)) – Image indices of the top-left corner
[y0, x0]and bottom-right corner[y1, x1](exclusive) of the rectangle to crop.left (int) – Number of columns to crop from the left
right (int) – Number of columns to crop from the right
top (int) – Number of rows to crop from the top
bottom (int) – Number of rows to crop from the bottom
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the cropped image.
- Returns:
stim – A copy of the stimulus object containing the cropped image
- Return type:
ImageStimulus
- property data
Stimulus data container A 2-D NumPy array that contains the stimulus data, where the rows denote electrodes and the columns denote points in time.
- property dt
Sampling time step (ms)
Defines the duration of the signal edge transitions.
Added in version 0.7.
- property duration
Stimulus duration (ms)
- property electrodes
Electrode names A list of electrode names, corresponding to the rows in the data container.
- encode(amp_range=(0, 50), freq=20, implant=None, **kwargs)[source]
Encode the image using amplitude modulation
Encodes the image as a train of biphasic pulses, where the gray level of a pixel sets the amplitude of its pulses.
This is a shorthand for
AmplitudeEncoder; use that directly for the full set of options.Changed in version 0.10.0: Gray levels now map onto
amp_rangeabsolutely rather than being stretched to fill it (passstretch=Truefor the old behavior), the image receives a pulse train rather than a single pulse, andimplantencodes at electrode rather than pixel resolution.- Parameters:
amp_range ((min_amp, max_amp), optional) – Range of pulse amplitudes (uA). A gray level of 0 maps onto
min_amp, a gray level of 1 ontomax_amp.freq (float, optional) – Pulse train frequency (Hz). The image is treated as a single frame lasting 500 ms unless
frame_dursays otherwise.implant (
ProsthesisSystem, optional) – If given, the image is first sampled at the implant’s electrode locations, so that the pulse trains are built at electrode rather than pixel resolution.**kwargs – Additional arguments passed to
AmplitudeEncoder.
- Returns:
stim – Encoded stimulus
- Return type:
- filter(filt, **kwargs)[source]
Filter the image
- Parameters:
filt (str) –
Image filter. Additional parameters can be passed as keyword arguments. The following filters are supported:
’sobel’: Edge filter the image using the `Sobel filter`_.
’scharr’: Edge filter the image using the `Scharr filter`_.
’canny’: Edge filter the image using the `Canny algorithm`_. You can also specify
sigma,low_threshold,high_threshold,mask, anduse_quantiles.’median’: Return local median of the image.
**kwargs – Additional parameters passed to the filter
filter (.. _Scharr)
filter
algorithm (.. _Canny)
- Returns:
stim – A copy of the stimulus object with the filtered image
- Return type:
ImageStimulus
- invert()[source]
Invert the gray levels of the image
- Returns:
stim – A copy of the stimulus object with all grayscale values inverted in the range [0, 1].
- Return type:
ImageStimulus
- property is_charge_balanced
Flag indicating whether the stimulus is charge-balanced
A stimulus with a time component is considered charge-balanced if its net current is smaller than 10 pico Amps. For the whole stimulus to be charge-balanced, every electrode must be charge-balanced as well.
Returns None if the stimulus is not a current at all: the gray levels of an
ImageStimulusintegrate to a number like any others, but that number is not a charge and asking whether it is zero answers nothing. Note that this is “not applicable”, not “unbalanced” – it issafe_modethat turns the question into an error, since a safety system genuinely cannot do its job on a stimulus that is not electrical.Changed in version 0.10.0: Returns None for a stimulus that is not measured in units of current (was: integrated the values anyway).
- property is_compressed
Flag indicating whether the stimulus has been compressed
Read-only: the flag is maintained by
compress. Assigning to it raises anAttributeError.
- plot(ax=None, **kwargs)[source]
Plot the stimulus
- Parameters:
ax (matplotlib.axes.Axes or list thereof; optional, default: None) – A Matplotlib Axes object or a list thereof (one per electrode to plot). If None, a new Axes object will be created.
- Returns:
ax – Returns the axes with the plot on it
- Return type:
matplotlib.axes.Axes
- property quantity
The stimulus data, with its unit attached
Added in version 0.10.0.
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA >>> Stimulus([500, 1000] * uA).quantity [[ 500.] [1000.]] uA
- remove(electrodes)[source]
Remove electrode(s)
Removes the stimulus of a certain electrode or list of electrodes.
Added in version 0.8.
- resize(shape, electrodes=None, **kwargs)[source]
Resize the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
shape ((rows, cols)) – Shape of the resized image
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
**kwargs – Additional keyword arguments passed to skimage.transform.resize, such as
order=0for nearest-neighbor interpolation (which keeps a binary image binary).
- Returns:
stim – A copy of the stimulus object containing the resized image
- Return type:
ImageStimulus
- rgb2gray(electrodes=None)[source]
Convert the image to grayscale
- Parameters:
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
- Returns:
stim – A copy of the stimulus object with all RGB values converted to grayscale in the range [0, 1].
- Return type:
ImageStimulus
Notes
A four-channel image is interpreted as RGBA (e.g., a PNG), and the alpha channel will be blended with the color black.
- rotate(angle, mode='constant', electrodes=None, **kwargs)[source]
Rotate the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
angle (float) – Angle by which to rotate the image (degrees). Positive: counter-clockwise, negative: clockwise
mode (str, optional) – How to fill in the corners the rotation leaves empty; see skimage.transform.rotate.
electrodes (int, string or list thereof; optional) – Optionally, you can provide your own electrode names. If none are given, each pixel keeps the name it had before the rotation, unless
resize=Truegrew the canvas, in which case the enlarged image is named after its own pixel grid. SeeElectrodeNames.**kwargs – Additional keyword arguments passed to skimage.transform.rotate, such as
order,cval, orresize=Trueto grow the image so that it contains every rotated pixel.
- Returns:
stim – A copy of the stimulus object containing the rotated image
- Return type:
ImageStimulus
- save(fname, vmin=0, vmax=None)[source]
Save the stimulus as an image
- Parameters:
fname (str) – The name of the image file to be created. Image type will be inferred from the file extension.
- scale(scaling_factor)[source]
Scale the image foreground
This function scales the image foreground (excluding black pixels) by a factor.
- Parameters:
scaling_factor (float) – Factory by which to scale the image
- Returns:
stim – A copy of the stimulus object containing the scaled image
- Return type:
ImageStimulus
- property shape
Data container shape
- shift(shift_cols, shift_rows)[source]
Shift the image foreground
This function shifts the center of mass (CoM) of the image by the specified number of rows and columns.
- Parameters:
- Returns:
stim – A copy of the stimulus object containing the shifted image
- Return type:
ImageStimulus
- threshold(thresh, **kwargs)[source]
Threshold the image
- Parameters:
If a float in [0,1] is provided, pixels whose grayscale value is above said threshold will be white, others black.
A number of additional methods are supported:
’mean’: Threshold image based on the mean of grayscale values.
- ’minimum’: Threshold image based on the minimum method, where
the histogram of the input image is computed and smoothed until there are only two maxima.
- ’local’: Threshold image based on `local pixel neighborhood`_.
Requires
block_size: odd number of pixels in the neighborhood.
’otsu’: `Otsu's method`_
- ’isodata’: `ISODATA method`_, also known as the Ridler-Calvard
method or intermeans.
neighborhood (.. _local pixel)
method (.. _ISODATA)
method
- Returns:
stim – A copy of the stimulus object with two gray levels 0.0 and 1.0
- Return type:
ImageStimulus
- property time
Time steps A list of time steps, corresponding to the columns in the data container.
- property time_quantity
The stimulus time axis with its unit attached, or None
Added in version 0.10.0.
- property time_unit
The unit
timeis expressed in (milliseconds)Added in version 0.10.0.
- times(unit=None)[source]
The stimulus time axis, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the time axis in. If None,timeis returned as it is stored (milliseconds).- Returns:
times – An ordinary NumPy array, or None if the stimulus has no time component.
- Return type:
np.ndarray or None
- trim(tol=0, electrodes=None)[source]
Remove any black border around the image
Added in version 0.7.
- Parameters:
tol (float) – Any pixels with gray levels > tol will be trimmed.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the trimmed image.
- Returns:
stim – A copy of the stimulus object with trimmed borders.
- Return type:
ImageStimulus
- property unit
The unit
datais expressed inMicroamps for an electrical stimulus, dimensionless for the gray levels of an
ImageStimulusorVideoStimulus.Read-only. The canonical storage unit is fixed so that models, safety checks and Cython kernels can rely on it; ask for another unit with
values().Added in version 0.10.0.
- values(unit=None)[source]
The stimulus data, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the data in. Must be compatible withunit. If None, the stimulus’ own unit is used anddatais returned as it is stored.- Returns:
values – An ordinary NumPy array, never a
Quantity. This is the boundary a numerical implementation should take its data across.- Return type:
np.ndarray
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA, mA >>> Stimulus([500, 1000] * uA).values(mA) array([[0.5], [1. ]], dtype=float32)
- class pulse2percept.stimuli.images.LogoBVL(resize=None, electrodes=None, metadata=None, as_gray=False)[source]
Bionic Vision Lab (BVL) logo
Load the 576x720x4 Bionic Vision Lab (BVL) logo.
Added in version 0.7.
- Parameters:
resize ((height, width) or None, optional) – A tuple specifying the desired height and the width of the image stimulus.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image: a letter for the row, a number for the column, and a suffix for the color channel (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the (resized) image.
metadata (dict, optional) – Additional stimulus metadata can be stored in a dictionary.
- append(other)[source]
Append another stimulus
This method appends another stimulus (with matching electrodes) in time. The combined stimulus duration will be the sum of the two individual stimuli.
Added in version 0.7.
- apply(func, *args, electrodes=None, **kwargs)[source]
Apply a function to the image
Changed in version 0.10.0:
funcmay now change the shape of the image, andelectrodescan name the result.- Parameters:
func (function) – The function to apply to the image. Must accept a 2D or 3D image and return a 2D or 3D image. The returned image need not have the same shape as the original; see
electrodes.args (*) – Additional positional arguments passed to the function
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, the original names are carried over whenever
funcleaves the shape of the image alone, and the result is named after its place in the new image otherwise (e.g. forskimage.transform.resize). SeeElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the returned image.
**kwargs – Additional keyword arguments passed to the function
- Returns:
stim – A copy of the stimulus object with the new image
- Return type:
ImageStimulus
- center(loc=None)[source]
Center the image foreground
This function shifts the center of mass (CoM) to the image center.
- Parameters:
loc ((col, row), optional) – The pixel location at which to center the CoM. By default, shifts the CoM to the image center.
- Returns:
stim – A copy of the stimulus object containing the centered image
- Return type:
ImageStimulus
- crop(idx_rect=None, left=0, right=0, top=0, bottom=0, electrodes=None)[source]
Crop the image
This method maps a rectangle (defined by two corners) from the image to a rectangle of the given size. Alternatively, this method can be used to crop a number of columns either from the left or the right of the image, or a number of rows either from the top or the bottom.
Added in version 0.8.
- Parameters:
idx_rect (4-tuple (y0, x0, y1, x1)) – Image indices of the top-left corner
[y0, x0]and bottom-right corner[y1, x1](exclusive) of the rectangle to crop.left (int) – Number of columns to crop from the left
right (int) – Number of columns to crop from the right
top (int) – Number of rows to crop from the top
bottom (int) – Number of rows to crop from the bottom
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the cropped image.
- Returns:
stim – A copy of the stimulus object containing the cropped image
- Return type:
ImageStimulus
- property data
Stimulus data container A 2-D NumPy array that contains the stimulus data, where the rows denote electrodes and the columns denote points in time.
- property dt
Sampling time step (ms)
Defines the duration of the signal edge transitions.
Added in version 0.7.
- property duration
Stimulus duration (ms)
- property electrodes
Electrode names A list of electrode names, corresponding to the rows in the data container.
- encode(amp_range=(0, 50), freq=20, implant=None, **kwargs)[source]
Encode the image using amplitude modulation
Encodes the image as a train of biphasic pulses, where the gray level of a pixel sets the amplitude of its pulses.
This is a shorthand for
AmplitudeEncoder; use that directly for the full set of options.Changed in version 0.10.0: Gray levels now map onto
amp_rangeabsolutely rather than being stretched to fill it (passstretch=Truefor the old behavior), the image receives a pulse train rather than a single pulse, andimplantencodes at electrode rather than pixel resolution.- Parameters:
amp_range ((min_amp, max_amp), optional) – Range of pulse amplitudes (uA). A gray level of 0 maps onto
min_amp, a gray level of 1 ontomax_amp.freq (float, optional) – Pulse train frequency (Hz). The image is treated as a single frame lasting 500 ms unless
frame_dursays otherwise.implant (
ProsthesisSystem, optional) – If given, the image is first sampled at the implant’s electrode locations, so that the pulse trains are built at electrode rather than pixel resolution.**kwargs – Additional arguments passed to
AmplitudeEncoder.
- Returns:
stim – Encoded stimulus
- Return type:
- filter(filt, **kwargs)[source]
Filter the image
- Parameters:
filt (str) –
Image filter. Additional parameters can be passed as keyword arguments. The following filters are supported:
’sobel’: Edge filter the image using the `Sobel filter`_.
’scharr’: Edge filter the image using the `Scharr filter`_.
’canny’: Edge filter the image using the `Canny algorithm`_. You can also specify
sigma,low_threshold,high_threshold,mask, anduse_quantiles.’median’: Return local median of the image.
**kwargs – Additional parameters passed to the filter
filter (.. _Scharr)
filter
algorithm (.. _Canny)
- Returns:
stim – A copy of the stimulus object with the filtered image
- Return type:
ImageStimulus
- invert()[source]
Invert the gray levels of the image
- Returns:
stim – A copy of the stimulus object with all grayscale values inverted in the range [0, 1].
- Return type:
ImageStimulus
- property is_charge_balanced
Flag indicating whether the stimulus is charge-balanced
A stimulus with a time component is considered charge-balanced if its net current is smaller than 10 pico Amps. For the whole stimulus to be charge-balanced, every electrode must be charge-balanced as well.
Returns None if the stimulus is not a current at all: the gray levels of an
ImageStimulusintegrate to a number like any others, but that number is not a charge and asking whether it is zero answers nothing. Note that this is “not applicable”, not “unbalanced” – it issafe_modethat turns the question into an error, since a safety system genuinely cannot do its job on a stimulus that is not electrical.Changed in version 0.10.0: Returns None for a stimulus that is not measured in units of current (was: integrated the values anyway).
- property is_compressed
Flag indicating whether the stimulus has been compressed
Read-only: the flag is maintained by
compress. Assigning to it raises anAttributeError.
- plot(ax=None, **kwargs)[source]
Plot the stimulus
- Parameters:
ax (matplotlib.axes.Axes or list thereof; optional, default: None) – A Matplotlib Axes object or a list thereof (one per electrode to plot). If None, a new Axes object will be created.
- Returns:
ax – Returns the axes with the plot on it
- Return type:
matplotlib.axes.Axes
- property quantity
The stimulus data, with its unit attached
Added in version 0.10.0.
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA >>> Stimulus([500, 1000] * uA).quantity [[ 500.] [1000.]] uA
- remove(electrodes)[source]
Remove electrode(s)
Removes the stimulus of a certain electrode or list of electrodes.
Added in version 0.8.
- resize(shape, electrodes=None, **kwargs)[source]
Resize the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
shape ((rows, cols)) – Shape of the resized image
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
**kwargs – Additional keyword arguments passed to skimage.transform.resize, such as
order=0for nearest-neighbor interpolation (which keeps a binary image binary).
- Returns:
stim – A copy of the stimulus object containing the resized image
- Return type:
ImageStimulus
- rgb2gray(electrodes=None)[source]
Convert the image to grayscale
- Parameters:
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
- Returns:
stim – A copy of the stimulus object with all RGB values converted to grayscale in the range [0, 1].
- Return type:
ImageStimulus
Notes
A four-channel image is interpreted as RGBA (e.g., a PNG), and the alpha channel will be blended with the color black.
- rotate(angle, mode='constant', electrodes=None, **kwargs)[source]
Rotate the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
angle (float) – Angle by which to rotate the image (degrees). Positive: counter-clockwise, negative: clockwise
mode (str, optional) – How to fill in the corners the rotation leaves empty; see skimage.transform.rotate.
electrodes (int, string or list thereof; optional) – Optionally, you can provide your own electrode names. If none are given, each pixel keeps the name it had before the rotation, unless
resize=Truegrew the canvas, in which case the enlarged image is named after its own pixel grid. SeeElectrodeNames.**kwargs – Additional keyword arguments passed to skimage.transform.rotate, such as
order,cval, orresize=Trueto grow the image so that it contains every rotated pixel.
- Returns:
stim – A copy of the stimulus object containing the rotated image
- Return type:
ImageStimulus
- save(fname, vmin=0, vmax=None)[source]
Save the stimulus as an image
- Parameters:
fname (str) – The name of the image file to be created. Image type will be inferred from the file extension.
- scale(scaling_factor)[source]
Scale the image foreground
This function scales the image foreground (excluding black pixels) by a factor.
- Parameters:
scaling_factor (float) – Factory by which to scale the image
- Returns:
stim – A copy of the stimulus object containing the scaled image
- Return type:
ImageStimulus
- property shape
Data container shape
- shift(shift_cols, shift_rows)[source]
Shift the image foreground
This function shifts the center of mass (CoM) of the image by the specified number of rows and columns.
- Parameters:
- Returns:
stim – A copy of the stimulus object containing the shifted image
- Return type:
ImageStimulus
- threshold(thresh, **kwargs)[source]
Threshold the image
- Parameters:
If a float in [0,1] is provided, pixels whose grayscale value is above said threshold will be white, others black.
A number of additional methods are supported:
’mean’: Threshold image based on the mean of grayscale values.
- ’minimum’: Threshold image based on the minimum method, where
the histogram of the input image is computed and smoothed until there are only two maxima.
- ’local’: Threshold image based on `local pixel neighborhood`_.
Requires
block_size: odd number of pixels in the neighborhood.
’otsu’: `Otsu's method`_
- ’isodata’: `ISODATA method`_, also known as the Ridler-Calvard
method or intermeans.
neighborhood (.. _local pixel)
method (.. _ISODATA)
method
- Returns:
stim – A copy of the stimulus object with two gray levels 0.0 and 1.0
- Return type:
ImageStimulus
- property time
Time steps A list of time steps, corresponding to the columns in the data container.
- property time_quantity
The stimulus time axis with its unit attached, or None
Added in version 0.10.0.
- property time_unit
The unit
timeis expressed in (milliseconds)Added in version 0.10.0.
- times(unit=None)[source]
The stimulus time axis, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the time axis in. If None,timeis returned as it is stored (milliseconds).- Returns:
times – An ordinary NumPy array, or None if the stimulus has no time component.
- Return type:
np.ndarray or None
- trim(tol=0, electrodes=None)[source]
Remove any black border around the image
Added in version 0.7.
- Parameters:
tol (float) – Any pixels with gray levels > tol will be trimmed.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the trimmed image.
- Returns:
stim – A copy of the stimulus object with trimmed borders.
- Return type:
ImageStimulus
- property unit
The unit
datais expressed inMicroamps for an electrical stimulus, dimensionless for the gray levels of an
ImageStimulusorVideoStimulus.Read-only. The canonical storage unit is fixed so that models, safety checks and Cython kernels can rely on it; ask for another unit with
values().Added in version 0.10.0.
- values(unit=None)[source]
The stimulus data, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the data in. Must be compatible withunit. If None, the stimulus’ own unit is used anddatais returned as it is stored.- Returns:
values – An ordinary NumPy array, never a
Quantity. This is the boundary a numerical implementation should take its data across.- Return type:
np.ndarray
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA, mA >>> Stimulus([500, 1000] * uA).values(mA) array([[0.5], [1. ]], dtype=float32)
- class pulse2percept.stimuli.images.LogoUCSB(resize=None, electrodes=None, metadata=None)[source]
UCSB logo
Load a 324x727 white-on-black logo of the University of California, Santa Barbara.
Added in version 0.7.
- Parameters:
resize ((height, width) or None, optional) – A tuple specifying the desired height and the width of the image stimulus.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image: a letter for the row, a number for the column, and a suffix for the color channel (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the (resized) image.
metadata (dict, optional) – Additional stimulus metadata can be stored in a dictionary.
- append(other)[source]
Append another stimulus
This method appends another stimulus (with matching electrodes) in time. The combined stimulus duration will be the sum of the two individual stimuli.
Added in version 0.7.
- apply(func, *args, electrodes=None, **kwargs)[source]
Apply a function to the image
Changed in version 0.10.0:
funcmay now change the shape of the image, andelectrodescan name the result.- Parameters:
func (function) – The function to apply to the image. Must accept a 2D or 3D image and return a 2D or 3D image. The returned image need not have the same shape as the original; see
electrodes.args (*) – Additional positional arguments passed to the function
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, the original names are carried over whenever
funcleaves the shape of the image alone, and the result is named after its place in the new image otherwise (e.g. forskimage.transform.resize). SeeElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the returned image.
**kwargs – Additional keyword arguments passed to the function
- Returns:
stim – A copy of the stimulus object with the new image
- Return type:
ImageStimulus
- center(loc=None)[source]
Center the image foreground
This function shifts the center of mass (CoM) to the image center.
- Parameters:
loc ((col, row), optional) – The pixel location at which to center the CoM. By default, shifts the CoM to the image center.
- Returns:
stim – A copy of the stimulus object containing the centered image
- Return type:
ImageStimulus
- crop(idx_rect=None, left=0, right=0, top=0, bottom=0, electrodes=None)[source]
Crop the image
This method maps a rectangle (defined by two corners) from the image to a rectangle of the given size. Alternatively, this method can be used to crop a number of columns either from the left or the right of the image, or a number of rows either from the top or the bottom.
Added in version 0.8.
- Parameters:
idx_rect (4-tuple (y0, x0, y1, x1)) – Image indices of the top-left corner
[y0, x0]and bottom-right corner[y1, x1](exclusive) of the rectangle to crop.left (int) – Number of columns to crop from the left
right (int) – Number of columns to crop from the right
top (int) – Number of rows to crop from the top
bottom (int) – Number of rows to crop from the bottom
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the cropped image.
- Returns:
stim – A copy of the stimulus object containing the cropped image
- Return type:
ImageStimulus
- property data
Stimulus data container A 2-D NumPy array that contains the stimulus data, where the rows denote electrodes and the columns denote points in time.
- property dt
Sampling time step (ms)
Defines the duration of the signal edge transitions.
Added in version 0.7.
- property duration
Stimulus duration (ms)
- property electrodes
Electrode names A list of electrode names, corresponding to the rows in the data container.
- encode(amp_range=(0, 50), freq=20, implant=None, **kwargs)[source]
Encode the image using amplitude modulation
Encodes the image as a train of biphasic pulses, where the gray level of a pixel sets the amplitude of its pulses.
This is a shorthand for
AmplitudeEncoder; use that directly for the full set of options.Changed in version 0.10.0: Gray levels now map onto
amp_rangeabsolutely rather than being stretched to fill it (passstretch=Truefor the old behavior), the image receives a pulse train rather than a single pulse, andimplantencodes at electrode rather than pixel resolution.- Parameters:
amp_range ((min_amp, max_amp), optional) – Range of pulse amplitudes (uA). A gray level of 0 maps onto
min_amp, a gray level of 1 ontomax_amp.freq (float, optional) – Pulse train frequency (Hz). The image is treated as a single frame lasting 500 ms unless
frame_dursays otherwise.implant (
ProsthesisSystem, optional) – If given, the image is first sampled at the implant’s electrode locations, so that the pulse trains are built at electrode rather than pixel resolution.**kwargs – Additional arguments passed to
AmplitudeEncoder.
- Returns:
stim – Encoded stimulus
- Return type:
- filter(filt, **kwargs)[source]
Filter the image
- Parameters:
filt (str) –
Image filter. Additional parameters can be passed as keyword arguments. The following filters are supported:
’sobel’: Edge filter the image using the `Sobel filter`_.
’scharr’: Edge filter the image using the `Scharr filter`_.
’canny’: Edge filter the image using the `Canny algorithm`_. You can also specify
sigma,low_threshold,high_threshold,mask, anduse_quantiles.’median’: Return local median of the image.
**kwargs – Additional parameters passed to the filter
filter (.. _Scharr)
filter
algorithm (.. _Canny)
- Returns:
stim – A copy of the stimulus object with the filtered image
- Return type:
ImageStimulus
- invert()[source]
Invert the gray levels of the image
- Returns:
stim – A copy of the stimulus object with all grayscale values inverted in the range [0, 1].
- Return type:
ImageStimulus
- property is_charge_balanced
Flag indicating whether the stimulus is charge-balanced
A stimulus with a time component is considered charge-balanced if its net current is smaller than 10 pico Amps. For the whole stimulus to be charge-balanced, every electrode must be charge-balanced as well.
Returns None if the stimulus is not a current at all: the gray levels of an
ImageStimulusintegrate to a number like any others, but that number is not a charge and asking whether it is zero answers nothing. Note that this is “not applicable”, not “unbalanced” – it issafe_modethat turns the question into an error, since a safety system genuinely cannot do its job on a stimulus that is not electrical.Changed in version 0.10.0: Returns None for a stimulus that is not measured in units of current (was: integrated the values anyway).
- property is_compressed
Flag indicating whether the stimulus has been compressed
Read-only: the flag is maintained by
compress. Assigning to it raises anAttributeError.
- plot(ax=None, **kwargs)[source]
Plot the stimulus
- Parameters:
ax (matplotlib.axes.Axes or list thereof; optional, default: None) – A Matplotlib Axes object or a list thereof (one per electrode to plot). If None, a new Axes object will be created.
- Returns:
ax – Returns the axes with the plot on it
- Return type:
matplotlib.axes.Axes
- property quantity
The stimulus data, with its unit attached
Added in version 0.10.0.
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA >>> Stimulus([500, 1000] * uA).quantity [[ 500.] [1000.]] uA
- remove(electrodes)[source]
Remove electrode(s)
Removes the stimulus of a certain electrode or list of electrodes.
Added in version 0.8.
- resize(shape, electrodes=None, **kwargs)[source]
Resize the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
shape ((rows, cols)) – Shape of the resized image
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
**kwargs – Additional keyword arguments passed to skimage.transform.resize, such as
order=0for nearest-neighbor interpolation (which keeps a binary image binary).
- Returns:
stim – A copy of the stimulus object containing the resized image
- Return type:
ImageStimulus
- rgb2gray(electrodes=None)[source]
Convert the image to grayscale
- Parameters:
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the grayscale image.
- Returns:
stim – A copy of the stimulus object with all RGB values converted to grayscale in the range [0, 1].
- Return type:
ImageStimulus
Notes
A four-channel image is interpreted as RGBA (e.g., a PNG), and the alpha channel will be blended with the color black.
- rotate(angle, mode='constant', electrodes=None, **kwargs)[source]
Rotate the image
Changed in version 0.10.0: Keyword arguments are passed on to scikit-image.
- Parameters:
angle (float) – Angle by which to rotate the image (degrees). Positive: counter-clockwise, negative: clockwise
mode (str, optional) – How to fill in the corners the rotation leaves empty; see skimage.transform.rotate.
electrodes (int, string or list thereof; optional) – Optionally, you can provide your own electrode names. If none are given, each pixel keeps the name it had before the rotation, unless
resize=Truegrew the canvas, in which case the enlarged image is named after its own pixel grid. SeeElectrodeNames.**kwargs – Additional keyword arguments passed to skimage.transform.rotate, such as
order,cval, orresize=Trueto grow the image so that it contains every rotated pixel.
- Returns:
stim – A copy of the stimulus object containing the rotated image
- Return type:
ImageStimulus
- save(fname, vmin=0, vmax=None)[source]
Save the stimulus as an image
- Parameters:
fname (str) – The name of the image file to be created. Image type will be inferred from the file extension.
- scale(scaling_factor)[source]
Scale the image foreground
This function scales the image foreground (excluding black pixels) by a factor.
- Parameters:
scaling_factor (float) – Factory by which to scale the image
- Returns:
stim – A copy of the stimulus object containing the scaled image
- Return type:
ImageStimulus
- property shape
Data container shape
- shift(shift_cols, shift_rows)[source]
Shift the image foreground
This function shifts the center of mass (CoM) of the image by the specified number of rows and columns.
- Parameters:
- Returns:
stim – A copy of the stimulus object containing the shifted image
- Return type:
ImageStimulus
- threshold(thresh, **kwargs)[source]
Threshold the image
- Parameters:
If a float in [0,1] is provided, pixels whose grayscale value is above said threshold will be white, others black.
A number of additional methods are supported:
’mean’: Threshold image based on the mean of grayscale values.
- ’minimum’: Threshold image based on the minimum method, where
the histogram of the input image is computed and smoothed until there are only two maxima.
- ’local’: Threshold image based on `local pixel neighborhood`_.
Requires
block_size: odd number of pixels in the neighborhood.
’otsu’: `Otsu's method`_
- ’isodata’: `ISODATA method`_, also known as the Ridler-Calvard
method or intermeans.
neighborhood (.. _local pixel)
method (.. _ISODATA)
method
- Returns:
stim – A copy of the stimulus object with two gray levels 0.0 and 1.0
- Return type:
ImageStimulus
- property time
Time steps A list of time steps, corresponding to the columns in the data container.
- property time_quantity
The stimulus time axis with its unit attached, or None
Added in version 0.10.0.
- property time_unit
The unit
timeis expressed in (milliseconds)Added in version 0.10.0.
- times(unit=None)[source]
The stimulus time axis, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the time axis in. If None,timeis returned as it is stored (milliseconds).- Returns:
times – An ordinary NumPy array, or None if the stimulus has no time component.
- Return type:
np.ndarray or None
- trim(tol=0, electrodes=None)[source]
Remove any black border around the image
Added in version 0.7.
- Parameters:
tol (float) – Any pixels with gray levels > tol will be trimmed.
electrodes (int, string or list thereof; optional) –
Optionally, you can provide your own electrode names. If none are given, each pixel is named after its place in the image (e.g. ‘A1’, ‘C12’, ‘A1_R’). See
ElectrodeNames.Note
The number of electrode names provided must match the number of pixels in the trimmed image.
- Returns:
stim – A copy of the stimulus object with trimmed borders.
- Return type:
ImageStimulus
- property unit
The unit
datais expressed inMicroamps for an electrical stimulus, dimensionless for the gray levels of an
ImageStimulusorVideoStimulus.Read-only. The canonical storage unit is fixed so that models, safety checks and Cython kernels can rely on it; ask for another unit with
values().Added in version 0.10.0.
- values(unit=None)[source]
The stimulus data, expressed in
unitAdded in version 0.10.0.
- Parameters:
unit (
Unit, optional) – The unit to express the data in. Must be compatible withunit. If None, the stimulus’ own unit is used anddatais returned as it is stored.- Returns:
values – An ordinary NumPy array, never a
Quantity. This is the boundary a numerical implementation should take its data across.- Return type:
np.ndarray
Examples
>>> from pulse2percept.stimuli import Stimulus >>> from pulse2percept.units import uA, mA >>> Stimulus([500, 1000] * uA).values(mA) array([[0.5], [1. ]], dtype=float32)