영상처리

AutoThreshold (Yen) C++

park__ 2024. 12. 11. 16:43

Java -> C++

 

Code

int Yen(float* histo, int n_length) 
{
	// Implements Yen  thresholding method
	// 1) Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion 
	//    for Automatic Multilevel Thresholding" IEEE Trans. on Image 
	//    Processing, 4(3): 370-378
	// 2) Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding 
	//    Techniques and Quantitative Performance Evaluation" Journal of 
	//    Electronic Imaging, 13(1): 146-165
	//    http://citeseer.ist.psu.edu/sezgin04survey.html
	//
	// M. Emre Celebi
	// 06.15.2007
	// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
	int threshold;
	int ih, it;
	double crit;
	double max_crit;
	double* norm_histo = nullptr;
	double* P1 = nullptr;
	double* P1_sq = nullptr; 
	double* P2_sq = nullptr; 
	
	norm_histo = new double[n_length]; /* normalized histogram */
	P1 = new double[n_length]; /* cumulative normalized histogram */
	P1_sq = new double[n_length];
	P2_sq = new double[n_length];

	int total = 0;

	for (ih = 0; ih < n_length; ih++)
		total += histo[ih];

	for (ih = 0; ih < n_length; ih++)
		norm_histo[ih] = (double)histo[ih] / total;

	P1[0] = norm_histo[0];

	for (ih = 1; ih < n_length; ih++)
		P1[ih] = P1[ih - 1] + norm_histo[ih];

	P1_sq[0] = norm_histo[0] * norm_histo[0];

	for (ih = 1; ih < n_length; ih++)
		P1_sq[ih] = P1_sq[ih - 1] + norm_histo[ih] * norm_histo[ih];

	P2_sq[n_length - 1] = 0.0;

	for (ih = n_length - 2; ih >= 0; ih--)
		P2_sq[ih] = P2_sq[ih + 1] + norm_histo[ih + 1] * norm_histo[ih + 1];

	/* Find the threshold that maximizes the criterion */
	threshold = -1;
	max_crit = -DBL_MAX;
	for (it = 0; it < n_length; it++) 
	{
		crit = -1.0 * ((P1_sq[it] * P2_sq[it]) > 0.0 ? log(P1_sq[it] * P2_sq[it]) : 0.0) + 2 * ((P1[it] * (1.0 - P1[it])) > 0.0 ? log(P1[it] * (1.0 - P1[it])) : 0.0);
		
		if (crit > max_crit) 
		{
			max_crit = crit;
			threshold = it;
		}
	}

	if (norm_histo)
		delete[] norm_histo;
	
	if (P1)
		delete[] P1;

	if(P1_sq)
		delete[] P1_sq;

	if(P2_sq)
		delete[] P2_sq;

	return threshold;
}

 

imageJ 관련 문서 : https://imagej.net/plugins/auto-threshold

github link : https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java

'영상처리' 카테고리의 다른 글

이미지 합성 - 1 (OpenCV, C++)  (0) 2024.12.12
OpenCV rectangle(Python)  (0) 2024.12.12
AutoThreshold (Triangle) C++  (0) 2024.12.11
AutoThreshold (Shanbhag) C++  (0) 2024.12.11
AutoThreshold (RenyiEntropy) C++  (1) 2024.12.11