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.pub.threshold.global;
011
012import imagingbook.pub.threshold.global.GlobalThresholder;
013
014public class MeanThresholder extends GlobalThresholder {
015        
016        public MeanThresholder() {
017                super();
018        }
019
020        public int getThreshold(int[] h) {
021                // calculate mean of entire image:
022                int K = h.length;
023                int cnt = 0;
024                long sum = 0;
025                for (int i=0; i<K; i++) {
026                        cnt += h[i];
027                        sum += i * h[i];
028                }
029                
030                int mean = (int) Math.rint((double)sum / cnt);
031
032                // count resulting background pixels:
033                int n0 = 0;
034                for (int i = 0; i <= mean; i++) {
035                        n0 += h[i];
036                }
037                
038                // determine if background or foreground is empty:
039                int q = (n0 < cnt) ? mean : -1; 
040                return q;
041        }
042}