miamResults4PublicationLIGHT.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # import
  2. # ------------------------------------------------------------------------------------------
  3. import os
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. import multiprocessing as mp
  7. import easygui
  8. import imageio
  9. # miam import
  10. import miam.image.Image as MIMG
  11. import miam.image.imageType as MTYPE
  12. import miam.image.channel as MCH
  13. import miam.processing.ColorSpaceTransform as MCST
  14. import miam.processing.TMO_Lightness as TMO_L
  15. import miam.processing.ContrastControl as PCC
  16. import miam.histogram.Histogram as MHIST
  17. import miam.aesthetics.LightnessAesthetics as MLAC
  18. import miam.aesthetics.Palette as MPAL
  19. import miam.imageDB.ImageDB
  20. import miam.imageDB.POGChecker
  21. import miam.imageDB.HwHDRBuilder
  22. import miam.html.generator
  23. import miam.utils
  24. import miam.pointcloud.PointCloud2D as MPC2D
  25. import miam.classification.kmeans
  26. import miam.math.Distance
  27. import miam.math.Normalize
  28. # ------------------------------------------------------------------------------------------
  29. # MIAM project 2020
  30. # ------------------------------------------------------------------------------------------
  31. # author: remi.cozot@univ-littoral.fr
  32. # ------------------------------------------------------------------------------------------
  33. # --------------------------------------------> Cluster
  34. # --------------------------------------------> Palette
  35. def clusterLightnessHist():
  36. # ------------------------------------------------------------------------------------------
  37. #
  38. # ------------------------------------------------------------------------------------------
  39. # config: configfile
  40. jsonfile = "../DB/config_POG_DB.json"
  41. # histogram files
  42. # all lightness moments file
  43. allLightness_Moments = "../DB/POG_DB_L_Moments.npy"
  44. # all lightness histogram file
  45. allLightness_50bins = "../DB/POG_DB_L_Hists_50bins.npy"
  46. allLightness_100bins = "../DB/POG_DB_L_Hists_100bins.npy"
  47. # clusters
  48. centroids_L_Hists_50bins = "../DB/POG_DB_centroids_L_Hists_50bins.npy"
  49. assigments_L_Hists_50bins = "../DB/POG_DB_assigments_L_Hists_50bins.npy"
  50. assigmentsIdx_L_Hists_50bins = "../DB/POG_DB_assigmentsIdx_L_Hists_50bins.npy"
  51. distanceToCentroids = "../DB/POG_DB_dist_to_centroids_L_Hists_50bins.npy"
  52. # ------------------------------------------------------------------------------------------
  53. # boolean to select what to do
  54. # ------------------------------------------------------------------------------------------
  55. display_StdMean = True
  56. clusterHistograms = False
  57. computeDistToCentroids = False
  58. displayClusters = True
  59. distance1percent = False
  60. displayDistance = True
  61. displayBestPerClass = True
  62. # pog
  63. # ------------------------------------------------------------------------------------------
  64. # loading POG
  65. pogDB = miam.imageDB.ImageDB.ImageDB(jsonConfigFile =jsonfile)
  66. pogDB.check(miam.imageDB.POGChecker.POGChecker(local=True))
  67. print("MIAM[POG Cluster Lightness Histogram]")
  68. # POG: display Lightness Moments
  69. # ------------------------------------------------------------------------------------------
  70. if display_StdMean:
  71. # load files
  72. allMoments = np.load(allLightness_Moments)
  73. # display
  74. plt.figure("Lightness: standard deviations/mean")
  75. plt.plot(allMoments[:,0],allMoments[:,1],'bo',markersize=2)
  76. pc = MPC2D.PointCloud2D(allMoments[:,0],allMoments[:,1])
  77. xx, yy = MPC2D.PointCloud2D.toXYarray(pc.contour(0.05))
  78. plt.plot(xx,yy,'r')
  79. plt.show(block=True)
  80. # POG: compute cluster Histograms
  81. # ------------------------------------------------------------------------------------------
  82. if clusterHistograms:
  83. print("MIAM[",pogDB.name," clustering Lightness launch !]")
  84. allHists = np.load(allLightness_50bins)
  85. # k-means
  86. km = miam.classification.kmeans.kmeans(miam.math.Distance.Distance(miam.math.Distance.cosineDistance),
  87. miam.math.Normalize.Normalize(miam.math.Normalize.cosineNorm))
  88. centroids,assigments,assigmentsIdx = km.kmeans(allHists, 5, 50, display = None)
  89. print("MIAM[",pogDB.name," clustering done !]")
  90. np.save(centroids_L_Hists_50bins,centroids)
  91. np.save(assigments_L_Hists_50bins,assigments)
  92. np.save(assigmentsIdx_L_Hists_50bins,assigmentsIdx)
  93. print("MIAM[",pogDB.name," clustering save saved !]")
  94. # POG: cluster analysis PART 1: distance to each centroids
  95. # -----------------------------------------------------------------------------------------
  96. if computeDistToCentroids:
  97. # load files
  98. allHists = np.load(allLightness_50bins) # lightnesshsitograms
  99. allMoments = np.load(allLightness_Moments) # lightness moments mean, std, skewness
  100. centroids = np.load(centroids_L_Hists_50bins, allow_pickle = True) # centroids: 5 histograms
  101. assigments = np.load(assigments_L_Hists_50bins, allow_pickle = True) # assigments
  102. assigmentsIdx = np.load(assigmentsIdx_L_Hists_50bins, allow_pickle = True) # assigments index: for each histograms index of class
  103. print("MIAM[",pogDB.name," compute fo each distance to all centroid !]")
  104. # get data
  105. L_mean = allMoments[:,0]
  106. L_std = allMoments[:,1]
  107. # buid histogram objects
  108. hCentroids = []
  109. for cent in centroids:
  110. c = MHIST.Histogram(cent,np.linspace(0,100,50+1),"hCentroid",MCH.channel.L)
  111. hCentroids.append(c)
  112. # distToCentroids
  113. distToCentroids = []
  114. # distance to centroids
  115. for i, rawHist in enumerate(allHists):
  116. # get raw image histogram and build Histogram Object
  117. h = MHIST.Histogram(allHists[i],np.linspace(0,100,50+1),"h_"+str(i),MCH.channel.L)
  118. distToCent = []
  119. for j,hc in enumerate(hCentroids):
  120. d = MHIST.Histogram.computeDistance(hc,h)
  121. distToCent.append(d)
  122. distToCentroids.append(distToCent)
  123. np.save(distanceToCentroids,distToCentroids)
  124. # POG: cluster analysis PART 2: aesthetics class
  125. # -----------------------------------------------------------------------------------------
  126. if displayClusters:
  127. # load files
  128. allHists = np.load(allLightness_50bins) # lightnesshsitograms
  129. allMoments = np.load(allLightness_Moments) # lightness moments mean, std, skewness
  130. centroids = np.load(centroids_L_Hists_50bins, allow_pickle = True) # centroids: 5 histograms
  131. assigments = np.load(assigments_L_Hists_50bins, allow_pickle = True) # assigments
  132. assigmentsIdx = np.load(assigmentsIdx_L_Hists_50bins, allow_pickle = True) # assigments index: for each histograms index of class
  133. distToCentroids = np.load(distanceToCentroids, allow_pickle = True) # for each histograms/image distance to each cluster
  134. # get data
  135. L_mean = allMoments[:,0]
  136. L_std = allMoments[:,1]
  137. # --------------------------------------------
  138. colors = ['b', 'g','r','c','m']
  139. # plot number of assigments per cluster
  140. figNBA = plt.figure("number of assigments per cluster ['b', 'g','r','c','m']")
  141. nbAss = []
  142. for i,p in enumerate(centroids): nbAss.append(len(assigmentsIdx[i]))
  143. plt.bar(colors,nbAss,color=colors)
  144. plt.show(block=False)
  145. # --------------------------------------------
  146. # plot histograms
  147. numberOfCluster =5
  148. fig, ax = plt.subplots(1,1)
  149. fig.suptitle("Centroids:"+str(numberOfCluster)+"/ Lightness Histograms ['b', 'g','r','c','m']")
  150. for i,c in enumerate(centroids):
  151. # create histograms object
  152. histoCentroids = MHIST.Histogram(c,np.linspace(0,100,50+1),"class("+str(i)+")",MCH.channel.L)
  153. # create image of palette
  154. histoCentroids.plot(ax,color=colors[i], title=True)
  155. #ax[1].plot(i*10,0,'o'+colors[i],markersize=10)
  156. #ax[1].axis("off")
  157. plt.show(block=False)
  158. # --------------------------------------------
  159. plt.figure("Lightness: clusters")
  160. colors = ['b', 'g','r','c','m','y','k']
  161. for i,assigmentId in enumerate(assigmentsIdx):
  162. print("assigmentId[",i,"].len:",len(assigmentId))
  163. pc = MPC2D.PointCloud2D(L_mean[assigmentId],L_std[assigmentId])
  164. # plot contour of clusters
  165. xx, yy = MPC2D.PointCloud2D.toXYarray(pc.contour(0.1))
  166. plt.plot(xx,yy,colors[i%len(colors)])
  167. plt.plot(L_mean[assigmentId],L_std[assigmentId],colors[i%len(colors)]+'o', markersize=1)
  168. plt.show(block=True)
  169. # -----------------------------------------------------------------------------------------
  170. if distance1percent:
  171. # load files
  172. allHists = np.load(allLightness_50bins) # lightnesshsitograms
  173. allMoments = np.load(allLightness_Moments) # lightness moments mean, std, skewness
  174. centroids = np.load(centroids_L_Hists_50bins, allow_pickle = True) # centroids: 5 histograms
  175. assigments = np.load(assigments_L_Hists_50bins, allow_pickle = True) # assigments
  176. assigmentsIdx = np.load(assigmentsIdx_L_Hists_50bins, allow_pickle = True) # assigments index: for each histograms index of class
  177. distToCentroids = np.load(distanceToCentroids, allow_pickle = True) # for each histograms/image distance to each cluster
  178. # get data
  179. L_mean = allMoments[:,0]
  180. L_std = allMoments[:,1]
  181. colors = ['b', 'g','r','c','m','y','k']
  182. plt.figure("Lightness: clusters 1%")
  183. for i, assigmentId in enumerate(assigmentsIdx):
  184. p25 = int(len(assigmentId) * 0.01)
  185. p100 = int(len(assigmentId) * 1.00)
  186. dd = distToCentroids[assigmentId,i]
  187. idxSorted = np.argsort(dd)#[::-1]
  188. i25 = idxSorted[0:p25]
  189. i100 = idxSorted[0:p100]
  190. ii25 = [assigmentId[k] for k in i25]
  191. ii100 = [assigmentId[k] for k in i100]
  192. pc25 = MPC2D.PointCloud2D(L_mean[ii25],L_std[ii25])
  193. pc100 = MPC2D.PointCloud2D(L_mean[ii100],L_std[ii100])
  194. xx25, yy25 = MPC2D.PointCloud2D.toXYarray(pc25.contour(0.1))
  195. xx100, yy100 = MPC2D.PointCloud2D.toXYarray(pc100.contour(0.1))
  196. plt.plot(xx25, yy25, colors[i%len(colors)]+"-.")
  197. plt.plot(xx100, yy100, colors[i%len(colors)])
  198. plt.show(block=True)
  199. # -----------------------------------------------------------------------------------------
  200. if displayDistance:
  201. print("MIAM[",pogDB.name," display distance !]")
  202. # load files
  203. allHists = np.load(allLightness_50bins) # lightnesshsitograms
  204. allMoments = np.load(allLightness_Moments) # lightness moments mean, std, skewness
  205. centroids = np.load(centroids_L_Hists_50bins, allow_pickle = True) # centroids: 5 histograms
  206. assigments = np.load(assigments_L_Hists_50bins, allow_pickle = True) # assigments
  207. assigmentsIdx = np.load(assigmentsIdx_L_Hists_50bins, allow_pickle = True) # assigments index: for each histograms index of class
  208. distToCentroids = np.load(distanceToCentroids, allow_pickle = True) # for each histograms/image distance to each cluster
  209. # get data
  210. fig, ax = plt.subplots(1,5)
  211. fig.suptitle('Distance to Histogram Class')
  212. colors = ['b', 'g','r','c','m','y','k']
  213. # sort
  214. for i in range(5):
  215. idxSorted = np.argsort(distToCentroids[:,i])#[::-1]
  216. for j in range(5):
  217. ax[i].plot((distToCentroids[idxSorted[0:1000],j]),colors[j%len(colors)]+'o', markersize=1)
  218. plt.show(block=True)
  219. # -----------------------------------------------------------------------------------------
  220. if displayBestPerClass:
  221. print("MIAM[display best image per class !]")
  222. # load files
  223. allHists = np.load(allLightness_50bins) # lightnesshsitograms
  224. allMoments = np.load(allLightness_Moments) # lightness moments mean, std, skewness
  225. centroids = np.load(centroids_L_Hists_50bins, allow_pickle = True) # centroids: 5 histograms
  226. assigments = np.load(assigments_L_Hists_50bins, allow_pickle = True) # assigments
  227. assigmentsIdx = np.load(assigmentsIdx_L_Hists_50bins, allow_pickle = True) # assigments index: for each histograms index of class
  228. distToCentroids = np.load(distanceToCentroids, allow_pickle = True) # for each histograms/image distance to each cluster
  229. # get data
  230. L_mean = allMoments[:,0]
  231. L_std = allMoments[:,1]
  232. colors = ['b', 'g','r','c','m','y','k']
  233. # for each class
  234. for i in range(5):
  235. # histogram of class
  236. centroidHist = MHIST.Histogram(centroids[i,:],np.linspace(0,100,50+1),"",MCH.channel.L)
  237. # contour of class
  238. pc = MPC2D.PointCloud2D(L_mean[assigmentsIdx[i]],L_std[assigmentsIdx[i]])
  239. xx, yy = MPC2D.PointCloud2D.toXYarray(pc.contour(0.1))
  240. # sort image according to class distance
  241. idxSorted = np.argsort(distToCentroids[:,i])
  242. # for ten best image of the current class
  243. for j in range(3):
  244. imagefilename = pogDB.db[idxSorted[j]]
  245. print("class(",i,"): best", j,">>",imagefilename)
  246. img = MIMG.Image.read(imagefilename)
  247. hist = MHIST.Histogram(allHists[idxSorted[j]],np.linspace(0,100,50+1),"",MCH.channel.L)
  248. # create figure
  249. fig, ax = plt.subplots(1,3)
  250. fig.suptitle("find 'best' image per class")
  251. centroidHist.plot(ax[0],colors[i%len(colors)])
  252. hist.plot(ax[0],'k')
  253. ax[0].set_title('image (black) & centroid histogram')
  254. ax[1].plot(xx,yy,colors[i%len(colors)])
  255. ax[1].plot(L_mean[idxSorted[j]],L_std[idxSorted[j]],'ko')
  256. ax[1].set_title('image lighness mean and constrast (black)/ contour of class')
  257. img.plot(ax[2])
  258. ax[2].set_title('image')
  259. plt.show(block=True)