pyrtools.tools package
Submodules
pyrtools.tools.compare_matpyrtools module
- pyrtools.tools.compare_matpyrtools.comparePyr(matPyr, pyPyr, rtol=1e-05, atol=1e-08)[source]
compare two pyramids
returns True if they are the same with in desired precision and False if not.
written for unit testing code.
- pyrtools.tools.compare_matpyrtools.compareRecon(recon1, recon2, rtol=1e-05, atol=1e-10)[source]
compare two arrays
returns True is they are the same within specified precision and False if not. function was made to accompany unit test code.
This function is deprecated. Instead use the builtin numpy:
np.allclose(recon1, recon2, rtol=1e-05, atol=1e-08, equal_nan=False)
This will not tell you where the error is, but you can find that yourself
pyrtools.tools.convolutions module
- pyrtools.tools.convolutions.blur(image, n_levels=1, filt='binom5')[source]
blur an image by filtering-downsampling and then upsampling-filtering
Blur an image, by filtering and downsampling n_levels times (default=1), followed by upsampling and filtering n_levels times. The blurring is done with filter kernel specified by filt (default = ‘binom5’), which can be a string (to be passed to named_filter), a vector (applied separably as a 1D convolution kernel in X and Y), or a matrix (applied as a 2D convolution kernel). The downsampling is always by 2 in each direction.
This differs from blurDn in that here we upsample afterwards.
- Parameters:
image (array_like) – 1d or 2d image to blur
n_levels (int) – the number of times to filter and downsample. the higher this is, the more blurred the resulting image will be
filt ({array_like, ‘binomN’, ‘haar’, ‘qmf8’, ‘qmf12’, ‘qmf16’, ‘daub2’, ‘daub3’, ‘daub4’,) –
‘qmf5’, ‘qmf9’, ‘qmf13’} filter to use for filtering image. If array_like, can be 1d or 2d. All scaled so L-1 norm is 1.0
- Returns:
image – the blurred image
- Return type:
array_like
References
[1]J D Johnston, “A filter family designed for use in quadrature mirror filter banks”, Proc. ICASSP, pp 291-294, 1980.
[2]I Daubechies, “Orthonormal bases of compactly supported wavelets”, Commun. Pure Appl. Math, vol. 42, pp 909-996, 1988.
[3]E P Simoncelli, “Orthogonal sub-band image transforms”, PhD Thesis, MIT Dept. of Elec. Eng. and Comp. Sci. May 1988. Also available as: MIT Media Laboratory Vision and Modeling Technical Report #100.
[4]E P Simoncelli and E H Adelson, “Subband image coding”, Subband Transforms, chapter 4, ed. John W Woods, Kluwer Academic Publishers, Norwell, MA, 1990, pp 143–192.
- pyrtools.tools.convolutions.blurDn(image, n_levels=1, filt='binom5')[source]
blur and downsample an image
Blur and downsample an image. The blurring is done with filter kernel specified by FILT (default = ‘binom5’), which can be a string (to be passed to named_filter), a vector (applied separably as a 1D convolution kernel in X and Y), or a matrix (applied as a 2D convolution kernel). The downsampling is always by 2 in each direction.
The procedure is applied recursively n_levels times (default=1).
This differs from blur in that we do NOT upsample afterwards.
- Parameters:
image (array_like) – 1d or 2d image to blur and downsample
n_levels (int) – the number of times to filter and downsample. the higher this is, the blurrier and smaller the resulting image will be
filt ({array_like, ‘binomN’, ‘haar’, ‘qmf8’, ‘qmf12’, ‘qmf16’, ‘daub2’, ‘daub3’, ‘daub4’,) –
‘qmf5’, ‘qmf9’, ‘qmf13’} filter to use for filtering image. If array_like, can be 1d or 2d. All scaled so L-1 norm is 1.0
- Returns:
image – the blurred and downsampled image
- Return type:
array_like
References
[1]J D Johnston, “A filter family designed for use in quadrature mirror filter banks”, Proc. ICASSP, pp 291-294, 1980.
[2]I Daubechies, “Orthonormal bases of compactly supported wavelets”, Commun. Pure Appl. Math, vol. 42, pp 909-996, 1988.
[3]E P Simoncelli, “Orthogonal sub-band image transforms”, PhD Thesis, MIT Dept. of Elec. Eng. and Comp. Sci. May 1988. Also available as: MIT Media Laboratory Vision and Modeling Technical Report #100.
[4]E P Simoncelli and E H Adelson, “Subband image coding”, Subband Transforms, chapter 4, ed. John W Woods, Kluwer Academic Publishers, Norwell, MA, 1990, pp 143–192.
- pyrtools.tools.convolutions.image_gradient(image, edge_type='dont-compute')[source]
Compute the gradient of the image using smooth derivative filters
Compute the gradient of the image using smooth derivative filters optimized for accurate direction estimation. Coordinate system corresponds to standard pixel indexing: X axis points rightward. Y axis points downward. edges specify boundary handling.
Notes
original filters from Int’l Conf Image Processing, 1994. updated filters 10/2003: see Farid & Simoncelli, IEEE Trans Image
Processing, 13(4):496-508, April 2004.
- Parameters:
image (array_like) – 2d array to compute the gradients of
edge_type ({'circular', 'reflect1', 'reflect2', 'repeat', 'zero', 'extend', 'dont-compute'}) –
Specifies how to handle edges. Options are:
’circular’ - circular convolution
’reflect1’ - reflect about the edge pixels
’reflect2’ - reflect, doubling the edge pixels
’repeat’ - repeat the edge pixels
’zero’ - assume values of zero outside image boundary
’extend’ - reflect and invert
’dont-compute’ - zero output when filter overhangs imput boundaries.
- Returns:
dx, dy – the X derivative and the Y derivative
- Return type:
np.array
- pyrtools.tools.convolutions.rconv2(mtx1, mtx2, ctr=0)[source]
Convolution of two matrices, with boundaries handled via reflection about the edge pixels.
Result will be of size of LARGER matrix.
The origin of the smaller matrix is assumed to be its center. For even dimensions, the origin is determined by the CTR (optional) argument:
- CTR origin
0 DIM/2 (default) 1 (DIM/2)+1
In general, you should not use this function, since it will be slow. Instead, use upConv or corrDn, which use the C code and so are much faster.
- pyrtools.tools.convolutions.upBlur(image, n_levels=1, filt='binom5')[source]
upsample and blur an image.
Upsample and blur an image. The blurring is done with filter kernel specified by FILT (default = ‘binom5’), which can be a string (to be passed to named_filter), a vector (applied separably as a 1D convolution kernel in X and Y), or a matrix (applied as a 2D convolution kernel). The downsampling is always by 2 in each direction.
The procedure is applied recursively n_levels times (default=1).
- Parameters:
image (array_like) – 1d or 2d image to upsample and blur
n_levels (int) – the number of times to filter and downsample. the higher this is, the blurrier and larger the resulting image will be
filt ({array_like, ‘binomN’, ‘haar’, ‘qmf8’, ‘qmf12’, ‘qmf16’, ‘daub2’, ‘daub3’, ‘daub4’,) –
‘qmf5’, ‘qmf9’, ‘qmf13’} filter to use for filtering image. If array_like, can be 1d or 2d. All scaled so L-1 norm is 1.0
- Returns:
image – the upsampled and blurred image
- Return type:
array_like
References
[1]J D Johnston, “A filter family designed for use in quadrature mirror filter banks”, Proc. ICASSP, pp 291-294, 1980.
[2]I Daubechies, “Orthonormal bases of compactly supported wavelets”, Commun. Pure Appl. Math, vol. 42, pp 909-996, 1988.
[3]E P Simoncelli, “Orthogonal sub-band image transforms”, PhD Thesis, MIT Dept. of Elec. Eng. and Comp. Sci. May 1988. Also available as: MIT Media Laboratory Vision and Modeling Technical Report #100.
[4]E P Simoncelli and E H Adelson, “Subband image coding”, Subband Transforms, chapter 4, ed. John W Woods, Kluwer Academic Publishers, Norwell, MA, 1990, pp 143–192.
pyrtools.tools.display module
- class pyrtools.tools.display.PyrFigure(dpi=96, *args, **kwargs)[source]
Bases:
Figurecustom figure class to ensure that plots are created and saved with a constant dpi
NOTE: generally, you shouldn’t use this directly, relying instead on the make_figure function.
If you do want to use, do the following: fig = plt.figure(FigureClass=PyrFigure) (NOT fig = PyrFigure()) and analogously for other pyplot functions (plt.subplots, etc)
this enables us to make sure there’s no aliasing: a single value in the (image) array that we’re plotting will be represented as an integer multiple of pixels in the displayed figure
The dpi that’s chosen is an arbitrary value, the only thing that matters is that we use the same one when creating and saving the figure, which is what we ensure here. This also means that you will be unable to use plt.tight_layout, since we set the spacing and size of the subplots very intentionally.
- Attributes:
axesList of Axes in the Figure.
dpiThe resolution in dots per inch.
figureThe root Figure.
frameonReturn the figure’s background patch visibility, i.e.
mouseoverReturn whether this artist is queried for custom context information when the mouse cursor moves over it.
numberThe figure id, used to identify figures in .pyplot.
staleWhether the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.
sticky_edgesxandysticky edge lists for autoscaling.
Methods
add_artist(artist[, clip])Add an .Artist to the figure.
add_axes(*args, **kwargs)Add an ~.axes.Axes to the figure.
add_axobserver(func)Whenever the Axes state change,
func(self)will be called.add_callback(func)Add a callback function that will be called whenever one of the .Artist's properties changes.
add_gridspec([nrows, ncols])Low-level API for creating a .GridSpec that has this figure as a parent.
add_subfigure(subplotspec, **kwargs)Add a .SubFigure to the figure as part of a subplot arrangement.
add_subplot(*args, **kwargs)Add an ~.axes.Axes to the figure as part of a subplot arrangement.
align_labels([axs])Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set).
align_titles([axs])Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).
align_xlabels([axs])Align the xlabels of subplots in the same subplot row if label alignment is being done automatically (i.e. the label position is not manually set).
align_ylabels([axs])Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).
autofmt_xdate([bottom, rotation, ha, which])Date ticklabels often overlap, so it is useful to rotate them and right align them.
clear([keep_observers])Clear the figure.
clf([keep_observers])[Discouraged] Alias for the clear() method.
colorbar(mappable[, cax, ax, use_gridspec])Add a colorbar to a plot.
contains(mouseevent)Test whether the mouse event occurred on the figure.
convert_xunits(x)Convert x using the unit type of the xaxis.
convert_yunits(y)Convert y using the unit type of the yaxis.
delaxes(ax)Remove the ~.axes.Axes ax from the figure; update the current Axes.
draw(renderer)Draw the Artist (and its children) using the given renderer.
draw_artist(a)Draw .Artist a only.
draw_without_rendering()Draw the figure with no output.
figimage(X[, xo, yo, alpha, norm, cmap, ...])Add a non-resampled image to the figure.
findobj([match, include_self])Find artist objects.
format_cursor_data(data)Return a string representation of data.
gca()Get the current Axes.
get_agg_filter()Return filter function to be used for agg filter.
get_alpha()Return the alpha value used for blending - not supported on all backends.
get_animated()Return whether the artist is animated.
get_axes()List of Axes in the Figure.
get_children()Get a list of artists contained in the figure.
get_clip_box()Return the clipbox.
get_clip_on()Return whether the artist uses clipping.
get_clip_path()Return the clip path.
get_constrained_layout()Return whether constrained layout is being used.
get_constrained_layout_pads([relative])[Deprecated] Get padding for
constrained_layout.get_cursor_data(event)Return the cursor data for a given event.
get_default_bbox_extra_artists()Return a list of Artists typically used in .Figure.get_tightbbox.
get_dpi()Return the resolution in dots per inch as a float.
get_edgecolor()Get the edge color of the Figure rectangle.
get_facecolor()Get the face color of the Figure rectangle.
get_figheight()Return the figure height in inches.
get_figure([root])Return the .Figure or .SubFigure instance the (Sub)Figure belongs to.
get_figwidth()Return the figure width in inches.
get_frameon()Return the figure's background patch visibility, i.e. whether the figure background will be drawn.
get_gid()Return the group id.
get_in_layout()Return boolean flag,
Trueif artist is included in layout calculations.get_label()Return the label used for this artist in the legend.
get_linewidth()Get the line width of the Figure rectangle.
get_mouseover()Return whether this artist is queried for custom context information when the mouse cursor moves over it.
get_picker()Return the picking behavior of the artist.
get_rasterized()Return whether the artist is to be rasterized.
get_size_inches()Return the current size of the figure in inches.
get_sketch_params()Return the sketch parameters for the artist.
get_snap()Return the snap setting.
get_suptitle()Return the suptitle as string or an empty string if not set.
get_supxlabel()Return the supxlabel as string or an empty string if not set.
get_supylabel()Return the supylabel as string or an empty string if not set.
get_tight_layout()Return whether .Figure.tight_layout is called when drawing.
get_tightbbox([renderer, bbox_extra_artists])Return a (tight) bounding box of the figure in inches.
get_transform()Return the .Transform instance used by this artist.
get_transformed_clip_path_and_affine()Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_url()Return the url.
get_visible()Return the visibility.
get_window_extent([renderer])Get the artist's bounding box in display space.
get_zorder()Return the artist's zorder.
ginput([n, timeout, show_clicks, mouse_add, ...])Blocking call to interact with a figure.
have_units()Return whether units are set on any axis.
is_transform_set()Return whether the Artist has an explicitly set transform.
legend(*args, **kwargs)Place a legend on the figure.
pchanged()Call all of the registered callbacks.
pick(mouseevent)Process a pick event.
pickable()Return whether the artist is pickable.
properties()Return a dictionary of all the properties of the artist.
remove()Remove the artist from the figure if possible.
remove_callback(oid)Remove a callback based on its observer id.
savefig(fname[, dpi_multiple])Save the current figure.
sca(a)Set the current Axes to be a and return a.
set(*[, agg_filter, alpha, animated, ...])Set multiple properties at once.
set_agg_filter(filter_func)Set the agg filter.
set_alpha(alpha)Set the alpha value used for blending - not supported on all backends.
set_animated(b)Set whether the artist is intended to be used in an animation.
set_canvas(canvas)Set the canvas that contains the figure
set_clip_box(clipbox)Set the artist's clip .Bbox.
set_clip_on(b)Set whether the artist uses clipping.
set_clip_path(path[, transform])Set the artist's clip path.
set_constrained_layout(constrained)[Deprecated] Set whether
constrained_layoutis used upon drawing.set_constrained_layout_pads(**kwargs)[Deprecated] Set padding for
constrained_layout.set_dpi(val)Set the resolution of the figure in dots-per-inch.
set_edgecolor(color)Set the edge color of the Figure rectangle.
set_facecolor(color)Set the face color of the Figure rectangle.
set_figheight(val[, forward])Set the height of the figure in inches.
set_figure(fig)set_figwidth(val[, forward])Set the width of the figure in inches.
set_frameon(b)Set the figure's background patch visibility, i.e. whether the figure background will be drawn.
set_gid(gid)Set the (group) id for the artist.
set_in_layout(in_layout)Set if artist is to be included in layout calculations, E.g.
set_label(s)Set a label that will be displayed in the legend.
set_layout_engine([layout])Set the layout engine for this figure.
set_linewidth(linewidth)Set the line width of the Figure rectangle.
set_mouseover(mouseover)Set whether this artist is queried for custom context information when the mouse cursor moves over it.
set_path_effects(path_effects)Set the path effects.
set_picker(picker)Define the picking behavior of the artist.
set_rasterized(rasterized)Force rasterized (bitmap) drawing for vector graphics output.
set_size_inches(w[, h, forward])Set the figure size in inches.
set_sketch_params([scale, length, randomness])Set the sketch parameters.
set_snap(snap)Set the snapping behavior.
set_tight_layout(tight)[Deprecated] Set whether and how .Figure.tight_layout is called when drawing.
set_transform(t)Set the artist transform.
set_url(url)Set the url for the artist.
set_visible(b)Set the artist's visibility.
set_zorder(level)Set the zorder for the artist.
show([warn])If using a GUI backend with pyplot, display the figure window.
subfigures([nrows, ncols, squeeze, wspace, ...])Add a set of subfigures to this figure or subfigure.
subplot_mosaic(mosaic, *[, sharex, sharey, ...])Build a layout of Axes based on ASCII art or nested lists.
subplots([nrows, ncols, sharex, sharey, ...])Add a set of subplots to this figure.
subplots_adjust([left, bottom, right, top, ...])Adjust the subplot layout parameters.
suptitle(t, **kwargs)Add a centered super title to the figure.
supxlabel(t, **kwargs)Add a centered super xlabel to the figure.
supylabel(t, **kwargs)Add a centered super ylabel to the figure.
text(x, y, s[, fontdict])Add text to figure.
tight_layout([renderer, pad, h_pad, w_pad, rect])THIS IS NOT SUPPORTED (we control placement very specifically)
update(props)Update this artist's properties from the dict props.
update_from(other)Copy properties from other to self.
waitforbuttonpress([timeout])Blocking call to interact with the figure.
get_layout_engine
get_path_effects
- savefig(fname, dpi_multiple=1, **kwargs)[source]
Save the current figure.
Call signature:
savefig(fname, dpi_multiple=1, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None)
The output formats available depend on the backend being used.
- Parameters:
fname (str or file-like object) –
A string containing a path to a filename, or a Python file-like object, or possibly some backend-dependent object such as
PdfPages.If format is None and fname is a string, the output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter
savefig.formatis used.If fname is not a string, remember to specify format to ensure that the correct backend is used.
Arguments (Other)
----------------
dpi_multiple ([ scalar integer > 0 ]) – How to scale the figure’s dots per inch (must be an integer to prevent aliasing). Default is 1, equivalent to using to the value of the figure (default matplotlib savefig behavior with dpi=’figure’)
facecolor (color spec or None, optional) – the facecolor of the figure; if None, defaults to savefig.facecolor
edgecolor (color spec or None, optional) – the edgecolor of the figure; if None, defaults to savefig.edgecolor
orientation ({'landscape', 'portrait'}) – not supported on all backends; currently only on postscript output
papertype (str) – One of ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through ‘a10’, ‘b0’ through ‘b10’. Only supported for postscript output.
format (str) – One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg.
transparent (bool) – If True, the axes patches will all be transparent; the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.
frameon (bool) – If True, the figure patch will be colored, if False, the figure background will be transparent. If not provided, the rcParam ‘savefig.frameon’ will be used.
bbox_inches (str or ~matplotlib.transforms.Bbox, optional) – Bbox in inches. Only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure. If None, use savefig.bbox
pad_inches (scalar, optional) – Amount of padding around the figure when bbox_inches is ‘tight’. If None, use savefig.pad_inches
bbox_extra_artists (list of ~matplotlib.artist.Artist, optional) – A list of extra artists that will be considered when the tight bbox is calculated.
- set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, canvas=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, constrained_layout=<UNSET>, constrained_layout_pads=<UNSET>, dpi=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, figheight=<UNSET>, figwidth=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, layout_engine=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, size_inches=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, tight_layout=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)
Set multiple properties at once.
Supported properties are
- Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: float or None animated: bool canvas: FigureCanvas clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None constrained_layout: unknown constrained_layout_pads: unknown dpi: float edgecolor: :mpltype:`color` facecolor: :mpltype:`color` figheight: float figure: unknown figwidth: float frameon: bool gid: str in_layout: bool label: object layout_engine: {‘constrained’, ‘compressed’, ‘tight’, ‘none’, .LayoutEngine, None} linewidth: number mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool size_inches: (float, float) or float sketch_params: (scale: float, length: float, randomness: float) snap: bool or None tight_layout: unknown transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float
- pyrtools.tools.display.animshow(video, framerate=2.0, as_html5=True, repeat=False, vrange='indep1', zoom=1, title='', col_wrap=None, ax=None, cmap=None, plot_complex='rectangular', **kwargs)[source]
Display one or more videos (3d array) as a matplotlib animation or an HTML video.
- Parameters:
video (np.array or list) – the videos(s) to show. Videos can be either grayscale, in which case they must be 3d arrays of shape (f,h,w), or RGB(A), in which case they must be 4d arrays of shape (f,h,w,c) where c is 3 (for RGB) or 4 (to also plot the alpha channel) and f indexes frames. If multiple videos, must be a list of such arrays (note this means we do not support an array of shape (n,f,h,w) for multiple grayscale videos). all videos will be automatically rescaled so they’re displayed at the same size. thus, their sizes must be scalar multiples of each other. If multiple videos, all must have the same number of frames (first dimension).
framerate (float) – Temporal resolution of the video, in Hz (frames per second).
as_html (bool) – If True, return an HTML5 video; otherwise return the underying matplotlib animation object (e.g. to save to .gif). should set to True to display in a Jupyter notebook. Requires ipython to be installed.
repeat (bool) – whether to loop the animation or just play it once
vrange (tuple or str) –
If a 2-tuple, specifies the image values vmin/vmax that are mapped to the minimum and maximum value of the colormap, respectively. If a string:
- ’auto/auto1’: all images have same vmin/vmax, which are the minimum/maximum values
across all images
- ’auto2’: all images have same vmin/vmax, which are the mean (across all images) minus/
plus 2 std dev (across all images)
- ’auto3’: all images have same vmin/vmax, chosen so as to map the 10th/90th percentile
values to the 10th/90th percentile of the display intensity range. For example: vmin is the 10th percentile image value minus 1/8 times the difference between the 90th and 10th percentile
- ’indep1’: each image has an independent vmin/vmax, which are their minimum/maximum
values
- ’indep2’: each image has an independent vmin/vmax, which is their mean minus/plus 2
std dev
- ’indep3’: each image has an independent vmin/vmax, chosen so that the 10th/90th
percentile values map to the 10th/90th percentile intensities.
zoom (float) – amount we zoom the video frames (must result in an integer when multiplied by video.shape[1:])
title (str , list or None) –
Title for the plot:
if str, will put the same title on every plot.
if list, all values must be str, must be the same length as img, assigning each title to corresponding image.
if None, no title will be printed.
col_wrap (int or None, optional) – number of axes to have in each row. If None, will fit all axes in a single row.
ax (matplotlib.pyplot.axis or None, optional) – if None, we make the appropriate figure. otherwise, we resize the axes so that it’s the appropriate number of pixels (done by shrinking the bbox - if the bbox is already too small, this will throw an Exception!, so first define a large enough figure using either make_figure or plt.figure)
cmap (matplotlib colormap, optional) – colormap to use when showing these images
plot_complex ({'rectangular', 'polar', 'logpolar'}, optional) –
specifies handling of complex values.
’rectangular’: plot real and imaginary components as separate images
’polar’: plot amplitude and phase as separate images
’logpolar’: plot log_2 amplitude and phase as separate images
kwargs – Passed to ax.imshow
- Returns:
anim – Animation, format depends on as_html.
- Return type:
HTML object or FuncAnimation object
- pyrtools.tools.display.colormap_range(image, vrange='indep1', cmap=None)[source]
Find the appropriate ranges for colormaps of provided images
- Parameters:
image (np.array or list) – the image(s) to be shown. should be a 2d array (one image to display), 3d array (multiple images to display, images are indexed along the first dimension), or list of 2d arrays. all images will be automatically rescaled so they’re displayed at the same size. thus, their sizes must be scalar multiples of each other.
vrange (tuple or str) –
If a 2-tuple, specifies the image values vmin/vmax that are mapped to (ie. clipped to) the minimum and maximum value of the colormap, respectively. If a string: * ‘auto0’: all images have same vmin/vmax, which have the same
absolute value, and come from the minimum or maximum across all images, whichever has the larger absolute value
- ’auto1’: all images have same vmin/vmax, which are the minimum/
maximum values across all images
- ’auto2’: all images have same vmin/vmax, which are the mean (across
all images) minus/plus 2 std dev (across all images)
- ’auto3’: all images have same vmin/vmax, chosen so as to map the
10th/90th percentile values to the 10th/90th percentile of the display intensity range. For example: vmin is the 10th percentile image value minus 1/8 times the difference between the 90th and 10th percentile
- ’indep0’: each image has an independent vmin/vmax, which have the
same absolute value, which comes from either their minimum or maximum value, whichever has the larger absolute value.
- ’indep1’: each image has an independent vmin/vmax, which are their
minimum/maximum values
- ’indep2’: each image has an independent vmin/vmax, which is their
mean minus/plus 2 std dev
- ’indep3’: each image has an independent vmin/vmax, chosen so that
the 10th/90th percentile values map to the 10th/90th percentile intensities.
- Returns:
vrange_list – list of tuples, same length as image. contains the (vmin, vmax) tuple for each image.
- Return type:
list
- pyrtools.tools.display.find_zooms(images, video=False)[source]
find the zooms necessary to display a list of images
- Parameters:
images (list) – list of numpy arrays to check the size of. In practice, these are 1d or 2d, but can in principle be any number of dimensions
video (bool, optional (default False)) – handling signals in both space and time or only space.
- Returns:
zooms (list) – list of integers showing how much each image needs to be zoomed
max_shape (tuple) – 2-tuple of integers, showing the shape of the largest image in the list
- Raises:
ValueError : – If the images cannot be zoomed to the same. that is, if there is not an integer for each image such that the image can be multiplied by that integer to be the same size as the biggest image.
ValueError : – If the two image dimensions require different levels of zoom (e.g., if the height must be zoomed by 2 but the width must be zoomed by 3).
- pyrtools.tools.display.imshow(image, vrange='indep1', zoom=1, title='', col_wrap=None, ax=None, cmap=None, plot_complex='rectangular', **kwargs)[source]
Show image(s).
- Parameters:
image (np.array or list) – the image(s) to plot. Images can be either grayscale, in which case they must be 2d arrays of shape (h,w), or RGB(A), in which case they must be 3d arrays of shape (h,w,c) where c is 3 (for RGB) or 4 (to also plot the alpha channel). If multiple images, must be a list of such arrays (note this means we do not support an array of shape (n,h,w) for multiple grayscale images). all images will be automatically rescaled so they’re displayed at the same size. thus, their sizes must be scalar multiples of each other.
vrange (tuple or str) –
If a 2-tuple, specifies the image values vmin/vmax that are mapped to the minimum and maximum value of the colormap, respectively. If a string:
- ’auto0’: all images have same vmin/vmax, which have the same absolute
value, and come from the minimum or maximum across all images, whichever has the larger absolute value
- ’auto/auto1’: all images have same vmin/vmax, which are the
minimum/maximum values across all images
- ’auto2’: all images have same vmin/vmax, which are the mean (across
all images) minus/ plus 2 std dev (across all images)
- ’auto3’: all images have same vmin/vmax, chosen so as to map the
10th/90th percentile values to the 10th/90th percentile of the display intensity range. For example: vmin is the 10th percentile image value minus 1/8 times the difference between the 90th and 10th percentile
- ’indep0’: each image has an independent vmin/vmax, which have the
same absolute value, which comes from either their minimum or maximum value, whichever has the larger absolute value.
- ’indep1’: each image has an independent vmin/vmax, which are their
minimum/maximum values
- ’indep2’: each image has an independent vmin/vmax, which is their
mean minus/plus 2 std dev
- ’indep3’: each image has an independent vmin/vmax, chosen so that
the 10th/90th percentile values map to the 10th/90th percentile intensities.
zoom (float) – ratio of display pixels to image pixels. if >1, must be an integer. If <1, must be 1/d where d is a a divisor of the size of the largest image.
title (str, list, or None, optional) –
Title for the plot. In addition to the specified title, we add a subtitle giving the plotted range and dimensionality (with zoom)
if str, will put the same title on every plot.
if list, all values must be str, must be the same length as img, assigning each title to corresponding image.
if None, no title will be printed (and subtitle will be removed; unsupported for complex tensors).
col_wrap (int or None, optional) – number of axes to have in each row. If None, will fit all axes in a single row.
ax (matplotlib.pyplot.axis or None, optional) – if None, we make the appropriate figure. otherwise, we resize the axes so that it’s the appropriate number of pixels (done by shrinking the bbox - if the bbox is already too small, this will throw an Exception!, so first define a large enough figure using either make_figure or plt.figure)
cmap (matplotlib colormap, optional) – colormap to use when showing these images
plot_complex ({'rectangular', 'polar', 'logpolar'}, optional) –
specifies handling of complex values.
’rectangular’: plot real and imaginary components as separate images
’polar’: plot amplitude and phase as separate images
’logpolar’: plot ln(1+ amplitude) and phase as separate images.
The compressive non-linear contrast function applied to amplitude is intended as a visualization step to avoid the large intensity components from dominating.
kwargs – Passed to ax.imshow
- Returns:
fig – figure containing the plotted images
- Return type:
PyrFigure
- pyrtools.tools.display.make_figure(n_rows, n_cols, axis_size_pix, col_margin_pix=10, row_margin_pix=10, vert_pct=0.8)[source]
make a nice figure.
this uses our custom PyrFigure class under the hood.
- Parameters:
n_rows (int) – the number of rows to create in the figure
n_cols (int) – the number of columns to create in the figure
axis_size_pix (tuple) – 2-tuple of ints specifying the size of each axis in the figure in pixels.
col_margin_pix (int) – the number of pixels to leave between each column of axes
row_margin_pix (int) – the number of pixels to leave between each row of axes
vert_pct (float) – must lie between 0 and 1. if less than 1, we leave a little extra room at the top to allow a title. for example, if .8, then we add an extra 20% on top to leave room for a title
- Returns:
fig – the figure containing the axes at the specified size.
- Return type:
PyrFigure
- pyrtools.tools.display.pyrshow(pyr_coeffs, is_complex=False, vrange='indep1', col_wrap=None, zoom=1, show_residuals=True, **kwargs)[source]
Display the coefficients of the pyramid in an orderly fashion
- Parameters:
pyr_coeffs (dict) – from the pyramid object (i.e. pyr.pyr_coeffs)
is_complex (bool) – default False, indicates whether the pyramids is real or complex indicating whether the pyramid is complex or real
vrange (tuple or str) –
If a 2-tuple, specifies the image values vmin/vmax that are mapped to the minimum and maximum value of the colormap, respectively. If a string:
- ’auto/auto1’: all images have same vmin/vmax, which are the minimum/maximum values
across all images
- ’auto2’: all images have same vmin/vmax, which are the mean (across all images) minus/
plus 2 std dev (across all images)
- ’auto3’: all images have same vmin/vmax, chosen so as to map the 10th/90th percentile
values to the 10th/90th percentile of the display intensity range. For example: vmin is the 10th percentile image value minus 1/8 times the difference between the 90th and 10th percentile
- ’indep1’: each image has an independent vmin/vmax, which are their minimum/maximum
values
- ’indep2’: each image has an independent vmin/vmax, which is their mean minus/plus 2
std dev
- ’indep3’: each image has an independent vmin/vmax, chosen so that the 10th/90th
percentile values map to the 10th/90th percentile intensities.
col_wrap (int or None) – Only usable when the pyramid is one-dimensional (e.g., Gaussian or Laplacian Pyramid), otherwise the column wrap is determined by the number of bands. If not None, how many axes to have in a given row.
zoom (float) – how much to scale the size of the images by. zoom times the size of the largest image must be an integer (and thus zoom should probably be an integer or 1/(2^n)).
show_residuals (bool) – whether to display the residual bands (lowpass, highpass depending on the pyramid type)
imshow. (any additional kwargs will be passed through to)
- Returns:
fig – the figure displaying the coefficients.
- Return type:
PyrFigure
- pyrtools.tools.display.reshape_axis(ax, axis_size_pix)[source]
reshape axis to the specified size in pixels
this will reshape an axis so that the given axis is the specified size in pixels, which we use to make sure that an axis is the same size as (or an integer multiple of) the array we’re trying to display. this is to prevent aliasing
NOTE: this can only shrink a big axis, not make a small one bigger, and will throw an exception if you try to do that.
- Parameters:
ax (matpotlib.pyplot.axis) – the axis to reshape
axis_size_pix (int) – the target size of the axis, in pixels
- Returns:
ax – the reshaped axis
- Return type:
matplotlib.pyplot.axis
pyrtools.tools.image_stats module
- pyrtools.tools.image_stats.entropy(vec, binsize=None)[source]
Compute the first-order sample entropy of vec
Samples of vec are first discretized. Optional argument binsize controls the discretization, and defaults to 256/(max(vec)-min(vec)).
NOTE: This is a heavily biased estimate of entropy when you don’t have much data.
- Parameters:
vec (array_like) – the 2d or 2d array to calculate the entropy of
binsize (float or None) – the size of the bins we discretize into. If None, will set to 256/(max(vec)-min(vec))
- Returns:
entropy – estimate of entropy from the data
- Return type:
float
- pyrtools.tools.image_stats.image_compare(im_array0, im_array1)[source]
Prints and returns min, max, mean, stdev of the difference, and SNR (relative to im_array0).
- Parameters:
im_array0 (np.array) – the first image to compare
im_array1 (np.array) – the second image to compare
- Returns:
min_diff (float) – the minimum difference between im_array0 and im_array1
max_diff (float) – the maximum difference between im_array0 and im_array1
mean_diff (float) – the mean difference between im_array0 and im_array1
std_diff (float) – the standard deviation of the difference between im_array0 and im_array1
snr (float) – the signal-to-noise ratio of the difference between im_array0 and im_array0 (relative to im_array0)
- pyrtools.tools.image_stats.image_stats(im_array)[source]
Prints and returns image statistics: min, max, mean, stdev, and kurtosis.
- Parameters:
im_array (np.array) – the image to summarize
- Returns:
array_min (float) – the minimum of im_array
array_max (float) – the maximum of im_array
array_mean (float) – the mean of im_array
array_std (float) – the standard deviation of im_array
array_kurt (float) – the kurtosis of im_array
- pyrtools.tools.image_stats.kurt(array, array_mean=None, array_var=None)[source]
Sample kurtosis (fourth moment divided by squared variance) of the input array.
For reference, kurtosis of a Gaussian distribution is 3.
mean (optional) and var (optional) make the computation faster. This works equally well for real and complex-valued array
- Parameters:
array (np.array) – array to calculate the variance of
array_mean (float or None) – the mean of array. If None, will calculate it.
array_var (float or None) – the variance of array. If None, will calculate it
- Returns:
array_kurt – the kurtosis of array.
- Return type:
float
- pyrtools.tools.image_stats.range(array)[source]
compute minimum and maximum values of the input array
array must be real-valued
- Parameters:
array (np.array) – array to calculate the range of
- Returns:
array_range – (min, max)
- Return type:
tuple
- pyrtools.tools.image_stats.skew(array, array_mean=None, array_var=None)[source]
Sample skew (third moment divided by variance^3/2) of the input array.
mean (optional) and var (optional) make the computation faster. This works equally well for real and complex-valued array
- Parameters:
array (np.array) – array to calculate the variance of
array_mean (float or None) – the mean of array. If None, will calculate it.
array_var (float or None) – the variance of array. If None, will calculate it
- Returns:
array_skew – the skew of array.
- Return type:
float
- pyrtools.tools.image_stats.var(array, array_mean=None)[source]
Sample variance of the input numpy array.
Passing mean (optional) makes the calculation faster. This works equally well for real and complex-valued array
- Parameters:
array (np.array) – array to calculate the variance of
array_mean (float or None) – the mean of array. If None, will calculate it.
- Returns:
array_var – the variance of array
- Return type:
float
pyrtools.tools.synthetic_images module
- pyrtools.tools.synthetic_images.angular_sine(size, harmonic=1, amplitude=1, phase=0, origin=None)[source]
make an angular sinusoidal image:
the angular sinusoid is amplitude * sin(harmonic`*theta + `phase), where theta is the angle about the origin (clockwise from the X-axis).
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
harmonic (float) – the frequency of the angular sinusoid.
amplitude (float) – the amplitude of the angular sinusoid.
phase (float) – the phase of the angular sinusoid. (in radians, clockwise from the X-axis).
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
- Returns:
res – the angular sinusoid
- Return type:
np.array
- pyrtools.tools.synthetic_images.blue_noise(size, fract_dim=1)[source]
make blue noise
Make a matrix of specified size containing blue noise with power spectral density of the form: f^(5-2*`fract_dim`). Image variance is normalized to 1.0.
Note that the power spectrum here is the reciprocal of the pink noises’s power spectrum
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
fract_dim (float) – the fractal dimension of the blue noise
- Returns:
res – the blue noise
- Return type:
np.array
- pyrtools.tools.synthetic_images.disk(size, radius=None, origin=None, twidth=2, vals=(1, 0))[source]
make a “disk” image
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
radius (float or None) – the radius of the disk (in pixels). If None, defaults to min(size)/4.
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
twidth (float) – the width (in pixels) over which a soft threshold transition is made.
vals (tuple) – 2-tuple of floats containing the intensity value inside and outside the disk.
- Returns:
res – the disk image matrix
- Return type:
np.array
- pyrtools.tools.synthetic_images.gaussian(size, covariance=None, origin=None, amplitude='norm')[source]
make a two dimensional Gaussian
make a two dimensional Gaussian function with specified size, centered at a given pixel position, with given covariance and amplitude
TODO - use built in scipy function
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
covariance (float, np.array, or None) – the covariance of the Gaussian. If a float, the covariance is [[covar, 0], [0, covar]]. If an array, must either be of shape (2,) (e.g., [1,2]) or (2,2) (e.g., [[1,0],[0,1]]). If it’s of shape (2,), we use [[covar[0], 0], [0, covar[1]]]. If it’s of shape (2,2), we use it as is. If None, defaults to (min(size)/6)^2
origin (int, tuple, or None) – the center of the Gaussian. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
amplitude (float or ‘norm’) – the amplitude of the Gaussian. If ‘norm’, will return the probability-normalized Gaussian
- Returns:
res – the 2d Gaussian
- Return type:
np.array
- pyrtools.tools.synthetic_images.impulse(size, origin=None, amplitude=1)[source]
make an impulse matrix
create an image that is all zeros except for an impulse of a given amplitude at the origin
NOTE: the origin is rounded to the nearest int
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
origin (int, tuple, or None) – the location of the impulse. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)//2 (note: this is rounded to the nearest int)
amplitude (float) – the amplitude of the impulse
- Returns:
res – the impulse matrix
- Return type:
np.array
- pyrtools.tools.synthetic_images.pink_noise(size, fract_dim=1)[source]
make pink noise
Make a matrix of specified size containing fractal (pink) noise with power spectral density of the form: 1/f^(5-2*`fract_dim`). Image variance is normalized to 1.0.
- TODO: Verify that this matches Mandelbrot defn of fractal dimension.
Make this more efficient!
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
fract_dim (float) – the fractal dimension of the pink noise
- Returns:
res – the pink noise
- Return type:
np.array
- pyrtools.tools.synthetic_images.polar_angle(size, phase=0, origin=None, direction='clockwise')[source]
make polar angle matrix (in radians)
Compute a matrix of given size containing samples of the polar angle (in radians, increasing in user-defined direction from the X-axis, ranging from -pi to pi), relative to given phase, about the given origin pixel.
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
phase (float) – the phase of the polar angle function (in radians, clockwise from the X-axis)
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
direction ({'clockwise', 'counter-clockwise'}) – Whether the angle increases in a clockwise or counter-clockwise direction from the x-axis. The standard mathematical convention is to increase counter-clockwise, so that 90 degrees corresponds to the positive y-axis.
- Returns:
res – the polar angle matrix
- Return type:
np.array
- pyrtools.tools.synthetic_images.polar_radius(size, exponent=1, origin=None)[source]
make distance-from-origin (r) matrix
Compute a matrix of given size containing samples of a radial ramp function, raised to given exponent, centered at given origin.
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
exponent (float) – the exponent of the radial ramp function.
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
- Returns:
res – the polar radius matrix
- Return type:
np.array
- pyrtools.tools.synthetic_images.ramp(size, direction=0, slope=1, intercept=0, origin=None)[source]
make a ramp matrix
Compute a matrix containing samples of a ramp function in a given direction.
- Parameters:
size (int or tuple) – if an int, we assume the ramp should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
direction (float) – the direction of the ramp’s gradient direction, in radians, clockwise from the X-axis
slope (float) – the slope of the ramp (per pixel)
intercept (intercept) – the value of the ramp at the origin
origin (int, tuple, or None) – the origin of the matrix. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size-1)/2.
- Returns:
res – the ramp matrix
- Return type:
np.array
- pyrtools.tools.synthetic_images.sine(size, period=None, direction=None, frequency=None, amplitude=1, phase=0, origin=None)[source]
make a two dimensional sinusoid
this uses either the period and direction or a 2-tuple of frequencies. So either frequency or period and direction should be None, and the other should be set. If period is set, it takes precedence over frequency. If neither are set, we default to (2*pi) / (log2(size[0])).
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
period (float or None) – the period of the two-dimensional sinusoid in pixels. If both period and frequency are None, we set frequency to (2*pi) / (log2(size[0])). If period is set, we ignore frequency
direction (float or None) – the direction of the two-dimensional sinusoid, in radians, clockwise from the X-axis. If period is set and this is None, set to 0.
frequency (tuple or None) – (f_x, f_y), the x and y frequency of the sinusoid in cycles per pixel. If both period and frequency are None, we set frequency to (2*pi) / (log2(size[0])).
amplitude (float) – the amplitude of the sinusoid.
phase (float) – the phase of the sinusoid (in radians, clockwise from the X-axis).
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
- Returns:
res – the two-dimensional sinusoid
- Return type:
np.array
- pyrtools.tools.synthetic_images.square_wave(size, period=None, direction=None, frequency=None, amplitude=1, phase=0, origin=None, twidth=None)[source]
make a two dimensional square wave
this uses either the period and direction or a 2-tuple of frequencies. So either frequency or period and direction should be None, and the other should be set. If period is set, it takes precedence over frequency. If neither are set, we default to (2*pi) / (log2(size[0])).
TODO: Add duty cycle
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
period (float or None) – the period of the square wave in pixels. If both period and frequency are None, we set frequency to (2*pi) / (log2(size[0])). If period is set, we ignore frequency
direction (float or None) – the direction of the square wave, in radians, clockwise from the X-axis. If period is set and this is None, set to 0.
frequency (tuple or None) – (f_x, f_y), the x and y frequency of the square wave in cycles per pixel. If both period and frequency are None, we set frequency to (2*pi) / (log2(size[0])).
amplitude (float) – the amplitude of the sinusoid.
phase (float) – the phase of the square wave (in radians, clockwise from the X-axis).
origin (int, tuple, or None) – the center of the image. if an int, we assume the origin is at (origin, origin). if a tuple, must be a 2-tuple of ints specifying the origin (where (0, 0) is the upper left). if None, we assume the origin lies at the center of the matrix, (size+1)/2.
twidth (float or None) – the width of the raised-cosine edges on the bars of the grating. If None, default to min(2, period/3)
- Returns:
res – the two-dimensional square wave
- Return type:
np.array
- pyrtools.tools.synthetic_images.zone_plate(size, amplitude=1, phase=0)[source]
make a “zone plate” image
zone plate is amplitude * cos( r^2 + phase)
- Parameters:
size (int or tuple) – if an int, we assume the image should be of dimensions (size, size). if a tuple, must be a 2-tuple of ints specifying the dimensions
amplitude (float) – the amplitude of the zone plate
phase (float) – the phase of the zone plate (in radians, clockwise from the X-axis).
- Returns:
res – the zone plate
- Return type:
np.array
pyrtools.tools.utils module
- pyrtools.tools.utils.matlab_histo(array, nbins=101, binsize=None, center=None)[source]
Compute a histogram of array.
- How does this differ from MatLab’s HIST function? This function:
allows uniformly spaced bins only.
operates on all elements of MTX, instead of columnwise.
is much faster (approximately a factor of 80 on my machine).
allows specification of number of bins OR binsize. Default=101 bins.
allows (optional) specification of binCenter.
- Parameters:
array (np.array) – the array to bin
nbins (int) – the number of histogram bins
binsize (float or None) – the size of each bin. if None, we use nbins to determine it as: (array.max() - array.min()) / nbins
center (float or None) – the center position for the histogram bins. if None, this is array.mean()
- Returns:
N (np.array) – the histogram counts
edges (np.array) – vector containing the centers of the histogram bins
- pyrtools.tools.utils.matlab_round(array)[source]
round equivalent to matlab function, which rounds .5 away from zero
(used in matlab_histo so we can unit test against matlab code).
But np.round() would rounds .5 to nearest even number, e.g.: - np.round(0.5) = 0, matlab_round(0.5) = 1 - np.round(2.5) = 2, matlab_round(2.5) = 3
- Parameters:
array (np.array) – the array to round
- Returns:
rounded_array – the rounded array
- Return type:
np.array
- pyrtools.tools.utils.project_polar_to_cartesian(data)[source]
Take a function defined in polar coordinates and project it into Cartesian coordinates
Inspired by https://pyabel.readthedocs.io/en/latest/_modules/abel/tools/polar.html, which went the other way. Note that we currently don’t implement the Cartesian to polar projection, but could do so based on this code fairly simply if it’s necessary.
Currently, this only works for square images and we require that the original image and the reprojected image are the same size. There should be a way to avoid both of these issues, but I can’t think of a way to do that right now.
- Parameters:
data (array_like) – The 2d array to convert from polar to Cartesian coordinates. We assume the first dimension is the polar radius and the second is the polar angle.
- Returns:
output – The 2d array in Cartesian coordinates.
- Return type:
np.array
- pyrtools.tools.utils.rcosFn(width=1, position=0, values=(0, 1))[source]
Return a lookup table containing a “raised cosine” soft threshold function
Y = VALUES(1) + (VALUES(2)-VALUES(1)) * cos^2( PI/2 * (X - POSITION + WIDTH)/WIDTH )
this lookup table is suitable for use by pointOp
- Parameters:
width (float) – the width of the region over which the transition occurs
position (float) – the location of the center of the threshold
values (tuple) – 2-tuple specifying the values to the left and right of the transition.
- Returns:
X (np.array) – the x valuesof this raised cosine
Y (np.array) – the y valuesof this raised cosine