Miscellaneous routines (scipy.misc)¶

Warning

This documentation is work-in-progress and unorganized.

Various utilities that don’t have another home.

Note that the Python Imaging Library (PIL) is not a dependency of SciPy and therefore the pilutil module is not available on systems that don’t have PIL installed.

Modules¶

 common Functions which are common and require SciPy Base and Level 1 SciPy doccer Utilities to allow inserting docstring fragments for common pilutil A collection of image utilities using the Python Imaging Library (PIL). setup setupscons

Functions¶

 bytescale(data[, cmin, cmax, high, low]) Byte scales an array (image). central_diff_weights(Np[, ndiv]) Return weights for an Np-point central derivative of order ndiv comb(N, k[, exact]) The number of combinations of N things taken k at a time. derivative(func, x0[, dx, n, args, order]) Find the n-th derivative of a function at point x0. factorial(n[, exact]) The factorial function, n! = special.gamma(n+1). factorial2(n[, exact]) Double factorial. factorialk(n, k[, exact]) n(!!...!) = multifactorial of order k fromimage(im[, flatten]) Return a copy of a PIL image as a numpy array. imfilter(arr, ftype) Simple filtering of an image. imread(name[, flatten]) Read an image file from a filename. imresize(arr, size[, interp, mode]) Resize an image. imrotate(arr, angle[, interp]) Rotate an image counter-clockwise by angle degrees. imsave(name, arr) Save an array to an image file. imshow(arr) Simple showing of an image through an external viewer. info([object, maxwidth, output, toplevel]) Get help information for a function, class, or module. lena() Get classic image processing example image, Lena, at 8-bit grayscale pade(an, m) Given Taylor series coefficients in an, return a Pade approximation to radon(arr[, theta]) toimage(arr[, high, low, cmin, cmax, pal, ...]) Takes a numpy array and returns a PIL image. The mode of the
scipy.misc.who(vardict=None)

Print the Numpy arrays in the given dictionary.

If there is no dictionary passed in or vardict is None then returns Numpy arrays in the globals() dictionary (all Numpy arrays in the namespace).

Parameters : vardict : dict, optional A dictionary possibly containing ndarrays. Default is globals(). out : None Returns ‘None’.

Notes

Prints out the name, shape, bytes and type of all of the ndarrays present in vardict.

Examples

```>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name            Shape            Bytes            Type
===========================================================
a               10               40               int32
b               20               160              float64
Upper bound on total bytes  =       200
```
```>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name            Shape            Bytes            Type
===========================================================
y               3                24               float64
x               2                16               float64
Upper bound on total bytes  =       40
```
scipy.misc.source(object, output=<open file '<stdout>', mode 'w' at 0x7f2b71af6198>)

Print or write to a file the source code for a Numpy object.

The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information.

Parameters : object : numpy object Input object. This can be any object (function, class, module, ...). output : file object, optional If output not supplied then source code is printed to screen (sys.stdout). File object must be created with either write ‘w’ or append ‘a’ modes.

lookfor, info

Examples

```>>> np.source(np.interp)
In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py
def interp(x, xp, fp, left=None, right=None):
""".... (full docstring printed)"""
if isinstance(x, (float, int, number)):
return compiled_interp([x], xp, fp, left, right).item()
else:
return compiled_interp(x, xp, fp, left, right)
```

The source code is only returned for objects written in Python.

```>>> np.source(np.array)
Not available for this object.
```
scipy.misc.info(object=None, maxwidth=76, output=<open file '<stdout>', mode 'w' at 0x7f2b71af6198>, toplevel='scipy')

Get help information for a function, class, or module.

Parameters : object : object or str, optional Input object or name to get information about. If object is a numpy object, its docstring is given. If it is a string, available modules are searched for matching objects. If None, information about info itself is returned. maxwidth : int, optional Printing width. output : file like object, optional File like object that the output is written to, default is stdout. The object has to be opened in ‘w’ or ‘a’ mode. toplevel : str, optional Start search at this level.

source, lookfor

Notes

When used interactively with an object, np.info(obj) is equivalent to help(obj) on the Python prompt or obj? on the IPython prompt.

Examples

```>>> np.info(np.polyval)
polyval(p, x)
Evaluate the polynomial p at x.
...
```

When using a string for object it is possible to get multiple results.

