// otsu.c               Section: 3.7
// Threshold Selection by Maximizing Between Class Variance
//      Copyright 1994, Center for Computer Vision and Visualization,
//      University of Florida.  All rights reserved.
//

#include "otsu.h"
#include "otsu-image.h"
#include "histogram.h"


///////////////////////////////////////////////////////////////////////
// otsu()
//   Calculate the possible partition points for image: a
//   based on the given partiton count.
//   Note that the number of partition points is one less
//   than the number of requested partitions.
//
template <class P, class T>
IA_Set<IA_Point<int> >      // Could also return an IA_Array
otsu( unsigned int partitionCount, const IA_Image<P,T> & a ) {

    IA_Image<IA_Point<int>,float>
	nh = normalized_histogram( a );

    // An OtsuImage may be thought of as a
    //    IA_Image<IA_Point<int>,float>
    // Each point in its domain represents a possible
    //    partitioning of the histogram.
    // The value at that point is the value of the objective function
    //    sigma-sub-b-squared as defined in the Otsu algoritm.
    IA_Image<IA_Point<int>,float>
	oim = OtsuImage( partitionCount - 1, nh );

    // A value set that only contains the maximum value in the image.
    IA_Set<float>
	oim_vs = max( oim );

    // Restrict the image to its maximum values.
    IA_Image<IA_Point<int>,float>
	oim_restrict( oim.restrict( oim_vs ) );

    // Return the domain of the restricted image.
    // Each point in this domain represents a possible partitioning
    //    where the OtsuImage obtained a maximum value.
    return oim_restrict.domain();
}
