SciPy-1-12-中文文档-九-

SciPy 1.12 中文文档(九)

原文:docs.scipy.org/doc/scipy-1.12.0/index.html

scipy.ndimage.spline_filter

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.spline_filter.html#scipy.ndimage.spline_filter

scipy.ndimage.spline_filter(input, order=3, output=<class 'numpy.float64'>, mode='mirror')

多维样条滤波器。

参数:

inputarray_like

输入数组。

orderint,可选

样条的顺序,默认为 3。

outputndarray 或 dtype,可选

用于放置输出的数组或返回数组的数据类型。默认为numpy.float64

mode,可选

mode参数确定输入数组在其边界之外如何扩展。默认为‘mirror’。每个有效值的行为如下(参见边界模式的附加图和详细信息):

‘reflect’(d c b a | a b c d | d c b a)

输入通过最后一个像素的边缘反射进行扩展。此模式有时也称为半样本对称。

‘grid-mirror’

这是“reflect”的同义词。

‘constant’(k k k k | a b c d | k k k k)

输入通过填充所有超出边缘的值相同的常量值(由cval参数定义)进行扩展。超出输入边界的部分不进行插值。

‘grid-constant’(k k k k | a b c d | k k k k)

输入通过填充所有超出边缘的值相同的常量值(由cval参数定义)进行扩展。超出输入范围的样本也会进行插值。

‘nearest’(a a a a | a b c d | d d d d)

输入通过复制最后一个像素进行扩展。

‘mirror’(d c b | a b c d | c b a)

输入通过最后一个像素的中心反射进行扩展。此模式有时也称为整样本对称。

‘grid-wrap’(a b c d | a b c d | a b c d)

输入通过环绕到相反边缘进行扩展。

‘wrap’(d b c d | a b c d | b c a b)

输入通过包装到相反边缘进行扩展,但以确保最后一个点和初始点完全重叠的方式。在这种情况下,无法定义在重叠点选择哪个样本。

返回:

spline_filterndarray

过滤后的数组。形状与input相同。

另见

spline_filter1d

沿给定轴计算 1-D 样条滤波器。

注意事项

多维滤波器实现为一系列 1-D 样条滤波器。中间数组以与输出相同的数据类型存储。因此,对于精度有限的输出类型,结果可能不精确,因为中间结果可能存储有限精度。

对于复值input,此函数独立处理实部和虚部。

自 1.6.0 版本开始:增加了对复数支持。

示例

我们可以使用多维样条对图像进行滤波:

>>> from scipy.ndimage import spline_filter
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> orig_img = np.eye(20)  # create an image
>>> orig_img[10, :] = 1.0
>>> sp_filter = spline_filter(orig_img, order=3)
>>> f, ax = plt.subplots(1, 2, sharex=True)
>>> for ind, data in enumerate([[orig_img, "original image"],
...                             [sp_filter, "spline filter"]]):
...     ax[ind].imshow(data[0], cmap='gray_r')
...     ax[ind].set_title(data[1])
>>> plt.tight_layout()
>>> plt.show() 

../../_images/scipy-ndimage-spline_filter-1.png

scipy.ndimage.spline_filter1d

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.spline_filter1d.html#scipy.ndimage.spline_filter1d

scipy.ndimage.spline_filter1d(input, order=3, axis=-1, output=<class 'numpy.float64'>, mode='mirror')

沿给定轴计算 1-D 样条滤波器。

沿给定轴的数组行通过样条滤波器进行滤波。样条的顺序必须 >= 2 且 <= 5。

参数:

inputarray_like

输入数组。

orderint,可选

样条的顺序,默认为 3。

axisint,可选

应用样条滤波器的轴。默认为最后一个轴。

outputndarray 或 dtype,可选

放置输出的数组或返回数组的 dtype。默认为numpy.float64

mode,可选

mode 参数决定了如何扩展输入数组超出其边界。默认为‘mirror’。每个有效值的行为如下(请参见边界模式上的附加图和详细信息):

