题目源: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;
}