cv2.EMD() 簡單解讀
參考鏈接:
函數解讀:
https://samvankooten.net/2018/09/25/earth-movers-distance-in-python/
https://gist.github.com/svank/6f3c2d776eea882fd271bba1bd2cc16d
原理:
https://blog.csdn.net/wangdonggg/article/details/32329879
函數定義:
float cv::EMD (
InputArray signature1, # 特征1 size1
InputArray signature2, # 特征2 size2
int distType,
# 使用的度量方式:
# cv2.DIST_USER : 用戶自定義距離(即下一個參數,cost_matrix)
# cv2.DIST_L1: distance = |x1-x2| + |y1-y2|
# cv2.DIST_L2: 歐式距離
# cv2.DIST_C: distance = max(|x1-x2|,|y1-y2|)
# cv2.DIST_L12: L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))
InputArray cost_matrix, # 用戶自定義度量方式 size1 * size2
float lowerBound = 0, # 一般來說不用,沒搞懂
OutputArray flow # 流矩陣 size1 * size2
Return cost # cost = flow * cost_matrix.sum()
)
注:signature1 和 signature2 在傳入 EMD()后會自動被歸一化:
import cv2
import numpy
import torch
a = torch.Tensor([1, 2, 3, 4, 5]).view(-1, 1).numpy()
b = torch.Tensor([2, 3, 4, 5, 1]).view(-1, 1).numpy()
# 歸一化,有無歸一,結果都一樣。
# a = a/a.sum(0)
# b = b/b.sum(0)
cost_matrix = torch.ones([5,5]).numpy()
print(a)
print(b)
print(cost_matrix)
cost, _, flow = cv2.EMD(a, b, cv2.DIST_USER, cost_matrix)
print(cost)
print(flow)