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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ opencv 图片二值化最佳阈值确定(大津法,OTSU算法)相关的知识,希望对你有一定的参考价值。

参考技术A //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算法)的主要内容,如果未能解决你的问题,请参考以下文章

大津法(最大类间阈值法)

大津法---OTSU算法

opencv-阈值分割

大津法

2021-09-23 opencv学习笔记(图像变换,二值化,滤波器介绍及python实现)

opencv实现KNN手写数字的识别