‘reflect’(d c b a | a b c d | d c b a

输入通过反射最后一个像素的边缘来扩展。这种模式有时也称为半样本对称。

‘grid-mirror’

这是‘reflect’的同义词。

‘constant’(k k k k | a b c d | k k k k

通过使用由 cval 参数定义的相同常量值填充超出边缘的所有值来扩展输入。超出输入边缘不执行插值。

‘grid-constant’(k k k k | a b c d | k k k k

通过使用由 cval 参数定义的相同常量值填充超出边缘的所有值来扩展输入。对于超出输入范围的样本也进行插值。

‘nearest’(a a a a | a b c d | d d d d

通过复制最后一个像素来扩展输入。

‘mirror’(d c b | a b c d | c b a

输入通过反射最后一个像素的中心来扩展。这种模式有时也称为全样本对称。

‘grid-wrap’(a b c d | a b c d | a b c d

输入通过环绕到相对边缘来扩展。

‘wrap’(d b c d | a b c d | b c a b

输入通过环绕到相对边缘,但在最后点和初始点完全重叠的方式扩展。在这种情况下,不确定在重叠点将选择哪个样本。

返回:

spline_filter1dndarray

过滤后的输入。

参见

spline_filter

多维样条滤波器。

注释

ndimage中的所有插值函数都对输入图像进行样条插值。如果使用阶数 > 1的 B 样条,则必须先将输入图像值转换为 B 样条系数,这是通过依次沿输入的所有轴应用此 1-D 滤波器来完成的。所有需要 B 样条系数的函数将自动过滤它们的输入,这种行为可以通过prefilter关键字参数进行控制。对于接受mode参数的函数,仅当结果与滤波时使用的mode匹配时,结果才正确。

对于复数输入,该函数独立处理实部和虚部。

新功能在版本 1.6.0 中添加:增加了对复数支持。

示例

我们可以沿指定轴使用 1-D 样条滤波来过滤图像:

>>> from scipy.ndimage import spline_filter1d
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> orig_img = np.eye(20)  # create an image
>>> orig_img[10, :] = 1.0
>>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
>>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
>>> f, ax = plt.subplots(1, 3, sharex=True)
>>> for ind, data in enumerate([[orig_img, "original image"],
...             [sp_filter_axis_0, "spline filter (axis=0)"],
...             [sp_filter_axis_1, "spline filter (axis=1)"]]):
...     ax[ind].imshow(data[0], cmap='gray_r')
...     ax[ind].set_title(data[1])
>>> plt.tight_layout()
>>> plt.show() 

../../_images/scipy-ndimage-spline_filter1d-1.png

scipy.ndimage.zoom

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.zoom.html#scipy.ndimage.zoom

scipy.ndimage.zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0, prefilter=True, *, grid_mode=False)

缩放数组。

通过请求的顺序进行样条插值来缩放数组。

参数:

inputarray_like

输入数组。

zoomfloat or sequence

沿轴的缩放因子。如果是浮点数,zoom对每个轴都是相同的。如果是序列,zoom应包含每个轴的一个值。

outputarray or dtype, optional

放置输出的数组或返回数组的 dtype。默认情况下,将创建与输入相同 dtype 的数组。

orderint, optional

样条插值的顺序,默认为 3。顺序必须在 0-5 的范围内。

mode, optional

mode参数确定如何扩展输入数组超出其边界的方式。默认值为‘constant’。每个有效值的行为如下(参见边界模式的其他图表和详细信息):

‘reflect’ (d c b a | a b c d | d c b a)

输入通过关于最后一个像素的边缘进行反射来扩展。此模式有时也称为半样本对称。

‘grid-mirror’

这是‘reflect’的同义词。

‘constant’ (k k k k | a b c d | k k k k)

输入通过使用定义的cval参数填充超出输入边缘的所有值进行扩展。超出输入边缘不执行插值。

‘grid-constant’ (k k k k | a b c d | k k k k)

输入通过使用相同的常数值填充超出边缘的所有值进行扩展,该常数值由cval参数定义。对超出输入范围的样本进行插值。

‘nearest’ (a a a a | a b c d | d d d d)

输入通过复制最后一个像素来扩展。

‘mirror’ (d c b | a b c d | c b a)

输入通过关于最后一个像素的中心进行反射来扩展。此模式有时也称为整样本对称。

‘grid-wrap’ (a b c d | a b c d | a b c d)

输入通过环绕到相反边缘进行扩展。

‘wrap’ (d b c d | a b c d | b c a b)

输入通过环绕到相反边缘来进行扩展,但最后一个点和初始点完全重叠。在这种情况下,无法定义在重叠点选择哪个样本。

cvalscalar, optional

如果mode是‘constant’,用于填充输入边缘之外的值的值。默认值为 0.0。

prefilterbool, optional

确定输入数组在插值之前是否使用了spline_filter进行预过滤。默认值为 True,如果order > 1,将创建一个临时的float64数组来存储过滤后的值。如果将其设置为 False,则在order > 1时输出会稍微模糊,除非输入已经预过滤,即调用spline_filter得到的结果。

grid_modebool,可选

如果为 False,则从像素中心的距离被缩放。否则,包括完整像素范围的距离被使用。例如,长度为 5 的 1 维信号在grid_mode为 False 时被认为有长度 4,但在grid_mode为 True 时长度为 5。参见以下视觉说明:

| pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
     |<-------------------------------------->|
                        vs.
|<----------------------------------------------->| 

上图箭头的起始点对应每种模式中坐标位置 0。

返回:

zoomndarray

缩放后的输入。

注释

对于复数输入,此函数将独立缩放实部和虚部。

自版本 1.6.0 起:增加了对复数支持。

示例

>>> from scipy import ndimage, datasets
>>> import matplotlib.pyplot as plt 
>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(121)  # left side
>>> ax2 = fig.add_subplot(122)  # right side
>>> ascent = datasets.ascent()
>>> result = ndimage.zoom(ascent, 3.0)
>>> ax1.imshow(ascent, vmin=0, vmax=255)
>>> ax2.imshow(result, vmin=0, vmax=255)
>>> plt.show() 

../../_images/scipy-ndimage-zoom-1_00_00.png

>>> print(ascent.shape)
(512, 512) 
>>> print(result.shape)
(1536, 1536) 

scipy.ndimage.center_of_mass

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.center_of_mass.html#scipy.ndimage.center_of_mass

scipy.ndimage.center_of_mass(input, labels=None, index=None)

在标签处计算数组值的质心。

参数:

输入ndarray

用于计算质心的数据。质量可以是正或负。

标签ndarray,可选

输入中对象的标签,由ndimage.label生成。仅与索引一起使用。维度必须与输入相同。

索引int 或整数序列,可选

用于计算质心的标签。如果未指定,则将计算大于零的所有标签的组合质心。仅与标签一起使用。

返回:

质心元组或元组列表

质心坐标。

示例

>>> import numpy as np
>>> a = np.array(([0,0,0,0],
...               [0,1,1,0],
...               [0,1,1,0],
...               [0,1,1,0]))
>>> from scipy import ndimage
>>> ndimage.center_of_mass(a)
(2.0, 1.5) 

图像中多个对象的计算

>>> b = np.array(([0,1,1,0],
...               [0,1,0,0],
...               [0,0,0,0],
...               [0,0,1,1],
...               [0,0,1,1]))
>>> lbl = ndimage.label(b)[0]
>>> ndimage.center_of_mass(b, lbl, [1,2])
[(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)] 

接受负质量,例如当由于随机噪声而从测量数据中去除偏差时可能发生。

>>> c = np.array(([-1,0,0,0],
...               [0,-1,-1,0],
...               [0,1,-1,0],
...               [0,1,1,0]))
>>> ndimage.center_of_mass(c)
(-4.0, 1.0) 

如果存在除零问题,该函数不会引发错误,而是在返回 inf 和/或 NaN 之前发出 RuntimeWarning。

>>> d = np.array([-1, 1])
>>> ndimage.center_of_mass(d)
(inf,) 

scipy.ndimage.extrema

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.extrema.html#scipy.ndimage.extrema

scipy.ndimage.extrema(input, labels=None, index=None)

计算数组在标签处的值的最小值和最大值,以及它们的位置。

参数:

input ndarray

要处理的 N-D 图像数据。

labels ndarray,可选

输入中的特征标签。如果不是 None,则必须与input的形状相同。

index int 或 int 序列,可选

要包含在输出中的标签。如果为 None(默认),则使用所有非零标签的值。

返回:

minimums, maximums int 或 ndarray

每个特征中最小值和最大值的值。

min_positions, max_positions tuple 或 元组列表

每个元组给出相应最小值或最大值的 N-D 坐标。

另请参见

maximum, minimum, maximum_position, minimum_position, center_of_mass

示例

>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> from scipy import ndimage
>>> ndimage.extrema(a)
(0, 9, (0, 2), (3, 0)) 

可以使用标签索引来指定要处理的特征:

>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
(array([1, 4, 3]),
 array([5, 7, 9]),
 [(0, 0), (1, 3), (3, 1)],
 [(1, 0), (2, 3), (3, 0)]) 

如果未给出索引,则处理非零标签

>>> ndimage.extrema(a, lbl)
(1, 9, (0, 0), (3, 0)) 

scipy.ndimage.find_objects

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.find_objects.html#scipy.ndimage.find_objects

scipy.ndimage.find_objects(input, max_label=0)

在标记数组中查找对象。

参数:

input整数的 ndarray

包含由不同标签定义的对象的数组。值为 0 的标签将被忽略。

max_label整数,可选

输入中要搜索的最大标签。如果未给出 max_label,则返回所有对象的位置。

返回值:

object_slices元组列表

一个元组列表,每个元组包含 N 个切片(其中 N 是输入数组的维数)。切片对应于包含对象的最小平行四边形体。如果有数字缺失,则返回 None 而不是切片。标签l对应于返回列表中的索引l-1

另请参阅

label, center_of_mass

注意事项

此函数非常适用于在 3D 数组中隔离感兴趣的体积,无法“透视”。

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((6,6), dtype=int)
>>> a[2:4, 2:4] = 1
>>> a[4, 4] = 1
>>> a[:2, :3] = 2
>>> a[0, 5] = 3
>>> a
array([[2, 2, 2, 0, 0, 3],
 [2, 2, 2, 0, 0, 0],
 [0, 0, 1, 1, 0, 0],
 [0, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0]])
>>> ndimage.find_objects(a)
[(slice(2, 5, None), slice(2, 5, None)),
 (slice(0, 2, None), slice(0, 3, None)),
 (slice(0, 1, None), slice(5, 6, None))]
>>> ndimage.find_objects(a, max_label=2)
[(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))]
>>> ndimage.find_objects(a == 1, max_label=2)
[(slice(2, 5, None), slice(2, 5, None)), None] 
>>> loc = ndimage.find_objects(a)[0]
>>> a[loc]
array([[1, 1, 0],
 [1, 1, 0],
 [0, 0, 1]]) 

scipy.ndimage.histogram

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.histogram.html#scipy.ndimage.histogram

scipy.ndimage.histogram(input, min, max, bins, labels=None, index=None)

计算数组值的直方图,可选择在标签处。

直方图计算数组中在由 minmaxbins 决定的区间内数值的频率。labelsindex 关键字可以限制直方图的范围到数组中指定的子区域。

参数:

input类数组

要计算直方图的数据。

min, max整数

直方图区间的最小值和最大值。

bins整数

bins 的数量。

labels类数组,可选

input 中对象的标签。如果不为 None,则必须与 input 的形状相同。

index整数或整数序列,可选

计算直方图时要使用的标签或标签。如果为 None,则使用标签大于零的所有值。

返回:

hist ndarray

直方图计数。

示例

>>> import numpy as np
>>> a = np.array([[ 0.    ,  0.2146,  0.5962,  0.    ],
...               [ 0.    ,  0.7778,  0.    ,  0.    ],
...               [ 0.    ,  0.    ,  0.    ,  0.    ],
...               [ 0.    ,  0.    ,  0.7181,  0.2787],
...               [ 0.    ,  0.    ,  0.6573,  0.3094]])
>>> from scipy import ndimage
>>> ndimage.histogram(a, 0, 1, 10)
array([13,  0,  2,  1,  0,  1,  1,  2,  0,  0]) 

使用标签而没有索引时,将计算非零元素:

>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.histogram(a, 0, 1, 10, lbl)
array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0]) 

可以使用索引来仅计数特定对象:

>>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0]) 

scipy.ndimage.label

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.label.html#scipy.ndimage.label

scipy.ndimage.label(input, structure=None, output=None)

在数组中标记特征。

参数:

输入array_like

要标记的类似数组对象。输入中的任何非零值都将被视为特征,而零值将被视为背景。

结构array_like,可选

定义特征连接的结构元素。结构必须是中心对称的(见注释)。如果未提供结构元素,则将自动生成一个平方连接度为 1 的结构元素。即,对于 2-D 输入数组,默认结构元素是:

[[0,1,0],
 [1,1,1],
 [0,1,0]] 

输出(None, 数据类型, array_like),可选

如果输出是数据类型,则指定结果标记特征数组的类型。如果输出是类似数组的对象,则将从此函数中的标记特征更新输出。此函数可以通过将 output=input 来原位操作。请注意,输出必须能够存储最大的标签,否则此函数将引发异常。

返回:

标签ndarray 或 int

整数 ndarray,其中输入中的每个唯一特征在返回的数组中有一个唯一标签。

num_featuresint

找到了多少个对象。

如果输出为 None,则此函数返回一个元组(labeled_arraynum_features)。

如果输出是一个 ndarray,则它将使用labeled_array中的值进行更新,并且此函数仅返回num_features

另请参阅

find_objects

生成用于标记特征(或对象)位置或尺寸的切片列表

注释

中心对称矩阵是关于中心对称的矩阵。有关更多信息,请参见[1]

结构矩阵必须是中心对称的,以确保双向连接。例如,如果结构矩阵不是中心对称的,并定义为:

[[0,1,0],
 [1,1,0],
 [0,0,0]] 

并且输入是:

[[1,2],
 [0,3]] 

那么结构矩阵将指示输入中的条目 2 连接到 1,但 1 不连接到 2。

参考文献

[1]

James R. Weaver,“中心对称(交叉对称)矩阵,它们的基本属性,特征值和特征向量。” 美国数学月刊 92.10(1985):711-717。

示例

创建一个具有一些特征的图像,然后使用默认的(十字形的)结构元素对其进行标记:

>>> from scipy.ndimage import label, generate_binary_structure
>>> import numpy as np
>>> a = np.array([[0,0,1,1,0,0],
...               [0,0,0,1,0,0],
...               [1,1,0,0,1,0],
...               [0,0,0,1,0,0]])
>>> labeled_array, num_features = label(a) 

每个特征都用不同的整数标记:

>>> num_features
4
>>> labeled_array
array([[0, 0, 1, 1, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [2, 2, 0, 0, 3, 0],
 [0, 0, 0, 4, 0, 0]]) 

生成一个将考虑特征连接的结构元素,即使它们对角接触:

>>> s = generate_binary_structure(2,2) 

或者,

>>> s = [[1,1,1],
...      [1,1,1],
...      [1,1,1]] 

使用新的结构元素标记图像:

>>> labeled_array, num_features = label(a, structure=s) 

显示 2 个标记的特征(请注意,上述的特征 1、3 和 4 现在被视为单个特征):

>>> num_features
2
>>> labeled_array
array([[0, 0, 1, 1, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [2, 2, 0, 0, 1, 0],
 [0, 0, 0, 1, 0, 0]]) 

scipy.ndimage.labeled_comprehension

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.labeled_comprehension.html#scipy.ndimage.labeled_comprehension

scipy.ndimage.labeled_comprehension(input, labels, index, func, out_dtype, default, pass_positions=False)

大致相当于[func(input[labels == i]) for i in index]。

顺序地将任意函数(适用于类似数组的输入)应用于由labelsindex指定的 N-D 图像数组的子集。有选项以位置参数形式提供函数作为第二个参数。

参数:

input类似数组

数据用于选择处理标签

labels类似数组或 None

input中对象的标签。如果不为 None,则数组必须与input具有相同的形状。如果为 None,则将func应用于展平的input

indexint、int 序列或 None

要应用funclabels子集。如果是标量,则返回单个值。如果为 None,则将func应用于labels的所有非零值。

func可调用对象

应用于input中的labels的 Python 函数。

out_dtype数据类型

用于result的数据类型。

defaultint、float 或 None

index的元素在labels中不存在时的默认返回值。

pass_positions布尔值,可选

如果为 True,则将线性索引作为第二个参数传递给func。默认为 False。

返回:

result ndarray

func应用于input中的每个labelsindex的结果。

示例

>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> from scipy import ndimage
>>> lbl, nlbl = ndimage.label(a)
>>> lbls = np.arange(1, nlbl+1)
>>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
array([ 2.75,  5.5 ,  6\.  ]) 

返回到default

>>> lbls = np.arange(1, nlbl+2)
>>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
array([ 2.75,  5.5 ,  6\.  , -1\.  ]) 

传递位置:

>>> def fn(val, pos):
...     print("fn says: %s : %s" % (val, pos))
...     return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
...
>>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
fn says: [1 2 5 3] : [0 1 4 5]
fn says: [4 7] : [ 7 11]
fn says: [9 3] : [12 13]
array([ 11.,  11., -12.,   0.]) 

scipy.ndimage.maximum

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.maximum.html#scipy.ndimage.maximum

scipy.ndimage.maximum(input, labels=None, index=None)

计算数组在标记区域上的最大值。

参数:

input:array_like

值的数组。对于由labels指定的每个区域,计算input在该区域内的最大值。

labels:array_like,可选

一个整数数组,标记了要计算input最大值的不同区域。labels必须与input具有相同的形状。如果未指定labels,则返回整个数组的最大值。

index:array_like,可选

一个包含用于计算最大值的区域标签的列表。如果index为 None,则返回labels非零的所有元素的最大值。

返回:

output:float 或 浮点数列表

返回inputlabels确定的区域中的最大值列表,并且其索引在index中。如果未指定indexlabels,则返回一个浮点数:如果labels为 None,则返回input的最大值;如果index为 None,则返回labels大于零的元素的最大值。

另请参见

label, minimum, median, maximum_position, extrema, sum, mean, variance

standard_deviation

注意

函数返回一个 Python 列表,而不是 NumPy 数组,使用np.array将列表转换为数组。

示例

>>> import numpy as np
>>> a = np.arange(16).reshape((4,4))
>>> a
array([[ 0,  1,  2,  3],
 [ 4,  5,  6,  7],
 [ 8,  9, 10, 11],
 [12, 13, 14, 15]])
>>> labels = np.zeros_like(a)
>>> labels[:2,:2] = 1
>>> labels[2:, 1:3] = 2
>>> labels
array([[1, 1, 0, 0],
 [1, 1, 0, 0],
 [0, 2, 2, 0],
 [0, 2, 2, 0]])
>>> from scipy import ndimage
>>> ndimage.maximum(a)
15.0
>>> ndimage.maximum(a, labels=labels, index=[1,2])
[5.0, 14.0]
>>> ndimage.maximum(a, labels=labels)
14.0 
>>> b = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(b)
>>> labels
array([[1, 1, 0, 0],
 [1, 1, 0, 2],
 [0, 0, 0, 2],
 [3, 3, 0, 0]])
>>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
[5.0, 7.0, 9.0] 

scipy.ndimage.maximum_position

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.maximum_position.html#scipy.ndimage.maximum_position

scipy.ndimage.maximum_position(input, labels=None, index=None)

查找数组值在标签处的最大值位置。

对于由labels指定的每个区域,返回input内最大值的位置。

参数:

input类似数组

数组或类似数组的值。

labels数组或类似数组,可选

一个标记了不同区域的整数数组,用于计算input的最大值位置。labels必须与input具有相同的形状。如果未指定labels,则返回整个数组的第一个极大值的位置。

参数labels指定时,index参数才有效。

index数组或类似数组,可选

一个包含区域标签的列表,用于找到极大值的位置。如果index为 None,则返回所有元素中第一个非零labels的最大值。

参数labels指定时,index参数才有效。

返回:

output整数元组列表

指定index中的索引并且由labels确定的input的最大值的位置的整数元组列表。

如果未指定indexlabels,则返回一个整数元组,指定input的第一个最大值的位置。

参见

label, minimum, median, maximum_position, extrema, sum, mean, variance

standard_deviation

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> ndimage.maximum_position(a)
(3, 0) 

可使用labelsindex指定要处理的特征:

>>> lbl = np.array([[0, 1, 2, 3],
...                 [0, 1, 2, 3],
...                 [0, 1, 2, 3],
...                 [0, 1, 2, 3]])
>>> ndimage.maximum_position(a, lbl, 1)
(1, 1) 

如果没有给出索引,则处理非零labels

>>> ndimage.maximum_position(a, lbl)
(2, 3) 

如果没有极大值,则返回第一个元素的位置:

>>> ndimage.maximum_position(a, lbl, 2)
(0, 2) 

scipy.ndimage.mean

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.mean.html#scipy.ndimage.mean

scipy.ndimage.mean(input, labels=None, index=None)

计算数组在标签处值的平均值。

参数:

input:array_like

要计算区域内元素平均值的数组。

labels:array_like,可选

具有与 input 相同形状的标签数组,或者可以广播到与 input 相同形状的数组。所有共享相同标签的元素形成一个区域,计算其元素的平均值。

index:int 或 int 序列,可选

要计算其平均值的对象的标签。默认为 None,此时计算标签大于 0 的所有值的平均值。

返回:

out:list

index 长度相同的序列,其中包含由 index 中标记的不同区域的平均值。

另请参阅

方差标准差最小值最大值总和标签

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(25).reshape((5,5))
>>> labels = np.zeros_like(a)
>>> labels[3:5,3:5] = 1
>>> index = np.unique(labels)
>>> labels
array([[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 1, 1],
 [0, 0, 0, 1, 1]])
>>> index
array([0, 1])
>>> ndimage.mean(a, labels=labels, index=index)
[10.285714285714286, 21.0] 

scipy.ndimage.median

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.median.html#scipy.ndimage.median

scipy.ndimage.median(input, labels=None, index=None)

计算带有标记区域的数组值的中位数。

参数:

input 数组类型

数组值的 Array_like。对于labels指定的每个区域,计算input在该区域上的中位数值。

labels 数组类型,可选

一个整数数组,标记计算input中位数值的不同区域。labels必须与input具有相同的形状。如果未指定labels,则返回整个数组的中位数值。

index 数组类型,可选

用于计算中位数值的区域标签列表。如果index为 None,则返回labels非零的所有元素的中位数值。

返回值:

median 浮点数或浮点数列表

根据labels确定的区域上,返回index的中位数列表。如果indexlabels未指定,则返回一个浮点数:如果labels为 None,则返回input的中位数值;如果index为 None,则返回labels大于零的元素的中位数值。

另请参阅

labelminimummaximumextremasummeanvariancestandard_deviation

注意

函数返回 Python 列表而不是 NumPy 数组,使用np.array将列表转换为数组。

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.array([[1, 2, 0, 1],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(a)
>>> labels
array([[1, 1, 0, 2],
 [1, 1, 0, 2],
 [0, 0, 0, 2],
 [3, 3, 0, 0]])
>>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
[2.5, 4.0, 6.0]
>>> ndimage.median(a)
1.0
>>> ndimage.median(a, labels=labels)
3.0 

scipy.ndimage.minimum

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.minimum.html#scipy.ndimage.minimum

scipy.ndimage.minimum(input, labels=None, index=None)

计算数组中标记区域上的值的最小值。

参数:

输入array_like

值的数组。对于 labels 指定的每个区域,计算区域内 input 的最小值。

标签array_like,可选

一个整数的数组,标记了要计算 input 最小值的不同区域。labels 必须与 input 的形状相同。如果未指定 labels,则返回整个数组的最小值。

索引array_like,可选

一个区域标签列表,用于计算最小值。如果索引为 None,则返回 labels 非零元素的所有元素的最小值。

返回:

最小值浮点数或浮点数列表

labels 确定的区域内 input 的最小值列表,其索引在 index 中。如果未指定 indexlabels,则返回一个浮点数:如果 labels 为 None,则返回 input 的最小值,如果 index 为 None,则返回 labels 大于零的元素的最小值。

另请参阅

标签, 最大, 中位数, 最小位置, 极值, , 均值, 方差

标准偏差

注意

函数返回一个 Python 列表而不是 NumPy 数组,使用 np.array 将列表转换为数组。

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> labels, labels_nb = ndimage.label(a)
>>> labels
array([[1, 1, 0, 0],
 [1, 1, 0, 2],
 [0, 0, 0, 2],
 [3, 3, 0, 0]])
>>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
[1.0, 4.0, 3.0]
>>> ndimage.minimum(a)
0.0
>>> ndimage.minimum(a, labels=labels)
1.0 

scipy.ndimage.minimum_position

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.minimum_position.html#scipy.ndimage.minimum_position

scipy.ndimage.minimum_position(input, labels=None, index=None)

在标签处找到数组值的最小值位置。

参数:

inputarray_like

数值数组。

labelsarray_like,可选

一个整数数组,标记了计算input最小值位置的不同区域。labels必须与input具有相同的形状。如果未指定labels,则返回整个数组的第一个最小值位置。

labels参数仅在指定index时有效。

indexarray_like,可选

一个区域标签列表,用于查找最小值位置。如果index为 None,则返回所有labels非零元素处的第一个最小值。

index参数仅在指定labels时有效。

返回:

output整数元组列表

一个整数元组或整数元组列表,指定了input在由labels确定的区域中的最小值位置,并且其索引在index中。

如果未指定indexlabels,则返回一个整数元组,指定了input的第一个最小值位置。

参见

labelminimummedianmaximum_positionextremasummeanvariance

standard_deviation

示例

>>> import numpy as np
>>> a = np.array([[10, 20, 30],
...               [40, 80, 100],
...               [1, 100, 200]])
>>> b = np.array([[1, 2, 0, 1],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]]) 
>>> from scipy import ndimage 
>>> ndimage.minimum_position(a)
(2, 0)
>>> ndimage.minimum_position(b)
(0, 2) 

可以使用labelsindex指定要处理的特征:

>>> label, pos = ndimage.label(a)
>>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
[(2, 0)] 
>>> label, pos = ndimage.label(b)
>>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
[(0, 0), (0, 3), (3, 1)] 

scipy.ndimage.standard_deviation

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.standard_deviation.html#scipy.ndimage.standard_deviation

scipy.ndimage.standard_deviation(input, labels=None, index=None)

计算 N 维图像数组值的标准差,可选地在指定的子区域进行计算。

参数:

input类似数组

要处理的 N 维图像数据。

标签类似数组,可选

用于识别输入中子区域的标签。如果不为 None,则必须与输入具有相同的形状。

index整数或整数序列,可选

要包含在输出中的标签。如果为 None(默认),则使用所有标签非零的值。

返回:

standard_deviation浮点数或 ndarray

如果指定了标签索引,则每个子区域的标准差值。

另请参见

label, variance, maximum, minimum, extrema

示例

>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> from scipy import ndimage
>>> ndimage.standard_deviation(a)
2.7585095613392387 

可以使用标签索引指定要处理的特征:

>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
array([ 1.479,  1.5  ,  3\.   ]) 

如果没有给出索引,则处理非零标签

>>> ndimage.standard_deviation(a, lbl)
2.4874685927665499 

scipy.ndimage.sum_labels

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.sum_labels.html#scipy.ndimage.sum_labels

scipy.ndimage.sum_labels(input, labels=None, index=None)

计算数组值的总和。

参数:

input:array_like

input 中由labels 定义的区域内的值被合并。

labels:array_like,整数,可选

为数组的值分配标签。必须与input具有相同的形状。

index:array_like,可选

单个标签号或要测量的对象的标签号序列。

返回:

sum:ndarray 或标量

index 形状与labels 定义的区域内input 值的和的数组相同。如果‘index’ 为 None 或标量,则返回标量。

另请参阅:

meanmedian

示例

>>> from scipy import ndimage
>>> input =  [0,1,2,3]
>>> labels = [1,1,2,2]
>>> ndimage.sum_labels(input, labels, index=[1,2])
[1.0, 5.0]
>>> ndimage.sum_labels(input, labels, index=1)
1
>>> ndimage.sum_labels(input, labels)
6 

scipy.ndimage.value_indices

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.value_indices.html#scipy.ndimage.value_indices

scipy.ndimage.value_indices(arr, *, ignore_value=None)

查找给定数组中每个不同值的索引。

参数:

arr整数的 ndarray

包含整数值的数组。

ignore_valueint,可选

在搜索 arr 数组时,将忽略该值。如果未提供,则输出中将包括所有找到的值。默认为 None。

返回:

indices字典

一个 Python 字典,用于每个不同值的数组索引。字典以不同的值作为键,条目是覆盖数组中所有出现值的数组索引元组。

此字典可能占用大量内存,通常是输入数组大小的几倍。

另请参见

labelmaximummedianminimum_positionextremasummeanvariance

standard_deviationnumpy.wherenumpy.unique

注释

对于具有少量不同值的小数组,可以使用 numpy.unique() 找到所有可能的值,并使用 (arr == val) 定位数组中的每个值。然而,对于具有许多不同值的大数组,这可能变得非常低效,因为每次定位值都需要对整个数组进行新的搜索。使用此函数,实际上只进行了一次搜索,并保存了所有不同值的索引。

当将分类图像(例如分割或分类)与其他数据的关联图像进行匹配时,这非常有用,允许然后计算任何每类统计量。提供了对 scipy.ndimage.mean()scipy.ndimage.variance() 等函数的更灵活的替代方案。

其他相关功能可在 scipy.stats.binned_statistic()scikit-image 函数 skimage.measure.regionprops() 中找到,它们各有优势和劣势。

IDL 用户注意:这提供了与 IDL 的 REVERSE_INDICES 选项相当的功能(根据HISTOGRAM函数的 IDL 文档)。

新版 1.10.0 中新增功能。

示例

>>> import numpy as np
>>> from scipy import ndimage
>>> a = np.zeros((6, 6), dtype=int)
>>> a[2:4, 2:4] = 1
>>> a[4, 4] = 1
>>> a[:2, :3] = 2
>>> a[0, 5] = 3
>>> a
array([[2, 2, 2, 0, 0, 3],
 [2, 2, 2, 0, 0, 0],
 [0, 0, 1, 1, 0, 0],
 [0, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0]])
>>> val_indices = ndimage.value_indices(a) 

字典val_indices将为输入数组中的每个不同值都有一个条目。

>>> val_indices.keys()
dict_keys([0, 1, 2, 3]) 

每个值的条目是一个索引元组,用于定位具有该值的元素。

>>> ndx1 = val_indices[1]
>>> ndx1
(array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4])) 

这可用于对原始数组或任何具有相同形状的数组进行索引。

>>> a[ndx1]
array([1, 1, 1, 1, 1]) 

如果忽略了零,则结果字典将不再包含零的条目。

>>> val_indices = ndimage.value_indices(a, ignore_value=0)
>>> val_indices.keys()
dict_keys([1, 2, 3]) 

scipy.ndimage.variance

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.variance.html#scipy.ndimage.variance

scipy.ndimage.variance(input, labels=None, index=None)

可选地计算 N 维图像数组值的方差,可选地在指定的子区域。

参数:

input:array_like

待处理的 Nd 图像数据。

labels:array_like,可选

定义input中子区域的标签。如果不是 None,则必须与input具有相同的形状。

index:int 或 int 序列,可选

labels要包含在输出中。如果为 None(默认),则使用所有labels非零的值。

返回:

variance:float 或 ndarray

如果指定了labelsindex,则每个子区域的方差值。

另请参见

label, standard_deviation, maximum, minimum, extrema

示例

>>> import numpy as np
>>> a = np.array([[1, 2, 0, 0],
...               [5, 3, 0, 4],
...               [0, 0, 0, 7],
...               [9, 3, 0, 0]])
>>> from scipy import ndimage
>>> ndimage.variance(a)
7.609375 

可使用labelsindex指定要处理的特征:

>>> lbl, nlbl = ndimage.label(a)
>>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
array([ 2.1875,  2.25  ,  9\.    ]) 

如果没有给出索引,则处理所有非零的labels

>>> ndimage.variance(a, lbl)
6.1875 

scipy.ndimage.watershed_ift

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.watershed_ift.html#scipy.ndimage.watershed_ift

scipy.ndimage.watershed_ift(input, markers, structure=None, output=None)

使用图像森林变换算法从标记中应用分水岭。

参数:

input:array_like

输入。

markers:array_like

标记是每个分水岭中形成过程开始的点。负标记被视为背景标记,这些标记在其他标记之后处理。

structure:结构元素,可选

可以提供一个定义对象连接性的结构元素。如果为 None,则生成一个具有方形连接性为一的元素。

output:ndarray,可选

可以选择性地提供输出数组。与输入相同的形状。

返回:

watershed_ift:ndarray

输出。与 input 相同的形状。

参考文献:

[1]

A.X. Falcao, J. Stolfi 和 R. de Alencar Lotufo,《图像森林变换:理论、算法和应用》,模式分析与机器智能,第 26 卷,第 19-29 页,2004 年。

scipy.ndimage.binary_closing

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_closing.html#scipy.ndimage.binary_closing

scipy.ndimage.binary_closing(input, structure=None, iterations=1, output=None, origin=0, mask=None, border_value=0, brute_force=False)

多维二进制使用给定的结构元素进行闭合。

通过结构元素对输入图像进行闭合,是通过结构元素对图像进行膨胀腐蚀的过程。

参数:

输入array_like

待闭合的二进制 array_like。非零(True)元素形成要闭合的子集。

structurearray_like,可选

用于闭合的结构元素。非零元素被视为 True。如果没有提供结构元素,则生成一个连接度为 1 的方形元素(即只有最近的邻居与中心相连,对角线相连的元素不视为邻居)。

迭代次数int,可选

膨胀步骤的闭合,然后是腐蚀步骤,每个操作重复迭代次数(默认为 1 次)。如果迭代次数小于 1,则每个操作重复直到结果不再改变。只接受整数迭代次数。

输出ndarray,可选

与输入相同形状的数组,其中输出被放置。默认情况下,会创建一个新数组。

原点int 或 int 元组,可选

滤波器的放置,默认为 0。

掩模array_like,可选

如果给定掩模,则只有对应掩模元素处为 True 的元素在每次迭代中才会被修改。

1.1.0 版本新增。

边界值int(转换为 0 或 1),可选

输出数组中边界的值。

1.1.0 版本新增。

蛮力布尔值,可选

存储条件:如果为 False,则仅跟踪上次迭代中值发生变化的像素作为当前迭代中更新的候选;如果为 True,则所有像素都被视为候选更新,不管上一次迭代发生了什么。默认为 False。

1.1.0 版本新增。

返回:

binary_closing布尔值的 ndarray

用给定的结构元素进行闭合。

参见

灰度闭合二值开运算二值膨胀二值腐蚀

生成二进制结构

注意事项

Closing [1] 是一种数学形态学操作 [2],由输入与相同结构元素的膨胀和腐蚀相继进行组成。因此,闭运算填充比结构元素小的空洞。

opening (binary_opening) 结合使用可以用于去除噪音。

参考资料

[1]

[zh.wikipedia.org/wiki/闭运算 _(形态学)](https://zh.wikipedia.org/wiki/闭运算 _(形态学))

[2]

zh.wikipedia.org/wiki/数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5,5), dtype=int)
>>> a[1:-1, 1:-1] = 1; a[2,2] = 0
>>> a
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 0, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]])
>>> # Closing removes small holes
>>> ndimage.binary_closing(a).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]])
>>> # Closing is the erosion of the dilation of the input
>>> ndimage.binary_dilation(a).astype(int)
array([[0, 1, 1, 1, 0],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [0, 1, 1, 1, 0]])
>>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]) 
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 2:5] = 1; a[1:3,3] = 0
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> # In addition to removing holes, closing can also
>>> # coarsen boundaries with fine hollows.
>>> ndimage.binary_closing(a).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.binary_dilation

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_dilation.html#scipy.ndimage.binary_dilation

