12. 对一幅灰度图像用最大类间方差法求阈值,并对其进行二值化。

#include <cv.h>
#include <highgui.h> 
#define GrayScale 256   
int mytsu( IplImage *frame);
int main()
{
    int a=0;
     IplImage * test;
    IplImage * test_1;
    test = cvLoadImage("6013202130.bmp", 0);//图片路径是 ConsoleApplication4 文件夹里,同时实验要求转为灰度图片
    test_1 = cvCreateImage(cvSize((test->width), (test->height)), IPL_DEPTH_8U, 1); //创建图像,给指针赋值
    a= mytsu(test);
    CvScalar s;

    for (int i = 0; i < test->height; i++)
    {

        for (int j = 0; j < test->width; j++)
        {
            s = cvGet2D(test, i, j);
            if (s.val[0] >a)
                s.val[0] = 255;
            else
                s.val[0] = 0;
            cvSet2D(test_1, i, j, s);
        }
    }

    cvNamedWindow("原图—6013202130", CV_WINDOW_AUTOSIZE);
    cvShowImage("原图—6013202130", test);
    cvNamedWindow("对数变换—6013202130", CV_WINDOW_AUTOSIZE);
    cvShowImage("对数变换—6013202130", test_1);
    cvWaitKey(0);//等待按键
    cvDestroyWindow("原图—6013202130");
    cvDestroyWindow("对数变换—6013202130");
    cvReleaseImage(&test);//释放内存。 
    cvReleaseImage(&test_1);
    return 0;
}

int mytsu( IplImage *frame)   
{

    int width = frame->width;
    int height = frame->height;
    int pixelCount[GrayScale] = { 0 };
    float pixelPro[GrayScale] = { 0 };
    int i, j, pixelSum = width * height, threshold = 0;
    uchar* data = (uchar*)frame->imageData;

    //统计每个灰度级中像素的个数   
    for (i = 0; i < height; i++)
    {
        for (j = 0; j < width; j++)
        {
            pixelCount[(int)data[i * width + j]]++;
        }
    }

    //计算每个灰度级的像素数目占整幅图像的比例   
    for (i = 0; i < GrayScale; i++)
    {
        pixelPro[i] = (float)pixelCount[i] / pixelSum;
    }

    //遍历灰度级[0,255],寻找合适的threshold   
    float w0, w1, u0tmp, u1tmp, u0, u1, deltaTmp, deltaMax = 0;
    for (i = 0; i < GrayScale; i++)
    {
        w0 = w1 = u0tmp = u1tmp = u0 = u1 = deltaTmp = 0;
        for (j = 0; j < GrayScale; j++)
        {
            if (j <= i)   //背景部分   
            {
                w0 += pixelPro[j];
                u0tmp += j * pixelPro[j];
            }
            else   //前景部分   
            {
                w1 += pixelPro[j];
                u1tmp += j * pixelPro[j];
            }
        }
        u0 = u0tmp / w0;
        u1 = u1tmp / w1;
        deltaTmp = (float)(w0 *w1* pow((u0 - u1), 2));
        if (deltaTmp > deltaMax)
        {
            deltaMax = deltaTmp;
            threshold = i;
        }
    }
    return threshold;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值