zoukankan      html  css  js  c++  java
  • OTSU方法计算图像二值化的自适应阈值

    2004年09月02日 10:42:00







    int otsu (unsigned char *image, int rows, int cols, int x0, int y0,int dx, int dy, int vvv)
    {

      unsigned char*np;     // 图像指针
      int thresholdValue=1;// 阈值
      intihist[256];            // 图像直方图,256个点

      int i, j,k;         // various counters
      int n, n1, n2, gmin, gmax;
      double m1, m2, sum, csum, fmax, sb;

      // 对直方图置零...
      memset(ihist, 0, sizeof(ihist));

      gmin=255; gmax=0;
      // 生成直方图
      for (i = y0 + 1; i < y0 + dy - 1; i++){
        np =&image[i*cols+x0+1];
        for (j = x0+ 1; j < x0 + dx - 1; j++) {
         ihist[*np]++;
         if(*np > gmax) gmax=*np;
         if(*np < gmin) gmin=*np;
         np++;
        }
      }

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

      for (k = 0; k <= 255; k++) {
        sum +=(double) k * (double)ihist[k];   
         +=ihist[k];                                        
      }

      if (!n) {
        // if n hasno value, there is problems...
        fprintf(stderr, "NOT NORMAL thresholdValue = 160\n");
        return(160);
      }

      // do the otsu global thresholdingmethod
      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 *ihist[k];
        m1 = csum /n1;
        m2 = (sum -csum) / n2;
        sb =(double) n1 *(double) n2 *(m1 - m2) * (m1 - m2);
       
        if (sb >fmax) {
         fmax = sb;
         thresholdValue = k;
        }
      }

      // at this point we have our thresholdingvalue

      // debug code to display thresholdingvalues
      if ( vvv & 1 )
      fprintf(stderr,"# OTSU: thresholdValue = %dgmin=%d gmax=%d\n",
        thresholdValue, gmin, gmax);

      return(thresholdValue);
    }



    Trackback:http://tb.blog.csdn.net/TrackBack.aspx?PostId=92086


  • 相关阅读:
    1039 到底买不买 (20分)
    流密码
    Socket网络编程:互相通讯
    1036 跟奥巴马一起编程
    1033 旧键盘打字
    1029 旧键盘
    1015 德才论 (25分)
    BUU_Real_刷题记录
    vue3 composition api 对比 react hooks
    vue3 文档相关
  • 原文地址:https://www.cnblogs.com/feisky/p/1586567.html
Copyright © 2011-2022 走看看