在Python中执行局部标准差

2024-06-16 13:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获得的地方标准偏差的每一个像素图像。这个也就是说,对于每个像素,我要计算它的值和它的邻域的标准差。我用了this库 我开发了以下代码:

def stdd(image, N):
    width = image.shape[0]
    heigth = image.shape[1]
    desv = np.zeros((width,heigth))
    for i in range (width):
        for j in range (heigth):
            if i < N :
                mini = 0
            else :
                mini = i - N
            if (i+N) > width :
                maxi = width
            else : 
                maxi = N + i
            if j < N :
                minj = 0
            else :
                minj = j - N
            if (j+N) > heigth :
                maxj = heigth
            else : 
                maxj = N + j
            window = image[mini:maxi,minj:maxj]
            desv[i,j] = window.std()
    return desv

其中N是每个像素的局部矩阵的大小,图像是a数字阵列()图像 我的代码的问题是它需要太多的处理,我想知道是否有一个已经定义的函数来优化它


Tags: 代码图像imageforif像素widthelse
1条回答
网友
1楼 · 发布于 2024-06-16 13:46:36

您可以使用the following identity一次计算所有标准差: Var(X) = E(X^2) - E(X)^2

要获得局部邻域中所有元素的和,可以使用convolution。在

def std_convoluted(image, N):
    im = np.array(image, dtype=float)
    im2 = im**2
    ones = np.ones(im.shape)

    kernel = np.ones((2*N+1, 2*N+1))
    s = scipy.signal.convolve2d(im, kernel, mode="same")
    s2 = scipy.signal.convolve2d(im2, kernel, mode="same")
    ns = scipy.signal.convolve2d(ones, kernel, mode="same")

    return np.sqrt((s2 - s**2 / ns) / ns)

警告:请注意,虽然结果在一些测试图像上看起来不错,但此函数返回的结果与代码不同,但我现在无法发现错误。(如果有人看到它:您是否愿意指出或编辑它?)在

不管怎样,这个想法仍然有效,运行速度快得多(在我的电脑上大约是10的倍数)。在

相关问题 更多 >