OTSU method calculates an adaptive threshold of image binarization

xiaoxiao2021-03-06  74

/ * OTSU algorithm can be said to be a simple and efficient method for adaptive calculation single threshold (used to convert grayscale images as a binary image). The following code is the earliest by Ryan Dibble, after which it is modified by many people Joerg.Schulenburg, R.z.Liu, etc.

Transferred from: http://forum.assuredigit.com/display_topic_threads.asp? ForumID = 8 & Topicid = 3480 The histogram of the input grayscale image analyzes the histogram of the input grayscale image, divides the histogram into two parts, so that the distance between the two parts is the largest. . The division point is the threshold for obtaining. Parameter: * Image --- Buffer for Image Rows, COLS --- Size of Image X0, Y0, DX, DY --- Region of Vector Used for Computing Threshold VVV --- Debug Option, IS 0, No Debug Information Output * // * ================================================================================================================================================================ ===================================================================================================== // * Number of cols in the array. Returns the value of the threshold * // * ============================== ========================================================== * / int otsu (unsigned char * image, INT ROWS, INT COLS, INT X0, INT Y0, INT DX, INT DY, INT VVV) {

Unsigned char * np; // Image pointer int thresholdValue = 1; // threshold int hist [256]; // Image histogram, 256 points INT I, J, K; // Various Counters Int N, N1, N2, Gmin, Gmax; Double M1, M2, SUM, CSUM, FMAX, SB;

// Troubleshooting zero ... MEMSET (IHIST, 0, SIZEOF (IHIST));

Gmin = 255; gmax = 0; // Generate histogram for (i = Y0 1; i gmax) gmax = * np; if (* np

// set up everything sum = csum = 0.0; n = 0;

For (k = 0; k <= 255; k ) {SUM = (double) k * (double) hist [k]; / * x * f (x) mass slum * / n = ihist [k]; / * F (x) quality * /}

IF (! n) {// if n Has No Value, There IS Problems ... fprintf (stderr, "not normal thresholdvalue = 160 / n"); Return (160);

// do the otsu global thresholding method fmax = -1.0; N1 = 0; for (k = 0; k <255; k ) {n1 = ihist [k]; if (! n1) {Continue;} n2 = n - N1; if (n2 == 0) {Break;} CSUM = (double) k * hist [k]; m1 = csum / n1; m2 = (sum - csum) / N2; SB = (double) N1 * (Double) N2 * (m1 - m2) * (m1 - m2); / * bbg: Note: can be optimized. * / if (sb> fmax) {fmax = sb; thresholdValue = k;}}

// at this point we have ot detolding value

// debug code to display thresholding value if (vvv & 1) fprintf (stderr, "# otsu: thresholdValue =% D gmin =% d gmax =% d / n", ThresholdValue, Gmin, gmax); Return (ThresholdValue); }

转载请注明原文地址:https://www.9cbs.com/read-120924.html

New Post(0)