Advertisement
Guest User

Untitled

a guest
Jun 8th, 2021
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. import numpy as np
  2. import PIL
  3. from kymatio.numpy import Scattering2D
  4. from kymatio.visuals import imshow
  5.  
  6. def load_rgb(img):
  7.     img = np.array(PIL.Image.open(path).convert("RGB")).astype('float64')
  8.     img /= np.abs(img).max(axis=(0, 1))
  9.     return img
  10.  
  11. def group_by_scale(out, J, L):
  12.     n_S1 = J * L  # number of first-order coeffs
  13.     S1_all = out[1:n_S1 + 1]
  14.     S1_scale = S1_all.reshape(L, -1, *out.shape[-3:], order='F').mean(axis=0)
  15.     return S1_scale
  16.  
  17. def viz_by_scale(S1_scale, J, ticks=0, second_order=False):
  18.     J = J - 1 if second_order else J
  19.     for j in range(J):
  20.         j_title = j + 1 if second_order else j
  21.         imshow(S1_scale[j], title=f"scale={j_title}",
  22.                w=.5, h=.5, abs=1, ticks=ticks)
  23.  
  24. def unpad(out, ref):
  25.     assert out.ndim == 4
  26.     rx, ry = ref.shape[:2]
  27.     ox, oy = out.shape[1:3]
  28.     dx, dy = abs(ox - rx) // 2, abs(oy - ry) // 2
  29.     return out[:, dx:-dx, dy:-dy]
  30.  
  31. #%%
  32. path = r"C:\Desktop\colors.png"
  33. path = r"C:\Desktop\lena.jpg"
  34. img = load_rgb(path)
  35. #%%
  36. imshow(img, w=.6, h=.6, title="%s x %s image" % img.shape[:2])
  37. #%%
  38. J, L = 4, 8  # largest scale; number of angles
  39. S = Scattering2D(shape=img.shape[:2], L=L, J=J)
  40.  
  41. #%%
  42. # take 3 wavelet transforms on each channel and average
  43. # out = np.mean([S(im) for im in img.transpose(-1, 0, 1)], axis=0)
  44. outs = [S(im) for im in img.transpose(-1, 0, 1)]
  45. #%%
  46. out = np.vstack([o[None] for o in outs]).transpose(1, 2, 3, 0)
  47. print(img.shape)
  48. print(out.shape)
  49. #%%
  50. S1_scale = group_by_scale(out, J, L)
  51. S1_scale /= S1_scale.max(axis=(0, 1, 2))
  52. S1_scale = unpad(S1_scale, ref=img)
  53. viz_by_scale(S1_scale, J)
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement