diff --git a/CamScanner.cs b/CamScanner.cs index f8ad70e..d99ab6a 100644 --- a/CamScanner.cs +++ b/CamScanner.cs @@ -437,8 +437,9 @@ public static class DocumentScanner } } int paperBright = (int)(centerSum / Math.Max(centerCount, 1)); - int darkThresh = (int)(paperBright * 0.6); - int maxScanDepth = Math.Max(w, h) / 4; // 最多扫描1/4深度 + int darkThresh = (int)(paperBright * 0.65); + int maxScanDepth = Math.Max(w, h) / 3; // 最多扫描1/3深度 + int tolerance = 5; // 允许跳过最多5个亮像素继续扫描 byte[] cleanedData = new byte[w * h]; Marshal.Copy(cleaned.Data, cleanedData, 0, cleanedData.Length); @@ -446,46 +447,86 @@ public static class DocumentScanner // 上边缘 for (int x = 0; x < w; x++) { + int skipCount = 0; + int lastDark = -1; for (int y = 0; y < Math.Min(maxScanDepth, h); y++) { if (grayData[y * w + x] < darkThresh) - cleanedData[y * w + x] = 255; + { + lastDark = y; + skipCount = 0; + } else - break; + { + skipCount++; + if (skipCount > tolerance) break; + } } + for (int y = 0; y <= lastDark; y++) + cleanedData[y * w + x] = 255; } // 下边缘 for (int x = 0; x < w; x++) { + int skipCount = 0; + int lastDark = h; for (int y = h - 1; y >= Math.Max(0, h - maxScanDepth); y--) { if (grayData[y * w + x] < darkThresh) - cleanedData[y * w + x] = 255; + { + lastDark = y; + skipCount = 0; + } else - break; + { + skipCount++; + if (skipCount > tolerance) break; + } } + for (int y = h - 1; y >= lastDark; y--) + cleanedData[y * w + x] = 255; } // 左边缘 for (int py = 0; py < h; py++) { + int skipCount = 0; + int lastDark = -1; for (int x = 0; x < Math.Min(maxScanDepth, w); x++) { if (grayData[py * w + x] < darkThresh) - cleanedData[py * w + x] = 255; + { + lastDark = x; + skipCount = 0; + } else - break; + { + skipCount++; + if (skipCount > tolerance) break; + } } + for (int x = 0; x <= lastDark; x++) + cleanedData[py * w + x] = 255; } // 右边缘 for (int py = 0; py < h; py++) { + int skipCount = 0; + int lastDark = w; for (int x = w - 1; x >= Math.Max(0, w - maxScanDepth); x--) { if (grayData[py * w + x] < darkThresh) - cleanedData[py * w + x] = 255; + { + lastDark = x; + skipCount = 0; + } else - break; + { + skipCount++; + if (skipCount > tolerance) break; + } } + for (int x = w - 1; x >= lastDark; x--) + cleanedData[py * w + x] = 255; } Marshal.Copy(cleanedData, 0, cleaned.Data, cleanedData.Length);