opencv中ostu算法

来源:互联网 发布:matlab for mac 2014b 编辑:程序博客网 时间:2024/06/03 19:19

注意mat 与ipilmage读取数据类型的差别。

#include"opencv2/core/core.hpp"#include"opencv2/highgui/highgui.hpp"  #include"opencv2/imgproc/imgproc.hpp"using namespace std;using namespace cv;int Otsu(Mat img){    int height = img.rows;  #Mat 中读数据的方式类型与Ipilmage中的区别    int width = img.cols;    float histogram[256] = {0};    for (int i =0;i<height;i++)    {        unsigned char *p = (unsigned char *)img.data+img.step*i;        for(int j=0;j<width;j++)        {            histogram[*p++]++;        }    }    int size = height*width;    for(int i =0;i<256;i++)    {        histogram[i] = histogram[i]/size;    }    float avgValue=0;    for (int i=0;i<256;i++)    {        avgValue += i*histogram[i];    }    int threshold;    float maxVariance=0;    float w=0,u=0;    for(int i=0;i<256;i++)    {        w += histogram[i];        u += i*histogram[i];        float t=avgValue*w - u;        float variance = t*t /(w*(1-w));        if(variance>maxVariance)        {            maxVariance = variance;            threshold = i;        }    }    return threshold;}int main(){    Mat img = imread("004.jpg",0);    Mat bin_img;    int thres = Otsu(img);    threshold(img,bin_img,thres,255,THRESH_BINARY);    imshow("src",bin_img);    waitKey(0);    destroyAllWindows();} 


原创粉丝点击