noise_svd_tend_visualization.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 numpy as np
  8. import matplotlib.pyplot as plt
  9. plt.style.use('ggplot')
  10. noise_list = cfg.noise_labels
  11. generated_folder = cfg.generated_folder
  12. filename_ext = cfg.filename_ext
  13. metric_choices = cfg.metric_choices_labels
  14. normalization_choices = cfg.normalization_choices
  15. pictures_folder = cfg.pictures_output_folder
  16. step_picture = 10
  17. error_data_choices = ['MAE', 'MSE']
  18. def compute_mae(previous_data, current_data):
  19. n = len(previous_data)
  20. mae_sum = 0.
  21. for id, x in enumerate(current_data):
  22. y = previous_data[id] # current data reduces error
  23. mae_sum += abs(x - y)
  24. return mae_sum / n
  25. def compute_mse(previous_data, current_data):
  26. n = len(previous_data)
  27. mse_sum = 0.
  28. for id, x in enumerate(current_data):
  29. y = previous_data[id] # current data reduces error
  30. mse_sum += abs(x - y)
  31. return mse_sum / n
  32. def main():
  33. # default values
  34. p_step = 1
  35. p_color = 0
  36. p_norm = 0
  37. p_ylim = (0, 1)
  38. max_value_svd = 0
  39. min_value_svd = sys.maxsize
  40. if len(sys.argv) <= 1:
  41. print('python noise_svd_mae_visualization.py --prefix generated/prefix/noise --metric lab --mode svdn --n 300 --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1" --error MAE')
  42. sys.exit(2)
  43. try:
  44. opts, args = getopt.getopt(sys.argv[1:], "h:p:m:m:n:i:s:c:n:y:e", ["help=", "prefix=", "metric=", "mode=", "n=", "interval=", "step=", "color=", "norm=", "ylim=", "error="])
  45. except getopt.GetoptError:
  46. # print help information and exit:
  47. print('python noise_svd_mae_visualization.py --prefix generated/prefix/noise --metric lab --mode svdn --n 300 --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1" --error MAE')
  48. sys.exit(2)
  49. for o, a in opts:
  50. if o == "-h":
  51. print('python noise_svd_mae_visualization.py --prefix generated/prefix/noise --metric lab --mode svdn --n 300 --interval "0, 200" --step 30 --color 1 --norm 1 --ylim "0, 1" --error MAE')
  52. sys.exit()
  53. elif o in ("-p", "--prefix"):
  54. p_path = a
  55. elif o in ("-m", "--mode"):
  56. p_mode = a
  57. if not p_mode in normalization_choices:
  58. assert False, "Unknown normalization choice, %s" % normalization_choices
  59. elif o in ("-m", "--metric"):
  60. p_metric = a
  61. if not p_metric in metric_choices:
  62. assert False, "Unknown metric choice, %s" % metric_choices
  63. elif o in ("-n", "--n"):
  64. p_n = int(a)
  65. elif o in ("-n", "--norm"):
  66. p_norm = int(a)
  67. elif o in ("-c", "--color"):
  68. p_color = int(a)
  69. elif o in ("-i", "--interval"):
  70. p_interval = list(map(int, a.split(',')))
  71. elif o in ("-s", "--step"):
  72. p_step = int(a)
  73. elif o in ("-y", "--ylim"):
  74. p_ylim = list(map(float, a.split(',')))
  75. elif o in ("-e", "--error"):
  76. p_error = a
  77. if p_error not in error_data_choices:
  78. assert False, "Unknow error choice to display %s" % error_data_choices
  79. else:
  80. assert False, "unhandled option"
  81. p_prefix = p_path.split('/')[1].replace('_', '')
  82. noise_name = p_path.split('/')[2]
  83. if p_color:
  84. file_path = os.path.join(p_path, p_prefix + "_" + noise_name + "_color_{}." + filename_ext)
  85. else:
  86. file_path = os.path.join(p_path, p_prefix + "_" + noise_name + "_{}." + filename_ext)
  87. begin, end = p_interval
  88. all_svd_data = []
  89. svd_data = []
  90. image_indices = []
  91. noise_indices = range(1, p_n)[::-1]
  92. # get all data from images
  93. for i in noise_indices:
  94. if i % step_picture == 0:
  95. image_path = file_path.format(str(i))
  96. img = Image.open(image_path)
  97. svd_values = dt.get_svd_data(p_metric, img)
  98. if p_norm:
  99. svd_values = svd_values[begin:end]
  100. all_svd_data.append(svd_values)
  101. # update min max values
  102. min_value = svd_values.min()
  103. max_value = svd_values.max()
  104. if min_value < min_value_svd:
  105. min_value_svd = min_value
  106. if max_value > min_value_svd:
  107. max_value_svd = max_value
  108. print('%.2f%%' % ((p_n - i + 1) / p_n * 100))
  109. sys.stdout.write("\033[F")
  110. previous_data = []
  111. error_data = [0.]
  112. for id, data in enumerate(all_svd_data):
  113. current_id = (p_n - ((id + 1) * 10))
  114. if current_id % p_step == 0:
  115. current_data = data
  116. if p_mode == 'svdn':
  117. current_data = utils.normalize_arr(current_data)
  118. if p_mode == 'svdne':
  119. current_data = utils.normalize_arr_with_range(current_data, min_value_svd, max_value_svd)
  120. svd_data.append(current_data)
  121. image_indices.append(current_id)
  122. if len(previous_data) > 0:
  123. current_mae = compute_mae(previous_data, current_data)
  124. error_data.append(current_mae)
  125. if len(previous_data) == 0:
  126. previous_data = current_data
  127. # display all data using matplotlib (configure plt)
  128. gridsize = (3, 2)
  129. # fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(30, 22))
  130. fig = plt.figure(figsize=(30, 22))
  131. ax1 = plt.subplot2grid(gridsize, (0, 0), colspan=2, rowspan=2)
  132. ax2 = plt.subplot2grid(gridsize, (2, 0), colspan=2)
  133. ax1.set_title(p_prefix + ', ' + noise_name + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + p_metric + ' metric, step ' + str(p_step) + ' normalization ' + p_mode)
  134. ax1.set_label('Importance of noise [1, 999]')
  135. ax1.set_xlabel('Vector features')
  136. for id, data in enumerate(svd_data):
  137. p_label = p_prefix + str(image_indices[id]) + " | MAE : " + str(error_data[id])
  138. ax1.plot(data, label=p_label)
  139. ax1.legend(bbox_to_anchor=(0.8, 1), loc=2, borderaxespad=0.2, fontsize=12)
  140. if not p_norm:
  141. ax1.set_xlim(begin, end)
  142. # adapt ylim
  143. y_begin, y_end = p_ylim
  144. ax1.set_ylim(y_begin, y_end)
  145. output_filename = p_prefix + "_" + noise_name + "_1_to_" + str(p_n) + "_B" + str(begin) + "_E" + str(end) + "_" + p_metric + "_S" + str(p_step) + "_norm" + str(p_norm )+ "_" + p_mode + "_" + p_error
  146. if p_color:
  147. output_filename = output_filename + '_color'
  148. ax2.set_title(p_error + " information for : " + p_prefix + ', ' + noise_name + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + p_metric + ' metric, step ' + str(p_step) + ', normalization ' + p_mode)
  149. ax2.set_ylabel('Mean Squared Error')
  150. ax2.set_xlabel('Number of samples per pixels')
  151. ax2.set_xticks(range(len(image_indices)))
  152. ax2.set_xticklabels(image_indices)
  153. ax2.plot(error_data)
  154. print("Generation of output figure... %s" % output_filename)
  155. output_path = os.path.join(pictures_folder, output_filename)
  156. if not os.path.exists(pictures_folder):
  157. os.makedirs(pictures_folder)
  158. fig.savefig(output_path, dpi=(200))
  159. if __name__== "__main__":
  160. main()