gpt4 book ai didi

python - 通过二值图像 Numpy 矩阵的矩阵运算计算均方误差

转载 作者:行者123 更新时间:2023-11-28 21:34:39 26 4
gpt4 key购买 nike

我有 2 张二值图像,一张是真实图像,一张是我生成的图像分割。

我正在尝试计算均方距离...

enter image description here

Let G = {g1, g2, . . . , gN} be the points in the ground truth boundary.
Let B = {b1, b2, . . . , bM} be the points in the segmented boundary.
Define d(p, p0) be a measure of distance between points p and p0 (e.g. Euclidean, city block, etc.)

使用以下算法在两个图像之间进行转换。

def MSD(A,G):
'''
Takes a thresholded binary image, and a ground truth img(binary), and computes the mean squared absolute difference
:param A: The thresholded binary image
:param G: The ground truth img
:return:
'''
sim = np.bitwise_xor(A,G)
sum = 0
for i in range(0,sim.shape[0]):
for j in range(0,sim.shape[1]):
if (sim[i,j] == True):
min = 9999999
for k in range(0,sim.shape[0]):
for l in range(0,sim.shape[1]):
if (sim[k, l] == True):
e = abs(i-k) + abs(j-l)
if e < min:
min = e
mink = k
minl = l
sum += min
return sum/(sim.shape[0]*sim.shape[1])

这个算法太慢了,而且永远不会完成。

这个examplethis example (答案 3)可能会展示如何使用矩阵算术获得均方误差的方法,但我不明白这些示例有何意义或它们为何起作用。

最佳答案

因此,如果我正确理解您的公式和代码,您将拥有一个(二进制)图像 B 和一个(地面实况)图像 G。 “点”由像素位置定义,其中任一图像具有 True(或至少非零)值。从您的 bitwise_xor 中,我推断出两个图像具有相同的形状 (M,N)

因此,数量 d^2(b,g) 在最坏的情况下是一个 (M*N, M*N) 大小的数组,关联 BG 的每个像素。更好的是:如果 Bn 中有 m 个非零值,我们只需要一个形状 (m,n) > G 中的非零值。除非您的图像很大,否则我们可以跟踪如此大的数量。这会消耗内存,但我们将通过矢量化赢得大量 CPU 时间。因此,我们只需针对每个 m 的每个 n 可能值找到该距离的最小值。然后将每个最小值相加。请注意,下面的解决方案使用极端矢量化,如果图像很大,它很容易耗尽您的内存。

假设曼哈顿距离(您的代码中似乎缺少 d^2 中的正方形):

import numpy as np

# generate dummy data
M,N = 100,100
B = np.random.rand(M,N) > 0.5
G = np.random.rand(M,N) > 0.5

def MSD(B, G):
# get indices of nonzero pixels
nnz_B = B.nonzero() # (x_inds, y_inds) tuple, x_inds and y_inds are shape (m,)
nnz_G = G.nonzero() # (x_inds', y_inds') each with shape (n,)

# np.array(nnz_B) has shape (2,m)
# compute squared Manhattan distance
dist2 = abs(np.array(nnz_B)[...,None] - np.array(nnz_G)[:,None,:]).sum(axis=0)**2 # shape (m,n)
# alternatively: Euclidean for comparison:
#dist2 = ((np.array(nnz_B)[...,None] - np.array(nnz_G)[:,None,:])**2).sum(axis=0)

mindist2 = dist2.min(axis=-1) # shape (m,) of minimum square distances

return mindist2.mean() # sum divided by m, i.e. the MSD itself

print(MSD(B, G))

如果上面使用了太多内存,我们可以在 nnz_B 的元素上引入一个循环,并且仅在 nnz_G 的元素中进行向量化。这将需要更多的 CPU 能力和更少的内存。这种权衡对于矢量化来说是典型的。

关于python - 通过二值图像 Numpy 矩阵的矩阵运算计算均方误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074758/

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