如何隔离高度受限的 3d 表面区域?
How to isolate regions of a 3d surface with a constrained height?
我有一个 2 变量离散函数,通过以下代码行以元组的形式表示:
hist_values, hist_x, hist_y = np.histogram2d()
您可以想到 非光滑 3d 表面,其中 hist_values 是表面在网格处的高度边缘坐标为 (hist_x, hist_y)。
现在,我想收集那些 hist_values 高于某个 阈值 水平的网格。
您可以简单地将 hist_values
与 threshold
进行比较,这将为您提供一个作为 bool
数组的掩码,可用于切片,例如:
import numpy as np
# prepare random input
arr1 = np.random.randint(0, 100, 1000)
arr2 = np.random.randint(0, 100, 1000)
# compute 2D histogram
hist_values, hist_x, hist_y = np.histogram2d(arr1, arr2)
mask = hist_values > threshold # the array of `bool`
hist_values[mask] # only the values above `threshold`
当然,然后将这些值收集在一个展平的数组中。
或者,您也可以使用 mask
实例化一个 masked-array 对象(使用 numpy.ma
,请参阅文档了解更多信息)。
如果您在发生这种情况的坐标之后,您应该使用 numpy.where()
。
# i0 and i1 contain the indices in the 0 and 1 dimensions respectively
i0, i1 = np.where(hist_values > threshold)
# e.g. this will give you the first value satisfying your condition
hist_values[i0[0], i1[0]]
对于 hist_x
和 hist_y
的对应值,您应该注意这些是 bin 的边界,而不是例如 mid-values,因此您可以求助于到它的下限或上限。
# lower edges of `hist_x` and `hist_y` respectively...
hist_x[i0]
hist_y[i1]
# ... and upper edges
hist_x[i0 + 1]
hist_y[i1 + 1]
我有一个 2 变量离散函数,通过以下代码行以元组的形式表示:
hist_values, hist_x, hist_y = np.histogram2d()
您可以想到 非光滑 3d 表面,其中 hist_values 是表面在网格处的高度边缘坐标为 (hist_x, hist_y)。
现在,我想收集那些 hist_values 高于某个 阈值 水平的网格。
您可以简单地将 hist_values
与 threshold
进行比较,这将为您提供一个作为 bool
数组的掩码,可用于切片,例如:
import numpy as np
# prepare random input
arr1 = np.random.randint(0, 100, 1000)
arr2 = np.random.randint(0, 100, 1000)
# compute 2D histogram
hist_values, hist_x, hist_y = np.histogram2d(arr1, arr2)
mask = hist_values > threshold # the array of `bool`
hist_values[mask] # only the values above `threshold`
当然,然后将这些值收集在一个展平的数组中。
或者,您也可以使用 mask
实例化一个 masked-array 对象(使用 numpy.ma
,请参阅文档了解更多信息)。
如果您在发生这种情况的坐标之后,您应该使用 numpy.where()
。
# i0 and i1 contain the indices in the 0 and 1 dimensions respectively
i0, i1 = np.where(hist_values > threshold)
# e.g. this will give you the first value satisfying your condition
hist_values[i0[0], i1[0]]
对于 hist_x
和 hist_y
的对应值,您应该注意这些是 bin 的边界,而不是例如 mid-values,因此您可以求助于到它的下限或上限。
# lower edges of `hist_x` and `hist_y` respectively...
hist_x[i0]
hist_y[i1]
# ... and upper edges
hist_x[i0 + 1]
hist_y[i1 + 1]