opencv 학습 시리즈: OSTU 알고리즘 선택 적응 한도 값

//-----------------------------------OpenCV  1------------------------------------- 
//      :OSTU        
//  2016 10  Created by   (Visual Studio 2013+OpenCV2.4.9)
#include  
#include 
#include  
#include 

using namespace cv;
using namespace std;
       
//#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")
int otsu(IplImage *image)
{
    assert(NULL != image);//      ,       

    int width = image->width;
    int height = image->height;
    int x = 0, y = 0;
    int pixelCount[256];
    float pixelPro[256];
    int i, j, pixelSum = width * height, threshold = 0;

    uchar* data = (uchar*)image->imageData;

    //     
    for (i = 0; i < 256; i++)
    {
        pixelCount[i] = 0;
        pixelPro[i] = 0;
    }

    //                     
    for (i = y; i < height; i++)
    {
        for (j = x; jwidthStep + j]]++;
    }


    //                 
    for (i = 0; i < 256; i++)
    {
        pixelPro[i] = (float)(pixelCount[i]) / (float)(pixelSum);
    }

    //  ostu  ,            
    //     [0,255],           ,       
    float w0, w1, u0tmp, u1tmp, u0, u1, u, deltaTmp, deltaMax = 0;
    for (i = 0; i < 256; i++)//i   
    {
        w0 = w1 = u0tmp = u1tmp = u0 = u1 = u = deltaTmp = 0;

        for (j = 0; j < 256; j++)//       i=0,1,2,3...255
        {
            if (j <= i) //      
            {
                // i     ,         
                w0 += pixelPro[j];
                u0tmp += j * pixelPro[j];
            }
            else       //      
            {
                // i     ,         
                w1 += pixelPro[j];
                u1tmp += j * pixelPro[j];
            }
        }

        u0 = u0tmp / w0;        //          
        u1 = u1tmp / w1;        //          
        u = u0tmp + u1tmp;      //           
        //        
        deltaTmp = w0 * (u0 - u)*(u0 - u) + w1 * (u1 - u)*(u1 - u);
        //                 
        if (deltaTmp > deltaMax)
        {
            deltaMax = deltaTmp;
            threshold = i;
        }
    }
    //      ;  
    return threshold;
}

int main(int argc, char* argv[])
{
    IplImage* srcImage = cvLoadImage("F:\\workplace\\opencv_training\\test2.png", 0);
    assert(NULL != srcImage);

    cvNamedWindow("src");
    cvShowImage("src", srcImage);

    IplImage* biImage = cvCreateImage(cvGetSize(srcImage), 8, 1);

    //        
    int threshold = otsu(srcImage);
    //        
    cvThreshold(srcImage, biImage, threshold, 255, CV_THRESH_BINARY);

    cvNamedWindow("binary");
    cvShowImage("binary", biImage);

    cvWaitKey(0);

    cvReleaseImage(&srcImage);
    cvReleaseImage(&biImage);
    cvDestroyWindow("src");
    cvDestroyWindow("binary");

    return 0;
}

좋은 웹페이지 즐겨찾기