python – 将2D Numpy像素阵列的坐标传递给距离函数

我正在使用OpenCV和numpy进行图像处理程序.对于大多数像素操作,我可以通过使用np.vectorize()避免嵌套for循环,但我需要实现的一个函数需要作为参数’距离中心’,或者基本上是点的坐标处理.

伪示例:

myArr = [[0,1,2]
         [3,4,5]]

def myFunc(val,row,col):
    return [row,col]

f = np.vectorize(myFunc)
myResult = f(myArr,row,col)

我显然无法从矢量化数组中获取elemX和elemY,但是在这种情况下我是否可以使用另一个numpy函数或者我必须使用for循环吗?有没有办法使用openCV?

我需要将每个像素放在一起的功能是:
f(i,j)= 1 /(1d(i,j)/ L),d(i,j)是该点距图像中心的欧几里德距离.

最佳答案 你可以使用以下几行从中心获得一个距离数组(这是一个例子,有很多方法可以做到这一点):

    import numpy as np

myArr = np.array([[0,1,2], [3,4,5]])

nx, ny = myArr.shape
x = np.arange(nx) - (nx-1)/2.  # x an y so they are distance from center, assuming array is "nx" long (as opposed to 1. which is the other common choice)
y = np.arange(ny) - (ny-1)/2.
X, Y = np.meshgrid(x, y)
d = np.sqrt(X**2 + Y**2)

#  d = 
#  [[ 1.11803399  1.11803399]
#   [ 0.5         0.5       ]
#   [ 1.11803399  1.11803399]]

然后你可以通过以下公式计算f(i,j):

f = 1/(1 + d/L)

顺便说一下,你大量使用np.vectorize()有点可疑.你确定它正在做你想要的,你是否注意到the documentation的声明:

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

通常更好的方法是以矢量化的形式编写代码(就像上面的f一行,无论L是数组还是缩放器都可以工作),而不是使用numpy.vectorize(),这些是不同的东西.

点赞