美文网首页计算机视觉
C++ opencv 图片二值化最佳阈值确定(大津法,OTSU算

C++ opencv 图片二值化最佳阈值确定(大津法,OTSU算

作者: 刘千予 | 来源:发表于2018-07-01 11:08 被阅读0次

//opencv

#include "opencv2/opencv.hpp"

#include "opencv2/highgui/highgui.hpp"

#include "opencv2/imgproc/imgproc.hpp"

/******************************************************************************************

Function:      OtsuThreshold

Description: 图片二值化最佳阈值确定(大津法,OTSU算法)

Input:          src:原图片

Return:        阈值

******************************************************************************************/

int OtsuThreshold(IplImage* src)

{

int threshold;

try

{

int height = src->height;

int width = src->width;

//histogram 

float histogram[256] = { 0 };

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

unsigned char* p = (unsigned char*)src->imageData + src->widthStep*i;

for (int j = 0; j < width; j++) {

histogram[*p++]++;

}

}

//normalize histogram 

int size = height*width;

for (int i = 0; i < 256; i++) {

histogram[i] = histogram[i] / size;

}

//average pixel value 

float avgValue = 0;

for (int i = 0; i < 256; i++) {

avgValue += i*histogram[i];

}

float maxVariance = 0;

float w = 0, u = 0;

for (int i = 0; i < 256; i++) {

w += histogram[i];

u += i*histogram[i];

float t = avgValue*w - u;

float variance = t*t / (w*(1 - w));

if (variance > maxVariance) {

maxVariance = variance;

threshold = i;

}

}

}

catch (cv::Exception e)

{

}

return threshold;

}

相关文章

网友评论

    本文标题:C++ opencv 图片二值化最佳阈值确定(大津法,OTSU算

    本文链接:https://www.haomeiwen.com/subject/cfycuftx.html