/// <summary> /// 去除区域噪音,联通域降噪方式,去除连通点数小于阀值的连通区域 /// </summary> /// <param name="binBytes">二进制数组</param> /// <param name="gray">灰度值</param> /// <param name="minAreaPoints">噪点阀值</param> /// <returns></returns> public static byte[,] ClearNoiseArea(this byte[,] binBytes, byte gray, int minAreaPoints) { int width = binBytes.GetLength(0), height = binBytes.GetLength(1); byte[,] newBinBytes = binBytes.Copy(); // 遍历所有点,是黑点0,把与黑点连通的所有点灰度都改为1,下一个连通区域改为2,直到所有连通区域都标记完毕 Dictionary <byte, Point[]> areaPointDict = new Dictionary <byte, Point[]>(); byte setGray = 1; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (IsBlack(newBinBytes[x, y])) { newBinBytes.FloodFill(new Point(x, y), setGray, out Point[] setPoints); areaPointDict.Add(setGray, setPoints); setGray++; if (setGray >= 255) { setGray = 254; } } } } // 筛选出区域点数小于阈值的区域,将原图相应点设置为白色 List <Point[]> pointsList = areaPointDict.Where(m => m.Value.Length < minAreaPoints).Select(m => m.Value).ToList(); foreach (var points in pointsList) { foreach (var point in points) { binBytes[point.X, point.Y] = 255; } } return(binBytes); }