noise_svd_threshold.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # main imports
  2. import sys, os, argparse
  3. import numpy as np
  4. # image processing imports
  5. from PIL import Image
  6. from ipfml import processing, utils
  7. import matplotlib.pyplot as plt
  8. # modules and config imports
  9. sys.path.insert(0, '') # trick to enable import of main folder module
  10. import custom_config as cfg
  11. from data_attributes import get_image_features
  12. noise_list = cfg.noise_labels
  13. generated_folder = cfg.generated_folder
  14. filename_ext = cfg.filename_ext
  15. feature_choices = cfg.features_choices_labels
  16. normalization_choices = cfg.normalization_choices
  17. pictures_folder = cfg.pictures_output_folder
  18. steparam_picture = 10
  19. class ThresholdData():
  20. """
  21. A simple class to store threshold data
  22. """
  23. def __init__(self, noise, threshold, color):
  24. self.noise = noise
  25. self.threshold = threshold
  26. self.color = color
  27. def get_noise(self):
  28. return self.noise
  29. def get_threshold(self):
  30. return self.threshold
  31. def isColor(self):
  32. return self.color
  33. def main():
  34. parser = argparse.ArgumentParser(description="Display threshold svd data")
  35. parser.add_argument('--prefix', type=str, help='Generated noise folder prefix (ex: `generated/prefix/noise`)')
  36. parser.add_argument('--file', type=str, help='Threshold file to use')
  37. parser.add_argument('--mode', type=str, help='Kind of normalization', default=normalization_choices)
  38. parser.add_argument('--feature', type=str, help='feature choice', default=feature_choices)
  39. parser.add_argument('--color', type=int, help='Use of color or grey level', default=0)
  40. parser.add_argument('--norm', type=int, help='Use of normalization from interval or whole data vector', default=0)
  41. parser.add_argument('--interval', type=str, help='Interval data choice (ex: `0, 200`)', default="0, 200")
  42. parser.add_argument('--step', type=int, help='Step of image indices to keep', default=1)
  43. parser.add_argument('--ylim', type=str, help='Limite to display data (ex: `0, 1`)', default="0, 1")
  44. args = parser.parse_args()
  45. param_prefix = args.prefix
  46. param_file = args.file
  47. param_mode = args.mode
  48. param_feature = args.feature
  49. param_n = args.n
  50. param_color = args.color
  51. param_norm = args.norm
  52. param_interval = list(map(int, args.interval.split(',')))
  53. param_step = args.step
  54. param_ylim = list(map(float, args.ylim.split(',')))
  55. param_prefix = param_prefix.split('/')[1].replace('_', '')
  56. if param_color:
  57. file_path = param_prefix + "{}/" + param_prefix + "_{}_color_{}." + filename_ext
  58. else:
  59. file_path = param_prefix + "{}/" + param_prefix + "_{}_{}." + filename_ext
  60. begin, end = param_interval
  61. svd_data = []
  62. final_svd_data = []
  63. image_indices = []
  64. min_max_list = {}
  65. threshold_data = []
  66. # read data threshold file
  67. with open(param_file, 'r') as f:
  68. lines = f.readlines()
  69. for line in lines:
  70. data = line.replace('\n', '').split(';')
  71. print(data)
  72. threshold = ThresholdData(data[0], float(data[1]), int(data[2]))
  73. threshold_data.append(threshold)
  74. # filter data if color or not
  75. threshold_data = [t for t in threshold_data if t.isColor() == param_color]
  76. for id, threshold in enumerate(threshold_data):
  77. current_noise = threshold.get_noise()
  78. current_threshold = threshold.get_threshold()
  79. min_max_list[current_noise] = (sys.maxsize, 0)
  80. threshold_found = False
  81. # get all data from images
  82. for i in range(1, param_n):
  83. if i % steparam_picture == 0:
  84. image_path = file_path.format(current_noise, current_noise, str(i))
  85. img = Image.open(image_path)
  86. svd_values = get_image_features(param_feature, img)
  87. if param_norm:
  88. svd_values = svd_values[begin:end]
  89. # only append data once
  90. if not threshold_found and current_threshold < i:
  91. svd_data.append(svd_values)
  92. image_indices.append(i)
  93. if current_threshold < i:
  94. threshold_found = True
  95. # update min max values
  96. min_value = svd_values.min()
  97. max_value = svd_values.max()
  98. # update of min max values for noise
  99. current_min, current_max = min_max_list[current_noise]
  100. if min_value < current_min:
  101. current_min = min_value
  102. if max_value > current_max:
  103. current_max = max_value
  104. min_max_list[current_noise] = (current_min, current_max)
  105. print('%.2f%%' % (((i + 1) * 100 + (id * param_n * 100)) / (param_n * len(threshold_data))))
  106. sys.stdout.write("\033[F")
  107. for id, data in enumerate(svd_data):
  108. current_data = data
  109. threshold = threshold_data[id]
  110. min_value_svd, max_value_svd = min_max_list[threshold.get_noise()]
  111. if param_mode == 'svdn':
  112. current_data = utils.normalize_arr(current_data)
  113. if param_mode == 'svdne':
  114. current_data = utils.normalize_arr_with_range(current_data, min_value_svd, max_value_svd)
  115. final_svd_data.append(current_data)
  116. # display all data using matplotlib (configure plt)
  117. plt.rcParams['figure.figsize'] = (25, 18)
  118. plt.title(param_prefix + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + param_feature + ' feature, step ' + str(param_step) + ' normalization ' + param_mode, fontsize=20)
  119. plt.ylabel('Importance of noise [1, 999]', fontsize=14)
  120. plt.xlabel('Vector features', fontsize=16)
  121. for id, data in enumerate(final_svd_data):
  122. param_label = param_prefix + '_' + threshold_data[id].get_noise() + str(image_indices[id])
  123. plt.plot(data, label=param_label)
  124. plt.legend(bbox_to_anchor=(0.8, 1), loc=2, borderaxespad=0.2, fontsize=14)
  125. if not param_norm:
  126. plt.xlim(begin, end)
  127. # adapt ylim
  128. y_begin, y_end = param_ylim
  129. plt.ylim(y_begin, y_end)
  130. output_filename = param_prefix + "_threshold_1_to_" + str(param_n) + "_B" + str(begin) + "_E" + str(end) + "_" + param_feature + "_S" + str(param_step) + "_norm" + str(param_norm )+ "_" + param_mode
  131. if param_color:
  132. output_filename = output_filename + '_color'
  133. print("Generation of output figure... %s" % output_filename)
  134. output_path = os.path.join(pictures_folder, output_filename)
  135. if not os.path.exists(pictures_folder):
  136. os.makedirs(pictures_folder)
  137. plt.savefig(output_path, dpi=(200))
  138. if __name__== "__main__":
  139. main()