方法原理:
1.对灰度算均值并二值化图像
2.利用二值化后的图像,遍历每个点,把符合条件的点邻域的点都设置为覆盖区,
3.再遍历一遍处理后的图像计算覆盖率
代码如下:
double img_coverage_calculate(unsigned char *img, int h, int w)
{
int i, j, n, m;
int sum = 0,mean = 0;
int expend = 2;//左右扩展2
int expend_size = (expend * 2 + 1);//5x5方形邻域大小
int total_corverage = 0;
unsigned char* temp_img = (unsigned char*)malloc(h*w);
memcpy(temp_img,img,h*w);
for (i = 0; i < h;i++)
{
for (j = 0; j < w;j++)
{
sum += temp_img[i * w + j];
}
}
mean = sum / (h * w);
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
if (temp_img[i*w + j] < mean)
temp_img[i*w + j] = 0;
else
temp_img[i*w + j] = 255;
}
}
memcpy(img,temp_img,h*w);
for (i = expend; i < h - expend; i++)
{
for (j = expend; j < w - expend; j++)
{
if (temp_img[i*w + j] == 0)
{
for (n = 0; n < expend_size; n++)
{
for (m = 0; m < expend_size; m++)
{
img[(i - expend + n) * w + (j - expend + m)] = 0;
}
}
}
}
}
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
if (img[i*w + j] == 0)
total_corverage += 1;
}
}
free(temp_img);
return double (total_corverage) / (h * w);
}