noise_svd_tend_visualization.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # main imports
  2. import sys, os, argparse
  3. import numpy as np
  4. # image processing imports
  5. from PIL import Image
  6. import matplotlib.pyplot as plt
  7. from ipfml import utils
  8. import ipfml.iqa.fr as fr_iqa
  9. # modules and config imports
  10. sys.path.insert(0, '') # trick to enable import of main folder module
  11. import custom_config as cfg
  12. from data_attributes import get_image_features
  13. # others variables
  14. noise_list = cfg.noise_labels
  15. generated_folder = cfg.generated_folder
  16. filename_ext = cfg.filename_ext
  17. feature_choices = cfg.features_choices_labels
  18. normalization_choices = cfg.normalization_choices
  19. pictures_folder = cfg.pictures_output_folder
  20. error_data_choices = cfg.error_data_choices
  21. steparam_picture = 10
  22. def get_error_distance(param_error, y_true, y_test):
  23. function_name = param_error
  24. try:
  25. error_method = getattr(fr_iqa, function_name)
  26. except AttributeError:
  27. raise NotImplementedError("Error method `{}` not implement `{}`".format(fr_iqa.__name__, function_name))
  28. return error_method(y_true, y_test)
  29. def main():
  30. max_value_svd = 0
  31. min_value_svd = sys.maxsize
  32. parser = argparse.ArgumentParser(description="Display svd tend of images with noise level")
  33. parser.add_argument('--prefix', type=str, help='Generated noise folder prefix (ex: `generated/prefix/noise`)')
  34. parser.add_argument('--mode', type=str, help='Kind of normalization', default=normalization_choices)
  35. parser.add_argument('--feature', type=str, help='feature choice', default=feature_choices)
  36. parser.add_argument('--n', type=int, help='Number of images')
  37. parser.add_argument('--color', type=int, help='Use of color or grey level', default=0)
  38. parser.add_argument('--norm', type=int, help='Use of normalization from interval or whole data vector', default=0)
  39. parser.add_argument('--interval', type=str, help='Interval data choice (ex: `0, 200`)', default="0, 200")
  40. parser.add_argument('--step', type=int, help='Step of image indices to keep', default=1)
  41. parser.add_argument('--ylim', type=str, help='Limite to display data (ex: `0, 1`)', default="0, 1")
  42. parser.add_argument('--error', type=str, help='Error used for information data', default=error_data_choices)
  43. args = parser.parse_args()
  44. param_prefix = args.prefix
  45. param_mode = args.mode
  46. param_feature = args.feature
  47. param_n = args.n
  48. param_color = args.color
  49. param_norm = args.norm
  50. param_interval = list(map(int, args.interval.split(',')))
  51. param_step = args.step
  52. param_ylim = list(map(float, args.ylim.split(',')))
  53. param_error = args.error
  54. param_prefix = param_prefix.split('/')[1].replace('_', '')
  55. noise_name = param_prefix.split('/')[2]
  56. if param_color:
  57. file_path = os.path.join(param_prefix, param_prefix + "_" + noise_name + "_color_{}." + filename_ext)
  58. else:
  59. file_path = os.path.join(param_prefix, param_prefix + "_" + noise_name + "_{}." + filename_ext)
  60. begin, end = param_interval
  61. all_svd_data = []
  62. svd_data = []
  63. image_indices = []
  64. noise_indices = range(1, param_n)[::-1]
  65. # get all data from images
  66. for i in noise_indices:
  67. if i % steparam_picture == 0:
  68. image_path = file_path.format(str(i))
  69. img = Image.open(image_path)
  70. svd_values = get_image_features(param_feature, img)
  71. if param_norm:
  72. svd_values = svd_values[begin:end]
  73. all_svd_data.append(svd_values)
  74. # update min max values
  75. min_value = svd_values.min()
  76. max_value = svd_values.max()
  77. if min_value < min_value_svd:
  78. min_value_svd = min_value
  79. if max_value > max_value_svd:
  80. max_value_svd = max_value
  81. print('%.2f%%' % ((param_n - i + 1) / param_n * 100))
  82. sys.stdout.write("\033[F")
  83. previous_data = []
  84. error_data = [0.]
  85. for id, data in enumerate(all_svd_data):
  86. current_id = (param_n - ((id + 1) * 10))
  87. if current_id % param_step == 0:
  88. current_data = data
  89. if param_mode == 'svdn':
  90. current_data = utils.normalize_arr(current_data)
  91. if param_mode == 'svdne':
  92. current_data = utils.normalize_arr_with_range(current_data, min_value_svd, max_value_svd)
  93. svd_data.append(current_data)
  94. image_indices.append(current_id)
  95. # use of whole image data for computation of ssim or psnr
  96. if param_error == 'ssim' or param_error == 'psnr':
  97. image_path = file_path.format(str(current_id))
  98. current_data = np.asarray(Image.open(image_path))
  99. if len(previous_data) > 0:
  100. current_error = get_error_distance(param_error, previous_data, current_data)
  101. error_data.append(current_error)
  102. if len(previous_data) == 0:
  103. previous_data = current_data
  104. # display all data using matplotlib (configure plt)
  105. gridsize = (3, 2)
  106. # fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(30, 22))
  107. fig = plt.figure(figsize=(30, 22))
  108. ax1 = plt.subplot2grid(gridsize, (0, 0), colspan=2, rowspan=2)
  109. ax2 = plt.subplot2grid(gridsize, (2, 0), colspan=2)
  110. ax1.set_title(param_prefix + ', ' + noise_name + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + param_feature + ' feature, step ' + str(param_step) + ' normalization ' + param_mode)
  111. ax1.set_label('Importance of noise [1, 999]')
  112. ax1.set_xlabel('Vector features')
  113. for id, data in enumerate(svd_data):
  114. param_label = param_prefix + str(image_indices[id]) + " | " + param_error + ": " + str(error_data[id])
  115. ax1.plot(data, label=param_label)
  116. ax1.legend(bbox_to_anchor=(0.75, 1), loc=2, borderaxespad=0.2, fontsize=12)
  117. if not param_norm:
  118. ax1.set_xlim(begin, end)
  119. # adapt ylim
  120. y_begin, y_end = param_ylim
  121. ax1.set_ylim(y_begin, y_end)
  122. output_filename = param_prefix + "_" + noise_name + "_1_to_" + str(param_n) + "_B" + str(begin) + "_E" + str(end) + "_" + param_feature + "_S" + str(param_step) + "_norm" + str(param_norm )+ "_" + param_mode + "_" + param_error
  123. if param_color:
  124. output_filename = output_filename + '_color'
  125. ax2.set_title(param_error + " information for : " + param_prefix + ', ' + noise_name + ' noise, interval information ['+ str(begin) +', '+ str(end) +'], ' + param_feature + ' feature, step ' + str(param_step) + ', normalization ' + param_mode)
  126. ax2.set_ylabel(param_error + ' error')
  127. ax2.set_xlabel('Number of samples per pixels')
  128. ax2.set_xticks(range(len(image_indices)))
  129. ax2.set_xticklabels(image_indices)
  130. ax2.plot(error_data)
  131. print("Generation of output figure... %s" % output_filename)
  132. output_path = os.path.join(pictures_folder, output_filename)
  133. if not os.path.exists(pictures_folder):
  134. os.makedirs(pictures_folder)
  135. fig.savefig(output_path, dpi=(200))
  136. if __name__== "__main__":
  137. main()