13

由于我是opencv的新手,我不知道如何将cv.CalcEMD2函数与numpy数组一起使用。
我有两个数组:

a=[1,2,3,4,5]  
b=[1,2,3,4]

我怎样才能转移到numpy array函数参数?CVhistogramCvhistogramsignature

我希望任何回答问题的人opencv通过提供的解决方案来解释任何使用的功能。

“EMD” ==推土机的距离

更新:-
另外,如果有人能告诉我如何设置cv.CalcEMD2参数,即"signature"使用numpy数组,那将会很有帮助!

注意:-
* 对于那些可能对这个问题感兴趣的人,这个答案需要更多的测试。

4

3 回答 3

17

您必须根据权重和坐标定义数组。如果您有两个表示一维直方图的数组 a = [1,1,0,0,1] 和 b = [0,1,0,1],那么 numpy 数组应该如下所示:

a = [[1 1]
     [1 2]
     [0 3]
     [0 4]
     [1 5]]

b = [[0 1]
     [1 2]
     [0 3]
     [1 4]]

请注意,行数可以不同。列数应该是维度 + 1。第一列包含权重,第二列包含坐标。

下一步是在将 numpy 数组作为签名输入到 CalcEMD2 函数之前,将数组转换为 CV_32FC1 Mat。代码如下所示:

from cv2 import *
import numpy as np

# Initialize a and b numpy arrays with coordinates and weights
a = np.zeros((5,2))

for i in range(0,5):
    a[i][1] = i+1

a[0][0] = 1
a[1][0] = 1
a[2][0] = 0
a[3][0] = 0
a[4][0] = 1

b = np.zeros((4,2))

for i in range(0,4):
    b[i][1] = i+1

b[0][0] = 0
b[1][0] = 1
b[2][0] = 0
b[3][0] = 1    

# Convert from numpy array to CV_32FC1 Mat
a64 = cv.fromarray(a)
a32 = cv.CreateMat(a64.rows, a64.cols, cv.CV_32FC1)
cv.Convert(a64, a32)

b64 = cv.fromarray(b)
b32 = cv.CreateMat(b64.rows, b64.cols, cv.CV_32FC1)
cv.Convert(b64, b32)

# Calculate Earth Mover's
print cv.CalcEMD2(a32,b32,cv.CV_DIST_L2)

# Wait for key
cv.WaitKey(0)

请注意,CalcEMD2 的第三个参数是欧几里得距离 CV_DIST_L2。第三个参数的另一个选项是曼哈顿距离 CV_DIST_L1。

我还想提一下,我编写了代码来计算 Python 中两个 2D 直方图的 Earth Mover 距离。您可以在此处找到此代码。

于 2013-04-08T15:33:11.877 回答
3

根据文档,CV.CalcEMD2 期望数组还包括每个信号的权重。

我建议将您的数组定义为权重 1,如下所示:

a=array([1,1],[2,1],[3,1],[4,1],[5,1])
b=array([1,1],[2,1],[3,1],[4,1])
于 2013-04-04T15:38:22.497 回答
3

我知道 OP 想使用 OpenCV 测量Earth Mover 的距离,但如果您想使用 Scipy 这样做,您可以使用以下方法(Wasserstein 距离也称为 Earth Mover 的距离):

from scipy.stats import wasserstein_distance
from scipy.ndimage import imread
import numpy as np

def get_histogram(img):
  '''
  Get the histogram of an image. For an 8-bit, grayscale image, the
  histogram will be a 256 unit vector in which the nth value indicates
  the percent of the pixels in the image with the given darkness level.
  The histogram's values sum to 1.
  '''
  h, w = img.shape
  hist = [0.0] * 256
  for i in range(h):
    for j in range(w):
      hist[img[i, j]] += 1
  return np.array(hist) / (h * w)

a = imread('a.jpg')
b = imread('b.jpg')
a_hist = get_histogram(a)
b_hist = get_histogram(b)
dist = wasserstein_distance(a_hist, b_hist)
print(dist)
于 2018-03-31T21:12:52.510 回答