嗨,我正在尝试在3D numpy数组中找到局部最大值,但是我似乎找不到一种简单的方法来使用numpy,scipy或其他任何方法。
目前,我使用scipy.signal.argrelexrema
实现了它。但是处理大型数组很长,并且只能在分离的轴上工作。
import numpy as np
from scipy.signal import argrelextrema
def local_maxima_3D(data, order=1):
"""Detects local maxima in a 3D array
Parameters
---------
data : 3d ndarray
order : int
How many points on each side to use for the comparison
Returns
-------
coords : ndarray
coordinates of the local maxima
values : ndarray
values of the local maxima
"""
# Coordinates of local maxima along each axis
peaks0 = np.array(argrelextrema(data, np.greater, axis=0, order=order))
peaks1 = np.array(argrelextrema(data, np.greater, axis=1, order=order))
peaks2 = np.array(argrelextrema(data, np.greater, axis=2, order=order))
# Stack all coordinates
stacked = np.vstack((peaks0.transpose(), peaks1.transpose(),
peaks2.transpose()))
# We keep coordinates that appear three times (once for each axis)
elements, counts = np.unique(stacked, axis=0, return_counts=True)
coords = elements[np.where(counts == 3)[0]]
# Compute values at filtered coordinates
values = data[coords[:, 0], coords[:, 1], coords[:, 2]]
return coords, values
我知道此解决方案远非最佳解决方案,仅适用于order = 1。有没有更好的方法可以在python的3D数组中找到局部最大值?
编辑:
我现在使用以下方法,它实际上要快得多,并且在order> 1时也可以使用:
import numpy as np
from scipy import ndimage as ndi
def local_maxima_3D(data, order=1):
"""Detects local maxima in a 3D array
Parameters
---------
data : 3d ndarray
order : int
How many points on each side to use for the comparison
Returns
-------
coords : ndarray
coordinates of the local maxima
values : ndarray
values of the local maxima
"""
size = 1 + 2 * order
footprint = np.ones((size, size, size))
footprint[order, order, order] = 0
filtered = ndi.maximum_filter(data, footprint=footprint)
mask_local_maxima = data > filtered
coords = np.asarray(np.where(mask_local_maxima)).T
values = data[mask_local_maxima]
return coords, values
答案 0 :(得分:0)
假设您对数据进行某种统计表示,则您应该能够像这样执行3D局部最大值。希望这能回答您的问题。
import numpy as np
import scipy.ndimage as ndimage
img = np.random.normal(size=(100, 256, 256))
# Get local maximum values of desired neighborhood
# I'll be looking in a 5x5x5 area
img2 = ndimage.maximum_filter(img, size=(5, 5, 5))
# Threshold the image to find locations of interest
# I'm assuming 6 standard deviations above the mean for the threshold
img_thresh = img2.mean() + img2.std() * 6
# Since we're looking for maxima find areas greater than img_thresh
labels, num_labels = ndimage.label(img2 > img_thresh)
# Get the positions of the maxima
coords = ndimage.measurements.center_of_mass(img, labels=labels, index=np.arange(1, num_labels + 1))
# Get the maximum value in the labels
values = ndimage.measurements.maximum(img, labels=labels, index=np.arange(1, num_labels + 1))