Seven common threshold segmentation codes (Otsu, maximum entropy, iterative method, adaptive threshold, Manual, iterative, basic global threshold method)

Source: Internet
Author: User
Tags abs manual split

First, tools: VC+OPENCV

Second, language: C + +

Three, the principle

Otsu method (maximum inter-class variance method, sometimes referred to as Dajing algorithm) uses the idea of clustering, the gray degree of the image is divided into 2 parts of gray scale, so that the gray value between the two parts of the largest difference, the gray difference between each part of the smallest, through the calculation of variance to find a suitable gray level to divide. Therefore, the Otsu algorithm can be used to automatically select the threshold value for binary value. The Otsu algorithm is considered as the best algorithm for the selection of threshold values in image segmentation, which is easy to calculate and unaffected by the brightness and contrast of the image. Therefore, the division of the maximum variance between classes means that the probability of error is minimized.


Set T as the threshold value.

Wo: The ratio of foreground pixels to image after separation

UO: Average grayscale of foreground pixel points after separation

W1: The proportion of pixels in the image after being separated

U1: The average grayscale of the pixel points of the scene after being separated

U=w0*u0 + W1*U1: Image Total average grayscale


The T-value is the threshold we want to traverse t from the L gray level, so that T is a value, and the variance of the foreground and background is the largest.

Where the variance is calculated as follows:

G=wo * (uo-u) * (uo-u) + W1 * (u1-u) * (u1-u)

[This formula is computationally large and can be used: g = wo * W1 * (UO-U1) * (UO-U1)]

Since the Otsu algorithm is clustering the gray level of the image, so before executing the Otsu algorithm, the gray histogram of the image needs to be computed.


Iterative method Principle: Iterative Selection method is to first guess an initial threshold value, and then through the multi-pass calculation of the image to improve the threshold value process. The images are repeatedly thresholding, the images are segmented into object classes and background classes, and the thresholds are improved using the grey class in each class.

An iterative algorithm for image threshold segmentation---

1. Processing process:

1. Select an initial estimate T (average grayscale for the image) for the global threshold value.
2. Divide the image with T. Two groups of Pixels are produced: G1 have pixels with a grayscale value greater than T, and G2 have less than or equal t pixels.
3. Calculate the average gray values of G1 and G2 pixels M1 and M2;
4. Calculate a new threshold value: T = (m1 + m2)/2;
5. Repeat steps 2 and 4 until the difference between T values in the continuous iteration is less than one of the predefined parameters.

Suitable for image histogram with obvious trough

Iv. procedures

Main program (core part)

