沿着圆形路径计算图像像素之和

3

我有一张图片,想要沿着一个圆形路径计算线积分(总和)。我的思路是:

  1. 计算要累加的圆形路径
  2. 基于路径对图像进行掩膜处理,除了与路径重合的像素外,其余所有像素都被清零。
  3. 对所有图像像素求和

我目前卡在第一步和第二步之间,无法想出如何在与图像相同的网格上生成一个圆形。

代码如下:

from scipy.stats import multivariate_normal

radius = 2

# Draw arbitrary image 
x, y = np.mgrid[-5:5:.1, -5:5:.1]
img = multivariate_normal.pdf(np.dstack((x, y)), cov=[[1, 0.7], [0.7, 1]])

# generate circle with desired radius 
circle = radius*np.exp(1j*np.linspace(-np.pi, np.pi, 100))

pyplot.pcolormesh(x, y, img)
pyplot.plot(np.real(circle), np.imag(circle), '-w')
pyplot.show()

这给出了:

enter image description here

问题:

如何使用圆形来掩盖与该圆相符的图像像素?


您可以使用中点圆算法链接生成圆形坐标,然后执行以下操作:np.sum(image[circle_coordinates]) - Brenlla
@Brenlla 我认为正确的方法应该考虑到不同像素之间的路径长度是不同的。例如,在(1/sqrt(2), 1/sqrt(2))处的像素应该比在(1, 0)处的像素(假设radius=1)加权sqr(2)倍。 - Paul Panzer
1个回答

3

这里有一种替代计算积分的方法:它使用插值,使图像成为在矩形上定义的函数,然后使用标准积分求解器计算路径积分。

from scipy.integrate import quad
from scipy.interpolate import RectBivariateSpline
from scipy.stats import multivariate_normal
import numpy as np

x, y = np.ogrid[-5:5:.1, -5:5:.1]
img = multivariate_normal.pdf(np.dstack(np.broadcast_arrays(x, y)),
                              cov=[[1, 0.7], [0.7, 1]])

f = RectBivariateSpline(x.ravel(), y.ravel(), img)

radius, centerx, centery = 3.0, 1.0, -1.5
def integrand(rad):
    return f(centerx+radius*np.cos(rad), centery+radius*np.sin(rad))

def true_integrand(rad):
    return multivariate_normal(cov=[[1, 0.7], [0.7, 1]]).pdf(
        (centerx+radius*np.cos(rad), centery+radius*np.sin(rad)))

print(quad(integrand, -np.pi, np.pi))
print(quad(true_integrand, -np.pi, np.pi))

输出:

(0.07985467350026378, 1.3411796499850778e-08)
(0.07985453947958436, 4.006916325573184e-11)

1
谢谢,这是一个巧妙的绕过计算的方法! - Gerges
我尝试使用 img = np.ones((max(x.shape), max(y.shape))) 进行测试,以计算周长,即应为 2 * pi * 半径,但这仅给出了 2 * pi。有什么想法吗?如果没有快速答案,我可以将其发布为新问题。 - Gerges
没关系,我理解错了,它确实给出了预期的答案,抱歉打扰你的回答 :)。 - Gerges

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接