我正在尝试在python中开发一个快速算法,用于在图像中找到峰值,然后找到这些峰值的质心。我使用scipy.ndimage.label和ndimage.find_objects编写了以下代码来定位对象。这似乎是代码中的瓶颈,在500x500图像中定位20个对象大约需要7毫秒。我想将其扩展到更大的(2000x2000)图像,但随后时间增加到几乎100毫秒。所以,我想知道是否有更快的选择。
这是我到目前为止的代码,它有效,但速度很慢。首先,我使用一些高斯峰来模拟我的数据。这部分很慢,但实际上我将使用真实数据,所以我不太关心加速那部分。我希望能够很快找到峰值。
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage
import matplotlib.patches
plt.figure(figsize=(10,10))
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(223)
ax4 = plt.subplot(224)
size = 500 #width and height of image in pixels
peak_height = 100 # define the height of the peaks
num_peaks = 20
noise_level = 50
threshold = 60
np.random.seed(3)
#set up a simple, blank image (Z)
x = np.linspace(0,size,size)
y = np.linspace(0,size,size)
X,Y = np.meshgrid(x,y)
Z = X*0
#now add some peaks
def gaussian(X,Y,xo,yo,amp=100,sigmax=4,sigmay=4):
return amp*np.exp(-(X-xo)**2/(2*sigmax**2) - (Y-yo)**2/(2*sigmay**2))
for xo,yo in size*np.random.rand(num_peaks,2):
widthx = 5 + np.random.randn(1)
widthy = 5 + np.random.randn(1)
Z += gaussian(X,Y,xo,yo,amp=peak_height,sigmax=widthx,sigmay=widthy)
#of course, add some noise:
Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=5)
Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=1)
t = time.time() #Start timing the peak-finding algorithm
#Set everything below the threshold to zero:
Z_thresh = np.copy(Z)
Z_thresh[Z_thresh<threshold] = 0
print 'Time after thresholding: %.5f seconds'%(time.time()-t)
#now find the objects
labeled_image, number_of_objects = scipy.ndimage.label(Z_thresh)
print 'Time after labeling: %.5f seconds'%(time.time()-t)
peak_slices = scipy.ndimage.find_objects(labeled_image)
print 'Time after finding objects: %.5f seconds'%(time.time()-t)
def centroid(data):
h,w = np.shape(data)
x = np.arange(0,w)
y = np.arange(0,h)
X,Y = np.meshgrid(x,y)
cx = np.sum(X*data)/np.sum(data)
cy = np.sum(Y*data)/np.sum(data)
return cx,cy
centroids = []
for peak_slice in peak_slices:
dy,dx = peak_slice
x,y = dx.start, dy.start
cx,cy = centroid(Z_thresh[peak_slice])
centroids.append((x+cx,y+cy))
print 'Total time: %.5f seconds\n'%(time.time()-t)
###########################################
#Now make the plots:
for ax in (ax1,ax2,ax3,ax4): ax.clear()
ax1.set_title('Original image')
ax1.imshow(Z,origin='lower')
ax2.set_title('Thresholded image')
ax2.imshow(Z_thresh,origin='lower')
ax3.set_title('Labeled image')
ax3.imshow(labeled_image,origin='lower') #display the color-coded regions
for peak_slice in peak_slices: #Draw some rectangles around the objects
dy,dx = peak_slice
xy = (dx.start, dy.start)
width = (dx.stop - dx.start + 1)
height = (dy.stop - dy.start + 1)
rect = matplotlib.patches.Rectangle(xy,width,height,fc='none',ec='red')
ax3.add_patch(rect,)
ax4.set_title('Centroids on original image')
ax4.imshow(Z,origin='lower')
for x,y in centroids:
ax4.plot(x,y,'kx',ms=10)
ax4.set_xlim(0,size)
ax4.set_ylim(0,size)
plt.tight_layout
plt.show()
size = 500的结果:
编辑:如果峰的数量很大(~100)并且图像的尺寸很小,则瓶颈实际上是质心部分。因此,也许这部分的速度也需要优化。
答案 0 :(得分:8)
找到峰值的方法(简单的阈值处理)当然对阈值的选择非常敏感:设置得太低,你会“检测”非峰值的东西;设置得太高,你会错过有效的峰值。
有更强大的替代方案,可以检测图像强度中的所有局部最大值,无论其强度值如何。我首选的是使用小(5x5或7x7)结构元素进行扩张,然后找到原始图像及其扩张版本具有相同值的像素。这是有效的,因为根据定义,膨胀(x,y,E,img)= {以像素(x,y)为中心的E中的img的最大值},因此膨胀(x,y,E,img)= img(x ,y)每当(x,y)是E标度的局部最大值的位置时。
通过快速实现形态学运算符(例如OpenCV中的那个),这个算法在空间和时间上都是线性的图像大小(一个额外的图像大小的缓冲区用于扩张图像,一个通过两个)。在紧要关头,它也可以在线实现,无需额外的缓冲区和一点额外的复杂性,而且它仍然是线性时间。
为了在存在盐和胡椒或类似噪音的情况下进一步强制它,这可能会引入许多假最大值,你可以应用该方法两次,使用不同大小的结构元素(例如,5x5和7x7),然后保留只有稳定的最大值,其中稳定性可以通过最大值的不变位置来定义,或者通过不改变多于一个像素的位置等来定义。此外,当您有理由相信它们是由于噪声。一种有效的方法是首先检测上面的所有局部最大值,按高度降序排序,然后沿着排序列表向下,如果它们在图像中的值没有改变则保留它们,如果它们被保留,则设置为将它们的(2d + 1)x(2d + 1)邻域中的所有像素归零,其中d是您愿意容忍的附近最大值之间的最小距离。
答案 1 :(得分:5)
如果您有许多峰值,则使用scipy.ndimage.center_of_mass
会更快。您可以从peak_slices
的定义开始替换代码,直到打印总时间,并使用以下两行:
centroids = scipy.ndimage.center_of_mass(Z_thresh, labeled_image,
np.arange(1, number_of_objects + 1))
centroids = [(j, i) for i, j in centroids]
对于num_peaks = 20
,这比您的方法运行大约3倍 ,但对于num_peaks = 100
,它运行大约10倍更快。因此,您最好的选择取决于您的实际数据。
答案 2 :(得分:2)
另一种方法是避免所有sum()
,meshgrid()
和其他内容。用直线代数替换所有东西。
>>> def centroid2(data):
h,w=data.shape
x=np.arange(h)
y=np.arange(w)
x1=np.ones((1,h))
y1=np.ones((w,1))
return ((np.dot(np.dot(x1, data), y))/(np.dot(np.dot(x1, data), y1)),
(np.dot(np.dot(x, data), y1))/(np.dot(np.dot(x1, data), y1)))
#be careful, it returns two arrays
这也可以用于更高的维度。 60%的加速比与centroid()
答案 3 :(得分:0)
以下质心计算比两者都快,特别是对于大数据:
def centroidnp(data):
h,w = data.shape
x = np.arange(w)
y = np.arange(h)
vx = data.sum(axis=0)
vx /= vx.sum()
vy = data.sum(axis=1)
vy /= vy.sum()
return np.dot(vx,x),np.dot(vy,y)