scipy.ndimage.binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False)

给定结构元素的多维二进制膨胀。

参数:

inputarray_like

二进制数组 _like,需进行膨胀操作。非零(True)元素形成需膨胀的子集。

structurearray_like, optional

用于膨胀的结构元素。非零元素被视为 True。如果未提供结构元素,则生成一个连通性为 1 的正方形元素。

iterationsint, optional

膨胀重复 iterations 次(默认一次)。如果 iterations 小于 1,则膨胀将重复,直到结果不再改变。只接受整数 iterations。

maskarray_like, optional

如果提供了掩码,则仅在每次迭代时修改相应掩码元素处为 True 的元素。

outputndarray, optional

与输入相同形状的数组,用于存放输出。默认情况下,将创建一个新数组。

border_valueint(强制为 0 或 1),可选

输出数组的边界值。

originint 或整数元组,可选

滤波器的放置位置,默认为 0。

brute_forceboolean, optional

内存条件:如果为 False,则仅跟踪在上一次迭代中更改值的像素作为当前迭代中待更新(膨胀)的候选像素;如果为 True,则所有像素均视为候选膨胀像素,不考虑上一次迭代中的情况。默认为 False。

返回:

binary_dilationbools 的 ndarray

使用结构元素对输入进行膨胀。

另请参见

grey_dilation, binary_erosion, binary_closing, binary_opening

generate_binary_structure

注意事项

膨胀 [1] 是一种使用结构元素扩展图像中形状的数学形态学操作 [2]。通过结构元素对图像的非零点进行膨胀,膨胀的图像点由结构元素的中心所在位置决定。

参考资料

[1]

en.wikipedia.org/wiki/Dilation_%28morphology%29

[2]

数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a)
array([[False, False, False, False, False],
 [False, False,  True, False, False],
 [False,  True,  True,  True, False],
 [False, False,  True, False, False],
 [False, False, False, False, False]], dtype=bool)
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> # 3x3 structuring element with connectivity 1, used by default
>>> struct1 = ndimage.generate_binary_structure(2, 1)
>>> struct1
array([[False,  True, False],
 [ True,  True,  True],
 [False,  True, False]], dtype=bool)
>>> # 3x3 structuring element with connectivity 2
>>> struct2 = ndimage.generate_binary_structure(2, 2)
>>> struct2
array([[ True,  True,  True],
 [ True,  True,  True],
 [ True,  True,  True]], dtype=bool)
>>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(a, structure=struct1,\
... iterations=2).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 1.,  1.,  1.,  1.,  1.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  1.,  0.,  0.]]) 

scipy.ndimage.binary_erosion

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_erosion.html#scipy.ndimage.binary_erosion

scipy.ndimage.binary_erosion(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False)

给定结构元素进行的多维二值侵蚀。

二值侵蚀是一种用于图像处理的数学形态学操作。

参数:

input array_like

待侵蚀的二值图像。非零(True)元素形成待侵蚀的子集。

structure array_like,可选

用于侵蚀的结构元素。非零元素被视为 True。若未提供结构元素,则生成一个具有正方形连接性的元素。

iterations int,可选

侵蚀操作重复 iterations 次数(默认为一次)。若 iterations 小于 1,则重复侵蚀直至结果不再改变。

mask array_like,可选

若给定掩模,则只有对应掩模元素值为 True 的元素在每次迭代中才会被修改。

output ndarray,可选

形状与输入相同的数组,用以放置输出。默认情况下,创建一个新数组。

border_value int(转换为 0 或 1),可选

输出数组中边界处的值。

origin int 或 int 元组,可选

滤波器的放置,默认为 0。

brute_force 布尔值,可选

内存条件:若为 False,则仅追踪上次迭代中值已更改的像素作为当前迭代中要更新(侵蚀)的候选;若为 True,则无论上次迭代中发生了什么,所有像素都被视为侵蚀的候选。默认为 False。

返回:

binary_erosion 布尔值的 ndarray

通过结构元素对输入进行的侵蚀。

参见

灰度侵蚀, 二值膨胀, 二值闭运算, 二值开运算

generate_binary_structure

注释

侵蚀 [1] 是一种数学形态学操作 [2],使用结构元素来缩小图像中的形状。图像的结构元素侵蚀是结构元素中心位于该点的叠加完全包含在图像非零元素集合中的点的轨迹。

参考文献

[1]

en.wikipedia.org/wiki/Erosion_%28morphology%29

[2]

数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> #Erosion removes objects smaller than the structure
>>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.binary_fill_holes

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_fill_holes.html#scipy.ndimage.binary_fill_holes

scipy.ndimage.binary_fill_holes(input, structure=None, output=None, origin=0)

填充二进制对象的空洞。

参数:

input类数组

N-D 二进制数组,其中含有待填充的孔洞

structure类数组,可选

用于计算的结构元素;大尺寸元素可以加快计算速度,但可能会忽略背景与细胞间隔开的孔洞。默认元素(方形连通性等于 1)产生直观结果,即输入中的所有孔洞已被填充。

outputndarray,可选

与输入相同形状的数组,其中放置了输出。默认情况下,将创建一个新数组。

origin整数,整数元组,可选

结构元素的位置。

返回:

outndarray

经过填充孔洞的初始图像 input 的变换。

另请参阅

binary_dilation, binary_propagation, label

注意事项

此函数中使用的算法是从图像的外部边界入侵 input 的形状的补集,使用二进制膨胀。孔洞未连接到边界,因此未被入侵。结果是入侵区域的补集子集。

参考文献

[1]

zh.wikipedia.org/wiki/数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5, 5), dtype=int)
>>> a[1:4, 1:4] = 1
>>> a[2,2] = 0
>>> a
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 0, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]])
>>> ndimage.binary_fill_holes(a).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]])
>>> # Too big structuring element
>>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 0, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]) 

scipy.ndimage.binary_hit_or_miss

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_hit_or_miss.html#scipy.ndimage.binary_hit_or_miss

scipy.ndimage.binary_hit_or_miss(input, structure1=None, structure2=None, output=None, origin1=0, origin2=None)

多维二进制命中或错过变换。

命中或错过变换找到输入图像中给定模式的位置。

参数:

inputarray_like(转换为布尔值)

二进制图像,其中要检测到模式。

structure1array_like(转换为布尔值),可选

