utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import numpy as np
  2. """
  3. Utils functions of ipfml package
  4. """
  5. def normalize_arr(arr):
  6. '''Normalize data of 1D array shape
  7. Args:
  8. arr: array data of 1D shape
  9. Returns:
  10. Normalized 1D array
  11. Example:
  12. >>> from ipfml import utils
  13. >>> import numpy as np
  14. >>> arr = np.arange(11)
  15. >>> arr_normalized = utils.normalize_arr(arr)
  16. >>> arr_normalized[1]
  17. 0.1
  18. '''
  19. output_arr = []
  20. max_value = max(arr)
  21. min_value = min(arr)
  22. for v in arr:
  23. output_arr.append((v - min_value) / (max_value - min_value))
  24. return output_arr
  25. def normalize_arr_with_range(arr, min, max):
  26. '''Normalize data of 1D array shape
  27. Args:
  28. arr: array data of 1D shape
  29. Returns:
  30. Normalized 1D Numpy array
  31. Example:
  32. >>> from ipfml import processing
  33. >>> import numpy as np
  34. >>> arr = np.arange(11)
  35. >>> arr_normalized = processing.normalize_arr_with_range(arr, 0, 20)
  36. >>> arr_normalized[1]
  37. 0.05
  38. '''
  39. output_arr = []
  40. for v in arr:
  41. output_arr.append((v - min) / (max - min))
  42. return output_arr
  43. def normalize_2D_arr(arr):
  44. """Return array normalize from its min and max values
  45. Args:
  46. arr: 2D Numpy array
  47. Returns:
  48. Normalized 2D Numpy array
  49. Example:
  50. >>> from PIL import Image
  51. >>> from ipfml import utils, processing
  52. >>> img = Image.open('./images/test_img.png')
  53. >>> img_mscn = processing.rgb_to_mscn(img)
  54. >>> img_normalized = utils.normalize_2D_arr(img_mscn)
  55. >>> img_normalized.shape
  56. (200, 200)
  57. """
  58. # getting min and max value from 2D array
  59. max_value = arr.max(axis=1).max()
  60. min_value = arr.min(axis=1).min()
  61. # normalize each row
  62. output_array = []
  63. width, height = arr.shape
  64. for row_index in range(0, height):
  65. values = arr[row_index, :]
  66. output_array.append(
  67. normalize_arr_with_range(values, min_value, max_value))
  68. return np.asarray(output_array)