Opencv4.5.5 C++ Problem Set No.4 大津二值化算法

题目源:GitHub - gzr2017/ImageProcessing100Wen: 「画像処理100本ノック」中文版本!为图像处理初学者设计的 100 个问题。

问题描述:

在Opencv455中,可以利用threshold函数中的otsu参数实现,因为只是简单的调用Api,所以不再赘述。

这里给出根据公式手写源代码的参考答案,注意,定义某些变量得用float,我一开始都用的int导致返回的t是0:

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat Gray(Mat img){
    int cols(img.cols),rows(img.rows);
    Mat gray=Mat::zeros(rows,cols,CV_8UC1);
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            gray.at<uchar>(i,j)=0.2126*(float)img.at<Vec3b>(i,j)[2]+0.7152*(float)img.at<Vec3b>(i,j)[1]+0.0722*(float)img.at<Vec3b>(i,j)[0];
        }
    }
    return gray;
}
int returnt(Mat img_gray){
    int cols(img_gray.cols),rows(img_gray.rows),size(rows*cols);

    float w0(0),w1(0),M0(0),M1(0);
    int maxt(0);
    float maxSb(0);

    for(int t=0;t<256;t++){
        for(int i=0;i<cols;i++){
            for(int j=0;j<rows;j++){
                if(img_gray.at<uchar>(i,j)<t){
                    w0++;
                    M0=M0+img_gray.at<uchar>(i,j);
                }else{
                    w1++;
                    M1=M1+img_gray.at<uchar>(i,j);
                }
            }
        }
        M0=M0/w0;
        M1=M1/w1;
        w0=w0/size;
        w1=w1/size;
        float Sb=w0*w1*(M0-M1)*(M0-M1);
        if(Sb>maxSb){
            maxSb=Sb;
            maxt=t;
        }
//        cout<<"M0="<<M0<<" "<<"M1="<<M1<<" "<<"w0="<<w0<<" "<<"w1="<<w1<<" ";
//        cout<<"Sb="<<Sb<<" ";
//        cout<<"t="<<t<<" ";
//        cout<<"maxt="<<maxt<<endl;
        M0=0;M1=0;w0=0;w1=0;
    }
    return maxt;
}
Mat otsuthresh(Mat img){
    int rows(img.rows),cols(img.cols);
    Mat gray=Gray(img);
    int t=returnt(gray);
    Mat otsuth=Mat::zeros(rows,cols,CV_8UC1);
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            if(gray.at<uchar>(i,j)<t){
                otsuth.at<uchar>(i,j)=0;
            }else{
                otsuth.at<uchar>(i,j)=255;
            }
        }
    }
    return otsuth;
}
int main()
{
    Mat img=imread("C:/Users/79490/Desktop/ImageProcessing100Wen-master/ImageProcessing100Wen-master/Question_01_10/imori.jpg",IMREAD_COLOR);
    Mat otsuimg=otsuthresh(img);
    imshow("otsuimg",otsuimg);
    waitKey(0);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值