适合于input的前景(非零元素)的结构元素的一部分。如果未提供值,则选择 1 的方形连接结构。

structure2array_like(转换为布尔值),可选

必须完全错过前景的第二部分结构元素。如果未提供值,则取structure1的补集。

outputndarray,可选

形状与输入相同的数组,其中放置输出。默认情况下,会创建一个新数组。

origin1int 或整数元组,可选

结构元素structure1的第一部分的放置位置,默认为 0 表示中心结构。

origin2int 或整数元组,可选

结构元素structure2的第二部分的放置位置,默认为 0 表示中心结构。如果为origin1提供了值但未提供origin2的值,则origin2设为origin1

返回:

binary_hit_or_missndarray

使用给定的结构元素(structure1structure2)对input执行命中或错过变换。

参见

binary_erosion

参考文献

[1]

en.wikipedia.org/wiki/Hit-or-miss_transform

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0, 0, 0],
 [0, 0, 1, 1, 0, 0, 0],
 [0, 0, 0, 0, 1, 1, 0],
 [0, 0, 0, 0, 1, 1, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]])
>>> structure1
array([[1, 0, 0],
 [0, 1, 1],
 [0, 1, 1]])
>>> # Find the matches of structure1 in the array a
>>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> # Change the origin of the filter
>>> # origin1=1 is equivalent to origin1=(1,1) here
>>> ndimage.binary_hit_or_miss(a, structure1=structure1,\
... origin1=1).astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.binary_opening

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_opening.html#scipy.ndimage.binary_opening

scipy.ndimage.binary_opening(input, structure=None, iterations=1, output=None, origin=0, mask=None, border_value=0, brute_force=False)

给定结构元素的多维二进制开运算。

输入图像通过结构元素的开运算是图像通过结构元素的侵蚀膨胀的过程。

参数:

输入类似数组

待开运算的二进制数组。非零(True)元素形成要开运算的子集。

结构类似数组,可选

用于开运算的结构元素。非零元素视为 True。如果未提供结构元素,则生成一个连接性等于一的方形元素(即,只有最近的邻居与中心连接,对角线连接的元素不被视为邻居)。

迭代次数整数,可选

开运算的侵蚀步骤,然后将膨胀步骤重复迭代次数次(默认为一次)。如果迭代次数小于 1,则每个操作重复,直到结果不再改变。只接受整数的迭代次数。

输出类似数组,可选

输出与输入相同形状的数组,其中输出被放置。默认情况下,创建一个新数组。

起始点整数或整数元组,可选

过滤器的放置,默认为 0。

掩码类似数组,可选

如果给定掩码,则仅修改每次迭代中对应掩码元素为 True 的元素。

新版本 1.1.0 中新增。

边界值整数(转换为 0 或 1),可选

输出数组的边界值。

新版本 1.1.0 中新增。

蛮力布尔值,可选

内存条件:如果为 False,则仅跟踪上次迭代中值发生更改的像素作为当前迭代中要更新的候选像素;如果为 True,则考虑所有像素作为候选像素,无论上次迭代中发生了什么。默认为 False。

新版本 1.1.0 中新增。

返回:

binary_opening布尔数组

通过结构元素开运算输入。

另见

灰度开运算, 二进制闭运算, 二进制侵蚀, 二进制膨胀

生成二进制结构

笔记

Opening [1] 是数学形态学操作 [2],包括对输入使用相同结构元素的侵蚀和膨胀的连续操作。因此,opening 可以去除小于结构元素的对象。

closing (binary_closing) 一起,opening 可用于去噪。

参考文献

[1]

en.wikipedia.org/wiki/Opening_%28morphology%29

[2]

en.wikipedia.org/wiki/Mathematical_morphology

例子

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((5,5), dtype=int)
>>> a[1:4, 1:4] = 1; a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 1]])
>>> # Opening removes small objects
>>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0]])
>>> # Opening is the dilation of the erosion of the input
>>> ndimage.binary_erosion(a).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]])
>>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int)
array([[0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0]]) 

scipy.ndimage.binary_propagation

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.binary_propagation.html#scipy.ndimage.binary_propagation

scipy.ndimage.binary_propagation(input, structure=None, mask=None, output=None, border_value=0, origin=0)

使用给定结构元素的多维二进制传播。

参数:

输入array_like

用于在掩模内部传播的二进制图像。

结构array_like,可选

用于连续膨胀的结构元素。输出可能取决于结构元素,特别是如果掩模有多个连通分量。如果未提供结构元素,则生成一个方形连通性为 1 的元素。

掩模array_like,可选

定义了输入允许传播到的区域的二进制掩模。

输出ndarray,可选

与输入形状相同的数组,其中放置了输出。默认情况下,会创建一个新数组。

边界值int(转换为 0 或 1),可选

输出数组中边界的值。

起点int 或 int 元组,可选

过滤器的放置,默认为 0。

返回:

二进制传播ndarray

掩模内部传播输入的二进制传播。

注释

此函数在功能上相当于调用二值膨胀,迭代次数小于 1:迭代膨胀,直到结果不再改变。

可以使用原始图像中的侵蚀和传播的连续序列来代替开运算,以删除小对象同时保持较大对象的轮廓不变。

参考文献

[1]

cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf,第 15 页.

[2]

I.T. Young, J.J. Gerbrands, 和 L.J. van Vliet,《图像处理基础》,1998 ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> input = np.zeros((8, 8), dtype=int)
>>> input[2, 2] = 1
>>> mask = np.zeros((8, 8), dtype=int)
>>> mask[1:4, 1:4] = mask[4, 4]  = mask[6:8, 6:8] = 1
>>> input
array([[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0]])
>>> mask
array([[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 1, 1],
 [0, 0, 0, 0, 0, 0, 1, 1]])
>>> ndimage.binary_propagation(input, mask=mask).astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_propagation(input, mask=mask,\
... structure=np.ones((3,3))).astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 1, 1, 1, 0, 0, 0, 0],
 [0, 0, 0, 0, 1, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0]]) 
>>> # Comparison between opening and erosion+propagation
>>> a = np.zeros((6,6), dtype=int)
>>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1
>>> a
array([[1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 1]])
>>> ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0, 0]])
>>> b = ndimage.binary_erosion(a)
>>> b.astype(int)
array([[0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_propagation(b, mask=a).astype(int)
array([[0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.black_tophat

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.black_tophat.html#scipy.ndimage.black_tophat

scipy.ndimage.black_tophat(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维黑帽滤波器。

参数:

input类似数组

输入。

size整数元组,可选

用于过滤器的平坦且完整的结构元素的形状。如果提供了footprintstructure,则可选。

footprint整数数组,可选

用于黑帽滤波器的平坦结构元素的非无限元素的位置。

structure整数数组,可选

用于滤波器的结构元素。structure可以是非平坦结构元素。

output数组,可选

可以提供用于存储滤波器输出的数组。

mode,可选

mode参数确定如何处理数组边界,当mode等于‘constant’时,cval为其值。默认为‘reflect’。

cval标量,可选

如果mode为‘constant’,则填充输入超出边缘的值。默认为 0.0。

origin标量,可选

origin参数控制滤波器的放置。默认为 0。

返回:

black_tophat ndarray

inputstructure的滤波器结果。

另请参阅

white_tophat, grey_opening, grey_closing

示例

将暗峰变为亮峰并减去背景。

>>> from scipy.ndimage import generate_binary_structure, black_tophat
>>> import numpy as np
>>> square = generate_binary_structure(rank=2, connectivity=3)
>>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
...                          [6, 5, 4, 5, 6],
...                          [6, 4, 0, 4, 6],
...                          [6, 5, 4, 5, 6],
...                          [7, 6, 6, 6, 7]])
>>> black_tophat(input=dark_on_gray, structure=square)
array([[0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 1, 5, 1, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0]]) 

scipy.ndimage.distance_transform_bf

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.distance_transform_bf.html#scipy.ndimage.distance_transform_bf

scipy.ndimage.distance_transform_bf(input, metric='euclidean', sampling=None, return_distances=True, return_indices=False, distances=None, indices=None)

通过蛮力算法的距离变换函数。

此函数通过用前景(非零)元素的最短距离替换到背景(任何零值元素)来计算input的距离变换。

除了距离变换之外,还可以计算特征变换。在这种情况下,将返回每个前景元素最接近的背景元素的索引。

参数:

inputarray_like

输入

metric,可选

‘cityblock’和‘manhattan’也是有效的,它们映射到‘taxicab’。默认为‘euclidean’。

samplingfloat 或 float 序列,可选

仅当metric为‘euclidean’时使用此参数。沿每个维度的元素间距。如果是序列,则必须与输入等级的长度相等;如果是单个数字,则用于所有轴。如果未指定,则暗示单位的网格间距。

return_distancesbool,可选

是否计算距离变换。默认为 True。

return_indicesbool,可选

是否计算特征变换。默认为 False。

distancesndarray,可选

用于存储计算的距离变换的输出数组,而不是返回它。return_distances必须为 True。如果metric为‘euclidean’,则其类型必须为 float64,否则为 uint32,形状必须与input相同。

indicesint32 ndarray,可选

用于存储计算的特征变换的输出数组,而不是返回它。return_indicies必须为 True。其形状必须为(input.ndim,) + input.shape

返回:

distancesndarray,可选

计算得出的距离变换。仅当return_distances为 True 且未提供distances时返回。它将具有与输入数组相同的形状。

indicesint32 ndarray,可选

计算得出的特征变换。它对于输入的每个维度都有一个类似形状的数组。详见distance_transform_edt文档的示例。仅在return_indices为 True 且未提供indices时返回。

另请参见

distance_transform_cdt

更快的出租车距离和棋盘距离变换

distance_transform_edt

更快的欧几里德距离变换

注意事项

此函数采用了一种缓慢的暴力算法。另请参阅函数distance_transform_cdt以获取更高效的出租车[1]和棋盘算法[2]

参考文献

[1]

出租车距离。维基百科,2023 年。zh.wikipedia.org/wiki/%E8%A1%8C%E8%BB%8A%E8%B7%9D%E9%9B%A2

[2]

棋盘距离。维基百科,2023 年。zh.wikipedia.org/wiki/%E6%A3%8B%E7%9B%98%E8%B7%9D%E7%A6%BB

示例

导入必要的模块。

>>> import numpy as np
>>> from scipy.ndimage import distance_transform_bf
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1 import ImageGrid 

首先,我们创建一个玩具二进制图像。

>>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
...     # fill circular area with 1
...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
...     circle_shape = np.sqrt(circle) < radius
...     image[circle_shape] = fillvalue
...     return image
>>> image = np.zeros((100, 100), dtype=np.uint8)
>>> image[35:65, 20:80] = 1
>>> image = add_circle(28, 65, 10, image)
>>> image = add_circle(37, 30, 10, image)
>>> image = add_circle(70, 45, 20, image)
>>> image = add_circle(45, 80, 10, image) 

接下来,我们设置图形。

>>> fig = plt.figure(figsize=(8, 8))  # set up the figure structure
>>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3),
...                  label_mode="1", share_all=True,
...                  cbar_location="right", cbar_mode="each",
...                  cbar_size="7%", cbar_pad="2%")
>>> for ax in grid:
...     ax.axis('off')  # remove axes from images 

左上图是原始的二进制图像。

>>> binary_image = grid[0].imshow(image, cmap='gray')
>>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image)
>>> cbar_binary_image.set_ticks([0, 1])
>>> grid[0].set_title("Binary image: foreground in white") 

距离变换根据距离度量计算前景像素与图像背景之间的距离。在distance_transform_bf中可用的度量包括:euclidean(默认)、taxicabchessboard。右上图包含基于euclidean度量的距离变换。

>>> distance_transform_euclidean = distance_transform_bf(image)
>>> euclidean_transform = grid[1].imshow(distance_transform_euclidean,
...                                      cmap='gray')
>>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform)
>>> colorbar_ticks = [0, 10, 20]
>>> cbar_euclidean.set_ticks(colorbar_ticks)
>>> grid[1].set_title("Euclidean distance") 

左下图包含使用taxicab度量的距离变换。

>>> distance_transform_taxicab = distance_transform_bf(image,
...                                                    metric='taxicab')
>>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab,
...                                         cmap='gray')
>>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> grid[2].set_title("Taxicab distance") 

最后,右下图包含使用chessboard度量的距离变换。

>>> distance_transform_cb = distance_transform_bf(image,
...                                               metric='chessboard')
>>> chessboard_transformation = grid[3].imshow(distance_transform_cb,
...                                            cmap='gray')
>>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> grid[3].set_title("Chessboard distance")
>>> plt.show() 

../../_images/scipy-ndimage-distance_transform_bf-1.png

scipy.ndimage.distance_transform_cdt

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.distance_transform_cdt.html#scipy.ndimage.distance_transform_cdt

scipy.ndimage.distance_transform_cdt(input, metric='chessboard', return_distances=True, return_indices=False, distances=None, indices=None)

按 chamfer 类型的转换的距离变换。

此函数通过将每个前景(非零)元素替换为其到背景(任何零值元素)的最短距离,计算input的距离变换。

除了距离变换之外,还可以计算特征变换。在这种情况下,将返回一个单独的数组,其中包含每个前景元素到最近背景元素的索引。

参数:

inputarray_like

输入。值为 0 被视为背景。

metric 或 array_like,可选

metric确定所执行的 chamfer 类型。如果metric等于'taxicab',则生成一个结构,使用generate_binary_structure ,其平方距离等于 1。如果metric等于'chessboard',则生成一个metric,使用generate_binary_structure ,其平方距离等于数组的维数。这些选择对应于在二维空间中‘taxicab’和‘chessboard’距离度量的常见解释。可以提供自定义的度量,形式为一个矩阵,其中每个维度长度为三。‘cityblock’和‘manhattan’也是有效的,并映射到‘taxicab’。默认值是‘chessboard’。

return_distancesbool,可选

是否计算距离变换。默认为 True。

return_indicesbool,可选

是否计算特征变换。默认为 False。

distancesint32 ndarray,可选

一个输出数组,用于存储计算得到的距离变换,而不是返回它。return_distances 必须为 True。它必须与input具有相同的形状。

indicesint32 ndarray,可选

一个输出数组,用于存储计算得到的特征变换,而不是返回它。return_indicies 必须为 True。其形状必须为(input.ndim,) + input.shape

返回:

distancesint32 ndarray,可选

计算得到的距离变换。仅在return_distances为 True 且未提供distances时返回。它的形状与输入数组相同。

indicesint32 ndarray,可选

计算得到的特征变换。对于输入的每个维度,它有一个形状相同的数组。详细示例请参见 distance_transform_edt 文档。仅在return_indices为 True 且未提供indices时返回。

参见

distance_transform_edt

欧几里得距离的快速距离变换

distance_transform_bf

使用较慢的蛮力算法进行不同度量的距离变换

示例

导入必要的模块。

>>> import numpy as np
>>> from scipy.ndimage import distance_transform_cdt
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1 import ImageGrid 

首先,我们创建一个玩具二进制图像。

>>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
...     # fill circular area with 1
...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
...     circle_shape = np.sqrt(circle) < radius
...     image[circle_shape] = fillvalue
...     return image
>>> image = np.zeros((100, 100), dtype=np.uint8)
>>> image[35:65, 20:80] = 1
>>> image = add_circle(28, 65, 10, image)
>>> image = add_circle(37, 30, 10, image)
>>> image = add_circle(70, 45, 20, image)
>>> image = add_circle(45, 80, 10, image) 

接下来,我们设置图表。

