3,424
社区成员
发帖
与我相关
我的任务
分享
#include "mex.h"
#include <iostream>
using namespace std;
double getThresh(int ** a, long row, long col)//Otsu法(最大类间方差法)
{
long N = row*col;
double global_gram[256] = { 0.0 };
double fangcha[256] = { 0.0 };
for (long i = 0; i < row; i++)
{
for (long j = 0; j < col; j++)
{
global_gram[a[i][j]]++; //统计灰度直方图(此时为统计像素数量)
}
}
int w0, w_back, w_front; // w0为全局平均灰度,背景灰度,前景灰度
double p_back, p_front; // 背景概率,前景概率
double data_back, data_front;
for (int i = 0; i < 256; i++) //全局平均灰度
{
global_gram[i] /= N;
w0 += i*global_gram[i];
}
for (int i = 0; i < 256; i++) // 对每个灰度值,计算类间方差
{
p_back += global_gram[i];
p_front = 1 - p_back;
data_back += global_gram[i] * i;
data_front = w0 - data_back;
w_back = data_back / p_back;
w_front = data_front / p_front;
fangcha[i] = p_back*(w0 - w_back)*(w0 - w_back) + p_front*(w0 - w_front)*(w0 - w_front);
}
double temp = 0;
double result = 0;
for (int i = 0; i < 256; i++)
{
if (fangcha[i]>temp)
{
temp = fangcha[i];
result = i;
}
}
return result;
}
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
if (nlhs != 1 || nrhs != 3) // 判断参数数量是否正确
{
cout << "参数个数不匹配!\n";
exit(0);
}
int **a;
a = (int **)(mxGetPr(prhs[0]));
long r = *(mxGetPr(prhs[1]));
long c = *(mxGetPr(prhs[2]));
double *result;
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*result = getThresh(a, r, c);
}