大津法二值化 linux c語言代碼

下面是linux 大津法二值化的c語言代碼,圖片的格式爲320*240

typedef struct hand_pic {
    int iWidth;   /* 寬度: 一行有多少個象素 */
    int iHeight;  /* 高度: 一列有多少個象素 */
    int iTotalBytes; /* 所有字節數 */ 
    int iBpp;
    int centre_x;
    int centre_y;
    int last_grade;
    int same_grade_count;
    unsigned char *green_pix;  //圖像的灰度值
}T_hand_pic, *PT_hand_pic;



/**********************************************************************
 * 函數名稱: otsu_method
 * 功能描述: 大津法二值化圖像
 * 輸入參數: PT_hand_pic - 一個結構體,包涵處理圖片的主要參數
 * 輸出參數:  
 * 返 回 值: 0 - 成功, 負數 - 失敗
 ***********************************************************************/
static  int  otsu_method(PT_hand_pic ptHandPic)
{
    unsigned int max,min;
    int x,y;
    unsigned int   color;
    unsigned char  *greed_pix=ptHandPic->green_pix;
    unsigned int   *count;
    double         probability[330]={0};
    double         sum_probability;
    max=min=*greed_pix;


    for (y = 0; y < ptHandPic->iHeight; y++){//get mix & min
        for (x = 0; x < ptHandPic->iWidth; x++){
            color = *(greed_pix+x+y * ptHandPic->iWidth);
            if(color > max)
                max = color;
            if(color < min)
                min = color;

            }
    }

    count=(unsigned int *)calloc(max-min+1,sizeof(int));


    for (y = 0; y < ptHandPic->iHeight; y++){
        for (x = 0; x < ptHandPic->iWidth; x++){

            color = *(greed_pix+x+y* ptHandPic->iWidth);
            *(count+color-min) +=1;

            }
    }



    y= ptHandPic->iWidth * ptHandPic->iHeight;
    for (x = 0; x <max-min+1; x++){
        *(probability+x) = (double)*(count+x)*100/(double)y;
    }


    sum_probability=0;
    //for (x = 0; x <max-min+1; x++){
    //  sum_probability += *(probability+x) * (double)(*(count+x));
    //}
    for (x = min,y=0; x <max+1; x++,y++){
        //printf("myyyyyyy :%d \n" ,y );
        sum_probability += *(probability+y) *(double)x;

    }

    sum_probability = sum_probability/100;
//  printf("hhhh%f",sum_probability);
    if(ptHandPic->iBpp==32)
        if((sum_probability<60)||(sum_probability>190)){
            free(count);
            return -1;
        }





    //printf("here sum_probability %f\n" ,sum_probability);

    //binaryzation
    for (y = 0; y < ptHandPic->iHeight; y++){
        for (x = 0; x < ptHandPic->iWidth; x++){
            if (*(greed_pix+x+y* ptHandPic->iWidth) >= sum_probability )
                *(greed_pix+x+y* ptHandPic->iWidth)=1;
            else
                *(greed_pix+x+y* ptHandPic->iWidth)=0;


        }
    }

    free(count);

    return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章