display_svd_data_scene.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Sep 14 21:02:42 2018
  5. @author: jbuisine
  6. """
  7. from __future__ import print_function
  8. import sys, os, getopt
  9. import numpy as np
  10. import random
  11. import time
  12. import json
  13. from PIL import Image
  14. from ipfml import processing, metrics, utils
  15. import ipfml.iqa.fr as fr_iqa
  16. from skimage import color
  17. import matplotlib.pyplot as plt
  18. from modules.utils.data import get_svd_data
  19. from modules.utils import config as cfg
  20. # getting configuration information
  21. config_filename = cfg.config_filename
  22. zone_folder = cfg.zone_folder
  23. min_max_filename = cfg.min_max_filename_extension
  24. # define all scenes values
  25. scenes_list = cfg.scenes_names
  26. scenes_indices = cfg.scenes_indices
  27. choices = cfg.normalization_choices
  28. path = cfg.dataset_path
  29. zones = cfg.zones_indices
  30. seuil_expe_filename = cfg.seuil_expe_filename
  31. metric_choices = cfg.metric_choices_labels
  32. max_nb_bits = 8
  33. display_error = False
  34. def display_svd_values(p_scene, p_interval, p_indices, p_metric, p_mode, p_step, p_norm, p_ylim):
  35. """
  36. @brief Method which gives information about svd curves from zone of picture
  37. @param p_scene, scene expected to show svd values
  38. @param p_interval, interval [begin, end] of svd data to display
  39. @param p_interval, interval [begin, end] of samples or minutes from render generation engine
  40. @param p_metric, metric computed to show
  41. @param p_mode, normalization's mode
  42. @param p_norm, normalization or not of selected svd data
  43. @param p_ylim, ylim choice to better display of data
  44. @return nothing
  45. """
  46. max_value_svd = 0
  47. min_value_svd = sys.maxsize
  48. image_indices = []
  49. scenes = os.listdir(path)
  50. # remove min max file from scenes folder
  51. scenes = [s for s in scenes if min_max_filename not in s]
  52. begin_data, end_data = p_interval
  53. begin_index, end_index = p_indices
  54. data_min_max_filename = os.path.join(path, p_metric + min_max_filename)
  55. # go ahead each scenes
  56. for id_scene, folder_scene in enumerate(scenes):
  57. if p_scene == folder_scene:
  58. scene_path = os.path.join(path, folder_scene)
  59. config_file_path = os.path.join(scene_path, config_filename)
  60. with open(config_file_path, "r") as config_file:
  61. last_image_name = config_file.readline().strip()
  62. prefix_image_name = config_file.readline().strip()
  63. start_index_image = config_file.readline().strip()
  64. end_index_image = config_file.readline().strip()
  65. step_counter = int(config_file.readline().strip())
  66. # construct each zones folder name
  67. zones_folder = []
  68. # get zones list info
  69. for index in zones:
  70. index_str = str(index)
  71. if len(index_str) < 2:
  72. index_str = "0" + index_str
  73. current_zone = "zone"+index_str
  74. zones_folder.append(current_zone)
  75. images_data = []
  76. images_indices = []
  77. threshold_learned_zones = []
  78. for id, zone_folder in enumerate(zones_folder):
  79. # get threshold information
  80. zone_path = os.path.join(scene_path, zone_folder)
  81. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  82. # open treshold path and get this information
  83. with open(path_seuil, "r") as seuil_file:
  84. threshold_learned = int(seuil_file.readline().strip())
  85. threshold_learned_zones.append(threshold_learned)
  86. current_counter_index = int(start_index_image)
  87. end_counter_index = int(end_index_image)
  88. threshold_mean = np.mean(np.asarray(threshold_learned_zones))
  89. threshold_image_found = False
  90. file_path = os.path.join(scene_path, prefix_image_name + "{}.png")
  91. svd_data = []
  92. while(current_counter_index <= end_counter_index):
  93. current_counter_index_str = str(current_counter_index)
  94. while len(start_index_image) > len(current_counter_index_str):
  95. current_counter_index_str = "0" + current_counter_index_str
  96. image_path = file_path.format(str(current_counter_index_str))
  97. img = Image.open(image_path)
  98. svd_values = get_svd_data(p_metric, img)
  99. if p_norm:
  100. svd_values = svd_values[begin_data:end_data]
  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. # keep in memory used data
  109. if current_counter_index % p_step == 0:
  110. if current_counter_index >= begin_index and current_counter_index <= end_index:
  111. images_indices.append(current_counter_index_str)
  112. svd_data.append(svd_values)
  113. if threshold_mean < int(current_counter_index) and not threshold_image_found:
  114. threshold_image_found = True
  115. threshold_image_zone = current_counter_index_str
  116. current_counter_index += step_counter
  117. print('%.2f%%' % (current_counter_index / end_counter_index * 100))
  118. sys.stdout.write("\033[F")
  119. # all indices of picture to plot
  120. print(images_indices)
  121. for id, data in enumerate(svd_data):
  122. current_data = data
  123. if not p_norm:
  124. current_data = current_data[begin_data:end_data]
  125. if p_mode == 'svdn':
  126. current_data = utils.normalize_arr(current_data)
  127. if p_mode == 'svdne':
  128. current_data = utils.normalize_arr_with_range(current_data, min_value_svd, max_value_svd)
  129. images_data.append(current_data)
  130. # display all data using matplotlib (configure plt)
  131. fig = plt.figure(figsize=(30, 22))
  132. plt.rc('xtick', labelsize=22)
  133. plt.rc('ytick', labelsize=22)
  134. plt.title(p_scene + ' scene interval information SVD['+ str(begin_data) +', '+ str(end_data) +'], from scenes indices [' + str(begin_index) + ', '+ str(end_index) + '], ' + p_metric + ' metric, ' + p_mode + ', with step of ' + str(p_step) + ', svd norm ' + str(p_norm), fontsize=24)
  135. plt.ylabel('Component values', fontsize=24)
  136. plt.xlabel('Vector features', fontsize=24)
  137. for id, data in enumerate(images_data):
  138. p_label = p_scene + '_' + str(images_indices[id])
  139. if images_indices[id] == threshold_image_zone:
  140. plt.plot(data, label=p_label + " (threshold mean)", lw=4, color='red')
  141. else:
  142. plt.plot(data, label=p_label)
  143. plt.legend(bbox_to_anchor=(0.65, 0.98), loc=2, borderaxespad=0.2, fontsize=22)
  144. start_ylim, end_ylim = p_ylim
  145. plt.ylim(start_ylim, end_ylim)
  146. plot_name = p_scene + '_' + p_metric + '_' + str(p_step) + '_' + p_mode + '_' + str(p_norm) + '.png'
  147. plt.savefig(plot_name)
  148. def main():
  149. # by default p_step value is 10 to enable all photos
  150. p_step = 10
  151. p_ylim = (0, 1)
  152. if len(sys.argv) <= 1:
  153. print('Run with default parameters...')
  154. print('python display_svd_data_scene.py --scene A --interval "0,800" --indices "0, 900" --metric lab --mode svdne --step 50 --norm 0 --ylim "0, 0.1"')
  155. sys.exit(2)
  156. try:
  157. opts, args = getopt.getopt(sys.argv[1:], "hs:i:i:z:l:m:s:n:e:y", ["help=", "scene=", "interval=", "indices=", "metric=", "mode=", "step=", "norm=", "error=", "ylim="])
  158. except getopt.GetoptError:
  159. # print help information and exit:
  160. print('python display_svd_data_scene.py --scene A --interval "0,800" --indices "0, 900" --metric lab --mode svdne --step 50 --norm 0 --ylim "0, 0.1"')
  161. sys.exit(2)
  162. for o, a in opts:
  163. if o == "-h":
  164. print('python display_svd_data_scene.py --scene A --interval "0,800" --indices "0, 900" --metric lab --mode svdne --step 50 --norm 0 --ylim "0, 0.1"')
  165. sys.exit()
  166. elif o in ("-s", "--scene"):
  167. p_scene = a
  168. if p_scene not in scenes_indices:
  169. assert False, "Invalid scene choice"
  170. else:
  171. p_scene = scenes_list[scenes_indices.index(p_scene)]
  172. elif o in ("-i", "--interval"):
  173. p_interval = list(map(int, a.split(',')))
  174. elif o in ("-i", "--indices"):
  175. p_indices = list(map(int, a.split(',')))
  176. elif o in ("-m", "--metric"):
  177. p_metric = a
  178. if p_metric not in metric_choices:
  179. assert False, "Invalid metric choice"
  180. elif o in ("-m", "--mode"):
  181. p_mode = a
  182. if p_mode not in choices:
  183. assert False, "Invalid normalization choice, expected ['svd', 'svdn', 'svdne']"
  184. elif o in ("-s", "--step"):
  185. p_step = int(a)
  186. elif o in ("-n", "--norm"):
  187. p_norm = int(a)
  188. elif o in ("-y", "--ylim"):
  189. p_ylim = list(map(float, a.split(',')))
  190. else:
  191. assert False, "unhandled option"
  192. display_svd_values(p_scene, p_interval, p_indices, p_metric, p_mode, p_step, p_norm, p_ylim)
  193. if __name__== "__main__":
  194. main()