-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcosts.py
62 lines (41 loc) · 1.4 KB
/
costs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from arrays import *
import numpy
# Matching cost functions
# Assumming a and b are the same size
# Returns a scalar representing the cost
def ssd(a, b): # Sum of the the Square Differences
# Range: non-negative
# 0.0 is maximal positive correlation
if (a.size == 0) or (a.shape != b.shape):
return numpy.nan
return numpy.sum((b - a)**2)
def sad(a, b): # Sum of the Absolute Differences
# Range: non-negative
# 0.0 is maximal positive correlation
if (a.size == 0) or (a.shape != b.shape):
return numpy.nan
return numpy.sum(numpy.abs(b - a))
def ncc(a, b): # Normalized Cross-Correlation
# Range: [-1, 1]
# 0.0 is zero correlation
# 1.0 is maximal positive correlation
# -1.0 is maximal negative correlation
# MATH:
# a_centroid = a - mean(a)
# b_centroid = b - mean(b)
# dot(a_centroid, b_centroid) / sqrt(ssd(a_centroid)*ssd(b_centroid))
if (a.size == 0) or (a.shape != b.shape):
return numpy.nan
a = a.flatten()
b = b.flatten()
a_centroid = a - numpy.mean(a)
b_centroid = b - numpy.mean(b)
# numerator = numpy.sum(a_centroid*b_centroid)
numerator = numpy.dot(a_centroid, b_centroid)
if is_nearly_zero(numerator):
return 0
# denominator = numpy.sqrt(numpy.sum(a_centroid**2)*numpy.sum(b_centroid**2))
denominator = numpy.sqrt(numpy.dot(a_centroid, a_centroid)*numpy.dot(b_centroid, b_centroid))
if is_nearly_zero(denominator):
return numpy.nan
return (numerator/denominator)