>>> fig = plt.figure(figsize=(5, 15))
>>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3),
...                  label_mode="1", share_all=True,
...                  cbar_location="right", cbar_mode="each",
...                  cbar_size="7%", cbar_pad="2%")
>>> for ax in grid:
...     ax.axis('off')
>>> top, middle, bottom = grid
>>> colorbar_ticks = [0, 10, 20] 

顶部图像包含原始的二进制图像。

>>> binary_image = top.imshow(image, cmap='gray')
>>> cbar_binary_image = top.cax.colorbar(binary_image)
>>> cbar_binary_image.set_ticks([0, 1])
>>> top.set_title("Binary image: foreground in white") 

中间图像包含使用曼哈顿距离度量的距离变换。

>>> distance_taxicab = distance_transform_cdt(image, metric="taxicab")
>>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray')
>>> cbar_taxicab = middle.cax.colorbar(taxicab_transform)
>>> cbar_taxicab.set_ticks(colorbar_ticks)
>>> middle.set_title("Taxicab metric") 

底部图像包含使用棋盘距离度量的距离变换。

>>> distance_chessboard = distance_transform_cdt(image,
...                                              metric="chessboard")
>>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray')
>>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform)
>>> cbar_chessboard.set_ticks(colorbar_ticks)
>>> bottom.set_title("Chessboard metric")
>>> plt.tight_layout()
>>> plt.show() 

../../_images/scipy-ndimage-distance_transform_cdt-1.png

scipy.ndimage.distance_transform_edt

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.distance_transform_edt.html#scipy.ndimage.distance_transform_edt

scipy.ndimage.distance_transform_edt(input, sampling=None, return_distances=True, return_indices=False, distances=None, indices=None)

精确的欧几里得距离变换。

此函数通过将每个前景(非零)元素替换为其到背景(任何零值元素)的最短距离,计算 input 的距离变换。

除了距离变换外,还可以计算特征变换。在这种情况下,返回每个前景元素到最接近的背景元素的索引的单独数组。

参数:

input类数组

转换的输入数据。可以是任何类型,但将转换为二进制:输入等于 True 的地方为 1,其他地方为 0。

samplingfloat 或浮点数序列,可选

每个维度上的元素间隔。如果是序列,必须与输入的秩相等;如果是单个数字,则用于所有轴。如果未指定,假定为单位网格间距。

return_distances布尔值,可选

是否计算距离变换。默认为 True。

return_indices布尔值,可选

是否计算特征变换。默认为 False。

distancesfloat64 数组,可选

一个输出数组,用于存储计算得到的距离变换,而不是返回它。return_distances 必须为 True。其形状必须与 input 相同。

indicesint32 数组,可选

一个输出数组,用于存储计算得到的特征变换,而不是返回它。return_indicies 必须为 True。其形状必须为 (input.ndim,) + input.shape

返回:

distancesfloat64 数组,可选

计算得到的距离变换。仅在 return_distances 为 True 且未提供 distances 时返回。其形状与输入数组相同。

indicesint32 数组,可选

计算得到的特征变换。它为输入的每个维度形状的数组。参见下面的示例。仅在 return_indices 为 True 且未提供 indices 时返回。

注:

欧几里得距离变换提供欧几里得距离的值:

 n
y_i = sqrt(sum (x[i]-b[i])**2)
              i 

其中 b[i] 是背景点(值为 0),其与输入点 x[i] 的欧几里得距离最小,n 是维度的数量。

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.array(([0,1,1,1,1],
...               [0,0,1,1,1],
...               [0,1,1,1,1],
...               [0,1,1,1,0],
...               [0,1,1,0,0]))
>>> ndimage.distance_transform_edt(a)
array([[ 0\.    ,  1\.    ,  1.4142,  2.2361,  3\.    ],
 [ 0\.    ,  0\.    ,  1\.    ,  2\.    ,  2\.    ],
 [ 0\.    ,  1\.    ,  1.4142,  1.4142,  1\.    ],
 [ 0\.    ,  1\.    ,  1.4142,  1\.    ,  0\.    ],
 [ 0\.    ,  1\.    ,  1\.    ,  0\.    ,  0\.    ]]) 

当沿 x 轴采样 2 单位,沿 y 轴采样 1 单位时:

>>> ndimage.distance_transform_edt(a, sampling=[2,1])
array([[ 0\.    ,  1\.    ,  2\.    ,  2.8284,  3.6056],
 [ 0\.    ,  0\.    ,  1\.    ,  2\.    ,  3\.    ],
 [ 0\.    ,  1\.    ,  2\.    ,  2.2361,  2\.    ],
 [ 0\.    ,  1\.    ,  2\.    ,  1\.    ,  0\.    ],
 [ 0\.    ,  1\.    ,  1\.    ,  0\.    ,  0\.    ]]) 

还要求返回索引:

>>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
>>> inds
array([[[0, 0, 1, 1, 3],
 [1, 1, 1, 1, 3],
 [2, 2, 1, 3, 3],
 [3, 3, 4, 4, 3],
 [4, 4, 4, 4, 4]],
 [[0, 0, 1, 1, 4],
 [0, 1, 1, 1, 4],
 [0, 0, 1, 4, 4],
 [0, 0, 3, 3, 4],
 [0, 0, 3, 3, 4]]]) 

提供用于原位输出的数组:

>>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
>>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
array([[ 0\.    ,  1\.    ,  1.4142,  2.2361,  3\.    ],
 [ 0\.    ,  0\.    ,  1\.    ,  2\.    ,  2\.    ],
 [ 0\.    ,  1\.    ,  1.4142,  1.4142,  1\.    ],
 [ 0\.    ,  1\.    ,  1.4142,  1\.    ,  0\.    ],
 [ 0\.    ,  1\.    ,  1\.    ,  0\.    ,  0\.    ]])
>>> indices
array([[[0, 0, 1, 1, 3],
 [1, 1, 1, 1, 3],
 [2, 2, 1, 3, 3],
 [3, 3, 4, 4, 3],
 [4, 4, 4, 4, 4]],
 [[0, 0, 1, 1, 4],
 [0, 1, 1, 1, 4],
 [0, 0, 1, 4, 4],
 [0, 0, 3, 3, 4],
 [0, 0, 3, 3, 4]]]) 

scipy.ndimage.generate_binary_structure

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.generate_binary_structure.html#scipy.ndimage.generate_binary_structure

scipy.ndimage.generate_binary_structure(rank, connectivity)

生成用于二进制形态学操作的二进制结构。

参数:

rankint

数组的维度,即由np.ndim返回的结构元素将应用到的数组的维度。

connectivityint

connectivity决定输出数组中哪些元素属于结构,即被视为中心元素的邻居。距离中心元素不超过connectivity的平方距离的元素被视为邻居。connectivity的范围可以从 1(没有对角线元素为邻居)到rank(所有元素都是邻居)。

返回:

outputbools 数组

用于二进制形态学操作的结构元素,具有rank维度和所有维度均为 3。

另请参阅

iterate_structurebinary_dilationbinary_erosion

注意事项

generate_binary_structure只能创建维度为 3 的结构元素,即最小维度。对于更大的结构元素(例如,用于侵蚀大物体),可以使用iterate_structure或直接使用 NumPy 函数(如numpy.ones)创建自定义数组。

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct
array([[False,  True, False],
 [ True,  True,  True],
 [False,  True, False]], dtype=bool)
>>> a = np.zeros((5,5))
>>> a[2, 2] = 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
>>> b
array([[ 0.,  0.,  0.,  0.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  0.,  0.,  0.,  0.]])
>>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
array([[ 0.,  0.,  1.,  0.,  0.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 1.,  1.,  1.,  1.,  1.],
 [ 0.,  1.,  1.,  1.,  0.],
 [ 0.,  0.,  1.,  0.,  0.]])
>>> struct = ndimage.generate_binary_structure(2, 2)
>>> struct
array([[ True,  True,  True],
 [ True,  True,  True],
 [ True,  True,  True]], dtype=bool)
>>> struct = ndimage.generate_binary_structure(3, 1)
>>> struct # no diagonal elements
array([[[False, False, False],
 [False,  True, False],
 [False, False, False]],
 [[False,  True, False],
 [ True,  True,  True],
 [False,  True, False]],
 [[False, False, False],
 [False,  True, False],
 [False, False, False]]], dtype=bool) 

scipy.ndimage.grey_closing

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.grey_closing.html#scipy.ndimage.grey_closing

scipy.ndimage.grey_closing(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维灰度闭合。

灰度闭合包括灰度膨胀和灰度腐蚀的连续操作。

参数:

input类似数组

需要计算灰度闭合的数组。

size整数元组

用于灰度闭合的平面和完整结构元素的形状。如果提供了 footprintstructure,则可选。

footprint整数数组,可选

用于灰度闭合的平面结构元素的非无限元素位置。

structure整数数组,可选

用于灰度闭合的结构元素。structure 可以是非平面结构元素。

output数组,可选

可以提供一个数组用于存储闭合操作的输出。

mode,可选

mode 参数确定如何处理数组边界,其中 cval 是当 mode 等于 'constant' 时的值。默认为 'reflect'。

cval标量,可选

如果 mode 为 'constant',则用来填充输入边界之外的值。默认为 0.0。

origin标量,可选

origin 参数控制滤波器的放置位置。默认为 0

返回:

grey_closing ndarray

inputstructure 进行灰度闭合的结果。

另请参阅

binary_closing, grey_dilation, grey_erosion, grey_opening

generate_binary_structure

注释

使用平面结构元素进行灰度闭合的操作相当于平滑深部局部最小值,而二值闭合则填补小孔。

参考

[1]

zh.wikipedia.org/wiki/数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(36).reshape((6,6))
>>> a[3,3] = 0
>>> a
array([[ 0,  1,  2,  3,  4,  5],
 [ 6,  7,  8,  9, 10, 11],
 [12, 13, 14, 15, 16, 17],
 [18, 19, 20,  0, 22, 23],
 [24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35]])
>>> ndimage.grey_closing(a, size=(3,3))
array([[ 7,  7,  8,  9, 10, 11],
 [ 7,  7,  8,  9, 10, 11],
 [13, 13, 14, 15, 16, 17],
 [19, 19, 20, 20, 22, 23],
 [25, 25, 26, 27, 28, 29],
 [31, 31, 32, 33, 34, 35]])
>>> # Note that the local minimum a[3,3] has disappeared 

scipy.ndimage.grey_dilation

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.grey_dilation.html#scipy.ndimage.grey_dilation

scipy.ndimage.grey_dilation(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

计算灰度膨胀,使用结构元素或对应于平坦结构元素的足迹。

灰度膨胀是一种数学形态学操作。对于完整且平坦的结构元素的简单情况,可以将其视为在滑动窗口上的最大过滤器。

参数:

input类似数组

用于计算灰度膨胀的数组。

size整数元组

用于灰度膨胀的平坦和完整结构元素的形状。如果提供footprintstructure,则可选。

足迹整数数组,可选

用于灰度膨胀的平坦结构元素的非无限元素位置。非零值给出中心的邻居集,用于选择最大值。

structure整数数组,可选

用于灰度膨胀的结构元素。structure可以是非平坦结构元素。

output数组,可选

可以提供一个用于存储膨胀输出的数组。

模式,可选

mode参数确定如何处理数组边界,当 mode 等于‘constant’时,cval为其值。默认为‘reflect’。

cval标量,可选

如果mode为‘constant’,则超出输入边界的值填充。默认为 0.0。

origin标量,可选

origin参数控制过滤器的放置。默认为 0。

返回:

grey_dilationndarray

input的灰度膨胀。

参见

binary_dilation, grey_erosion, grey_closing, grey_opening

generate_binary_structure, maximum_filter

注意事项

对由定义在域 E 上的结构元素 s 输入的灰度膨胀的计算如下:

(input+s)(x) = max {input(y) + s(x-y),y 在 E 中}

特别地,对于定义为 s(y) = 0 的结构元素 E,灰度膨胀计算输入图像在由 E 定义的滑动窗口内的最大值。

灰度膨胀[1]是一种数学形态学操作[2]

参考文献

[1]

en.wikipedia.org/wiki/Dilation_%28morphology%29

[2]

en.wikipedia.org/wiki/Mathematical_morphology

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> a[4,4] = 2; a[2,3] = 3
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 3, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 2, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 3, 3, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, footprint=np.ones((3,3)))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 3, 3, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> s = ndimage.generate_binary_structure(2,1)
>>> s
array([[False,  True, False],
 [ True,  True,  True],
 [False,  True, False]], dtype=bool)
>>> ndimage.grey_dilation(a, footprint=s)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 3, 1, 0, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 1, 3, 2, 1, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 0, 1, 1, 2, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3)))
array([[1, 1, 1, 1, 1, 1, 1],
 [1, 2, 4, 4, 4, 2, 1],
 [1, 2, 4, 4, 4, 2, 1],
 [1, 2, 4, 4, 4, 3, 1],
 [1, 2, 2, 3, 3, 3, 1],
 [1, 2, 2, 3, 3, 3, 1],
 [1, 1, 1, 1, 1, 1, 1]]) 

scipy.ndimage.grey_erosion

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.grey_erosion.html#scipy.ndimage.grey_erosion

