augs.py 796 B

1234567891011121314151617181920212223242526272829
  1. import random
  2. from fastai.vision.image import TfmPixel
  3. # Contributed by Rani Horev. Thank you!
  4. def _noisify(
  5. x, pct_pixels_min: float = 0.001, pct_pixels_max: float = 0.4, noise_range: int = 30
  6. ):
  7. if noise_range > 255 or noise_range < 0:
  8. raise Exception("noise_range must be between 0 and 255, inclusively.")
  9. h, w = x.shape[1:]
  10. img_size = h * w
  11. mult = 10000.0
  12. pct_pixels = (
  13. random.randrange(int(pct_pixels_min * mult), int(pct_pixels_max * mult)) / mult
  14. )
  15. noise_count = int(img_size * pct_pixels)
  16. for ii in range(noise_count):
  17. yy = random.randrange(h)
  18. xx = random.randrange(w)
  19. noise = random.randrange(-noise_range, noise_range) / 255.0
  20. x[:, yy, xx].add_(noise)
  21. return x
  22. noisify = TfmPixel(_noisify)