android中对dstmap的自适应二值化函数的源代码
时间: 2023-12-03 15:46:41 浏览: 31
以下是Android中对dstmap的自适应二值化函数的源代码:
```
public static Bitmap adaptiveThreshold(Bitmap src, int blockSize, int C) {
if (src == null) {
return null;
}
int width = src.getWidth();
int height = src.getHeight();
Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int[] srcPixels = new int[width * height];
int[] dstPixels = new int[width * height];
src.getPixels(srcPixels, 0, width, 0, 0, width, height);
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int sum = 0;
int count = 0;
for (int dy = -blockSize / 2; dy <= blockSize / 2; dy++) {
int yy = y + dy;
if (yy < 0 || yy >= height) {
continue;
}
for (int dx = -blockSize / 2; dx <= blockSize / 2; dx++) {
int xx = x + dx;
if (xx < 0 || xx >= width) {
continue;
}
int pixel = srcPixels[yy * width + xx];
int red = Color.red(pixel);
int green = Color.green(pixel);
int blue = Color.blue(pixel);
int gray = (int) (0.299 * red + 0.587 * green + 0.114 * blue);
sum += gray;
count++;
}
}
int threshold = (int) (sum / count + C);
int pixel = srcPixels[y * width + x];
int red = Color.red(pixel);
int green = Color.green(pixel);
int blue = Color.blue(pixel);
int gray = (int) (0.299 * red + 0.587 * green + 0.114 * blue);
if (gray > threshold) {
dstPixels[index] = Color.WHITE;
} else {
dstPixels[index] = Color.BLACK;
}
index++;
}
}
dst.setPixels(dstPixels, 0, width, 0, 0, width, height);
return dst;
}
```
这个函数使用了一个方块块大小和一个常数C来进行自适应二值化。函数首先将原始图像的像素存储在一个数组中,然后遍历每个像素并计算其周围方块中像素的平均灰度值。然后,函数将该平均值加上常数C,并将其用作阈值来将该像素转换为黑色或白色。最后,将转换后的像素存储在一个新的数组中,并将其用于创建输出图像。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)