scipy.ndimage.grey_erosion(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

计算灰度侵蚀,可以使用结构元素,或者对应于平面结构元素的足迹。

灰度侵蚀是一种数学形态学操作。对于简单情况下的全平面结构元素,可以视为滑动窗口上的最小滤波器。

参数:

input 类似数组

计算灰度侵蚀的数组。

size 整数元组

用于灰度侵蚀的平坦全结构元素的形状。如果提供了 footprintstructure,则可选。

footprint 数组,整数,可选

用于计算灰度侵蚀的平坦结构元素的非无限元素位置。非零值给出中心的邻域集,其中选择最小值。

structure 数组,整数,可选

用于灰度侵蚀的结构元素。structure 可以是非平坦的结构元素。

output 数组,可选

可提供用于存储侵蚀输出的数组。

mode {‘reflect’,’constant’,’nearest’,’mirror’, ‘wrap’},可选

mode 参数决定如何处理数组边界,其中 cval 是当 mode 等于 'constant' 时的值。默认为 'reflect'。

cval 标量,可选

如果 mode 是 'constant',则填充输入边界之外的值。默认为 0.0。

origin 标量,可选

origin 参数控制滤波器的放置。默认为 0。

返回:

output ndarray

输入图像的灰度侵蚀。

另见

binary_erosion, grey_dilation, grey_opening, grey_closing

generate_binary_structure, minimum_filter

注意

由结构元素 s 定义的输入图像的灰度侵蚀在域 E 上给出:

(input+s)(x) = min {input(y) - s(x-y),y∈E}

特别地,对于定义为 s(y) = 0 的结构元素,灰度侵蚀计算在 E 定义的滑动窗口内输入图像的最小值。

灰度侵蚀 [1] 是一种 数学形态学 操作 [2]

参考文献

[1]

en.wikipedia.org/wiki/Erosion_%28morphology%29

[2]

en.wikipedia.org/wiki/Mathematical_morphology

Examples

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 1:6] = 3
>>> a[4,4] = 2; a[2,3] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 3, 3, 3, 3, 3, 0],
 [0, 3, 3, 1, 3, 3, 0],
 [0, 3, 3, 3, 3, 3, 0],
 [0, 3, 3, 3, 2, 3, 0],
 [0, 3, 3, 3, 3, 3, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_erosion(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 3, 2, 2, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> footprint = ndimage.generate_binary_structure(2, 1)
>>> footprint
array([[False,  True, False],
 [ True,  True,  True],
 [False,  True, False]], dtype=bool)
>>> # Diagonally-connected elements are not considered neighbors
>>> ndimage.grey_erosion(a, footprint=footprint)
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 3, 1, 2, 0, 0],
 [0, 0, 3, 2, 2, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.grey_opening

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.grey_opening.html#scipy.ndimage.grey_opening

scipy.ndimage.grey_opening(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维灰度开运算。

灰度开运算由灰度侵蚀和灰度膨胀的连续进行组成。

参数:

input 数组类型

用于计算灰度开运算的数组。

size 整数元组

用于灰度开运算的平坦全结构元素的形状。如果提供了 footprintstructure,则为可选。

footprint 整数数组,可选

用于灰度开运算的平坦结构元素的非无限元素的位置。

structure 整数数组,可选

用于灰度开运算的结构元素。structure 可以是非平坦的结构元素。

output 数组,可选

可以提供用于存储开运算输出的数组。

mode {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’},可选

mode 参数确定如何处理数组边界,当 mode 等于 ‘constant’ 时,cval 是数值。默认为 ‘reflect’

cval 标量,可选

如果 mode 为 ‘constant’,则在输入边缘之外填充值的数值。默认为 0.0。

origin 标量,可选

参数 origin 控制滤波器的放置。默认为 0

返回:

grey_opening ndarray

input 使用 structure 的灰度开运算的结果。

另请参阅

binary_openinggrey_dilationgrey_erosiongrey_closing

generate_binary_structure

说明

使用平坦结构元素的灰度开运算的作用是平滑高局部最大值,而二值开运算则擦除小对象。

参考文献

[1]

数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.arange(36).reshape((6,6))
>>> a[3, 3] = 50
>>> a
array([[ 0,  1,  2,  3,  4,  5],
 [ 6,  7,  8,  9, 10, 11],
 [12, 13, 14, 15, 16, 17],
 [18, 19, 20, 50, 22, 23],
 [24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35]])
>>> ndimage.grey_opening(a, size=(3,3))
array([[ 0,  1,  2,  3,  4,  4],
 [ 6,  7,  8,  9, 10, 10],
 [12, 13, 14, 15, 16, 16],
 [18, 19, 20, 22, 22, 22],
 [24, 25, 26, 27, 28, 28],
 [24, 25, 26, 27, 28, 28]])
>>> # Note that the local maximum a[3,3] has disappeared 

scipy.ndimage.iterate_structure

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.iterate_structure.html#scipy.ndimage.iterate_structure

scipy.ndimage.iterate_structure(structure, iterations, origin=None)

通过与自身膨胀来迭代结构。

参数:

structure array_like

结构元素(例如布尔数组),用于与自身进行膨胀。

iterations 整数

对结构与自身执行的膨胀次数

origin 可选

如果 origin 为 None,则仅返回迭代后的结构。如果不为 None,则返回迭代后的结构和修改后的原点的元组。

返回:

iterate_structure 布尔值的 ndarray

通过将 structure 与自身膨胀 (iterations - 1) 次获得的新结构元素。

另请参见

generate_binary_structure

示例

>>> from scipy import ndimage
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct.astype(int)
array([[0, 1, 0],
 [1, 1, 1],
 [0, 1, 0]])
>>> ndimage.iterate_structure(struct, 2).astype(int)
array([[0, 0, 1, 0, 0],
 [0, 1, 1, 1, 0],
 [1, 1, 1, 1, 1],
 [0, 1, 1, 1, 0],
 [0, 0, 1, 0, 0]])
>>> ndimage.iterate_structure(struct, 3).astype(int)
array([[0, 0, 0, 1, 0, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [1, 1, 1, 1, 1, 1, 1],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 1, 0, 0, 0]]) 

scipy.ndimage.morphological_gradient

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.morphological_gradient.html#scipy.ndimage.morphological_gradient

scipy.ndimage.morphological_gradient(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维形态学梯度。

形态学梯度计算为输入与给定结构元素的膨胀和腐蚀之间的差异。

参数:

input数组型

用于计算形态学梯度的数组。

size整数元组

用于数学形态学操作的平坦和完整的结构元素的形状。如果提供了footprintstructure,则可选。较大的size会产生更模糊的梯度。

footprint整数数组,可选

用于形态学操作的平坦结构元素的非无穷元素的位置。较大的足迹会产生更模糊的形态学梯度。

structure整数数组,可选

用于形态学操作的结构元素。structure可以是非平坦的结构元素。

output数组,可选

可以提供用于存储形态学梯度输出的数组。

mode,可选

mode参数确定如何处理数组边界,当mode等于'constant'时,cval为值。默认为'reflect'

cval标量,可选

如果mode为'constant',用于填充输入边缘之外的值。默认为 0.0。

origin标量,可选

origin参数控制滤波器的放置位置。默认值为 0

返回:

morphological_gradientn 维数组

input的形态学梯度。

另请参阅

grey_dilation, grey_erosion, gaussian_gradient_magnitude

注释

对于平坦的结构元素,给定点处计算的形态学梯度对应于由以该点为中心的结构元素覆盖的元素中的输入元素之间的最大差异。

参考资料

[1]

zh.wikipedia.org/wiki/数学形态学

示例

>>> from scipy import ndimage
>>> import numpy as np
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> ndimage.morphological_gradient(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 0, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> # The morphological gradient is computed as the difference
>>> # between a dilation and an erosion
>>> ndimage.grey_dilation(a, size=(3,3)) -\
...  ndimage.grey_erosion(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 0, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 1, 1, 1, 1, 1, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> a = np.zeros((7,7), dtype=int)
>>> a[2:5, 2:5] = 1
>>> a[4,4] = 2; a[2,3] = 3
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 3, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 1, 1, 2, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.morphological_gradient(a, size=(3,3))
array([[0, 0, 0, 0, 0, 0, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 3, 3, 1, 0],
 [0, 1, 3, 2, 3, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 1, 1, 2, 2, 2, 0],
 [0, 0, 0, 0, 0, 0, 0]]) 

scipy.ndimage.morphological_laplace

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.morphological_laplace.html#scipy.ndimage.morphological_laplace

scipy.ndimage.morphological_laplace(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维形态拉普拉斯。

参数:

输入array_like

输入。

大小int 或 int 序列,可选

结构

足迹bool 或 ndarray,可选

结构

结构structure,可选

必须提供sizefootprintstructure中的一个。

输出ndarray,可选

可以选择提供输出数组。

模式,可选

参数mode决定了如何处理数组边界。对于‘constant’模式,超出边界的值将被设为cval。默认为‘reflect’。

cval标量,可选

如果mode为‘constant’,则用于填充输入的边缘的值。默认为 0.0。

原点origin,可选

原点参数控制滤波器的放置位置。

返回:

形态拉普拉斯ndarray

输出

scipy.ndimage.white_tophat

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.ndimage.white_tophat.html#scipy.ndimage.white_tophat

scipy.ndimage.white_tophat(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0)

多维白顶帽滤波器。

参数:

input数组形式

输入。

size整数元组

用于滤波器的平坦且完整的结构元素的形状。如果提供footprintstructure,则为可选。

footprint整数数组,可选

用于白顶帽滤波器的平坦结构元素的元素位置。

structure整数数组,可选

用于滤波器的结构元素。structure可以是非平坦的结构元素。

output数组,可选

可以提供用于存储滤波器输出的数组。

mode,可选

参数mode决定如何处理数组边界,其中cval是 mode 等于'constant'时的值。默认为'reflect'。

cval标量,可选

mode为'constant'时,用于填充输入边缘之外的值。默认为 0.0。

origin标量,可选

参数origin控制滤波器的放置位置。默认为 0。

返回:

outputndarray

使用structureinput的滤波器结果。

参见

black_tophat

示例

从亮峰中减去灰色背景。

>>> from scipy.ndimage import generate_binary_structure, white_tophat
>>> import numpy as np
>>> square = generate_binary_structure(rank=2, connectivity=3)
>>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
...                            [3, 4, 5, 4, 3],
...                            [3, 5, 9, 5, 3],
...                            [3, 4, 5, 4, 3],
...                            [2, 3, 3, 3, 2]])
>>> white_tophat(input=bright_on_gray, structure=square)
array([[0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 1, 5, 1, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0]]) 

Orthogonal distance regression (scipy.odr)

Original text:docs.scipy.org/doc/scipy-1.12.0/reference/odr.html

Package Content

Data(x[, y, we, wd, fix, meta]) 要拟合的数据。
RealData(x[, y, sx, sy, covx, covy, fix, meta]) 数据,带有实际标准偏差和/或协方差作为加权。
Model(fcn[, fjacb, fjacd, extra_args, ...]) 存储关于您希望拟合的函数的信息的 Model 类。
ODR(data, model[, beta0, delta0, ifixb, ...]) ODR 类汇总所有信息并协调主拟合例程的运行。
Output(output) Output 类存储 ODR 运行的输出。
odr(fcn, beta0, y, x[, we, wd, fjacb, ...]) ODR 的底层函数。
OdrWarning 警告指示传递到 ODR 的数据在传递到 'odr' 时可能会引起问题,用户应该注意。
OdrError 拟合中出现错误的异常。
OdrStop 停止拟合的异常。
polynomial(order) 通用多项式模型的工厂函数。
exponential 指数模型
multilinear 任意维度线性模型
unilinear 单变量线性模型
quadratic 二次模型

Usage information

Introduction

为什么要使用正交距离回归(ODR)?有时解释变量(即“自变量”)存在测量误差,而不仅仅是响应变量(即“因变量”)。普通最小二乘(OLS)拟合程序将解释变量的数据视为固定的,即不受任何误差的影响。此外,OLS 程序要求响应变量是解释变量的显式函数;有时使方程显式化是不切实际的和/或会引入误差。ODR 可以轻松处理这两种情况,甚至可以在问题仅需 OLS 的情况下简化处理。

ODRPACK 是一个用于执行可能非线性拟合函数的 FORTRAN-77 库。它使用修改的信赖域 Levenberg-Marquardt 类型算法[1]来估计函数参数。拟合函数由操作 NumPy 数组的 Python 函数提供。所需的导数也可以由 Python 函数提供,或者可以通过数值方法估计。ODRPACK 可以进行显式或隐式 ODR 拟合,或者可以进行 OLS 拟合。输入和输出变量可以是多维的。可以提供权重以考虑观测值的不同方差,甚至可以考虑变量维度之间的协方差。

scipy.odr 包提供了对 ODRPACK 的面向对象接口,除了低级别的 odr 函数。

有关 ODRPACK 的更多背景信息,请参阅ODRPACK 用户指南,推荐阅读。

基本用法

  1. 定义要拟合的函数。

    def f(B, x):
      '''Linear function y = m*x + b'''
        # B is a vector of the parameters.
        # x is an array of the current x values.
        # x is in the same format as the x passed to Data or RealData.
        #
        # Return an array in the same format as y passed to Data or RealData.
        return B[0]*x + B[1] 
    
  2. 创建模型。

    linear = Model(f) 
    
  3. 创建 Data 或 RealData 实例。

    mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2)) 
    

    或者,当实际协方差已知时:

    mydata = RealData(x, y, sx=sx, sy=sy) 
    
  4. 使用您的数据、模型和初始参数估计来实例化 ODR。

    myodr = ODR(mydata, linear, beta0=[1., 2.]) 
    
  5. 运行拟合。

    myoutput = myodr.run() 
    
  6. 检查输出。

    myoutput.pprint() 
    

参考文献

[1]

P. T. Boggs 和 J. E. Rogers,在《测量误差模型的统计分析及其应用:1989 年 6 月 10 日至 16 日举行的 AMS-IMS-SIAM 联合暑期研究会议会议录》中,"Orthogonal Distance Regression"一文中讨论了“正交距离回归”,出自《当代数学》,第 112 卷,第 186 页,1990 年。

scipy.odr.Data

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.Data.html#scipy.odr.Data

class scipy.odr.Data(x, y=None, we=None, wd=None, fix=None, meta=None)

要拟合的数据。

参数:

xarray_like

回归的自变量的观察数据

yarray_like,可选

如果是类数组,用于回归的因变量的观察数据。标量输入意味着要在数据上使用的模型是隐含的。

wearray_like,可选

如果 we 是一个标量,则该值将用于所有数据点(以及响应变量的所有维度)。如果 we 是长度为 q 的秩为 1 的数组(响应变量的维度),则该向量是所有数据点的协变权重矩阵的对角线。如果 we 是长度为 n 的秩为 1 的数组(数据点的数量),则第 i 个元素是第 i 个响应变量观测的权重(仅适用于单维度)。如果 we 是形状为 (q, q) 的秩为 2 的数组,则这是广播到每个观测的完整协变权重矩阵。如果 we 是形状为 (q, n) 的秩为 2 的数组,则 we[:,i] 是第 i 个观测的协变权重矩阵的对角线。如果 we 是形状为 (q, q, n) 的秩为 3 的数组,则 we[:,:,i] 是每个观测的协变权重矩阵的完整规格。如果拟合是隐含的,则只使用正标量值。

wdarray_like,可选

如果 wd 是一个标量,则该值将用于所有数据点(以及输入变量的所有维度)。如果 wd = 0,则每个观测的协变权重矩阵被设置为单位矩阵(因此每个观测的每个维度具有相同的权重)。如果 wd 是长度为 m 的秩为 1 的数组(输入变量的维度),则该向量是所有数据点的协变权重矩阵的对角线。如果 wd 是长度为 n 的秩为 1 的数组(数据点的数量),则第 i 个元素是第 i 个输入变量观测的权重(仅适用于单维度)。如果 wd 是形状为 (m, m) 的秩为 2 的数组,则这是广播到每个观测的完整协变权重矩阵。如果 wd 是形状为 (m, n) 的秩为 2 的数组,则 wd[:,i] 是第 i 个观测的协变权重矩阵的对角线。如果 wd 是形状为 (m, m, n) 的秩为 3 的数组,则 wd[:,:,i] 是每个观测的协变权重矩阵的完整规格。

fixarray_like 的整数,可选

fix 参数与 ODR 类中的 ifixx 相同。它是一个整数数组,与数据 x 具有相同的形状,用于确定哪些输入观测被视为固定。可以使用长度为 m 的序列(输入观测的维度)来为所有观测固定一些维度。值为 0 表示固定观测,值 > 0 表示自由观测。

metadict,可选

自由格式的元数据字典。

注释

每个参数都附加到相同名称的实例成员。 xy 的结构在 Model 类的文档字符串中有描述。 如果 y 是整数,则 Data 实例仅可用于适应响应维度等于 y 指定值的隐式模型。

we 参数加权响应变量偏差对拟合的影响。 wd 参数加权输入变量偏差对拟合的影响。 为了方便处理多维输入和响应,这些参数的结构首先具有第 n 维轴。 这些参数大量使用 ODRPACK 的结构化参数功能,以方便和灵活地支持所有选项。 有关这些权重在算法中的使用方式的完整说明,请参见 ODRPACK 用户指南。 基本上,对于特定数据点的权重值更高会使该点处的偏差对拟合更具有破坏性。

方法

set_meta(**kwds) 使用关键字和数据更新元数据字典。

scipy.odr.RealData

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.RealData.html#scipy.odr.RealData

class scipy.odr.RealData(x, y=None, sx=None, sy=None, covx=None, covy=None, fix=None, meta=None)

数据,带有实际标准偏差和/或协方差的权重。

参数:

xarray_like

回归自变量的观测数据

yarray_like, optional

如果是类似数组,则是回归因变量的观测数据。标量输入意味着数据上的模型是隐含的。

sxarray_like, optional

x 的标准偏差。sxx 的标准偏差,通过将其平方的倒数来转换为权重。

syarray_like, optional

y 的标准偏差。syy 的标准偏差,通过将其平方的倒数来转换为权重。

covxarray_like, optional

covx 的协方差矩阵是 x 的协方差矩阵的数组,并通过对每个观测的协方差矩阵进行矩阵求逆来转换为权重。

covyarray_like, optional

covy 的协方差矩阵是一个数组,并通过对每个观测的协方差矩阵进行矩阵求逆来转换为权重。

fixarray_like, optional

参数和成员修复与 Data.fix 和 ODR.ifixx 相同:它是一个与 x 具有相同形状的整数数组,决定哪些输入观测被视为固定。可以使用长度为 m(输入观测的维度)的序列来固定所有观测的某些维度。值为 0 表示固定观测,值 > 0 表示自由观测。

metadict, optional

自由形式的元数据字典。

注释

权重 wdwe 从提供的值计算而来,计算方法如下:

sxsy 通过将其平方的倒数来转换为权重。例如,wd = 1./numpy.power(`sx`, 2)

covxcovy 是协方差矩阵的数组,并通过对每个观测的协方差矩阵进行矩阵求逆来转换为权重。例如,we[i] = numpy.linalg.inv(covy[i])

这些参数遵循与 wdwe 相同的结构化参数约定:sxsy 的性质只受限于它们的自然属性:sxsy 不能是三阶的,但 covxcovy 可以。

只设置 sxcovx(不能同时设置)。同时设置将引发异常。sycovy 亦如此。

方法

set_meta(**kwds) 使用关键词提供的关键词和数据更新元数据字典。

scipy.odr.Model

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.Model.html#scipy.odr.Model

class scipy.odr.Model(fcn, fjacb=None, fjacd=None, extra_args=None, estimate=None, implicit=0, meta=None)

Model 类存储了您希望拟合的函数的信息。

它至少存储函数本身,并可选地存储用于拟合期间计算的雅可比函数。此外,可以提供一个函数,该函数将根据给定的数据集可能提供合理的拟合参数起始值。

参数:

fcn函数

fcn(beta, x) –> y

fjacb函数

对 fcn 关于拟合参数 beta 的雅可比矩阵。

fjacb(beta, x) –> @f_i(x,B)/@B_j

fjacd函数

对 fcn 关于(可能是多维的)输入变量的雅可比矩阵。

fjacd(beta, x) –> @f_i(x,B)/@x_j

额外参数元组,可选

如果指定,extra_args 应为传递给 fcnfjacbfjacd 的额外参数元组。每个将通过 apply(fcn, (beta, x) + extra_args) 调用。

估计秩-1 的数组类型

提供从数据中估计的拟合参数。

estimate(data) –> estbeta

隐式布尔值

如果为 TRUE,指定模型是隐式的;即 fcn(beta, x) ~= 0,并且没有 y 数据进行拟合。

字典,可选

模型的自由格式元数据字典

笔记

请注意,fcnfjacbfjacd 操作于 NumPy 数组并返回 NumPy 数组。 estimate 对象接受 Data 类的实例。

这里是回调函数的参数和返回数组形状的规则:

x

如果输入数据是单维的,则 x 是一个秩为 1 的数组;即 x = array([1, 2, 3, ...]); x.shape = (n,) 如果输入数据是多维的,则 x 是一个秩为 2 的数组;即 x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n) 在所有情况下,它与传递给 odr 的输入数据数组具有相同的形状。 m 是输入数据的维数, n 是观测值的数量。

y

如果响应变量是单维的,则 y 是一个秩为 1 的数组,即 y = array([2, 4, ...]); y.shape = (n,)。如果响应变量是多维的,则 y 是一个秩为 2 的数组,即 y = array([[2, 4, ...], [3, 6, ...]]); y.shape = (q, n),其中 q 是响应变量的维数。

beta

长度为 p 的秩-1 数组,其中 p 是参数的数量;即 beta = array([B_1, B_2, ..., B_p])

fjacb

如果响应变量是多维的,则返回数组的形状是 (q, p, n),其中 fjacb(x,beta)[l,k,i] = d f_l(X,B)/d B_k 在第 i 个数据点处求值。如果 q == 1,则返回数组仅为秩 2 且形状为 (p, n)

fjacd

与 fjacb 类似,仅返回数组的形状为(q, m, n),使得fjacd(x,beta)[l,j,i] = d f_l(X,B)/d X_j在第 i 个数据点。如果q == 1,则返回数组的形状为(m, n)。如果m == 1,则形状为(q, n)。如果m == q == 1,则形状为(n,)

方法

set_meta(**kwds) 使用提供的关键词和数据更新元数据字典。

scipy.odr.ODR

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.ODR.html#scipy.odr.ODR

class scipy.odr.ODR(data, model, beta0=None, delta0=None, ifixb=None, ifixx=None, job=None, iprint=None, errfile=None, rptfile=None, ndigit=None, taufac=None, sstol=None, partol=None, maxit=None, stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None, overwrite=False)

ODR 类收集所有信息并协调主拟合程序的运行。

ODR 类的实例成员与初始化程序的参数名称相同。

参数:

dataData 类实例

Data 类的实例

modelModel 类实例

Model 类的实例

其他参数:

beta0秩-1 的 array_like

初始参数值的秩-1 序列。如果模型提供“estimate”函数来估算这些值,则可选。

delta0浮点数秩-1 的 array_like,可选

用于保存输入变量错误初始值的(双精度)浮点数数组。必须与 data.x 相同形状。

ifixb秩-1 整数的 array_like,可选

与 beta0 长度相同的整数序列,确定哪些参数被固定。值为 0 表示固定参数,值大于 0 表示参数自由。

ifixx与 data.x 形状相同的整数秩-1 array_like,可选

与 data.x 相同形状的整数数组,确定哪些输入观测值被视为固定。可以使用长度为 m(输入观测值的维数)的序列来为所有观测值固定一些维度。值为 0 表示固定观测值,值大于 0 表示自由观测值。

job整数,可选

告诉 ODRPACK 要执行的任务的整数。如果您非常需要在此设置该值,请参阅 ODRPACK 用户指南第 31 页。在初始化后使用 set_job 方法以获得更可读的界面。

iprint整数,可选

告诉 ODRPACK 要打印什么的整数。如果您非常需要在此设置该值,请参阅 ODRPACK 用户指南第 33-34 页。在初始化后使用 set_iprint 方法以获得更可读的界面。

errfile字符串,可选

用于打印 ODRPACK 错误的文件名。如果文件已存在,则会抛出错误。可以使用 overwrite 参数来防止这种情况。不要自行打开此文件!

rptfile字符串,可选

指定要打印 ODRPACK 摘要的文件名。如果文件已存在,则会抛出错误。可以使用 overwrite 参数来防止这种情况。不要自行打开此文件!

ndigit整数,可选

计算函数可靠位数的整数。

taufac浮点数,可选

指定初始信任域的浮点数。默认值为 1。初始信任域等于 taufac 乘以第一个计算的高斯-牛顿步长的长度。taufac 必须小于 1。

sstol浮点数,可选

指定收敛容差的浮点数,基于平方和的相对变化。默认值为 eps**(1/2),其中 eps 是使得在计算机上进行双精度计算时,1 + eps > 1 的最小值。sstol 必须小于 1。

partolfloat,可选

指定基于估计参数的相对变化的收敛容差的浮点数。默认值对于显式模型是 eps**(2/3),对于隐式模型是 eps**(1/3)。partol 必须小于 1。

maxitint,可选

指定要执行的最大迭代次数的整数。对于首次运行,maxit 是执行的总迭代次数,默认为 50。对于重新启动,maxit 是要执行的附加迭代次数,默认为 10。

stpbarray_like,可选

序列(len(stpb) == len(beta0)),用于相对步长大小以计算关于参数的有限差分导数。

stpd可选

数组(stpd.shape == data.x.shapestpd.shape == (m,)),用于相对步长大小以计算关于输入变量误差的有限差分导数。如果 stpd 是长度为 m 的秩-1 数组(输入变量的维度),则这些值将广播到所有观测值。

sclbarray_like,可选

序列(len(stpb) == len(beta0)),用于参数的缩放因子。这些缩放因子的目的是将所有参数缩放到大约统一的范围内。如果未指定此参数,则通常会自动计算适当的缩放因子。如果自动过程出现问题,请自行指定。

scldarray_like,可选

数组(scld.shape == data.x.shapescld.shape == (m,))用于输入变量中errors的缩放因子。如果未提供,则这些因子将自动计算。如果 scld.shape == (m,),则缩放因子将广播到所有观测值。

workndarray,可选

数组,用于保存双精度工作数据以供 ODRPACK 使用。在重新启动时,其取值为self.output.work

iworkndarray,可选

数组,用于保存整数值工作数据以供 ODRPACK 使用。在重新启动时,其取值为self.output.iwork

overwritebool,可选

如果为 True,则会覆盖errfilerptfile定义的输出文件。默认值为 False。

属性:

dataData

用于此拟合的数据

modelModel

用于拟合的模型

outputOutput

包含从 ODR.run()或 ODR.restart()调用返回的所有数据的 Output 类的实例

方法

restart 使用更多迭代次数重新启动运行。
run 使用给定的所有信息运行拟合程序,并使用full_output=1
set_iprint 设置 iprint 参数以打印计算报告。
set_job 以希望易于理解的方式设置“job”参数。

scipy.odr.Output

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.Output.html#scipy.odr.Output

class scipy.odr.Output(output)

Output 类存储了 ODR 运行的输出结果。

注释

接受一个初始化参数,即来自函数 odr 的返回值。如果 odr 设置为 full_output=1,则上述标注为“可选”的属性才会存在。

属性:

beta ndarray

估计参数值,形状为 (q,) 的数组。

sd_beta ndarray

估计参数的标准偏差,形状为 (p,)。

cov_beta ndarray

估计参数的协方差矩阵,形状为 (p,p)。注意 cov_beta 未按残差方差 res_var 缩放,而 sd_beta 是。这意味着 np.sqrt(np.diag(output.cov_beta * output.res_var))output.sd_beta 得到的结果相同。

delta ndarray,可选

x 相同形状的输入变量估计误差数组。

eps ndarray,可选

y 相同形状的响应变量估计误差数组。

xplus ndarray,可选

x + delta 的数组。

y ndarray,可选

数组 y = fcn(x + delta)

res_var 浮点数,可选

残差方差。

sum_square 浮点数,可选

误差平方和。

sum_square_delta 浮点数,可选

误差 δ 的平方和。

sum_square_eps 浮点数,可选

误差 eps 的平方和。

inv_condnum 浮点数,可选

条件数的倒数(参见 ODRPACK UG 第 77 页)。

rel_error 浮点数,可选

在 fcn 内计算的函数值相对误差。

work ndarray,可选

最终工作数组。

work_ind 字典,可选

用于提取数值的 work 的索引(参见 ODRPACK UG 第 83 页)。

info 整数,可选

ODRPACK 返回的原因(参见 ODRPACK UG 第 38 页)。

stopreason 字符串列表,可选

info 被解释成英文。

方法

pprint() 精美打印重要结果。

scipy.odr.odr

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/odr-function.html#scipy.odr.odr

scipy.odr.odr(fcn, beta0, y, x, we=None, wd=None, fjacb=None, fjacd=None, extra_args=None, ifixx=None, ifixb=None, job=0, iprint=0, errfile=None, rptfile=None, ndigit=0, taufac=0.0, sstol=-1.0, partol=-1.0, maxit=-1, stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None, full_output=0)

ODR 的底层函数。

另请参阅

ODR

ODR 类收集所有信息并协调主要拟合例程的运行。

Model

Model 类存储关于您希望拟合的函数的信息。

Data

要拟合的数据。

RealData

数据与实际标准偏差和/或协方差的权重。

注释

这是一个执行与 ODR, Model, 和 Data 类相同操作的函数。此函数的参数在类文档中有解释。

scipy.odr.OdrWarning

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.OdrWarning.html#scipy.odr.OdrWarning

exception scipy.odr.OdrWarning

警告表明传递给 ODR 的数据在传递给 'odr' 时会导致问题,用户应当注意。

with_traceback()

Exception.with_traceback(tb) – 设置 self.__traceback__ 为 tb 并返回 self。

scipy.odr.OdrError

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.OdrError.html#scipy.odr.OdrError

exception scipy.odr.OdrError

表示拟合过程中出现的异常。

当拟合过程中发生错误时,odr 会引发此异常。

with_traceback()

Exception.with_traceback(tb) – 设置 self.traceback 为 tb 并返回 self。

scipy.odr.OdrStop

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.OdrStop.html#scipy.odr.OdrStop

exception scipy.odr.OdrStop

异常停止拟合。

你可以在你的目标函数中引发这个异常,告诉odr停止拟合。

with_traceback()

Exception.with_traceback(tb) – 设置self.__traceback__tb并返回self

scipy.odr.polynomial

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.polynomial.html#scipy.odr.polynomial

scipy.odr.polynomial(order)

工厂函数用于创建一个通用的多项式模型。

参数:

order整数或序列

如果是一个整数,它将成为要拟合的多项式的阶数。如果是一个数字序列,那么这些数字将是多项式中的显式幂。始终包含一个常数项(幂为 0),因此不要包含 0。因此,polynomial(n)等同于 polynomial(range(1, n+1))。

返回:

polynomial模型实例

模型实例。

示例

我们可以使用正交距离回归(ODR)来拟合输入数据,使用一个多项式模型:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy import odr
>>> x = np.linspace(0.0, 5.0)
>>> y = np.sin(x)
>>> poly_model = odr.polynomial(3)  # using third order polynomial model
>>> data = odr.Data(x, y)
>>> odr_obj = odr.ODR(data, poly_model)
>>> output = odr_obj.run()  # running ODR fitting
>>> poly = np.poly1d(output.beta[::-1])
>>> poly_y = poly(x)
>>> plt.plot(x, y, label="input data")
>>> plt.plot(x, poly_y, label="polynomial ODR")
>>> plt.legend()
>>> plt.show() 

../../_images/scipy-odr-polynomial-1.png

scipy.odr.exponential

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.exponential.html#scipy.odr.exponential

scipy.odr.exponential = <scipy.odr._models._ExponentialModel object>

指数模型

这个模型由公式 (y=\beta_0 + e^{\beta_1 x}) 定义。

示例

我们可以使用指数模型计算正交距离回归:

>>> from scipy import odr
>>> import numpy as np
>>> x = np.linspace(0.0, 5.0)
>>> y = -10.0 + np.exp(0.5*x)
>>> data = odr.Data(x, y)
>>> odr_obj = odr.ODR(data, odr.exponential)
>>> output = odr_obj.run()
>>> print(output.beta)
[-10\.    0.5] 

scipy.odr.multilinear

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.multilinear.html#scipy.odr.multilinear

scipy.odr.multilinear = <scipy.odr._models._MultilinearModel object>

任意维线性模型

这个模型的定义是 (y=\beta_0 + \sum_{i=1}^m \beta_i x_i)

示例

我们可以用任意维线性模型计算正交距离回归:

>>> from scipy import odr
>>> import numpy as np
>>> x = np.linspace(0.0, 5.0)
>>> y = 10.0 + 5.0 * x
>>> data = odr.Data(x, y)
>>> odr_obj = odr.ODR(data, odr.multilinear)
>>> output = odr_obj.run()
>>> print(output.beta)
[10\.  5.] 

scipy.odr.unilinear

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.unilinear.html#scipy.odr.unilinear

scipy.odr.unilinear = <scipy.odr._models._UnilinearModel object>

单变量线性模型

这个模型由 (y = \beta_0 x + \beta_1) 定义

示例

我们可以用单线性模型计算正交距离回归:

>>> from scipy import odr
>>> import numpy as np
>>> x = np.linspace(0.0, 5.0)
>>> y = 1.0 * x + 2.0
>>> data = odr.Data(x, y)
>>> odr_obj = odr.ODR(data, odr.unilinear)
>>> output = odr_obj.run()
>>> print(output.beta)
[1\. 2.] 

scipy.odr.quadratic

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.odr.quadratic.html#scipy.odr.quadratic

scipy.odr.quadratic = <scipy.odr._models._QuadraticModel object>

二次模型

此模型由 (y = \beta_0 x² + \beta_1 x + \beta_2) 定义

示例

我们可以使用二次模型计算正交距离回归:

>>> from scipy import odr
>>> import numpy as np
>>> x = np.linspace(0.0, 5.0)
>>> y = 1.0 * x ** 2 + 2.0 * x + 3.0
>>> data = odr.Data(x, y)
>>> odr_obj = odr.ODR(data, odr.quadratic)
>>> output = odr_obj.run()
>>> print(output.beta)
[1\. 2\. 3.] 

优化和根查找(scipy.optimize

原文链接:docs.scipy.org/doc/scipy-1.12.0/reference/optimize.html

SciPy optimize 提供了用于最小化(或最大化)目标函数的函数,可能受约束条件限制。它包括非线性问题的求解器(支持局部和全局优化算法)、线性规划、约束和非线性最小二乘法、根查找和曲线拟合。

不同求解器共享的常见函数和对象包括:

show_options([solver, method, disp]) 显示优化求解器的附加选项文档。
OptimizeResult 表示优化结果。
OptimizeWarning

优化

标量函数优化

minimize_scalar(fun[, bracket, bounds, ...]) 对一维标量函数进行局部最小化。

minimize_scalar 函数支持以下方法:

  • minimize_scalar(method=’brent’)

  • minimize_scalar(method=’bounded’)

  • minimize_scalar(method=’golden’)

本地(多变量)优化

minimize(fun, x0[, args, method, jac, hess, ...]) 对一个或多个变量的标量函数进行最小化。

minimize 函数支持以下方法:

  • minimize(method=’Nelder-Mead’)

  • minimize(method=’Powell’)

  • minimize(method=’CG’)

  • minimize(method=’BFGS’)

  • minimize(method=’Newton-CG’)

  • minimize(method=’L-BFGS-B’)

  • minimize(method=’TNC’)

  • minimize(method=’COBYLA’)

  • minimize(method=’SLSQP’)

  • minimize(method=’trust-constr’)

  • minimize(method=’dogleg’)

  • minimize(method=’trust-ncg’)

  • minimize(method=’trust-krylov’)

  • minimize(method=’trust-exact’)

约束以单个对象或来自以下类的对象列表形式传递给minimize函数:

NonlinearConstraint(fun, lb, ub[, jac, ...]) 变量的非线性约束。
LinearConstraint(A[, lb, ub, keep_feasible]) 变量的线性约束。

简单的边界约束分别处理,并且有一个专门的类:

Bounds([lb, ub, keep_feasible]) 变量的边界约束。

实现HessianUpdateStrategy接口的拟牛顿策略可用于在minimize函数中近似黑塞矩阵(仅适用于“trust-constr”方法)。实现此接口的可用拟牛顿方法包括:

BFGS([exception_strategy, min_curvature, ...]) BFGS(Broyden-Fletcher-Goldfarb-Shanno)海森更新策略。
SR1([min_denominator, init_scale]) 对称秩-1 海森更新策略。

全局优化

basinhopping(func, x0[, niter, T, stepsize, ...]) 使用盆地跳跃算法找到函数的全局最小值。
brute(func, ranges[, args, Ns, full_output, ...]) 通过蛮力法在给定范围内最小化函数。
differential_evolution(func, bounds[, args, ...]) 多元函数的全局最小值。
shgo(func, bounds[, args, constraints, n, ...]) 使用 SHG 优化找到函数的全局最小值。
dual_annealing(func, bounds[, args, ...]) 使用双退火法找到函数的全局最小值。
direct(func, bounds, *[, args, eps, maxfun, ...]) 使用 DIRECT 算法寻找函数的全局最小值。

最小二乘和曲线拟合

非线性最小二乘

least_squares(fun, x0[, jac, bounds, ...]) 解决带有变量边界的非线性最小二乘问题。

线性最小二乘

nnls(A, b[, maxiter, atol]) 解决 `argmin_x Ax - b _2x>=0`。
lsq_linear(A, b[, bounds, method, tol, ...]) 解决带有变量边界的线性最小二乘问题。
isotonic_regression(y, *[, weights, increasing]) 非参数等距回归。

曲线拟合

curve_fit(f, xdata, ydata[, p0, sigma, ...]) 使用非线性最小二乘拟合函数 f 到数据。

根查找

标量函数

root_scalar(f[, args, method, bracket, ...]) 寻找标量函数的根。
brentq(f, a, b[, args, xtol, rtol, maxiter, ...]) 使用 Brent 方法在一个区间内寻找函数的根。
brenth(f, a, b[, args, xtol, rtol, maxiter, ...]) 使用 Brent 方法及双曲线外推在一个区间内寻找函数的根。
ridder(f, a, b[, args, xtol, rtol, maxiter, ...]) 使用 Ridder 方法在一个区间内寻找函数的根。
bisect(f, a, b[, args, xtol, rtol, maxiter, ...]) 使用二分法在一个区间内寻找函数的根。
newton(func, x0[, fprime, args, tol, ...]) 使用牛顿-拉弗森(或割线或哈雷)方法寻找实数或复数函数的根。
toms748(f, a, b[, args, k, xtol, rtol, ...]) 使用 TOMS 算法 748 方法寻找根。
RootResults(root, iterations, ...) 表示根查找结果。

root_scalar 函数支持以下方法:

  • root_scalar(method=’brentq’)

  • root_scalar(method=’brenth’)

  • root_scalar(method=’bisect’)

  • root_scalar(method=’ridder’)

  • root_scalar(method=’newton’)

  • root_scalar(method=’toms748’)

  • root_scalar(method=’secant’)

  • root_scalar(method=’halley’)

下表列出了情况及适当的方法,以及每次迭代(和每次函数评估)的渐近收敛率,以便成功收敛到简单根(*)。二分法是最慢的,每次函数评估增加一位有效数字,但保证收敛。其他括号法(最终)每次函数评估增加大约 50%的准确位数。基于导数的方法,都建立在newton上,如果初始值接近根,可以相当快速地收敛。它们也可应用于在复平面(的子集上)定义的函数。

函数域 是否括号化? 是否有导数? 求解器 收敛性
fprime fprime2 是否保证? 收敛率(*)
--- --- --- ---
R N/A N/A
  • 二分法

  • brentq

  • brenth

  • ridder

  • toms748

|

|

  • 1 “线性”

  • =1, <= 1.62

  • =1, <= 1.62

  • 2.0 (1.41)

  • 2.7 (1.65)

|

RC 切线法 1.62 (1.62)
RC 牛顿法 2.00 (1.41)
RC 亥姆法 3.00 (1.44)

另见

scipy.optimize.cython_optimize – Typed Cython 版本的根查找函数

寻找不动点:

fixed_point(func, x0[, args, xtol, maxiter, ...]) 查找函数的不动点。

多维的

root(fun, x0[, args, method, jac, tol, ...]) 查找向量函数的根。

root 函数支持以下方法:

  • root(method=’hybr’)

  • root(method=’lm’)

  • root(method=’broyden1’)

  • root(method=’broyden2’)

  • root(method=’anderson’)

  • root(method=’linearmixing’)

  • root(method=’diagbroyden’)

  • root(method=’excitingmixing’)

  • root(method=’krylov’)

  • root(method=’df-sane’)

线性规划 / MILP

milp(c, *[, integrality, bounds, ...]) 混合整数线性规划
linprog(c[, A_ub, b_ub, A_eq, b_eq, bounds, ...]) 线性规划:最小化线性目标函数,满足线性等式和不等式约束。

linprog 函数支持以下方法:

  • linprog(method=’simplex’)

  • linprog(method=’interior-point’)

  • linprog(method=’revised simplex’)

  • linprog(method=’highs-ipm’)

  • linprog(method=’highs-ds’)

  • linprog(method=’highs’)

简单法、内点法和修订单纯法方法支持回调函数,例如:

linprog_verbose_callback(res) 演示 linprog 回调接口的样本回调函数。

分配问题

linear_sum_assignment 解决线性求和分配问题。
quadratic_assignment(A, B[, method, options]) 近似解决二次分配问题和图匹配问题。

quadratic_assignment 函数支持以下方法:

  • quadratic_assignment(method=’faq’)

  • quadratic_assignment(method=’2opt’)

实用工具

Finite-difference approximation

approx_fprime(xk, f[, epsilon]) 标量或向量值函数的有限差分近似导数。
check_grad(func, grad, x0, *args[, epsilon, ...]) 通过将其与梯度的(前向)有限差分近似比较,检查梯度函数的正确性。

线搜索:

bracket(func[, xa, xb, args, grow_limit, ...]) 定位函数最小值的区间。
line_search(f, myfprime, xk, pk[, gfk, ...]) 寻找满足强 Wolfe 条件的 alpha。

Hessian 近似:

LbfgsInvHessProduct(*args, **kwargs) L-BFGS 近似逆 Hessian 的线性算子。
HessianUpdateStrategy() 实现 Hessian 更新策略的接口。

基准问题:

rosen(x) Rosenbrock 函数。
rosen_der(x) Rosenbrock 函数的导数(即梯度)。
rosen_hess(x) Rosenbrock 函数的 Hessian 矩阵。
rosen_hess_prod(x, p) Rosenbrock 函数的 Hessian 矩阵与向量的乘积。

遗留函数:

下面的函数不建议在新脚本中使用;所有这些方法都可以通过提供的更新、更一致的接口访问。

优化:

通用多元方法:

fmin(func, x0[, args, xtol, ftol, maxiter, ...]) 使用下降单纯形算法最小化函数。
fmin_powell(func, x0[, args, xtol, ftol, ...]) 使用修改后的 Powell 方法最小化函数。
fmin_cg(f, x0[, fprime, args, gtol, norm, ...]) 使用非线性共轭梯度算法最小化函数。
fmin_bfgs(f, x0[, fprime, args, gtol, norm, ...]) 使用 BFGS 算法最小化函数。
fmin_ncg(f, x0, fprime[, fhess_p, fhess, ...]) 使用牛顿-CG 方法无约束最小化函数。

约束多元方法:

fmin_l_bfgs_b(func, x0[, fprime, args, ...]) 使用 L-BFGS-B 算法最小化函数 func。
fmin_tnc(func, x0[, fprime, args, ...]) 使用截断牛顿算法最小化受界限约束的变量函数,并使用梯度信息。
fmin_cobyla(func, x0, cons[, args, ...]) 使用线性逼近约束优化(COBYLA)方法最小化函数。
fmin_slsqp(func, x0[, eqcons, f_eqcons, ...]) 使用顺序最小二乘规划(SLSQP)方法最小化函数。

单变量(标量)最小化方法:

fminbound(func, x1, x2[, args, xtol, ...]) 标量函数的有界最小化。
brent(func[, args, brack, tol, full_output, ...]) 给定一个变量函数和可能的区间,返回函数的局部最小化器,精确到 tol 的分数精度。
golden(func[, args, brack, tol, ...]) 使用黄金分割法返回单变量函数的最小化器。

最小二乘

leastsq(func, x0[, args, Dfun, full_output, ...]) 最小化一组方程的平方和。

根查找:

一般非线性求解器:

fsolve(func, x0[, args, fprime, ...]) 找到函数的根。
broyden1(F, xin[, iter, alpha, ...]) 使用布罗伊登第一雅可比逼近找到函数的根。
broyden2(F, xin[, iter, alpha, ...]) 使用布罗伊登第二雅可比逼近找到函数的根。

大规模非线性求解器:

newton_krylov(F, xin[, iter, rdiff, method, ...]) 使用 Krylov 逼近方法求解函数的根,用于逆雅可比矩阵。
anderson(F, xin[, iter, alpha, w0, M, ...]) 使用(扩展的)安德森混合方法寻找函数的根。
BroydenFirst([alpha, reduction_method, max_rank]) 使用 Broyden 第一雅可比逼近方法寻找函数的根。
InverseJacobian(jacobian)

属性:

|

KrylovJacobian([rdiff, method, ...]) 使用 Krylov 逼近方法求解函数的根,用于逆雅可比矩阵。

简单迭代求解器:

excitingmixing(F, xin[, iter, alpha, ...]) 使用调整的对角雅可比逼近方法寻找函数的根。
linearmixing(F, xin[, iter, alpha, verbose, ...]) 使用标量雅可比逼近方法寻找函数的根。
diagbroyden(F, xin[, iter, alpha, verbose, ...]) 使用对角 Broyden 雅可比逼近方法寻找函数的根。

scipy.optimize.show_options

原文:docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.optimize.show_options.html#scipy.optimize.show_options

scipy.optimize.show_options(solver=None, method=None, disp=True)

显示优化求解器附加选项的文档。

这些是可以通过options字典提供的特定于方法的选项。

参数:

solverstr

优化求解器的类型。可为‘minimize’、‘minimize_scalar’、‘root’、‘root_scalar’、‘linprog’或‘quadratic_assignment’之一。

methodstr,可选

如果未指定,则显示指定求解器的所有方法。否则,仅显示指定方法的选项。有效值对应于相应求解器的方法名称(例如,‘minimize’的‘BFGS’)。

dispbool,可选

是否打印结果而非返回结果。

返回:

文本

disp=True时为 None,否则为文本字符串(disp=False)。

注意

求解器特定的方法包括:

scipy.optimize.minimize

  • Nelder-Mead

  • Powell

  • CG

  • BFGS

  • Newton-CG

  • L-BFGS-B

  • TNC

  • COBYLA

  • SLSQP

  • dogleg

  • trust-ncg

scipy.optimize.root

  • hybr

  • lm

  • broyden1

  • broyden2

  • anderson

  • linearmixing

  • diagbroyden

  • excitingmixing

  • krylov

  • df-sane

scipy.optimize.minimize_scalar

  • brent

  • golden

  • bounded

scipy.optimize.root_scalar

  • bisect

  • brentq

  • brenth

  • ridder

  • toms748

  • newton

  • secant

  • halley

scipy.optimize.linprog

  • simplex

  • interior-point

  • revised simplex

  • highs

  • highs-ds

  • highs-ipm

scipy.optimize.quadratic_assignment

  • faq

  • 2opt

Examples

我们可以在标准输出中打印求解器的文档:

>>> from scipy.optimize import show_options
>>> show_options(solver="minimize")
... 

可以指定使用的方法:

>>> show_options(solver="minimize", method="Nelder-Mead")
... 

我们也可以将文档作为字符串获取:

>>> show_options(solver="minimize", method="Nelder-Mead", disp=False)
Minimization of scalar function of one or more variables using the ... 
posted @ 2024-06-27 17:07  绝不原创的飞龙  阅读(13)  评论(0编辑  收藏  举报