2012年3月13日

影像處理:Otsu_Algorithm

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <math.h>
using namespace std;

double His_Arr[256]={0};
double Sort_Arr[256]={0};
int count_number=0;
double temp_number=0.0;
int temp_index=0.0;
CvScalar temp;
int K=0;
int main()
{
    double P_i=0.0;
    double P1_K=0.0;
    double M_K=0.0;
    double M_G=0.0;
    double sigma_B_K=0.0;
    IplImage *src,*dst;
    src=cvLoadImage("D:\\img\\006.jpg",-1);
    dst=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1);
    cvCvtColor(src,dst,CV_RGB2GRAY);
    int M=dst->height;
    int N=dst->width;
    for(int i=0;i<src->height;i++)
    {
        for(int j=0;j<src->width;j++)
        {
            temp=cvGet2D(dst,i,j);
            count_number=temp.val[0];
            His_Arr[count_number]++;
        }
    }
    for(int C=0;C<256;C++)
    {
        P1_K=0.0;
        M_G=0.0;
        M_K=0.0;
        K=C;
    for(int i=0;i<K+1;i++)
    {
        P1_K=(His_Arr[i]/(M*N))+P1_K;
        M_K=((His_Arr[i]/(M*N))*i)+M_K;
    }
    for(int i=0;i<256;i++)
    {
        M_G=((His_Arr[i]/(M*N))*i)+M_G;
    }
        sigma_B_K=(((M_G*P1_K)-M_K)*((M_G*P1_K)-M_K))/((P1_K)*(1-P1_K));
        Sort_Arr[C]=sigma_B_K;
        cout<<"P1_K="<<P1_K<<endl;
    }
    for(int i=0;i<256;i++)
    {
        if(Sort_Arr[i]>temp_number)
        {
            temp_number=Sort_Arr[i];
            temp_index=i;
        }
    }
    for(int i=0;i<dst->height;i++)
    {
        for(int j=0;j<dst->width;j++)
        {
            temp=cvGet2D(dst,i,j);
            if(temp.val[0]>=temp_index)
            {
                temp.val[0]=255;
                cvSet2D(dst,i,j,temp);
            }
            else
            {
                temp.val[0]=0;
                cvSet2D(dst,i,j,temp);
            }
        }
    }
    cvNamedWindow("src",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("dst",CV_WINDOW_AUTOSIZE);
    cvShowImage("src",src);
    cvShowImage("dst",dst);
    cvWaitKey(0);
    cvDestroyWindow("src");
    cvReleaseImage(&src);
    cvDestroyWindow("dst");
    cvReleaseImage(&dst);
}


沒有留言:

張貼留言