static ImageTableCollection DetectTables(CellBoxes cellBoxes, int pageWidth, int pageHeight, int lineDistance, int textSize) { ImageTableCollection tables = new ImageTableCollection(); CrossPoints crossPoints; ImageCellCollection cells; int[,] crossPointIndexes; int index = 0, minX, minY, maxX, maxY; int spacingMin = (int)(textSize * RATIO_TEXT_HEIGHT); double widthRatio = 1d / pageWidth; double heightRatio = 1d / pageHeight; foreach (CellBox box in cellBoxes) { // box 안의 line이 5개가 넘어야 table로 인정한다. top, bottom, left, right가 있으므로 나머지 line이 적어도 1개 이상 있어야 함. if (box.Horizontals.Count + box.Verticals.Count > 0) { // 교차점을 구한다. crossPoints = DetectRawCrossPoints(horizontals: box.Horizontals, verticals: box.Verticals, lineDistance: lineDistance, crossPointIndexes: out crossPointIndexes); // 일단 cell을 구한다. cells = DetectRawCells(crossPoints: crossPoints, crossPointIndexes: crossPointIndexes, spacingMin: spacingMin, widthRatio: widthRatio, heightRatio: heightRatio); if (cells.Count > 0) { minX = minY = int.MaxValue; maxX = maxY = int.MinValue; foreach (ImageCell cell in cells) { if (cell.LeftX < minX) { minX = cell.LeftX; } if (cell.RightX > maxX) { maxX = cell.RightX; } if (cell.TopY < minY) { minY = cell.TopY; } if (cell.BottomY > maxY) { maxY = cell.BottomY; } } tables.Add(new ImageTable(index: index++, x: minX, y: minY, width: maxX - minX, height: maxY - minY, cells: cells)); } } } return(tables); }
static void DrawTables(ImageTableCollection tables, string imagePath) { using (Mat img = Cv2.ImRead(fileName: imagePath, flags: ImreadModes.Color)) { foreach (ImageTable table in tables) { foreach (ImageCell cell in table.cells) { Cv2.Rectangle(img: img, rect: new Rect(x: cell.LeftX, y: cell.TopY, width: cell.RightX - cell.LeftX, height: cell.BottomY - cell.TopY), color: new Scalar(0, 0, 255), thickness: 2); } Cv2.Rectangle(img: img, rect: new Rect(x: table.X, y: table.Y, width: table.Width, height: table.Height), color: new Scalar(0, 0, 255), thickness: 2); } Cv2.ImWrite($"{imagePath}_Tables.png", img); } }
public static ImageTableCollection GetTables(string imagePath, int textSize, bool drawTable = false, bool drawLine = false) { CellLines horizontals, verticals; int pageWidth, pageHeight; DetectLines(imagePath: imagePath, textSize: textSize, horizontals: out horizontals, verticals: out verticals, pageWidth: out pageWidth, pageHeight: out pageHeight); int lineDistance = GetLineDistanceByModeThickness(horizontals: ref horizontals, verticals: ref verticals); CellBoxes cellBoxes = DetectCellBoxes(lineDistance: lineDistance, horizontals: ref horizontals, verticals: ref verticals); ImageTableCollection tables = DetectTables(cellBoxes: cellBoxes, pageWidth: pageWidth, pageHeight: pageHeight, lineDistance: lineDistance, textSize: textSize); if (drawLine) { DrawLines(horizontals: horizontals, verticals: verticals, imagePath: imagePath); } if (drawTable) { DrawTables(tables: tables, imagePath: imagePath); } return(tables); }