display_scenes_zones.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. from skimage import color
  16. import matplotlib.pyplot as plt
  17. from modules.utils import config as cfg
  18. config_filename = cfg.config_filename
  19. zone_folder = cfg.zone_folder
  20. min_max_filename = cfg.min_max_filename_extension
  21. # define all scenes values
  22. scenes_list = cfg.scenes_names
  23. scenes_indexes = cfg.scenes_indices
  24. choices = cfg.normalization_choices
  25. path = cfg.dataset_path
  26. zones = cfg.zones_indices
  27. seuil_expe_filename = cfg.seuil_expe_filename
  28. metric_choices = cfg.metric_choices_labels
  29. def display_data_scenes(data_type, p_scene, p_kind):
  30. """
  31. @brief Method which displays data from scene
  32. @param data_type, metric choice
  33. @param scene, scene choice
  34. @param mode, normalization choice
  35. @return nothing
  36. """
  37. scenes = os.listdir(path)
  38. # remove min max file from scenes folder
  39. scenes = [s for s in scenes if min_max_filename not in s]
  40. # go ahead each scenes
  41. for id_scene, folder_scene in enumerate(scenes):
  42. if p_scene == folder_scene:
  43. print(folder_scene)
  44. scene_path = os.path.join(path, folder_scene)
  45. config_file_path = os.path.join(scene_path, config_filename)
  46. with open(config_file_path, "r") as config_file:
  47. last_image_name = config_file.readline().strip()
  48. prefix_image_name = config_file.readline().strip()
  49. start_index_image = config_file.readline().strip()
  50. end_index_image = config_file.readline().strip()
  51. step_counter = int(config_file.readline().strip())
  52. # construct each zones folder name
  53. zones_folder = []
  54. # get zones list info
  55. for index in zones:
  56. index_str = str(index)
  57. if len(index_str) < 2:
  58. index_str = "0" + index_str
  59. current_zone = "zone"+index_str
  60. zones_folder.append(current_zone)
  61. zones_images_data = []
  62. threshold_info = []
  63. for id_zone, zone_folder in enumerate(zones_folder):
  64. zone_path = os.path.join(scene_path, zone_folder)
  65. current_counter_index = int(start_index_image)
  66. end_counter_index = int(end_index_image)
  67. # get threshold information
  68. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  69. # open treshold path and get this information
  70. with open(path_seuil, "r") as seuil_file:
  71. seuil_learned = int(seuil_file.readline().strip())
  72. threshold_image_found = False
  73. while(current_counter_index <= end_counter_index and not threshold_image_found):
  74. if seuil_learned < int(current_counter_index):
  75. current_counter_index_str = str(current_counter_index)
  76. while len(start_index_image) > len(current_counter_index_str):
  77. current_counter_index_str = "0" + current_counter_index_str
  78. threshold_image_found = True
  79. threshold_image_zone = current_counter_index_str
  80. threshold_info.append(threshold_image_zone)
  81. current_counter_index += step_counter
  82. # all indexes of picture to plot
  83. images_indexes = [start_index_image, threshold_image_zone, end_index_image]
  84. images_data = []
  85. print(images_indexes)
  86. for index in images_indexes:
  87. img_path = os.path.join(scene_path, prefix_image_name + index + ".png")
  88. current_img = Image.open(img_path)
  89. img_blocks = processing.divide_in_blocks(current_img, (200, 200))
  90. # getting expected block id
  91. block = img_blocks[id_zone]
  92. # get data from mode
  93. # Here you can add the way you compute data
  94. if data_type == 'lab':
  95. block_file_path = '/tmp/lab_img.png'
  96. block.save(block_file_path)
  97. data = processing.get_LAB_L_SVD_s(Image.open(block_file_path))
  98. if data_type == 'mscn_revisited':
  99. img_mscn_revisited = processing.rgb_to_mscn(block)
  100. # save tmp as img
  101. img_output = Image.fromarray(img_mscn_revisited.astype('uint8'), 'L')
  102. mscn_revisited_file_path = '/tmp/mscn_revisited_img.png'
  103. img_output.save(mscn_revisited_file_path)
  104. img_block = Image.open(mscn_revisited_file_path)
  105. # extract from temp image
  106. data = metrics.get_SVD_s(img_block)
  107. if data_type == 'mscn':
  108. img_gray = np.array(color.rgb2gray(np.asarray(block))*255, 'uint8')
  109. img_mscn = processing.calculate_mscn_coefficients(img_gray, 7)
  110. img_mscn_norm = utils.normalize_2D_arr(img_mscn)
  111. img_mscn_gray = np.array(img_mscn_norm*255, 'uint8')
  112. data = metrics.get_SVD_s(img_mscn_gray)
  113. if data_type == 'low_bits_6':
  114. low_bits_6 = processing.rgb_to_LAB_L_low_bits(block, 63)
  115. # extract from temp image
  116. data = metrics.get_SVD_s(low_bits_6)
  117. if data_type == 'low_bits_5':
  118. low_bits_5 = processing.rgb_to_LAB_L_low_bits(block, 31)
  119. # extract from temp image
  120. data = metrics.get_SVD_s(low_bits_5)
  121. if data_type == 'low_bits_4':
  122. low_bits_4 = processing.rgb_to_LAB_L_low_bits(block)
  123. # extract from temp image
  124. data = metrics.get_SVD_s(low_bits_4)
  125. if data_type == 'low_bits_3':
  126. low_bits_3 = processing.rgb_to_LAB_L_low_bits(block, 7)
  127. # extract from temp image
  128. data = metrics.get_SVD_s(low_bits_3)
  129. if data_type == 'low_bits_2':
  130. low_bits_2 = processing.rgb_to_LAB_L_low_bits(block, 3)
  131. # extract from temp image
  132. data = metrics.get_SVD_s(low_bits_2)
  133. ##################
  134. # Data mode part #
  135. ##################
  136. # modify data depending mode
  137. if p_kind == 'svdn':
  138. data = utils.normalize_arr(data)
  139. if p_kind == 'svdne':
  140. path_min_max = os.path.join(path, data_type + min_max_filename)
  141. with open(path_min_max, 'r') as f:
  142. min_val = float(f.readline())
  143. max_val = float(f.readline())
  144. data = utils.normalize_arr_with_range(data, min_val, max_val)
  145. # append of data
  146. images_data.append(data)
  147. zones_images_data.append(images_data)
  148. fig=plt.figure(figsize=(8, 8))
  149. fig.suptitle(data_type + " values for " + p_scene + " scene (normalization : " + p_kind + ")", fontsize=20)
  150. for id, data in enumerate(zones_images_data):
  151. fig.add_subplot(4, 4, (id + 1))
  152. plt.plot(data[0], label='Noisy_' + start_index_image)
  153. plt.plot(data[1], label='Threshold_' + threshold_info[id])
  154. plt.plot(data[2], label='Reference_' + end_index_image)
  155. plt.ylabel(data_type + ' SVD, ZONE_' + str(id + 1), fontsize=18)
  156. plt.xlabel('Vector features', fontsize=18)
  157. plt.legend(bbox_to_anchor=(0.5, 1), loc=2, borderaxespad=0.2, fontsize=18)
  158. plt.ylim(0, 0.1)
  159. plt.show()
  160. def main():
  161. if len(sys.argv) <= 1:
  162. print('Run with default parameters...')
  163. print('python generate_all_data.py --metric all --scene A --kind svdn')
  164. sys.exit(2)
  165. try:
  166. opts, args = getopt.getopt(sys.argv[1:], "hm:s:k", ["help=", "metric=", "scene=", "kind="])
  167. except getopt.GetoptError:
  168. # print help information and exit:
  169. print('python generate_all_data.py --metric all --scene A --kind svdn')
  170. sys.exit(2)
  171. for o, a in opts:
  172. if o == "-h":
  173. print('python generate_all_data.py --metric all --scene A --kind svdn')
  174. sys.exit()
  175. elif o in ("-m", "--metric"):
  176. p_metric = a
  177. if p_metric != 'all' and p_metric not in metric_choices:
  178. assert False, "Invalid metric choice"
  179. elif o in ("-s", "--scene"):
  180. p_scene = a
  181. if p_scene not in scenes_indexes:
  182. assert False, "Invalid metric choice"
  183. else:
  184. p_scene = scenes_list[scenes_indexes.index(p_scene)]
  185. elif o in ("-k", "--kind"):
  186. p_kind = a
  187. if p_kind not in choices:
  188. assert False, "Invalid metric choice"
  189. else:
  190. assert False, "unhandled option"
  191. display_data_scenes(p_metric, p_scene, p_kind)
  192. if __name__== "__main__":
  193. main()