```>>> np.info('fft')
*** Found in numpy ***
Core FFT routines
...
*** Found in numpy.fft ***
fft(a, n=None, axis=-1)
...
*** Repeat reference found in numpy.fft.fftpack ***
*** Total of 3 references found. ***
```
scipy.misc.fromimage(im, flatten=0)

Return a copy of a PIL image as a numpy array.

Parameters : im : PIL image Input image. flatten : bool If true, convert the output to grey-scale. img_array : ndarray The different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4.
scipy.misc.toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None, mode=None, channel_axis=None)

Takes a numpy array and returns a PIL image. The mode of the PIL image depends on the array shape, the pal keyword, and the mode keyword.

For 2-D arrays, if pal is a valid (N,3) byte-array giving the RGB values (from 0 to 255) then mode=’P’, otherwise mode=’L’, unless mode is given as ‘F’ or ‘I’ in which case a float and/or integer array is made

For 3-D arrays, the channel_axis argument tells which dimension of the
array holds the channel data.
For 3-D arrays if one of the dimensions is 3, the mode is ‘RGB’
by default or ‘YCbCr’ if selected.

if the

The numpy array must be either 2 dimensional or 3 dimensional.

scipy.misc.imsave(name, arr)

Save an array to an image file.

Parameters : im : PIL image Input image. flatten : bool If true, convert the output to grey-scale. img_array : ndarray The different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4.

Read an image file from a filename.

Parameters : name : str The file name to be read. flatten : bool, optional If True, flattens the color layers into a single gray-scale layer. : nd_array : The array obtained by reading image.

Notes

The image is flattened by calling convert(‘F’) on the resulting image object.

scipy.misc.bytescale(data, cmin=None, cmax=None, high=255, low=0)

Byte scales an array (image).

Parameters : data : ndarray PIL image data array. cmin : Scalar Bias scaling of small values, Default is data.min(). cmax : scalar Bias scaling of large values, Default is data.max(). high : scalar Scale max value to high. low : scalar Scale min value to low. img_array : ndarray Bytescaled array.

Examples

```>>> img = array([[ 91.06794177,   3.39058326,  84.4221549 ],
[ 73.88003259,  80.91433048,   4.88878881],
[ 51.53875334,  34.45808177,  27.5873488 ]])
>>> bytescale(img)
array([[255,   0, 236],
[205, 225,   4],
[140,  90,  70]], dtype=uint8)
>>> bytescale(img, high=200, low=100)
array([[200, 100, 192],
[180, 188, 102],
[155, 135, 128]], dtype=uint8)
>>> bytescale(img, cmin=0, cmax=255)
array([[91,  3, 84],
[74, 81,  5],
[52, 34, 28]], dtype=uint8)
```
scipy.misc.imrotate(arr, angle, interp='bilinear')

Rotate an image counter-clockwise by angle degrees.

Parameters : arr : nd_array Input array of image to be rotated. angle : float The angle of rotation. interp : str, optional Interpolation : nd_array : The rotated array of image.

Notes

Interpolation methods can be: * ‘nearest’ : for nearest neighbor * ‘bilinear’ : for bilinear * ‘cubic’ : cubic * ‘bicubic’ : for bicubic

scipy.misc.imresize(arr, size, interp='bilinear', mode=None)

Resize an image.

Parameters : arr : nd_array The array of image to be resized. size : int, float or tuple int - Percentage of current size. float - Fraction of current size. tuple - Size of the output image. interp : string interpolation to use for re-sizing (‘nearest’, ‘bilinear’, ‘bicubic’ or ‘cubic’) mode : : mode is the PIL image mode (‘P’, ‘L’, etc.) : nd_array : The resized array of image.
scipy.misc.imshow(arr)

Simple showing of an image through an external viewer.

Uses the image viewer specified by the environment variable SCIPY_PIL_IMAGE_VIEWER, or if that is not defined then see, to view a temporary file generated from array data.

Parameters : arr : ndarray Array of image data to show. None :

Examples

```>>> a = np.tile(np.arange(255), (255,1))
>>> from scipy import misc
>>> misc.pilutil.imshow(a)
```
scipy.misc.imfilter(arr, ftype)

Simple filtering of an image.