Threshold split 1/*=============================== image Segmentation =====================================*/2/*-------------------------- -------------------------------------------------*/3/* Manually set the threshold */4 iplimage* binaryimg = Cvcreateimage (Cvsize (W, h),
ipl_depth_8u, 1); 
5 Cvthreshold (smoothimggauss,binaryimg,71,255,cv_thresh_binary);
6 Cvnamedwindow ("Cvthreshold", cv_window_autosize);
7 Cvshowimage ("Cvthreshold", binaryimg); 
8//cvreleaseimage (&BINARYIMG); 9/*---------------------------------------------------------------------------*/10//Adaptive threshold//Calculate the average gray level in the neighborhood of the domain,
To determine the value of the binary */one iplimage* adthresimg = Cvcreateimage (Cvsize (W, h), ipl_depth_8u, 1);
Double max_value=255; int Adpative_method=cv_adaptive_thresh_gaussian_c;//cv_adaptive_thresh_mean_c int Threshold_type=cv_thresh_
BINARY; The pixel neighborhood size of the block_size=3;//threshold for the Int offset=5;//window size is cvadaptivethreshold (Smoothimggauss,adthresimg,max_value,
Adpative_method,threshold_type,block_size,offset); Cvnamedwindow ("Cvadaptivethreshold", Cv_windoW_autosize);
Cvshowimage ("Cvadaptivethreshold", adthresimg);
Cvreleaseimage (&ADTHRESIMG); */*---------------------------------------------------------------------------*/22 */Maximum entropy threshold Split method */iplimage*
Imgmaxentropy = Cvcreateimage (Cvgetsize (Imggrey), ipl_depth_8u,1);
Maxentropy (smoothimggauss,imgmaxentropy);
Cvnamedwindow ("Maxentroythreshold", cv_window_autosize); 
Cvshowimage ("Maxentroythreshold", imgmaxentropy);//Display Image cvreleaseimage (&imgmaxentropy); */*---------------------------------------------------------------------------*/29 */Basic Global threshold method */iplimage*
Imgbasicglobalthreshold = Cvcreateimage (Cvgetsize (Imggrey), ipl_depth_8u,1);
Cvcopyimage (Srcimggrey,imgbasicglobalthreshold); 
Pg[256],i,thre int;
for (i=0;i<256;i++) pg[i]=0; i=0;iimagesize;i++//Histogram statistics pg[(BYTE) imgbasicglobalthreshold-> 
imagedata[i]]++; thre = Basicglobalthreshold (pg,0,256); Determining the threshold value of PNs cout<< "the Threshold of this Image in Basicglobalthreshold is: "<<thre<<endl;//output shows threshold of cvthreshold (Imgbasicglobalthreshold, Imgbasicglobalthreshold,thre,255,cv_thresh_binary);
Two-valued Cvnamedwindow ("Basicglobalthreshold", cv_window_autosize); Cvshowimage ("Basicglobalthreshold", imgbasicglobalthreshold);//Display Image Cvreleaseimage (&
Imgbasicglobalthreshold); */*---------------------------------------------------------------------------*//*otsu*/iplimage* Imgotsu =
Cvcreateimage (Cvgetsize (Imggrey), ipl_depth_8u,1);
Cvcopyimage (Srcimggrey,imgotsu);
Thre2 int;
Thre2 = OTSU2 (Imgotsu); cout<< "The Threshold of this Image in Otsu is:" The <<thre2<<endl;//output shows the valve value cvthreshold (Imgotsu, Imgotsu,thre2,255,cv_thresh_binary);
Binary Cvnamedwindow ("Imgotsu", cv_window_autosize);
Wuyi cvshowimage ("Imgotsu", Imgotsu);//Display Image cvreleaseimage (&imgotsu); */*---------------------------------------------------------------------------*/54 */Up/Down threshold method: Use normal distribution to find credibilityInterval */iplimage* Imgtopdown = Cvcreateimage (Cvgetsize (Imggrey), ipl_depth_8u, 1);
Cvcopyimage (Srcimggrey,imgtopdown);
Cvscalar mean, std_dev;//average, standard deviation of double u_threshold,d_threshold; 
CVAVGSDV (Imgtopdown,&mean,&std_dev,null); U_threshold = mean.val[0] +2.5* std_dev.val[0];//upper threshold of d_threshold = mean.val[0] -2.5* std_dev.val[0];//lower threshold//u_thr Eshold = mean + 2.5 * STD_DEV;
Error//d_threshold = mean-2.5 * STD_DEV; cout<< "The topthreshold of this Image in Topdown is:" <<d_threshold<<endl;//output display threshold of cout<< "
The downthreshold of this Image in Topdown is: "<<u_threshold<<endl; Cvthreshold (IMGTOPDOWN,IMGTOPDOWN,D_THRESHOLD,U_THRESHOLD,CV_THRESH_BINARY_INV);//upper and lower threshold CvNamedWindow ("
Imgtopdown ", cv_window_autosize);
Cvshowimage ("Imgtopdown", imgtopdown);//Display Image cvreleaseimage (&imgtopdown); */*---------------------------------------------------------------------------*/71 * * Iterative method */iplimage* Imgiteration = CVcreateimage (Cvgetsize (Imggrey), ipl_depth_8u, 1);
Cvcopyimage (srcimggrey,imgiteration);
Thre3,ndiffrec int;
Thre3 =detectthreshold (imgiteration, Ndiffrec); cout<< "The Threshold of this Image in Imgiteration is:" <<thre3<<endl;//output shows threshold Cvthreshold ( IMGITERATION,IMGITERATION,THRE3,255,CV_THRESH_BINARY_INV)///up/Down threshold Cvnamedwindow ("imgiteration", CV_WINDOW_
AUTOSIZE);
Cvshowimage ("Imgiteration", imgiteration);
Cvreleaseimage (&imgiteration); Iteration 1/*======================================================================*/2/* Iterative method */3/*====================== ================================================*/4//Nmaxiter: Maximum number of iterations; Ndiffrec: Average gray difference between bright and dark areas using a given threshold value 5 int Detectthreshold (iplimage*img, int nmaxiter, int& idiffrec)//Threshold Segmentation: Iterative Method 6 {7//image information 8 int height = img->height; 9 in
T width = img->width;
Ten int step = img->widthstep/sizeof (Uchar);
One Uchar *data = (uchar*) img->imagedata;
Idiffrec = 0; f[256]={int 0}; StraightSquare map Arrays of itotalgray=0;//gray values and itotalpixel of =0;//pixels and the pixel values of a byte bt;//a point, Uchar ithrehold,inewthrehold;//threshold,
The new threshold value of Uchar imaxgrayvalue=0,imingrayvalue=255;//the maximum gray value and the minimum gray value of the original image Uchar Imeangrayvalue1,imeangrayvalue2; 22 23//Gets the value of (i,j), stored in the histogram array f for (int i=0;i<width;i++) (int.) (int j=0;j 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.