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

//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;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容