Skip to content

Commit f8e9ba2

Browse files
authored
Merge pull request qupath#2041 from petebankhead/histogram
Create Histogram from edges and counts
2 parents c9f0ef5 + 9f3a64f commit f8e9ba2

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

qupath-core/src/main/java/qupath/lib/analysis/stats/Histogram.java

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@
2323

2424
package qupath.lib.analysis.stats;
2525

26-
import java.util.Collection;
27-
2826
import qupath.lib.objects.PathObject;
2927

28+
import java.util.Collection;
29+
3030

3131
/**
3232
* Class for storing histogram data & basic statistics.
@@ -350,6 +350,39 @@ public Histogram(ArrayWrappers.ArrayWrapper values, int nBins, double minEdge, d
350350
buildHistogram(values, nBins, minEdge, maxEdge);
351351
}
352352

353+
/**
354+
* Create histogram from an existing edges and counts arrays.
355+
* <p>
356+
* This is useful when a histogram already exists in another format, and it would be too expensive to rebuild
357+
* from the original values.
358+
* <p>
359+
* Note that the statistics (min, max, mean, std.dev. and variance) are estimated from the bin centers, and may not
360+
* match the values from the data originally used to build the histogram.
361+
*
362+
* @param edges an array of edges, which should be of length {@code nBins + 1}.
363+
* @param counts an array of counts, which should be of length {@code nBins}.
364+
*/
365+
public Histogram(double[] edges, long[] counts) {
366+
this.edgeMin = edges[0];
367+
this.edgeMax = edges[edges.length-1];
368+
this.edges = edges.clone();
369+
this.counts = counts.clone();
370+
boolean maybeInteger = true;
371+
long countsSum = 0L;
372+
var stats = new RunningStatistics();
373+
for (int i = 0; i < edges.length-1; i++) {
374+
double center = (edges[i] + edges[i+1]) / 2.0;
375+
maybeInteger = maybeInteger && Math.round(center) == center;
376+
for (long k = 0; k < counts[i]; k++) {
377+
stats.addValue(center);
378+
countsSum++;
379+
}
380+
}
381+
this.isInteger = maybeInteger;
382+
this.stats = stats;
383+
this.countSum = countsSum;
384+
}
385+
353386

354387
private void buildHistogram(final ArrayWrappers.ArrayWrapper values, int nBins, double minEdge, double maxEdge) {
355388

0 commit comments

Comments
 (0)