【问题标题】:Compute sum of image pixels along a circular path计算沿圆形路径的图像像素总和
【发布时间】:2018-04-17 17:41:23
【问题描述】:

我有一张图像,我正在尝试沿着圆形路径计算线积分(总和)。我的想法是:

  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()

这给出了:

问题:

如何使用圆圈来掩盖与该圆圈重合的图像像素?

【问题讨论】:

  • 您可以使用中点圆算法生成圆坐标。 link 然后:np.sum(image[circle_coordinates])
  • @Brenlla 我认为正确的是必须考虑不同像素的不同路径长度。例如,(1/sqrt(2), 1/sqrt(2)) 处的像素的权重应该是sqrt(2) 的倍数,是(1, 0) 处的像素(假设为radius=1)。

标签: python numpy mask calculus


【解决方案1】:

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

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)

【讨论】:

  • 谢谢,这是绕过计算的聪明方法!
  • 我尝试使用img = np.ones((max(x.shape), max(y.shape))) 对此进行测试,所以我会计算周长,它应该是 2 * pi * 半径,但这只会给我 2 * pi。有任何想法吗?如果没有快速答案,我可以将此作为新问题发布。
  • 没关系,我解释错了,它确实给出了预期的答案,很抱歉给你的答案发垃圾邮件:)。
猜你喜欢
  • 2021-08-01
  • 2012-05-13
  • 1970-01-01
  • 2021-02-23
  • 2023-04-03
  • 1970-01-01
  • 2021-03-14
  • 2011-08-20
  • 2018-11-06
相关资源
最近更新 更多