python - 用 python 计算图像径向平均值的最佳方法是什么?

标签 python image algorithm matplotlib average

我有一张方形图片,例如这张:

Scipy coin demo image

我想计算从位置 (0,0) 开始的每个半径的图像的一维平均值。我已经为此编写了一些代码,但首先即使是小图像也非常慢,其次我发现它背后的想法也存在一些问题。代码在这里:

import matplotlib.pyplot as plt
import numpy as np
import collections
from skimage import data

image = data.coins()
image = image[:,0:303]
print(image.shape)

projection = {}
total_count = {}

for x_i,x in enumerate(image):
    for y_i,y in enumerate(x):
        if round(np.sqrt(x_i**2+y_i**2),1) not in projection:
            projection[round(np.sqrt(x_i**2+y_i**2),1)] = y
            total_count[round(np.sqrt(x_i**2+y_i**2),1)] = 1
        elif np.sqrt(round(np.sqrt(x_i**2+y_i**2),1)) in projection:
            projection[round(np.sqrt(x_i**2+y_i**2),1)] += y
            total_count[round(np.sqrt(x_i ** 2 + y_i ** 2), 1)] += 1

od = collections.OrderedDict(sorted(projection.items()))
x, y = [],[]

for k, v in od.items():
    x.append(k)
    y.append(v/total_count[k])

plt.plot(x,y)
plt.xlabel('Radius from (0,0)')
plt.ylabel('Averaged pixel value')
plt.show()

代码的结果如下所示:

Result of radius average of picture

有没有人知道如何改进我的脚本?我也不知道为什么在某些情况下会出现一些平均值非常小的尖峰。我真的很感激一些提示。谢谢!

最佳答案

您可以通过创建半径 R 矩阵按半径过滤图像 并计算

image[(R >= r-.5) & (R < r+.5)].mean()

其中 r 是您感兴趣的半径。

enter image description here

import numpy as np
import matplotlib.pyplot as plt
from skimage import data

# get some image
image = data.coins()
image = image[:,0:303]

# create array of radii
x,y = np.meshgrid(np.arange(image.shape[1]),np.arange(image.shape[0]))
R = np.sqrt(x**2+y**2)

# calculate the mean
f = lambda r : image[(R >= r-.5) & (R < r+.5)].mean()
r  = np.linspace(1,302,num=302)
mean = np.vectorize(f)(r)

# plot it
fig,ax=plt.subplots()
ax.plot(r,mean)
plt.show()

enter image description here

关于python - 用 python 计算图像径向平均值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842320/

相关文章:

python - 使用张量索引对张量进行切片

python - 在 python 工具套件中延迟导入

Python 替代 fscanf C 代码

python - 带有 MultiIndex : check if string is contained in index level 的 Pandas 数据框

java - 将字节数组写入 bmp java

c# - 自动调整图片框中的图像

ios - 如何使用 AWS iOS SDK 从设备上传图像并设置为公开

c++ - 在 C++ 中使用合并函数算法时遇到问题

c# - 从数学符号翻译交叉熵方法

arrays - 找到最长的子数组