灰度图像简单二值化方法


方法原理:

1.算出图像的均值

2.判断每个像素值,大于均值的赋值为255,小于均值的赋值为0

示例代码如下:

void img_binary(unsigned char* img, int h, int w)
{
	int i, j;
	int totalPixValue = 0;
	int mean = 0;
	for (i = 0; i < h; i++)
	{
		for (j = 0; j < w; j++)
		{
			totalPixValue += img[i*w + j];
		}
	}
	mean = totalPixValue / (h*w);
	for (i = 0; i < h; i++)
	{
		for (j = 0; j < w; j++)
		{
			if (img[i*w + j] < mean)
				img[i*w + j] = 0;
			else
				img[i*w + j] = 255;
		}
	}
}