Distance.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # import
  2. # ------------------------------------------------------------------------------------------
  3. import miam
  4. import copy
  5. import numpy as np
  6. # ------------------------------------------------------------------------------------------
  7. # MIAM project 2020
  8. # ------------------------------------------------------------------------------------------
  9. # author: remi.cozot@univ-littoral.fr
  10. # ------------------------------------------------------------------------------------------
  11. class Distance(object):
  12. """description of class"""
  13. def __init__(self,f):
  14. self.distanceFunction = f
  15. def eval(self, u,v): return self.distanceFunction(u,v)
  16. def cosineDistance(u,v):
  17. # normalise u, v
  18. u = u / np.sqrt(np.dot(u,u))
  19. v = v / np.sqrt(np.dot(v,v))
  20. # cosine
  21. uv = np.dot(u,v)
  22. # return
  23. return np.maximum(1 - uv, 0.0)
  24. def L2Distance(u,v):
  25. u = np.asarray(u)
  26. v = np.asarray(v)
  27. # return
  28. return np.sqrt(np.dot(u-v,u-v))
  29. def cL2distance(c0,c1):
  30. # sorted L2 distanec between palette.colors
  31. # no border effect
  32. c0, c1 = copy.deepcopy(c0), copy.deepcopy(c1)
  33. # init iteration
  34. totalDist = 0.0
  35. while (len(c0)>0):
  36. # init find mininal distance between two colors
  37. u, v = c0[0], c1[0]
  38. uMv = u-v
  39. distMin = np.sqrt(np.dot(uMv,uMv))
  40. iMin, jMin =0, 0
  41. for i in range(len(c0)):
  42. for j in range(len(c1)):
  43. u, v = c0[i], c1[j]
  44. uMv = u-v
  45. dist = np.sqrt(np.dot(uMv,uMv))
  46. if dist < distMin:
  47. distMin, iMin, jMin = dist,i,j
  48. else:
  49. pass
  50. # remove colors that are closest
  51. c0, c1 = np.delete(c0,iMin, axis=0), np.delete(c1,jMin, axis=0)
  52. # add to distance
  53. totalDist = totalDist + distMin
  54. return totalDist