Parameters : arr : ndarray The array of Image in which the filter is to be applied. ftype : str The filter that has to be applied. Legal values are: ‘blur’, ‘contour’, ‘detail’, ‘edge_enhance’, ‘edge_enhance_more’, ‘emboss’, ‘find_edges’, ‘smooth’, ‘smooth_more’, ‘sharpen’. res : nd_array The array with filter applied. ValueError : Unknown filter type. . If the filter you are trying to apply is unsupported.
scipy.misc.factorial(n, exact=0)

The factorial function, n! = special.gamma(n+1).

If exact is 0, then floating point precision is used, otherwise exact long integer is computed.

• Array argument accepted only for exact=0 case.
• If n<0, the return value is 0.
Parameters : n : int or array_like of ints Calculate n!. Arrays are only supported with exact set to False. If n < 0, the return value is 0. exact : bool, optional The result can be approximated rapidly using the gamma-formula above. If exact is set to True, calculate the answer exactly using integer arithmetic. Default is False. nf : float or int Factorial of n, as an integer or a float depending on exact.

Examples

```>>> arr = np.array([3,4,5])
>>> sc.factorial(arr, exact=False)
array([   6.,   24.,  120.])
>>> sc.factorial(5, exact=True)
120L
```
scipy.misc.factorial2(n, exact=False)

Double factorial.

This is the factorial with every second value skipped, i.e., 7!! = 7 * 5 * 3 * 1. It can be approximated numerically as:

```n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi)  n odd
= 2**(n/2) * (n/2)!                           n even```
Parameters : n : int or array_like Calculate n!!. Arrays are only supported with exact set to False. If n < 0, the return value is 0. exact : bool, optional The result can be approximated rapidly using the gamma-formula above (default). If exact is set to True, calculate the answer exactly using integer arithmetic. nff : float or int Double factorial of n, as an int or a float depending on exact.

Examples

```>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105L
```
scipy.misc.factorialk(n, k, exact=1)

n(!!...!) = multifactorial of order k k times

Parameters : n : int, array_like Calculate multifactorial. Arrays are only supported with exact set to False. If n < 0, the return value is 0. exact : bool, optional If exact is set to True, calculate the answer exactly using integer arithmetic. val : int Multi factorial of n. NotImplementedError : Raises when exact is False

Examples

```>>> sc.factorialk(5, 1, exact=True)
120L
>>> sc.factorialk(5, 3, exact=True)
10L
```
scipy.misc.comb(N, k, exact=0)

The number of combinations of N things taken k at a time. This is often expressed as “N choose k”.

Parameters : N : int, array Number of things. k : int, array Number of elements taken. exact : int, optional If exact is 0, then floating point precision is used, otherwise exact long integer is computed. val : int, array The total number of combinations.

Notes

• Array arguments accepted only for exact=0 case.
• If k > N, N < 0, or k < 0, then a 0 is returned.

Examples

```>>> k = np.array([3, 4])
>>> n = np.array([10, 10])
>>> sc.comb(n, k, exact=False)
array([ 120.,  210.])
>>> sc.comb(10, 3, exact=True)
120L
```
scipy.misc.central_diff_weights(Np, ndiv=1)

Return weights for an Np-point central derivative of order ndiv assuming equally-spaced function points.

If weights are in the vector w, then derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx)

Notes

Can be inaccurate for large number of points.

scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)

Find the n-th derivative of a function at point x0.

Given a function, use a central difference formula with spacing dx to compute the n-th derivative at x0.

Parameters : func : function Input function. x0 : float The point at which nth derivative is found. dx : int, optional Spacing. n : int, optional Order of the derivative. Default is 1. args : tuple, optional Arguments order : int, optional Number of points to use, must be odd.

Notes

Decreasing the step size too small can result in round-off error.

Examples

```>>> def x2(x):
...     return x*x
...
>>> derivative(x2, 2)
4.0
```

Given Taylor series coefficients in an, return a Pade approximation to the function as the ratio of two polynomials p / q where the order of q is m.

scipy.misc.lena()

Get classic image processing example image, Lena, at 8-bit grayscale bit-depth, 512 x 512 size.

Parameters : None : lena : ndarray Lena image

Examples

```>>> import scipy.misc
>>> lena = scipy.misc.lena()
>>> lena.shape
(512, 512)
>>> lena.max()
245
>>> lena.dtype
dtype('int32')
```
```>>> import matplotlib.pyplot as plt
>>> plt.gray()
>>> plt.imshow(lena)
>>> plt.show()
```