wavelet.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import numpy as np
  2. def wavelet(image, width=None):
  3. shape = image.shape
  4. if len(shape) != 2 or shape[0] != shape[1]:
  5. raise(f"Expected quadratic image but got data with shape: {shape}")
  6. if width is None:
  7. width = shape[0]
  8. if shape[0] < width:
  9. raise(f"Image with shape {shape} is smaller then the requested size {width}.")
  10. result = image.copy()
  11. half = width // 2
  12. for y in range(half):
  13. for x in range(half):
  14. px = 2 * x
  15. py = 2 * y
  16. result[y, x] = image[py, px]
  17. result[y, x + half] = image[py, px + 1] - image[py, px]
  18. result[y + half, x] = image[py + 1, px] - image[py, px]
  19. result[y + half, x + half] = image[py + 1, px + 1] - image[py, px]
  20. return result
  21. def refine(image):
  22. shape = image.shape
  23. if len(shape) != 2 or shape[0] != shape[1]:
  24. raise(f"Expected quadratic image but got data with shape: {shape}")
  25. width = shape[0]
  26. while width > 1:
  27. image = wavelet(image, width)
  28. width = width // 2
  29. return image
  30. def rotate(image, n=1):
  31. shape = image.shape
  32. if len(shape) != 2 or shape[0] != shape[1]:
  33. raise(f"Expected quadratic image but got data with shape: {shape}")
  34. result = image.copy()
  35. w = shape[0] - 1
  36. if n == 0: # id
  37. p = lambda y, x: (y, x)
  38. elif n == 1:
  39. p = lambda y, x: (y, w - x)
  40. elif n == 2:
  41. p = lambda y, x: (w - y, x)
  42. elif n == 3:
  43. p = lambda y, x: (w - y, w - x)
  44. elif n == 4:
  45. p = lambda y, x: (x, y)
  46. elif n == 5:
  47. p = lambda y, x: (x, w - y)
  48. elif n == 6:
  49. p = lambda y, x: (w - x, y)
  50. elif n == 7:
  51. p = lambda y, x: (w - x, w - y)
  52. else:
  53. raise f"Unexpected n={n} for n in {0,1,2,3,4,5,6}"
  54. for y in range(w):
  55. for x in range(w):
  56. result[x,y] = image[y,x]
  57. return result