001/*******************************************************************************
002 * This software is provided as a supplement to the authors' textbooks on digital
003 *  image processing published by Springer-Verlag in various languages and editions.
004 * Permission to use and distribute this software is granted under the BSD 2-Clause 
005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 
006 * Copyright (c) 2006-2016 Wilhelm Burger, Mark J. Burge. All rights reserved. 
007 * Visit http://imagingbook.com for additional details.
008 *******************************************************************************/
009
010package imagingbook.lib.image;
011
012import ij.process.FloatProcessor;
013
014public abstract class Statistics {
015        
016        
017        public static double getMean(FloatProcessor ip) {
018                final int W = ip.getWidth();
019                final int H = ip.getHeight();
020                final int N = W * H;
021
022                double sum = 0;
023                for (int j = 0; j < H; j++) {
024                        for (int i = 0; i < W; i++) {
025                                sum = sum + ip.getf(i, j);
026                        }
027                }
028                return sum / N;
029        }
030        
031        public static double getVariance(FloatProcessor ip) {
032                final int W = ip.getWidth();
033                final int H = ip.getHeight();
034                final int N = W * H;
035                
036                final double mean = getMean(ip);
037
038                double sum = 0;
039                for (int j = 0; j < H; j++) {
040                        for (int i = 0; i < W; i++) {
041                                double d = ip.getf(i, j) - mean;
042                                sum = sum + d * d;
043                        }
044                }
045                return sum / N;
046        }
047        
048        
049        public static double getVariance2(FloatProcessor ip) {
050                final int W = ip.getWidth();
051                final int H = ip.getHeight();
052                final int N = W * H;
053
054                double sumX = 0;
055                double sumX2 = 0;
056                
057                for (int j = 0; j < H; j++) {
058                        for (int i = 0; i < W; i++) {
059                                double x = ip.getf(i, j);
060                                sumX = sumX + x;
061                                sumX2 = sumX2 + x * x;
062                        }
063                }
064                
065                double var = (sumX2 - sumX * sumX / N) / N ;
066                return var;
067        }
068
069}