IMHOTEP Framework
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Pages
Histogram.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using UnityEngine;
5 
6 public class Histogram {
7 
8  List<double> values = new List<double>();
9  long[] bins;
10 
11  bool textureNeedsToBeRegenerated = true;
12  bool needsToBeResorted = true;
13  Texture2D texture;
14 
15  double binSize;
16  double minValue = 0;
17  double maxValue = 1;
18  int numOfBins;
19  long max = 0;
20 
21  public Histogram() {
22  }
23 
24  public void addValue( double val )
25  {
26  values.Add (val);
27  textureNeedsToBeRegenerated = true; // Texture needs to be re-generated.
28  needsToBeResorted = true; // Texture needs to be re-generated.
29  }
30 
31  public Texture2D asTexture()
32  {
33  if (textureNeedsToBeRegenerated) {
34  generateTexture ();
35  }
36  return texture;
37  }
38 
39  public void setMinMaxPixelValues( float min, float max )
40  {
41  minValue = min;
42  maxValue = max;
43  }
44 
45  public void sortIntoBins( int numOfBins )
46  {
47  bins = new long[numOfBins];
48  binSize = (maxValue - minValue)/(double)numOfBins;
49  this.numOfBins = numOfBins;
50 
51  for (int i = 1; i < values.Count; i++) {
52  if (values[i] < minValue || values[i] > maxValue)
53  continue;
54  int binIndex = (int)Math.Floor ((values[i] - minValue) / binSize + 0.5);
55  if (binIndex >= 0 && binIndex < numOfBins)
56  bins [binIndex]++;
57  }
58 
59  // search the maximum value:
60  max = 1;
61  for (int i = 0; i < numOfBins; i++) {
62  if (bins [i] > max)
63  max = bins [i];
64  }
65 
66  needsToBeResorted = false;
67  }
68 
69  public void generateTexture()
70  {
71  if (needsToBeResorted)
72  sortIntoBins (200); // Default values
73 
74  int texHeight = 100;
75 
76  texture = new Texture2D (numOfBins, texHeight, TextureFormat.ARGB32, false, true);
77 
78  for (int i = 0; i < numOfBins; i++) {
79  long height = (long)(texHeight-1) * bins [i] / max;
80  //Debug.Log (i + " " + bins [i]);
81  if (bins [i] > 0 && height == 0)
82  height = 1;
83  for (int y = 0; y < height; y++)
84  texture.SetPixel (i, y, Color.white);
85  for (int y = (int)height; y < texHeight; y++) {
86  texture.SetPixel (i, y, Color.black);
87  }
88  }
89  texture.Apply ();
90  textureNeedsToBeRegenerated = false;
91 
92  // Save to file for debugging purposes:
93  /*byte[] bytes = texture.EncodeToPNG ();
94  System.IO.File.WriteAllBytes ("histogram.png", bytes);*/
95  }
96 
97 }