Qt 之图像处理(七) 迭代选择阈值法

迭代选择阈值法

原理:

代码:

//图像迭代选择阈值法
int MainWindow::DetectThreshold_pro(QImage *inputImage,int nMaxIter, int &nDiffRet)
{
    int nThreshold;
    QColor oldColor;

    nDiffRet = 0;

    //直方图数组
    int nHistogram[255] = {0};
    int bt;
    int nMax = 0;
    int nMin = 255;


    //扫描图像,计算出最大值 最小灰度的直方图
    for(int i = 0;i<inputImage->height(); i++)
    {
        for(int j = 0; j<inputImage->width(); j++)
        {
            oldColor = QColor(inputImage->pixel(j,i));
            bt = oldColor.red();

            if(bt<nMin)
            {
               nMin = bt;
            }
            if(bt>nMax)
            {
                nMax = bt;
            }

            nHistogram[bt] ++;
        }
    }


    int nTotalGray = 0;   //灰度值得和
    int nTotalPixel = 0;   //像素数的和
    int nNewThreshold = (nMax + nMin)/2; //初始阈值

    nDiffRet = nMax - nMin;

    if(nMax == nMin)
    {
        nThreshold = nNewThreshold;
    }
    else {
        nThreshold = 0;

        //迭代开始,直接迭代次数达到100 或新阈值与上一轮得到的阈值相等,迭代结束
        while(nThreshold != nNewThreshold && nMaxIter>0)
        {
            nThreshold = nNewThreshold;
            nTotalGray = 0;
            nTotalPixel = 0;

            //计算图像中小于当前的阈值部分的平均灰度
            for(int i = nMin; i<nThreshold; i++)
            {
                nTotalGray += nHistogram[i]*i;
                nTotalPixel += nHistogram[i];

            }

            int nMean1GrayValue = nTotalGray/nTotalPixel;

            nTotalGray = 0;
            nTotalPixel = 0;


            //计算图像中小于当前的阈值部分的平均灰度
            for(int i = nThreshold; i<nMax; i++)
            {
                nTotalGray += nHistogram[i]*i;
                nTotalPixel += nHistogram[i];

            }

            int nMean2GrayValue = nTotalGray/nTotalPixel;

            nNewThreshold = (nMean1GrayValue + nMean2GrayValue) / 2;
            nDiffRet = abs(nMean1GrayValue - nMean2GrayValue);

        }

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值