pulse2percept.stimuli.LogoUCSB
- class pulse2percept.stimuli.LogoUCSB(**kwargs)[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’).
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.
- __init__(**kwargs)[source]
Deprecated since version 0.11.0.
Class LogoUCSB is deprecated since version 0.11.0, and will be removed in version 0.12.0. Use
pulse2percept.stimuli.samples.logo_ucsbinstead.
Methods
__init__(**kwargs)append(other)Append another stimulus
apply(func, *args[, electrodes])Apply a function to the image
center([loc])Center the image foreground
compress()Compress the source data in place
crop([idx_rect, left, right, top, bottom, ...])Crop the image
Crop the image to the largest centered square
encode([amp_range, freq, implant])Encode the image using amplitude modulation
filter(filt, **kwargs)Filter the image
invert()Invert the gray levels of the image
pad(duration)Pad the stimulus with zeros up to a given time.
plot([ax])Plot the stimulus
remove(electrodes)Remove electrode(s)
resize(shape[, electrodes])Resize the image
rgb2gray([electrodes])Convert the image to grayscale
rotate(angle[, mode, electrodes])Rotate the image
save(fname[, vmin, vmax])Save the stimulus as an image
scale(scaling_factor)Scale the image foreground
shift(shift_cols, shift_rows)Shift the image foreground
threshold(thresh, **kwargs)Threshold the image
times([unit])The stimulus time axis, expressed in
unittrim([tol, electrodes])Remove any black border around the image
values([unit])The stimulus data, expressed in
unitAttributes
Stimulus data container
Sampling time step (duration of signal edge transitions)
Stimulus duration (ms)
Electrode names A list of electrode names, corresponding to the rows in the data container.
img_shapeFlag indicating whether the stimulus is charge-balanced
Flag indicating whether the stimulus has been compressed
metadataThe stimulus data, with its unit attached
Data container shape
A list of time steps (i.e., the columns in the data container)
The stimulus time axis with its unit attached, or None
The unit
timeis expressed inThe unit
datais expressed in- 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).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
- compress()[source]
Compress the source data in place
- 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’).
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
- crop_square()[source]
Crop the image to the largest centered square
The image is cropped without resizing. If its dimensions differ by an odd number of pixels, the extra pixel is removed from the bottom or right.
Added in version 0.11.0.
- Returns:
stim – A copy of the stimulus containing the centered square crop.
- Return type:
ImageStimulus
- property data
Stimulus data container
A read-only 2-D NumPy array that contains the sampled waveform, where the rows denote electrodes and the columns denote points in time.
- property dt
Sampling time step (duration of 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 (
Implant, 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
- 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.
Changed in version 0.10.0: Returns None for a stimulus that is not measured in units of current.
- property is_compressed
Flag indicating whether the stimulus has been compressed
- pad(duration)[source]
Pad the stimulus with zeros up to a given time.
Adds zero-valued endpoints at
t=0andt=durationas needed.durationspecifies the final time, not the amount of padding to add.Added in version 0.10.0.
- Parameters:
duration (float or
Quantity) – Final time of the padded stimulus. Bare values are interpreted in the stimulus’ time unit.- Returns:
padded – Padded copy of the stimulus.
- Return type:
Notes
Padding requires existing boundary values to be zero; otherwise interpolation would create a ramp. It never truncates the stimulus or removes negative time points.
- 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:
- 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’).
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’).
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 or Quantity) – 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.**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 or os.PathLike) –
The name of the image file to be created. Image type will be inferred from the file extension.
Changed in version 0.11.0: A
pathlib.Pathis accepted.
- 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.
- Returns:
stim – A copy of the stimulus object with two gray levels 0.0 and 1.0
- Return type:
ImageStimulus
- property time
A list of time steps (i.e., 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 inAdded 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’).
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 inAdded 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.- 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)