noise_svd_threshold.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import sys, os, getopt
  2. from PIL import Image
  3. from ipfml import processing, utils
  4. from modules.utils import config as cfg
  5. from modules.utils import data_type as dt
  6. from modules import noise
  7. import matplotlib.pyplot as plt
  8. noise_list = cfg.noise_labels
  9. generated_folder = cfg.generated_folder
  10. filename_ext = cfg.filename_ext
  11. metric_choices = cfg.metric_choices_labels
  12. normalization_choices = cfg.normalization_choices
  13. pictures_folder = cfg.pictures_output_folder
  14. step_picture = 10
  15. class ThresholdData():
  16. """
  17. A simple class to store threshold data
  18. """
  19. def __init__(self, noise, threshold, color):
  20. self.noise = noise
  21. self.threshold = threshold
  22. self.color = color
  23. def get_noise(self):
  24. return self.noise
  25. def get_threshold(self):
  26. return self.threshold
  27. def isColor(self):
  28. return self.color
  29. def main():
  30. # default values
  31. p_step = 1
  32. p_color = 0
  33. p_norm = 0
  34. p_ylim = (0, 1)
  35. p_n = 1000
  36. if len(sys.argv) <= 1:
  37. print('python noise_svd_threshold.py --prefix generated/scene --file threshold_file --metric lab --mode svdn --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1"')
  38. sys.exit(2)
  39. try:
  40. opts, args = getopt.getopt(sys.argv[1:], "h:p:f:m:m:i:s:c:n:y", ["help=", "prefix=", "file=", "metric=", "mode=", "interval=", "step=", "color=", "norm=", "ylim="])
  41. except getopt.GetoptError:
  42. # print help information and exit:
  43. print('python noise_svd_threshold.py --prefix generated/scene --file threshold_file --metric lab --mode svdn --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1"')
  44. sys.exit(2)
  45. for o, a in opts:
  46. if o == "-h":
  47. print('python noise_svd_threshold.py --prefix generated/scene --file threshold_file --metric lab --mode svdn --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1"')
  48. sys.exit()
  49. elif o in ("-p", "--prefix"):
  50. p_path = a
  51. elif o in ("-f", "--file"):
  52. p_data_file = a
  53. elif o in ("-m", "--mode"):
  54. p_mode = a
  55. if not p_mode in normalization_choices:
  56. assert False, "Unknown normalization choice, %s" % normalization_choices
  57. elif o in ("-m", "--metric"):
  58. p_metric = a
  59. if not p_metric in metric_choices:
  60. assert False, "Unknown metric choice, %s" % metric_choices
  61. elif o in ("-n", "--norm"):
  62. p_norm = int(a)
  63. elif o in ("-c", "--color"):
  64. p_color = int(a)
  65. elif o in ("-i", "--interval"):
  66. p_interval = list(map(int, a.split(',')))
  67. elif o in ("-s", "--step"):
  68. p_step = int(a)
  69. elif o in ("-y", "--ylim"):
  70. p_ylim = list(map(float, a.split(',')))
  71. else:
  72. assert False, "unhandled option"
  73. p_prefix = p_path.split('/')[1].replace('_', '')
  74. if p_color:
  75. file_path = p_path + "{}/" + p_prefix + "_{}_color_{}." + filename_ext
  76. else:
  77. file_path = p_path + "{}/" + p_prefix + "_{}_{}." + filename_ext
  78. begin, end = p_interval
  79. svd_data = []
  80. final_svd_data = []
  81. image_indices = []
  82. min_max_list = {}
  83. threshold_data = []
  84. # read data threshold file
  85. with open(p_data_file, 'r') as f:
  86. lines = f.readlines()
  87. for line in lines:
  88. data = line.replace('\n', '').split(';')
  89. print(data)
  90. threshold = ThresholdData(data[0], float(data[1]), int(data[2]))
  91. threshold_data.append(threshold)
  92. # filter data if color or not
  93. threshold_data = [t for t in threshold_data if t.isColor() == p_color]
  94. for id, threshold in enumerate(threshold_data):
  95. current_noise = threshold.get_noise()
  96. current_threshold = threshold.get_threshold()
  97. min_max_list[current_noise] = (sys.maxsize, 0)
  98. threshold_found = False
  99. # get all data from images
  100. for i in range(1, p_n):
  101. if i % step_picture == 0:
  102. image_path = file_path.format(current_noise, current_noise, str(i))
  103. img = Image.open(image_path)
  104. svd_values = dt.get_svd_data(p_metric, img)
  105. if p_norm:
  106. svd_values = svd_values[begin:end]
  107. # only append data once
  108. if not threshold_found and current_threshold < i:
  109. svd_data.append(svd_values)
  110. image_indices.append(i)
  111. if current_threshold < i:
  112. threshold_found = True
  113. # update min max values
  114. min_value = svd_values.min()
  115. max_value = svd_values.max()
  116. # update of min max values for noise
  117. current_min, current_max = min_max_list[current_noise]
  118. if min_value < current_min:
  119. current_min = min_value
  120. if max_value > current_max:
  121. current_max = max_value
  122. min_max_list[current_noise] = (current_min, current_max)
  123. print('%.2f%%' % (((i + 1) * 100 + (id * p_n * 100)) / (p_n * len(threshold_data))))
  124. sys.stdout.write("\033[F")
  125. for id, data in enumerate(svd_data):
  126. current_data = data
  127. threshold = threshold_data[id]
  128. min_value_svd, max_value_svd = min_max_list[threshold.get_noise()]
  129. if p_mode == 'svdn':
  130. current_data = utils.normalize_arr(current_data)
  131. if p_mode == 'svdne':
  132. current_data = utils.normalize_arr_with_range(current_data, min_value_svd, max_value_svd)
  133. final_svd_data.append(current_data)
  134. # display all data using matplotlib (configure plt)
  135. plt.rcParams['figure.figsize'] = (25, 18)
  136. plt.title(p_prefix + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + p_metric + ' metric, step ' + str(p_step) + ' normalization ' + p_mode, fontsize=20)
  137. plt.ylabel('Importance of noise [1, 999]', fontsize=14)
  138. plt.xlabel('Vector features', fontsize=16)
  139. for id, data in enumerate(final_svd_data):
  140. p_label = p_prefix + '_' + threshold_data[id].get_noise() + str(image_indices[id])
  141. plt.plot(data, label=p_label)
  142. plt.legend(bbox_to_anchor=(0.8, 1), loc=2, borderaxespad=0.2, fontsize=14)
  143. if not p_norm:
  144. plt.xlim(begin, end)
  145. # adapt ylim
  146. y_begin, y_end = p_ylim
  147. plt.ylim(y_begin, y_end)
  148. output_filename = p_prefix + "_threshold_1_to_" + str(p_n) + "_B" + str(begin) + "_E" + str(end) + "_" + p_metric + "_S" + str(p_step) + "_norm" + str(p_norm )+ "_" + p_mode
  149. if p_color:
  150. output_filename = output_filename + '_color'
  151. print("Generation of output figure... %s" % output_filename)
  152. output_path = os.path.join(pictures_folder, output_filename)
  153. if not os.path.exists(pictures_folder):
  154. os.makedirs(pictures_folder)
  155. plt.savefig(output_path, dpi=(200))
  156. if __name__== "__main__":
  157. main()