gpt4 book ai didi

python - 在 python 中计算图像的特征向量

转载 作者:太空狗 更新时间:2023-10-30 00:22:02 26 4
gpt4 key购买 nike

我正在尝试使 2D 高斯分布适合图​​像。噪音非常低,所以我尝试旋转图像,使两个主轴不共同变化,找出最大值并计算两个维度的标准偏差。选择的武器是 python 。

2d more-or-less gaussian distribution

但是我在寻找图像的特征向量时遇到了困难 - numpy.linalg.py 假定离散数据点。我考虑过将此图像作为概率分布,采样几千个点,然后计算该分布的特征向量,但我确信必须有一种方法可以找到特征向量(即,半主要和半高斯椭圆的短轴)直接来自该图像。有什么想法吗?

非常感谢:)

最佳答案

简单说明一下,有几种工具可以使高斯分布适合图​​像。我唯一能想到的就是scikits.learn ,这不是完全面向图像的,但我知道还有其他的。

要完全按照您的想法计算协方差矩阵的特征向量,计算成本非常高。您必须将图像的每个像素(或较大的随机样本)与 x、y 点相关联。

基本上,你会做类似的事情:

    import numpy as np
# grid is your image data, here...
grid = np.random.random((10,10))

nrows, ncols = grid.shape
i,j = np.mgrid[:nrows, :ncols]
coords = np.vstack((i.reshape(-1), j.reshape(-1), grid.reshape(-1))).T
cov = np.cov(coords)
eigvals, eigvecs = np.linalg.eigh(cov)

您可以利用它是定期采样图像这一事实来计算它的矩(或“惯性轴”)。对于大图像,这会快得多。

举个简单的例子,(我正在使用我的 previous answers 的一部分,以防你发现它有用......)

import numpy as np
import matplotlib.pyplot as plt

def main():
data = generate_data()
xbar, ybar, cov = intertial_axis(data)

fig, ax = plt.subplots()
ax.imshow(data)
plot_bars(xbar, ybar, cov, ax)
plt.show()

def generate_data():
data = np.zeros((200, 200), dtype=np.float)
cov = np.array([[200, 100], [100, 200]])
ij = np.random.multivariate_normal((100,100), cov, int(1e5))
for i,j in ij:
data[int(i), int(j)] += 1
return data

def raw_moment(data, iord, jord):
nrows, ncols = data.shape
y, x = np.mgrid[:nrows, :ncols]
data = data * x**iord * y**jord
return data.sum()

def intertial_axis(data):
"""Calculate the x-mean, y-mean, and cov matrix of an image."""
data_sum = data.sum()
m10 = raw_moment(data, 1, 0)
m01 = raw_moment(data, 0, 1)
x_bar = m10 / data_sum
y_bar = m01 / data_sum
u11 = (raw_moment(data, 1, 1) - x_bar * m01) / data_sum
u20 = (raw_moment(data, 2, 0) - x_bar * m10) / data_sum
u02 = (raw_moment(data, 0, 2) - y_bar * m01) / data_sum
cov = np.array([[u20, u11], [u11, u02]])
return x_bar, y_bar, cov

def plot_bars(x_bar, y_bar, cov, ax):
"""Plot bars with a length of 2 stddev along the principal axes."""
def make_lines(eigvals, eigvecs, mean, i):
"""Make lines a length of 2 stddev."""
std = np.sqrt(eigvals[i])
vec = 2 * std * eigvecs[:,i] / np.hypot(*eigvecs[:,i])
x, y = np.vstack((mean-vec, mean, mean+vec)).T
return x, y
mean = np.array([x_bar, y_bar])
eigvals, eigvecs = np.linalg.eigh(cov)
ax.plot(*make_lines(eigvals, eigvecs, mean, 0), marker='o', color='white')
ax.plot(*make_lines(eigvals, eigvecs, mean, -1), marker='o', color='red')
ax.axis('image')

if __name__ == '__main__':
main()

enter image description here

关于python - 在 python 中计算图像的特征向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com