From 687aba1fa288074e3e326e06866cc5acc4beb235 Mon Sep 17 00:00:00 2001 From: Clemens Neudecker <952378+cneud@users.noreply.github.com> Date: Mon, 3 Mar 2025 22:10:40 +0100 Subject: [PATCH 01/19] replace usages of `imutils` with opencv equivalents should fix https://github.com/qurator-spk/eynollah/issues/141 --- src/eynollah/utils/rotate.py | 40 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/eynollah/utils/rotate.py b/src/eynollah/utils/rotate.py index 603c2d9..c01f5e8 100644 --- a/src/eynollah/utils/rotate.py +++ b/src/eynollah/utils/rotate.py @@ -1,6 +1,4 @@ import math - -import imutils import cv2 def rotatedRectWithMaxArea(w, h, angle): @@ -11,11 +9,11 @@ def rotatedRectWithMaxArea(w, h, angle): side_long, side_short = (w, h) if width_is_longer else (h, w) # since the solutions for angle, -angle and 180-angle are all the same, - # if suffices to look at the first quadrant and the absolute values of sin,cos: + # it suffices to look at the first quadrant and the absolute values of sin,cos: sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle)) if side_short <= 2.0 * sin_a * cos_a * side_long or abs(sin_a - cos_a) < 1e-10: - # half constrained case: two crop corners touch the longer side, - # the other two corners are on the mid-line parallel to the longer line + # half constrained case: two crop corners touch the longer side, + # the other two corners are on the mid-line parallel to the longer line x = 0.5 * side_short wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a) else: @@ -25,6 +23,12 @@ def rotatedRectWithMaxArea(w, h, angle): return wr, hr +def rotate_image_opencv(image, angle): + (h, w) = image.shape[:2] + center = (w // 2, h // 2) + M = cv2.getRotationMatrix2D(center, angle, 1.0) + return cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) + def rotate_max_area_new(image, rotated, angle): wr, hr = rotatedRectWithMaxArea(image.shape[1], image.shape[0], math.radians(angle)) h, w, _ = rotated.shape @@ -35,7 +39,7 @@ def rotate_max_area_new(image, rotated, angle): return rotated[y1:y2, x1:x2] def rotation_image_new(img, thetha): - rotated = imutils.rotate(img, thetha) + rotated = rotate_image_opencv(img, thetha) return rotate_max_area_new(img, rotated, thetha) def rotate_image(img_patch, slope): @@ -44,13 +48,10 @@ def rotate_image(img_patch, slope): M = cv2.getRotationMatrix2D(center, slope, 1.0) return cv2.warpAffine(img_patch, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) -def rotate_image_different( img, slope): - # img = cv2.imread('images/input.jpg') +def rotate_image_different(img, slope): num_rows, num_cols = img.shape[:2] - rotation_matrix = cv2.getRotationMatrix2D((num_cols / 2, num_rows / 2), slope, 1) - img_rotation = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows)) - return img_rotation + return cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows)) def rotate_max_area(image, rotated, rotated_textline, rotated_layout, rotated_table_prediction, angle): wr, hr = rotatedRectWithMaxArea(image.shape[1], image.shape[0], math.radians(angle)) @@ -62,17 +63,17 @@ def rotate_max_area(image, rotated, rotated_textline, rotated_layout, rotated_ta return rotated[y1:y2, x1:x2], rotated_textline[y1:y2, x1:x2], rotated_layout[y1:y2, x1:x2], rotated_table_prediction[y1:y2, x1:x2] def rotation_not_90_func(img, textline, text_regions_p_1, table_prediction, thetha): - rotated = imutils.rotate(img, thetha) - rotated_textline = imutils.rotate(textline, thetha) - rotated_layout = imutils.rotate(text_regions_p_1, thetha) - rotated_table_prediction = imutils.rotate(table_prediction, thetha) + rotated = rotate_image_opencv(img, thetha) + rotated_textline = rotate_image_opencv(textline, thetha) + rotated_layout = rotate_image_opencv(text_regions_p_1, thetha) + rotated_table_prediction = rotate_image_opencv(table_prediction, thetha) return rotate_max_area(img, rotated, rotated_textline, rotated_layout, rotated_table_prediction, thetha) def rotation_not_90_func_full_layout(img, textline, text_regions_p_1, text_regions_p_fully, thetha): - rotated = imutils.rotate(img, thetha) - rotated_textline = imutils.rotate(textline, thetha) - rotated_layout = imutils.rotate(text_regions_p_1, thetha) - rotated_layout_full = imutils.rotate(text_regions_p_fully, thetha) + rotated = rotate_image_opencv(img, thetha) + rotated_textline = rotate_image_opencv(textline, thetha) + rotated_layout = rotate_image_opencv(text_regions_p_1, thetha) + rotated_layout_full = rotate_image_opencv(text_regions_p_fully, thetha) return rotate_max_area_full_layout(img, rotated, rotated_textline, rotated_layout, rotated_layout_full, thetha) def rotate_max_area_full_layout(image, rotated, rotated_textline, rotated_layout, rotated_layout_full, angle): @@ -83,4 +84,3 @@ def rotate_max_area_full_layout(image, rotated, rotated_textline, rotated_layout x1 = w // 2 - int(wr / 2) x2 = x1 + int(wr) return rotated[y1:y2, x1:x2], rotated_textline[y1:y2, x1:x2], rotated_layout[y1:y2, x1:x2], rotated_layout_full[y1:y2, x1:x2] - From 0b2c1b9275077eed0a7963fd4ad2c25624b9b88a Mon Sep 17 00:00:00 2001 From: cneud <952378+cneud@users.noreply.github.com> Date: Mon, 3 Mar 2025 22:21:57 +0100 Subject: [PATCH 02/19] remove `imutils` dependency --- requirements.txt | 1 - src/eynollah/utils/__init__.py | 1 - 2 files changed, 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index e6f6e4b..7817f27 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,5 @@ ocrd >= 2.23.3 numpy <1.24.0 scikit-learn >= 0.23.2 tensorflow < 2.13 -imutils >= 0.5.3 matplotlib setuptools >= 50 diff --git a/src/eynollah/utils/__init__.py b/src/eynollah/utils/__init__.py index d2b2488..149de6d 100644 --- a/src/eynollah/utils/__init__.py +++ b/src/eynollah/utils/__init__.py @@ -4,7 +4,6 @@ import matplotlib.pyplot as plt import numpy as np from shapely import geometry import cv2 -import imutils from scipy.signal import find_peaks from scipy.ndimage import gaussian_filter1d From 370d44a66b8bbca23eacec0521dd3e68138638bd Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Wed, 26 Mar 2025 10:45:34 +0100 Subject: [PATCH 03/19] Slope deskew in the light version is set to zero because when the slope_deskew value exceeds the slope_threshold, the reading order becomes incorrect. This issue needs to be addressed. Additionally, the textlines order within text region in the light version was reversed, and this has been corrected. --- src/eynollah/eynollah.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 7acee39..fd3eb25 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -1575,7 +1575,7 @@ class Eynollah: indexes_in = args_textlines[results==1] textlines_ins = [polygons_of_textlines[ind] for ind in indexes_in] - all_found_textline_polygons.append(textlines_ins) + all_found_textline_polygons.append(textlines_ins[::-1]) slopes.append(slope_deskew) _, crop_coor = crop_image_inside_box(boxes[index],image_page_rotated) @@ -4417,9 +4417,9 @@ class Eynollah: textline_mask_tot_ea_deskew = resize_image(textline_mask_tot_ea,img_h_new, img_w_new ) - slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea_deskew) + slope_deskew, slope_first = 0, 0 #self.run_deskew(textline_mask_tot_ea_deskew) else: - slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea) + slope_deskew, slope_first = 0, 0 #self.run_deskew(textline_mask_tot_ea) #print("text region early -2,5 in %.1fs", time.time() - t0) #self.logger.info("Textregion detection took %.1fs ", time.time() - t1t) num_col, num_col_classifier, img_only_regions, page_coord, image_page, mask_images, mask_lines, \ @@ -4965,7 +4965,7 @@ class Eynollah_ocr: self.model_ocr.to(self.device) else: - self.model_ocr_dir = dir_models + "/model_3_new_ocrcnn"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" + self.model_ocr_dir = dir_models + "/model_step_100000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" model_ocr = load_model(self.model_ocr_dir , compile=False) self.prediction_model = tf.keras.models.Model( @@ -5309,9 +5309,7 @@ class Eynollah_ocr: for cheild_text in child_textlines: if cheild_text.tag.endswith("Unicode"): textline_text = cheild_text.text - if not textline_text: - pass - else: + if textline_text: with open(os.path.join(self.dir_out, file_name+'_line_'+str(indexer_textlines)+'.txt'), 'w') as text_file: text_file.write(textline_text) From 7df0427b0479bdfb00cc789e09ae3ecb08cc9bb7 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Wed, 26 Mar 2025 18:42:06 +0100 Subject: [PATCH 04/19] In the context of OCR, if Page-XML files already contain text, the new predicted text will replace the existing text. --- src/eynollah/eynollah.py | 43 +++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index fd3eb25..7cbab6a 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -4965,7 +4965,7 @@ class Eynollah_ocr: self.model_ocr.to(self.device) else: - self.model_ocr_dir = dir_models + "/model_step_100000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" + self.model_ocr_dir = dir_models + "/model_step_150000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" model_ocr = load_model(self.model_ocr_dir , compile=False) self.prediction_model = tf.keras.models.Model( @@ -5358,20 +5358,49 @@ class Eynollah_ocr: indexer = 0 indexer_textregion = 0 for nn in root1.iter(region_tags): - text_subelement_textregion = ET.SubElement(nn, 'TextEquiv') - unicode_textregion = ET.SubElement(text_subelement_textregion, 'Unicode') + + is_textregion_text = False + for childtest in nn: + if childtest.tag.endswith("TextEquiv"): + is_textregion_text = True + + if not is_textregion_text: + text_subelement_textregion = ET.SubElement(nn, 'TextEquiv') + unicode_textregion = ET.SubElement(text_subelement_textregion, 'Unicode') has_textline = False for child_textregion in nn: if child_textregion.tag.endswith("TextLine"): - text_subelement = ET.SubElement(child_textregion, 'TextEquiv') - unicode_textline = ET.SubElement(text_subelement, 'Unicode') - unicode_textline.text = extracted_texts_merged[indexer] + + is_textline_text = False + for childtest2 in child_textregion: + if childtest2.tag.endswith("TextEquiv"): + is_textline_text = True + + + if not is_textline_text: + text_subelement = ET.SubElement(child_textregion, 'TextEquiv') + unicode_textline = ET.SubElement(text_subelement, 'Unicode') + unicode_textline.text = extracted_texts_merged[indexer] + else: + for childtest3 in child_textregion: + if childtest3.tag.endswith("TextEquiv"): + for child_uc in childtest3: + if child_uc.tag.endswith("Unicode"): + child_uc.text = extracted_texts_merged[indexer] + indexer = indexer + 1 has_textline = True if has_textline: - unicode_textregion.text = text_by_textregion[indexer_textregion] + if is_textregion_text: + for child4 in nn: + if child4.tag.endswith("TextEquiv"): + for childtr_uc in child4: + if childtr_uc.tag.endswith("Unicode"): + childtr_uc.text = text_by_textregion[indexer_textregion] + else: + unicode_textregion.text = text_by_textregion[indexer_textregion] indexer_textregion = indexer_textregion + 1 ET.register_namespace("",name_space) From 181c0c584f0370c789557b8db0610636bed414fb Mon Sep 17 00:00:00 2001 From: cneud <952378+cneud@users.noreply.github.com> Date: Wed, 26 Mar 2025 22:25:22 +0100 Subject: [PATCH 05/19] bbox rotation with opencv --- src/eynollah/utils/rotate.py | 42 ++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/eynollah/utils/rotate.py b/src/eynollah/utils/rotate.py index c01f5e8..734f924 100644 --- a/src/eynollah/utils/rotate.py +++ b/src/eynollah/utils/rotate.py @@ -1,4 +1,5 @@ import math +import numpy as np import cv2 def rotatedRectWithMaxArea(w, h, angle): @@ -23,11 +24,44 @@ def rotatedRectWithMaxArea(w, h, angle): return wr, hr + def rotate_image_opencv(image, angle): - (h, w) = image.shape[:2] - center = (w // 2, h // 2) - M = cv2.getRotationMatrix2D(center, angle, 1.0) - return cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) + # Calculate the original image dimensions (h, w) and the center point (cx, cy) + h, w = image.shape[:2] + cx, cy = (w // 2, h // 2) + + # Compute the rotation matrix + M = cv2.getRotationMatrix2D((cx, cy), angle, 1.0) + + # Calculate the new bounding box + corners = np.array([ + [0, 0], + [w, 0], + [w, h], + [0, h] + ]) + + # Apply rotation matrix to the corner points + ones = np.ones(shape=(len(corners), 1)) + corners_ones = np.hstack([corners, ones]) + transformed_corners = M @ corners_ones.T + transformed_corners = transformed_corners.T + + # Calculate the new bounding box dimensions + min_x, min_y = np.min(transformed_corners, axis=0) + max_x, max_y = np.max(transformed_corners, axis=0) + + newW = int(np.ceil(max_x - min_x)) + newH = int(np.ceil(max_y - min_y)) + + # Adjust the rotation matrix to account for translation + M[0, 2] += (newW / 2) - cx + M[1, 2] += (newH / 2) - cy + + # Perform the affine transformation (rotation) + rotated_image = cv2.warpAffine(image, M, (newW, newH)) + + return rotated_image def rotate_max_area_new(image, rotated, angle): wr, hr = rotatedRectWithMaxArea(image.shape[1], image.shape[0], math.radians(angle)) From 6f36c7177f0b1c9d9ad5cf398f0211a8f07a8f5b Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Thu, 27 Mar 2025 18:24:47 +0100 Subject: [PATCH 06/19] For OCR, the splitting ratio of text lines is adjusted --- src/eynollah/eynollah.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 7cbab6a..34fc8cb 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -5091,6 +5091,7 @@ class Eynollah_ocr: width_new = w_ratio else: width_new = image_width + img = resize_image(img, image_height, width_new) img_fin = np.ones((image_height, image_width, 3))*255 img_fin[:,:width_new,:] = img[:,:,:] @@ -5285,7 +5286,7 @@ class Eynollah_ocr: img_crop[mask_poly==0] = 255 if not self.export_textline_images_and_text: - if h2w_ratio > 0.05: + if h2w_ratio > 0.1: img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(img_crop, image_height, image_width) cropped_lines.append(img_fin) cropped_lines_meging_indexing.append(0) @@ -5345,7 +5346,7 @@ class Eynollah_ocr: pred_texts_ib = pred_texts[ib].strip("[UNK]") extracted_texts.append(pred_texts_ib) - extracted_texts_merged = [extracted_texts[ind] if cropped_lines_meging_indexing[ind]==0 else extracted_texts[ind]+extracted_texts[ind+1] if cropped_lines_meging_indexing[ind]==1 else None for ind in range(len(cropped_lines_meging_indexing))] + extracted_texts_merged = [extracted_texts[ind] if cropped_lines_meging_indexing[ind]==0 else extracted_texts[ind]+" "+extracted_texts[ind+1] if cropped_lines_meging_indexing[ind]==1 else None for ind in range(len(cropped_lines_meging_indexing))] extracted_texts_merged = [ind for ind in extracted_texts_merged if ind is not None] unique_cropped_lines_region_indexer = np.unique(cropped_lines_region_indexer) From e9fa6913081f16f6bd7df3238b91437f230ab785 Mon Sep 17 00:00:00 2001 From: cneud <952378+cneud@users.noreply.github.com> Date: Thu, 27 Mar 2025 22:41:10 +0100 Subject: [PATCH 07/19] add model and training documentation --- README.md | 17 +- docs/models.md | 145 ++++++++++++ docs/train.md | 632 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 783 insertions(+), 11 deletions(-) create mode 100644 docs/models.md create mode 100644 docs/train.md diff --git a/README.md b/README.md index 916c556..5699948 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,10 @@ Alternatively, you can run `make install` or `make install-dev` for editable ins ## Models Pre-trained models can be downloaded from [qurator-data.de](https://qurator-data.de/eynollah/) or [huggingface](https://huggingface.co/SBB?search_models=eynollah). +For documentation on methods and models, have a look at [`models.md`](https://github.com/qurator-spk/eynollah/tree/main/docs/models.md). + ## Train -🚧 **Work in progress** - -In case you want to train your own model, have a look at [`sbb_pixelwise_segmentation`](https://github.com/qurator-spk/sbb_pixelwise_segmentation). +In case you want to train your own model with Eynollah, have a look at [`train.md`](https://github.com/qurator-spk/eynollah/tree/main/docs/train.md). ## Usage The command-line interface can be called like this: @@ -83,11 +83,9 @@ If no option is set, the tool performs layout detection of main regions (backgro The best output quality is produced when RGB images are used as input rather than greyscale or binarized images. #### Use as OCR-D processor -🚧 **Work in progress** - -Eynollah ships with a CLI interface to be used as [OCR-D](https://ocr-d.de) processor. +Eynollah ships with a CLI interface to be used as [OCR-D](https://ocr-d.de) processor that is described in [`ocrd-tool.json`](https://github.com/qurator-spk/eynollah/tree/main/src/eynollah/ocrd-tool.json). -In this case, the source image file group with (preferably) RGB images should be used as input like this: +The source image file group with (preferably) RGB images should be used as input for Eynollah like this: ``` ocrd-eynollah-segment -I OCR-D-IMG -O SEG-LINE -P models @@ -99,10 +97,7 @@ Any image referenced by `@imageFilename` in PAGE-XML is passed on directly to Ey ocrd-eynollah-segment -I OCR-D-IMG-BIN -O SEG-LINE -P models ``` -uses the original (RGB) image despite any binarization that may have occured in previous OCR-D processing steps - -#### Additional documentation -Please check the [wiki](https://github.com/qurator-spk/eynollah/wiki). +uses the original (RGB) image despite any binarization that may have occured in previous OCR-D processing steps. ## How to cite If you find this tool useful in your work, please consider citing our paper: diff --git a/docs/models.md b/docs/models.md new file mode 100644 index 0000000..c6f7340 --- /dev/null +++ b/docs/models.md @@ -0,0 +1,145 @@ +# Models documentation +This suite of 14 models presents a document layout analysis (DLA) system for historical documents implemented by +pixel-wise segmentation using a combination of a ResNet50 encoder with various U-Net decoders. In addition, heuristic +methods are applied to detect marginals and to determine the reading order of text regions. + +The detection and classification of multiple classes of layout elements such as headings, images, tables etc. as part of +DLA is required in order to extract and process them in subsequent steps. Altogether, the combination of image +detection, classification and segmentation on the wide variety that can be found in over 400 years of printed cultural +heritage makes this a very challenging task. Deep learning models are complemented with heuristics for the detection of +text lines, marginals, and reading order. Furthermore, an optional image enhancement step was added in case of documents +that either have insufficient pixel density and/or require scaling. Also, a column classifier for the analysis of +multi-column documents was added. With these additions, DLA performance was improved, and a high accuracy in the +prediction of the reading order is accomplished. + +Two Arabic/Persian terms form the name of the model suite: عين الله, which can be transcribed as "ain'allah" or +"eynollah"; it translates into English as "God's Eye" -- it sees (nearly) everything on the document image. + +See the flowchart below for the different stages and how they interact: +![](https://user-images.githubusercontent.com/952378/100619946-1936f680-331e-11eb-9297-6e8b4cab3c16.png) + +## Models + +### Image enhancement +Model card: [Image Enhancement](https://huggingface.co/SBB/eynollah-enhancement) + +This model addresses image resolution, specifically targeting documents with suboptimal resolution. In instances where +the detection of document layout exhibits inadequate performance, the proposed enhancement aims to significantly improve +the quality and clarity of the images, thus facilitating enhanced visual interpretation and analysis. + +### Page extraction / border detection +Model card: [Page Extraction/Border Detection](https://huggingface.co/SBB/eynollah-page-extraction) + +A problem that can negatively affect OCR are black margins around a page caused by document scanning. A deep learning +model helps to crop to the page borders by using a pixel-wise segmentation method. + +### Column classification +Model card: [Column Classification](https://huggingface.co/SBB/eynollah-column-classifier) + +This model is a trained classifier that recognizes the number of columns in a document by use of a training set with +manual classification of all documents into six classes with either one, two, three, four, five, or six and more columns +respectively. + +### Binarization +Model card: [Binarization](https://huggingface.co/SBB/eynollah-binarization) + +This model is designed to tackle the intricate task of document image binarization, which involves segmentation of the +image into white and black pixels. This process significantly contributes to the overall performance of the layout +models, particularly in scenarios where the documents are degraded or exhibit subpar quality. The robust binarization +capability of the model enables improved accuracy and reliability in subsequent layout analysis, thereby facilitating +enhanced document understanding and interpretation. + +### Main region detection +Model card: [Main Region Detection](https://huggingface.co/SBB/eynollah-main-regions) + +This model has employed a different set of labels, including an artificial class specifically designed to encompass the +text regions. The inclusion of this artificial class facilitates easier isolation of text regions by the model. This +approach grants the advantage of training the model using downscaled images, which in turn leads to faster predictions +during the inference phase. By incorporating this methodology, improved efficiency is achieved without compromising the +model's ability to accurately identify and classify text regions within documents. + +### Main region detection (with scaling augmentation) +Model card: [Main Region Detection (with scaling augmentation)](https://huggingface.co/SBB/eynollah-main-regions-aug-scaling) + +Utilizing scaling augmentation, this model leverages the capability to effectively segment elements of extremely high or +low scales within documents. By harnessing this technique, the tool gains a significant advantage in accurately +categorizing and isolating such elements, thereby enhancing its overall performance and enabling precise analysis of +documents with varying scale characteristics. + +### Main region detection (with rotation augmentation) +Model card: [Main Region Detection (with rotation augmentation)](https://huggingface.co/SBB/eynollah-main-regions-aug-rotation) + +This model takes advantage of rotation augmentation. This helps the tool to segment the vertical text regions in a +robust way. + +### Main region detection (ensembled) +Model card: [Main Region Detection (ensembled)](https://huggingface.co/SBB/eynollah-main-regions-ensembled) + +The robustness of this model is attained through an ensembling technique that combines the weights from various epochs. +By employing this approach, the model achieves a high level of resilience and stability, effectively leveraging the +strengths of multiple epochs to enhance its overall performance and deliver consistent and reliable results. + +### Full region detection (1,2-column documents) +Model card: [Full Region Detection (1,2-column documents)](https://huggingface.co/SBB/eynollah-full-regions-1column) + +This model deals with documents comprising of one and two columns. + +### Full region detection (3,n-column documents) +Model card: [Full Region Detection (3,n-column documents)](https://huggingface.co/SBB/eynollah-full-regions-3pluscolumn) + +This model is responsible for detecting headers and drop capitals in documents with three or more columns. + +### Textline detection +Model card: [Textline Detection](https://huggingface.co/SBB/eynollah-textline) + +The method for textline detection combines deep learning and heuristics. In the deep learning part, an image-to-image +model performs binary segmentation of the document into the classes textline vs. background. In the heuristics part, +bounding boxes or contours are derived from binary segmentation. + +Skewed documents can heavily affect textline detection accuracy, so robust deskewing is needed. But detecting textlines +with rectangle bounding boxes cannot deal with partially curved textlines. To address this, a functionality +specifically for documents with curved textlines was included. After finding the contour of a text region and its +corresponding textline segmentation, the text region is cut into smaller vertical straps. For each strap, its textline +segmentation is first deskewed and then the textlines are separated with the same heuristic method as for finding +textline bounding boxes. Later, the strap is rotated back into its original orientation. + +### Textline detection (light) +Model card: [Textline Detection Light (simpler but faster method)](https://huggingface.co/SBB/eynollah-textline_light) + +The method for textline detection combines deep learning and heuristics. In the deep learning part, an image-to-image +model performs binary segmentation of the document into the classes textline vs. background. In the heuristics part, +bounding boxes or contours are derived from binary segmentation. + +In the context of this textline model, a distinct labeling approach has been employed to ensure accurate predictions. +Specifically, an artificial bounding class has been incorporated alongside the textline classes. This strategic +inclusion effectively prevents any spurious connections between adjacent textlines during the prediction phase, thereby +enhancing the model's ability to accurately identify and delineate individual textlines within documents. This model +eliminates the need for additional heuristics in extracting textline contours. + +### Table detection +Model card: [Table Detection](https://huggingface.co/SBB/eynollah-tables) + +The objective of this model is to perform table segmentation in historical document images. Due to the pixel-wise +segmentation approach employed and the presence of traditional tables predominantly composed of text, the detection of +tables required the incorporation of heuristics to achieve reasonable performance. These heuristics were necessary to +effectively identify and delineate tables within the historical document images, ensuring accurate segmentation and +enabling subsequent analysis and interpretation. + +### Image detection +Model card: [Image Detection](https://huggingface.co/SBB/eynollah-image-extraction) + +This model is used for the task of illustration detection only. + +### Reading order detection +Model card: [Reading Order Detection]() + +TODO + +## Heuristic methods +Additionally, some heuristic methods are employed to further improve the model predictions: +* After border detection, the largest contour is determined by a bounding box, and the image cropped to these coordinates. +* For text region detection, the image is scaled up to make it easier for the model to detect background space between text regions. +* A minimum area is defined for text regions in relation to the overall image dimensions, so that very small regions that are noise can be filtered out. +* Deskewing is applied on the text region level (due to regions having different degrees of skew) in order to improve the textline segmentation result. +* After deskewing, a calculation of the pixel distribution on the X-axis allows the separation of textlines (foreground) and background pixels. +* Finally, using the derived coordinates, bounding boxes are determined for each textline. diff --git a/docs/train.md b/docs/train.md new file mode 100644 index 0000000..9f44a63 --- /dev/null +++ b/docs/train.md @@ -0,0 +1,632 @@ +# Training documentation +This aims to assist users in preparing training datasets, training models, and performing inference with trained models. +We cover various use cases including pixel-wise segmentation, image classification, image enhancement, and machine-based +reading order detection. For each use case, we provide guidance on how to generate the corresponding training dataset. + +The following three tasks can all be accomplished using the code in the +[`train`](https://github.com/qurator-spk/sbb_pixelwise_segmentation/tree/unifying-training-models) directory: + +* generate training dataset +* train a model +* inference with the trained model + +## Generate training dataset +The script `generate_gt_for_training.py` is used for generating training datasets. As the results of the following +command demonstrates, the dataset generator provides three different commands: + +`python generate_gt_for_training.py --help` + +These three commands are: + +* image-enhancement +* machine-based-reading-order +* pagexml2label + +### image-enhancement +Generating a training dataset for image enhancement is quite straightforward. All that is needed is a set of +high-resolution images. The training dataset can then be generated using the following command: + +`python generate_gt_for_training.py image-enhancement -dis "dir of high resolution images" -dois "dir where degraded +images will be written" -dols "dir where the corresponding high resolution image will be written as label" -scs +"degrading scales json file"` + +The scales JSON file is a dictionary with a key named 'scales' and values representing scales smaller than 1. Images are +downscaled based on these scales and then upscaled again to their original size. This process causes the images to lose +resolution at different scales. The degraded images are used as input images, and the original high-resolution images +serve as labels. The enhancement model can be trained with this generated dataset. The scales JSON file looks like this: + +```yaml +{ + "scales": [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9] +} +``` + +### machine-based-reading-order +For machine-based reading order, we aim to determine the reading priority between two sets of text regions. The model's +input is a three-channel image: the first and last channels contain information about each of the two text regions, +while the middle channel encodes prominent layout elements necessary for reading order, such as separators and headers. +To generate the training dataset, our script requires a page XML file that specifies the image layout with the correct +reading order. + +For output images, it is necessary to specify the width and height. Additionally, a minimum text region size can be set +to filter out regions smaller than this minimum size. This minimum size is defined as the ratio of the text region area +to the image area, with a default value of zero. To run the dataset generator, use the following command: + +`python generate_gt_for_training.py machine-based-reading-order -dx "dir of GT xml files" -domi "dir where output images +will be written" -docl "dir where the labels will be written" -ih "height" -iw "width" -min "min area ratio"` + +### pagexml2label +pagexml2label is designed to generate labels from GT page XML files for various pixel-wise segmentation use cases, +including 'layout,' 'textline,' 'printspace,' 'glyph,' and 'word' segmentation. +To train a pixel-wise segmentation model, we require images along with their corresponding labels. Our training script +expects a PNG image where each pixel corresponds to a label, represented by an integer. The background is always labeled +as zero, while other elements are assigned different integers. For instance, if we have ground truth data with four +elements including the background, the classes would be labeled as 0, 1, 2, and 3 respectively. + +In binary segmentation scenarios such as textline or page extraction, the background is encoded as 0, and the desired +element is automatically encoded as 1 in the PNG label. + +To specify the desired use case and the elements to be extracted in the PNG labels, a custom JSON file can be passed. +For example, in the case of 'textline' detection, the JSON file would resemble this: + +```yaml +{ +"use_case": "textline" +} +``` + +In the case of layout segmentation a custom config json file can look like this: + +```yaml +{ +"use_case": "layout", +"textregions":{"rest_as_paragraph":1 , "drop-capital": 1, "header":2, "heading":2, "marginalia":3}, +"imageregion":4, +"separatorregion":5, +"graphicregions" :{"rest_as_decoration":6 ,"stamp":7} +} +``` + +A possible custom config json file for layout segmentation where the "printspace" is a class: + +```yaml +{ +"use_case": "layout", +"textregions":{"rest_as_paragraph":1 , "drop-capital": 1, "header":2, "heading":2, "marginalia":3}, +"imageregion":4, +"separatorregion":5, +"graphicregions" :{"rest_as_decoration":6 ,"stamp":7} +"printspace_as_class_in_layout" : 8 +} +``` + +For the layout use case, it is beneficial to first understand the structure of the page XML file and its elements. +In a given image, the annotations of elements are recorded in a page XML file, including their contours and classes. +For an image document, the known regions are 'textregion', 'separatorregion', 'imageregion', 'graphicregion', +'noiseregion', and 'tableregion'. + +Text regions and graphic regions also have their own specific types. The known types for text regions are 'paragraph', +'header', 'heading', 'marginalia', 'drop-capital', 'footnote', 'footnote-continued', 'signature-mark', 'page-number', +and 'catch-word'. The known types for graphic regions are 'handwritten-annotation', 'decoration', 'stamp', and +'signature'. +Since we don't know all types of text and graphic regions, unknown cases can arise. To handle these, we have defined +two additional types, "rest_as_paragraph" and "rest_as_decoration", to ensure that no unknown types are missed. +This way, users can extract all known types from the labels and be confident that no unknown types are overlooked. + +In the custom JSON file shown above, "header" and "heading" are extracted as the same class, while "marginalia" is shown +as a different class. All other text region types, including "drop-capital," are grouped into the same class. For the +graphic region, "stamp" has its own class, while all other types are classified together. "Image region" and "separator +region" are also present in the label. However, other regions like "noise region" and "table region" will not be +included in the label PNG file, even if they have information in the page XML files, as we chose not to include them. + +`python generate_gt_for_training.py pagexml2label -dx "dir of GT xml files" -do "dir where output label png files will +be written" -cfg "custom config json file" -to "output type which has 2d and 3d. 2d is used for training and 3d is just +to visualise the labels" "` + +We have also defined an artificial class that can be added to the boundary of text region types or text lines. This key +is called "artificial_class_on_boundary." If users want to apply this to certain text regions in the layout use case, +the example JSON config file should look like this: + +```yaml +{ + "use_case": "layout", + "textregions": { + "paragraph": 1, + "drop-capital": 1, + "header": 2, + "heading": 2, + "marginalia": 3 + }, + "imageregion": 4, + "separatorregion": 5, + "graphicregions": { + "rest_as_decoration": 6 + }, + "artificial_class_on_boundary": ["paragraph", "header", "heading", "marginalia"], + "artificial_class_label": 7 +} +``` + +This implies that the artificial class label, denoted by 7, will be present on PNG files and will only be added to the +elements labeled as "paragraph," "header," "heading," and "marginalia." + +For "textline", "word", and "glyph", the artificial class on the boundaries will be activated only if the +"artificial_class_label" key is specified in the config file. Its value should be set as 2 since these elements +represent binary cases. For example, if the background and textline are denoted as 0 and 1 respectively, then the +artificial class should be assigned the value 2. The example JSON config file should look like this for "textline" use +case: + +```yaml +{ + "use_case": "textline", + "artificial_class_label": 2 +} +``` + +If the coordinates of "PrintSpace" or "Border" are present in the page XML ground truth files, and the user wishes to +crop only the print space area, this can be achieved by activating the "-ps" argument. However, it should be noted that +in this scenario, since cropping will be applied to the label files, the directory of the original images must be +provided to ensure that they are cropped in sync with the labels. This ensures that the correct images and labels +required for training are obtained. The command should resemble the following: + +`python generate_gt_for_training.py pagexml2label -dx "dir of GT xml files" -do "dir where output label png files will +be written" -cfg "custom config json file" -to "output type which has 2d and 3d. 2d is used for training and 3d is just +to visualise the labels" -ps -di "dir where the org images are located" -doi "dir where the cropped output images will +be written" ` + +## Train a model +### classification + +For the classification use case, we haven't provided a ground truth generator, as it's unnecessary. For classification, +all we require is a training directory with subdirectories, each containing images of its respective classes. We need +separate directories for training and evaluation, and the class names (subdirectories) must be consistent across both +directories. Additionally, the class names should be specified in the config JSON file, as shown in the following +example. If, for instance, we aim to classify "apple" and "orange," with a total of 2 classes, the +"classification_classes_name" key in the config file should appear as follows: + +```yaml +{ + "backbone_type" : "nontransformer", + "task": "classification", + "n_classes" : 2, + "n_epochs" : 10, + "input_height" : 448, + "input_width" : 448, + "weight_decay" : 1e-6, + "n_batch" : 4, + "learning_rate": 1e-4, + "f1_threshold_classification": 0.8, + "pretraining" : true, + "classification_classes_name" : {"0":"apple", "1":"orange"}, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +The "dir_train" should be like this: + +``` +. +└── train # train directory + ├── apple # directory of images for apple class + └── orange # directory of images for orange class +``` + +And the "dir_eval" the same structure as train directory: + +``` +. +└── eval # evaluation directory + ├── apple # directory of images for apple class + └── orange # directory of images for orange class + +``` + +The classification model can be trained using the following command line: + +`python train.py with config_classification.json` + +As evident in the example JSON file above, for classification, we utilize a "f1_threshold_classification" parameter. +This parameter is employed to gather all models with an evaluation f1 score surpassing this threshold. Subsequently, +an ensemble of these model weights is executed, and a model is saved in the output directory as "model_ens_avg". +Additionally, the weight of the best model based on the evaluation f1 score is saved as "model_best". + +### reading order +An example config json file for machine based reading order should be like this: + +```yaml +{ + "backbone_type" : "nontransformer", + "task": "reading_order", + "n_classes" : 1, + "n_epochs" : 5, + "input_height" : 672, + "input_width" : 448, + "weight_decay" : 1e-6, + "n_batch" : 4, + "learning_rate": 1e-4, + "pretraining" : true, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +The "dir_train" should be like this: + +``` +. +└── train # train directory + ├── images # directory of images + └── labels # directory of labels +``` + +And the "dir_eval" the same structure as train directory: + +``` +. +└── eval # evaluation directory + ├── images # directory of images + └── labels # directory of labels +``` + +The classification model can be trained like the classification case command line. + +### Segmentation (Textline, Binarization, Page extraction and layout) and enhancement + +#### Parameter configuration for segmentation or enhancement usecases +The following parameter configuration can be applied to all segmentation use cases and enhancements. The augmentation, +its sub-parameters, and continued training are defined only for segmentation use cases and enhancements, not for +classification and machine-based reading order, as you can see in their example config files. + +* backbone_type: For segmentation tasks (such as text line, binarization, and layout detection) and enhancement, we +* offer two backbone options: a "nontransformer" and a "transformer" backbone. For the "transformer" backbone, we first +* apply a CNN followed by a transformer. In contrast, the "nontransformer" backbone utilizes only a CNN ResNet-50. +* task : The task parameter can have values such as "segmentation", "enhancement", "classification", and "reading_order". +* patches: If you want to break input images into smaller patches (input size of the model) you need to set this +* parameter to ``true``. In the case that the model should see the image once, like page extraction, patches should be +* set to ``false``. +* n_batch: Number of batches at each iteration. +* n_classes: Number of classes. In the case of binary classification this should be 2. In the case of reading_order it +* should set to 1. And for the case of layout detection just the unique number of classes should be given. +* n_epochs: Number of epochs. +* input_height: This indicates the height of model's input. +* input_width: This indicates the width of model's input. +* weight_decay: Weight decay of l2 regularization of model layers. +* pretraining: Set to ``true`` to load pretrained weights of ResNet50 encoder. The downloaded weights should be saved +* in a folder named "pretrained_model" in the same directory of "train.py" script. +* augmentation: If you want to apply any kind of augmentation this parameter should first set to ``true``. +* flip_aug: If ``true``, different types of filp will be applied on image. Type of flips is given with "flip_index" parameter. +* blur_aug: If ``true``, different types of blurring will be applied on image. Type of blurrings is given with "blur_k" parameter. +* scaling: If ``true``, scaling will be applied on image. Scale of scaling is given with "scales" parameter. +* degrading: If ``true``, degrading will be applied to the image. The amount of degrading is defined with "degrade_scales" parameter. +* brightening: If ``true``, brightening will be applied to the image. The amount of brightening is defined with "brightness" parameter. +* rotation_not_90: If ``true``, rotation (not 90 degree) will be applied on image. Rotation angles are given with "thetha" parameter. +* rotation: If ``true``, 90 degree rotation will be applied on image. +* binarization: If ``true``,Otsu thresholding will be applied to augment the input data with binarized images. +* scaling_bluring: If ``true``, combination of scaling and blurring will be applied on image. +* scaling_binarization: If ``true``, combination of scaling and binarization will be applied on image. +* scaling_flip: If ``true``, combination of scaling and flip will be applied on image. +* flip_index: Type of flips. +* blur_k: Type of blurrings. +* scales: Scales of scaling. +* brightness: The amount of brightenings. +* thetha: Rotation angles. +* degrade_scales: The amount of degradings. +* continue_training: If ``true``, it means that you have already trained a model and you would like to continue the training. So it is needed to provide the dir of trained model with "dir_of_start_model" and index for naming the models. For example if you have already trained for 3 epochs then your last index is 2 and if you want to continue from model_1.h5, you can set ``index_start`` to 3 to start naming model with index 3. +* weighted_loss: If ``true``, this means that you want to apply weighted categorical_crossentropy as loss fucntion. Be carefull if you set to ``true``the parameter "is_loss_soft_dice" should be ``false`` +* data_is_provided: If you have already provided the input data you can set this to ``true``. Be sure that the train and eval data are in "dir_output". Since when once we provide training data we resize and augment them and then we write them in sub-directories train and eval in "dir_output". +* dir_train: This is the directory of "images" and "labels" (dir_train should include two subdirectories with names of images and labels ) for raw images and labels. Namely they are not prepared (not resized and not augmented) yet for training the model. When we run this tool these raw data will be transformed to suitable size needed for the model and they will be written in "dir_output" in train and eval directories. Each of train and eval include "images" and "labels" sub-directories. +* index_start: Starting index for saved models in the case that "continue_training" is ``true``. +* dir_of_start_model: Directory containing pretrained model to continue training the model in the case that "continue_training" is ``true``. +* transformer_num_patches_xy: Number of patches for vision transformer in x and y direction respectively. +* transformer_patchsize_x: Patch size of vision transformer patches in x direction. +* transformer_patchsize_y: Patch size of vision transformer patches in y direction. +* transformer_projection_dim: Transformer projection dimension. Default value is 64. +* transformer_mlp_head_units: Transformer Multilayer Perceptron (MLP) head units. Default value is [128, 64]. +* transformer_layers: transformer layers. Default value is 8. +* transformer_num_heads: Transformer number of heads. Default value is 4. +* transformer_cnn_first: We have two types of vision transformers. In one type, a CNN is applied first, followed by a transformer. In the other type, this order is reversed. If transformer_cnn_first is true, it means the CNN will be applied before the transformer. Default value is true. + +In the case of segmentation and enhancement the train and evaluation directory should be as following. + +The "dir_train" should be like this: + +``` +. +└── train # train directory + ├── images # directory of images + └── labels # directory of labels +``` + +And the "dir_eval" the same structure as train directory: + +``` +. +└── eval # evaluation directory + ├── images # directory of images + └── labels # directory of labels +``` + +After configuring the JSON file for segmentation or enhancement, training can be initiated by running the following +command, similar to the process for classification and reading order: + +`python train.py with config_classification.json` + +#### Binarization +An example config json file for binarization can be like this: + +```yaml +{ + "backbone_type" : "transformer", + "task": "binarization", + "n_classes" : 2, + "n_epochs" : 4, + "input_height" : 224, + "input_width" : 672, + "weight_decay" : 1e-6, + "n_batch" : 1, + "learning_rate": 1e-4, + "patches" : true, + "pretraining" : true, + "augmentation" : true, + "flip_aug" : false, + "blur_aug" : false, + "scaling" : true, + "degrading": false, + "brightening": false, + "binarization" : false, + "scaling_bluring" : false, + "scaling_binarization" : false, + "scaling_flip" : false, + "rotation": false, + "rotation_not_90": false, + "transformer_num_patches_xy": [7, 7], + "transformer_patchsize_x": 3, + "transformer_patchsize_y": 1, + "transformer_projection_dim": 192, + "transformer_mlp_head_units": [128, 64], + "transformer_layers": 8, + "transformer_num_heads": 4, + "transformer_cnn_first": true, + "blur_k" : ["blur","guass","median"], + "scales" : [0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.4], + "brightness" : [1.3, 1.5, 1.7, 2], + "degrade_scales" : [0.2, 0.4], + "flip_index" : [0, 1, -1], + "thetha" : [10, -10], + "continue_training": false, + "index_start" : 0, + "dir_of_start_model" : " ", + "weighted_loss": false, + "is_loss_soft_dice": false, + "data_is_provided": false, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +#### Textline + +```yaml +{ + "backbone_type" : "nontransformer", + "task": "segmentation", + "n_classes" : 2, + "n_epochs" : 4, + "input_height" : 448, + "input_width" : 224, + "weight_decay" : 1e-6, + "n_batch" : 1, + "learning_rate": 1e-4, + "patches" : true, + "pretraining" : true, + "augmentation" : true, + "flip_aug" : false, + "blur_aug" : false, + "scaling" : true, + "degrading": false, + "brightening": false, + "binarization" : false, + "scaling_bluring" : false, + "scaling_binarization" : false, + "scaling_flip" : false, + "rotation": false, + "rotation_not_90": false, + "blur_k" : ["blur","guass","median"], + "scales" : [0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.4], + "brightness" : [1.3, 1.5, 1.7, 2], + "degrade_scales" : [0.2, 0.4], + "flip_index" : [0, 1, -1], + "thetha" : [10, -10], + "continue_training": false, + "index_start" : 0, + "dir_of_start_model" : " ", + "weighted_loss": false, + "is_loss_soft_dice": false, + "data_is_provided": false, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +#### Enhancement + +```yaml +{ + "backbone_type" : "nontransformer", + "task": "enhancement", + "n_classes" : 3, + "n_epochs" : 4, + "input_height" : 448, + "input_width" : 224, + "weight_decay" : 1e-6, + "n_batch" : 4, + "learning_rate": 1e-4, + "patches" : true, + "pretraining" : true, + "augmentation" : true, + "flip_aug" : false, + "blur_aug" : false, + "scaling" : true, + "degrading": false, + "brightening": false, + "binarization" : false, + "scaling_bluring" : false, + "scaling_binarization" : false, + "scaling_flip" : false, + "rotation": false, + "rotation_not_90": false, + "blur_k" : ["blur","guass","median"], + "scales" : [0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.4], + "brightness" : [1.3, 1.5, 1.7, 2], + "degrade_scales" : [0.2, 0.4], + "flip_index" : [0, 1, -1], + "thetha" : [10, -10], + "continue_training": false, + "index_start" : 0, + "dir_of_start_model" : " ", + "weighted_loss": false, + "is_loss_soft_dice": false, + "data_is_provided": false, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +It's important to mention that the value of n_classes for enhancement should be 3, as the model's output is a 3-channel +image. + +#### Page extraction + +```yaml +{ + "backbone_type" : "nontransformer", + "task": "segmentation", + "n_classes" : 2, + "n_epochs" : 4, + "input_height" : 448, + "input_width" : 224, + "weight_decay" : 1e-6, + "n_batch" : 1, + "learning_rate": 1e-4, + "patches" : false, + "pretraining" : true, + "augmentation" : false, + "flip_aug" : false, + "blur_aug" : false, + "scaling" : true, + "degrading": false, + "brightening": false, + "binarization" : false, + "scaling_bluring" : false, + "scaling_binarization" : false, + "scaling_flip" : false, + "rotation": false, + "rotation_not_90": false, + "blur_k" : ["blur","guass","median"], + "scales" : [0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.4], + "brightness" : [1.3, 1.5, 1.7, 2], + "degrade_scales" : [0.2, 0.4], + "flip_index" : [0, 1, -1], + "thetha" : [10, -10], + "continue_training": false, + "index_start" : 0, + "dir_of_start_model" : " ", + "weighted_loss": false, + "is_loss_soft_dice": false, + "data_is_provided": false, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` + +For page segmentation (or printspace or border segmentation), the model needs to view the input image in its entirety, +hence the patches parameter should be set to false. + +#### layout segmentation +An example config json file for layout segmentation with 5 classes (including background) can be like this: + +```yaml +{ + "backbone_type" : "transformer", + "task": "segmentation", + "n_classes" : 5, + "n_epochs" : 4, + "input_height" : 448, + "input_width" : 224, + "weight_decay" : 1e-6, + "n_batch" : 1, + "learning_rate": 1e-4, + "patches" : true, + "pretraining" : true, + "augmentation" : true, + "flip_aug" : false, + "blur_aug" : false, + "scaling" : true, + "degrading": false, + "brightening": false, + "binarization" : false, + "scaling_bluring" : false, + "scaling_binarization" : false, + "scaling_flip" : false, + "rotation": false, + "rotation_not_90": false, + "transformer_num_patches_xy": [7, 14], + "transformer_patchsize_x": 1, + "transformer_patchsize_y": 1, + "transformer_projection_dim": 64, + "transformer_mlp_head_units": [128, 64], + "transformer_layers": 8, + "transformer_num_heads": 4, + "transformer_cnn_first": true, + "blur_k" : ["blur","guass","median"], + "scales" : [0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.4], + "brightness" : [1.3, 1.5, 1.7, 2], + "degrade_scales" : [0.2, 0.4], + "flip_index" : [0, 1, -1], + "thetha" : [10, -10], + "continue_training": false, + "index_start" : 0, + "dir_of_start_model" : " ", + "weighted_loss": false, + "is_loss_soft_dice": false, + "data_is_provided": false, + "dir_train": "./train", + "dir_eval": "./eval", + "dir_output": "./output" +} +``` +## Inference with the trained model + +### classification +For conducting inference with a trained model, you simply need to execute the following command line, specifying the +directory of the model and the image on which to perform inference: + +`python inference.py -m "model dir" -i "image" ` + +This will straightforwardly return the class of the image. + +### machine based reading order +To infer the reading order using a reading order model, we need a page XML file containing layout information but +without the reading order. We simply need to provide the model directory, the XML file, and the output directory. +The new XML file with the added reading order will be written to the output directory with the same name. +We need to run: + +`python inference.py -m "model dir" -xml "page xml file" -o "output dir to write new xml with reading order" ` + +### Segmentation (Textline, Binarization, Page extraction and layout) and enhancement +For conducting inference with a trained model for segmentation and enhancement you need to run the following command +line: + +`python inference.py -m "model dir" -i "image" -p -s "output image" ` + +Note that in the case of page extraction the -p flag is not needed. + +For segmentation or binarization tasks, if a ground truth (GT) label is available, the IoU evaluation metric can be +calculated for the output. To do this, you need to provide the GT label using the argument -gt. From 3a55b6ce91efda9c170152e8e364e5151c83f14c Mon Sep 17 00:00:00 2001 From: cneud <952378+cneud@users.noreply.github.com> Date: Thu, 27 Mar 2025 23:11:18 +0100 Subject: [PATCH 08/19] consolidate usage documentation --- docs/models.md | 2 ++ docs/usage.md | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 docs/usage.md diff --git a/docs/models.md b/docs/models.md index c6f7340..ac563b0 100644 --- a/docs/models.md +++ b/docs/models.md @@ -16,8 +16,10 @@ Two Arabic/Persian terms form the name of the model suite: عين الله, whic "eynollah"; it translates into English as "God's Eye" -- it sees (nearly) everything on the document image. See the flowchart below for the different stages and how they interact: + ![](https://user-images.githubusercontent.com/952378/100619946-1936f680-331e-11eb-9297-6e8b4cab3c16.png) + ## Models ### Image enhancement diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..22443a2 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,97 @@ +# Usage documentation +The command-line interface can be called like this: + +```sh +eynollah \ + -i | -di \ + -o \ + -m \ + [OPTIONS] +``` + +The following options can be used to further configure the processing: + +| option | description | +|-------------------|:-------------------------------------------------------------------------------| +| `-fl` | full layout analysis including all steps and segmentation classes | +| `-light` | lighter and faster but simpler method for main region detection and deskewing | +| `-tab` | apply table detection | +| `-ae` | apply enhancement (the resulting image is saved to the output directory) | +| `-as` | apply scaling | +| `-cl` | apply contour detection for curved text lines instead of bounding boxes | +| `-ib` | apply binarization (the resulting image is saved to the output directory) | +| `-ep` | enable plotting (MUST always be used with `-sl`, `-sd`, `-sa`, `-si` or `-ae`) | +| `-eoi` | extract only images to output directory (other processing will not be done) | +| `-ho` | ignore headers for reading order dectection | +| `-si ` | save image regions detected to this directory | +| `-sd ` | save deskewed image to this directory | +| `-sl ` | save layout prediction as plot to this directory | +| `-sp ` | save cropped page image to this directory | +| `-sa ` | save all (plot, enhanced/binary image, layout) to this directory | + +If no option is set, the tool performs layout detection of main regions (background, text, images, separators and marginals). + +The best output quality is produced when RGB images are used as input rather than greyscale or binarized images. + +### `--full-layout` vs `--no-full-layout` + +Here are the difference in elements detected depending on the `--full-layout`/`--no-full-layout` command line flags: + +| | `--full-layout` | `--no-full-layout` | +|--------------------------|-----------------|--------------------| +| reading order | x | x | +| header regions | x | - | +| text regions | x | x | +| text regions / text line | x | x | +| drop-capitals | x | - | +| marginals | x | x | +| marginals / text line | x | x | +| image region | x | x | + +## Use as OCR-D processor +Eynollah ships with a CLI interface to be used as [OCR-D](https://ocr-d.de) processor that is described in [`ocrd-tool.json`](https://github.com/qurator-spk/eynollah/tree/main/src/eynollah/ocrd-tool.json). + +The source image file group with (preferably) RGB images should be used as input for Eynollah like this: + +``` +ocrd-eynollah-segment -I OCR-D-IMG -O SEG-LINE -P models +``` + +Any image referenced by `@imageFilename` in PAGE-XML is passed on directly to Eynollah as a processor, so that e.g. + +``` +ocrd-eynollah-segment -I OCR-D-IMG-BIN -O SEG-LINE -P models +``` + +uses the original (RGB) image despite any binarization that may have occured in previous OCR-D processing steps. + +## Use with Docker +TODO + +## Hints +* If none of the parameters is set to `true`, the tool will perform a layout detection of main regions (background, +text, images, separators and marginals). An advantage of this tool is that it tries to extract main text regions +separately as much as possible. + +* If you set `-ae` (**a**llow image **e**nhancement) parameter to `true`, the tool will first check the ppi +(pixel-per-inch) of the image and when it is less than 300, the tool will resize it and only then image enhancement will +occur. Image enhancement can also take place without this option, but by setting this option to `true`, the layout xml +data (e.g. coordinates) will be based on the resized and enhanced image instead of the original image. + +* For some documents, while the quality is good, their scale is very large, and the performance of tool decreases. In +such cases you can set `-as` (**a**llow **s**caling) to `true`. With this option enabled, the tool will try to rescale +the image and only then the layout detection process will begin. + +* If you care about drop capitals (initials) and headings, you can set `-fl` (**f**ull **l**ayout) to `true`. With this +setting, the tool can currently distinguish 7 document layout classes/elements. + +* In cases where the document includes curved headers or curved lines, rectangular bounding boxes for textlines will not +be a great option. In such cases it is strongly recommended setting the flag `-cl` (**c**urved **l**ines) to `true` to +find contours of curved lines instead of rectangular bounding boxes. Be advised that enabling this option increases the +processing time of the tool. + +* To crop and save image regions inside the document, set the parameter `-si` (**s**ave **i**mages) to true and provide +a directory path to store the extracted images. + +* To extract only images from a document, set the parameter `-eoi` (**e**xtract **o**nly **i**mages). Choosing this +option disables any other processing. To save the cropped images add `-ep` and `-si`. From 0e9a72ea522609e3d45cc9114e1c5b96219d3434 Mon Sep 17 00:00:00 2001 From: cneud <952378+cneud@users.noreply.github.com> Date: Thu, 27 Mar 2025 23:14:59 +0100 Subject: [PATCH 09/19] consolidate usage documentation --- docs/usage.md | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index 22443a2..da164de 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -9,6 +9,7 @@ eynollah \ [OPTIONS] ``` +## Processing options The following options can be used to further configure the processing: | option | description | @@ -29,9 +30,7 @@ The following options can be used to further configure the processing: | `-sp ` | save cropped page image to this directory | | `-sa ` | save all (plot, enhanced/binary image, layout) to this directory | -If no option is set, the tool performs layout detection of main regions (background, text, images, separators and marginals). - -The best output quality is produced when RGB images are used as input rather than greyscale or binarized images. +If no option is set, the tool performs detection of main regions (background, text, images, separators and marginals). ### `--full-layout` vs `--no-full-layout` @@ -49,7 +48,8 @@ Here are the difference in elements detected depending on the `--full-layout`/`- | image region | x | x | ## Use as OCR-D processor -Eynollah ships with a CLI interface to be used as [OCR-D](https://ocr-d.de) processor that is described in [`ocrd-tool.json`](https://github.com/qurator-spk/eynollah/tree/main/src/eynollah/ocrd-tool.json). +Eynollah ships with a CLI interface to be used as [OCR-D](https://ocr-d.de) processor that is described in +[`ocrd-tool.json`](https://github.com/qurator-spk/eynollah/tree/main/src/eynollah/ocrd-tool.json). The source image file group with (preferably) RGB images should be used as input for Eynollah like this: @@ -69,29 +69,24 @@ uses the original (RGB) image despite any binarization that may have occured in TODO ## Hints +* The best output quality is produced when RGB images are used as input rather than greyscale or binarized images. * If none of the parameters is set to `true`, the tool will perform a layout detection of main regions (background, text, images, separators and marginals). An advantage of this tool is that it tries to extract main text regions separately as much as possible. - * If you set `-ae` (**a**llow image **e**nhancement) parameter to `true`, the tool will first check the ppi (pixel-per-inch) of the image and when it is less than 300, the tool will resize it and only then image enhancement will occur. Image enhancement can also take place without this option, but by setting this option to `true`, the layout xml data (e.g. coordinates) will be based on the resized and enhanced image instead of the original image. - * For some documents, while the quality is good, their scale is very large, and the performance of tool decreases. In such cases you can set `-as` (**a**llow **s**caling) to `true`. With this option enabled, the tool will try to rescale the image and only then the layout detection process will begin. - * If you care about drop capitals (initials) and headings, you can set `-fl` (**f**ull **l**ayout) to `true`. With this setting, the tool can currently distinguish 7 document layout classes/elements. - * In cases where the document includes curved headers or curved lines, rectangular bounding boxes for textlines will not be a great option. In such cases it is strongly recommended setting the flag `-cl` (**c**urved **l**ines) to `true` to find contours of curved lines instead of rectangular bounding boxes. Be advised that enabling this option increases the processing time of the tool. - * To crop and save image regions inside the document, set the parameter `-si` (**s**ave **i**mages) to true and provide a directory path to store the extracted images. - * To extract only images from a document, set the parameter `-eoi` (**e**xtract **o**nly **i**mages). Choosing this option disables any other processing. To save the cropped images add `-ep` and `-si`. From c9de578d4de50e77aff20f2aba79e6cce800381e Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Fri, 28 Mar 2025 11:25:03 +0100 Subject: [PATCH 10/19] removing imutils from requirements --- requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index ef3fe31..9b821c3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,5 @@ ocrd >= 2.23.3 numpy <1.24.0 scikit-learn >= 0.23.2 tensorflow < 2.13 -imutils >= 0.5.3 numba <= 0.58.1 loky From f756b08c9ba0ae07f3ba756f46447b6e417bf354 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Fri, 28 Mar 2025 14:57:40 +0100 Subject: [PATCH 11/19] Revert "replace usages of `imutils` with opencv equivalents" --- src/eynollah/utils/__init__.py | 1 + src/eynollah/utils/rotate.py | 74 +++++++++------------------------- 2 files changed, 21 insertions(+), 54 deletions(-) diff --git a/src/eynollah/utils/__init__.py b/src/eynollah/utils/__init__.py index faa32b0..a67fc38 100644 --- a/src/eynollah/utils/__init__.py +++ b/src/eynollah/utils/__init__.py @@ -4,6 +4,7 @@ import matplotlib.pyplot as plt import numpy as np from shapely import geometry import cv2 +import imutils from scipy.signal import find_peaks from scipy.ndimage import gaussian_filter1d import time diff --git a/src/eynollah/utils/rotate.py b/src/eynollah/utils/rotate.py index 734f924..603c2d9 100644 --- a/src/eynollah/utils/rotate.py +++ b/src/eynollah/utils/rotate.py @@ -1,5 +1,6 @@ import math -import numpy as np + +import imutils import cv2 def rotatedRectWithMaxArea(w, h, angle): @@ -10,11 +11,11 @@ def rotatedRectWithMaxArea(w, h, angle): side_long, side_short = (w, h) if width_is_longer else (h, w) # since the solutions for angle, -angle and 180-angle are all the same, - # it suffices to look at the first quadrant and the absolute values of sin,cos: + # if suffices to look at the first quadrant and the absolute values of sin,cos: sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle)) if side_short <= 2.0 * sin_a * cos_a * side_long or abs(sin_a - cos_a) < 1e-10: - # half constrained case: two crop corners touch the longer side, - # the other two corners are on the mid-line parallel to the longer line + # half constrained case: two crop corners touch the longer side, + # the other two corners are on the mid-line parallel to the longer line x = 0.5 * side_short wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a) else: @@ -24,45 +25,6 @@ def rotatedRectWithMaxArea(w, h, angle): return wr, hr - -def rotate_image_opencv(image, angle): - # Calculate the original image dimensions (h, w) and the center point (cx, cy) - h, w = image.shape[:2] - cx, cy = (w // 2, h // 2) - - # Compute the rotation matrix - M = cv2.getRotationMatrix2D((cx, cy), angle, 1.0) - - # Calculate the new bounding box - corners = np.array([ - [0, 0], - [w, 0], - [w, h], - [0, h] - ]) - - # Apply rotation matrix to the corner points - ones = np.ones(shape=(len(corners), 1)) - corners_ones = np.hstack([corners, ones]) - transformed_corners = M @ corners_ones.T - transformed_corners = transformed_corners.T - - # Calculate the new bounding box dimensions - min_x, min_y = np.min(transformed_corners, axis=0) - max_x, max_y = np.max(transformed_corners, axis=0) - - newW = int(np.ceil(max_x - min_x)) - newH = int(np.ceil(max_y - min_y)) - - # Adjust the rotation matrix to account for translation - M[0, 2] += (newW / 2) - cx - M[1, 2] += (newH / 2) - cy - - # Perform the affine transformation (rotation) - rotated_image = cv2.warpAffine(image, M, (newW, newH)) - - return rotated_image - def rotate_max_area_new(image, rotated, angle): wr, hr = rotatedRectWithMaxArea(image.shape[1], image.shape[0], math.radians(angle)) h, w, _ = rotated.shape @@ -73,7 +35,7 @@ def rotate_max_area_new(image, rotated, angle): return rotated[y1:y2, x1:x2] def rotation_image_new(img, thetha): - rotated = rotate_image_opencv(img, thetha) + rotated = imutils.rotate(img, thetha) return rotate_max_area_new(img, rotated, thetha) def rotate_image(img_patch, slope): @@ -82,10 +44,13 @@ def rotate_image(img_patch, slope): M = cv2.getRotationMatrix2D(center, slope, 1.0) return cv2.warpAffine(img_patch, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) -def rotate_image_different(img, slope): +def rotate_image_different( img, slope): + # img = cv2.imread('images/input.jpg') num_rows, num_cols = img.shape[:2] + rotation_matrix = cv2.getRotationMatrix2D((num_cols / 2, num_rows / 2), slope, 1) - return cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows)) + img_rotation = cv2.warpAffine(img, rotation_matrix, (num_cols, num_rows)) + return img_rotation def rotate_max_area(image, rotated, rotated_textline, rotated_layout, rotated_table_prediction, angle): wr, hr = rotatedRectWithMaxArea(image.shape[1], image.shape[0], math.radians(angle)) @@ -97,17 +62,17 @@ def rotate_max_area(image, rotated, rotated_textline, rotated_layout, rotated_ta return rotated[y1:y2, x1:x2], rotated_textline[y1:y2, x1:x2], rotated_layout[y1:y2, x1:x2], rotated_table_prediction[y1:y2, x1:x2] def rotation_not_90_func(img, textline, text_regions_p_1, table_prediction, thetha): - rotated = rotate_image_opencv(img, thetha) - rotated_textline = rotate_image_opencv(textline, thetha) - rotated_layout = rotate_image_opencv(text_regions_p_1, thetha) - rotated_table_prediction = rotate_image_opencv(table_prediction, thetha) + rotated = imutils.rotate(img, thetha) + rotated_textline = imutils.rotate(textline, thetha) + rotated_layout = imutils.rotate(text_regions_p_1, thetha) + rotated_table_prediction = imutils.rotate(table_prediction, thetha) return rotate_max_area(img, rotated, rotated_textline, rotated_layout, rotated_table_prediction, thetha) def rotation_not_90_func_full_layout(img, textline, text_regions_p_1, text_regions_p_fully, thetha): - rotated = rotate_image_opencv(img, thetha) - rotated_textline = rotate_image_opencv(textline, thetha) - rotated_layout = rotate_image_opencv(text_regions_p_1, thetha) - rotated_layout_full = rotate_image_opencv(text_regions_p_fully, thetha) + rotated = imutils.rotate(img, thetha) + rotated_textline = imutils.rotate(textline, thetha) + rotated_layout = imutils.rotate(text_regions_p_1, thetha) + rotated_layout_full = imutils.rotate(text_regions_p_fully, thetha) return rotate_max_area_full_layout(img, rotated, rotated_textline, rotated_layout, rotated_layout_full, thetha) def rotate_max_area_full_layout(image, rotated, rotated_textline, rotated_layout, rotated_layout_full, angle): @@ -118,3 +83,4 @@ def rotate_max_area_full_layout(image, rotated, rotated_textline, rotated_layout x1 = w // 2 - int(wr / 2) x2 = x1 + int(wr) return rotated[y1:y2, x1:x2], rotated_textline[y1:y2, x1:x2], rotated_layout[y1:y2, x1:x2], rotated_layout_full[y1:y2, x1:x2] + From b55389ac62f2b32455ee9d15b849777381ee740b Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Fri, 28 Mar 2025 14:59:31 +0100 Subject: [PATCH 12/19] Update requirements.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 9b821c3..ef3fe31 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,5 +3,6 @@ ocrd >= 2.23.3 numpy <1.24.0 scikit-learn >= 0.23.2 tensorflow < 2.13 +imutils >= 0.5.3 numba <= 0.58.1 loky From cf40f9ecc5afb4fec2bc9b815ad3250fbde42728 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Fri, 28 Mar 2025 20:58:32 +0100 Subject: [PATCH 13/19] The rotate_image function produces the exact same rotation as Imutils. Therefore, there is no need to retain the remove-imutils-1 branch. --- requirements.txt | 1 - src/eynollah/utils/__init__.py | 1 - src/eynollah/utils/rotate.py | 20 +++++++++----------- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/requirements.txt b/requirements.txt index ef3fe31..9b821c3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,5 @@ ocrd >= 2.23.3 numpy <1.24.0 scikit-learn >= 0.23.2 tensorflow < 2.13 -imutils >= 0.5.3 numba <= 0.58.1 loky diff --git a/src/eynollah/utils/__init__.py b/src/eynollah/utils/__init__.py index a67fc38..faa32b0 100644 --- a/src/eynollah/utils/__init__.py +++ b/src/eynollah/utils/__init__.py @@ -4,7 +4,6 @@ import matplotlib.pyplot as plt import numpy as np from shapely import geometry import cv2 -import imutils from scipy.signal import find_peaks from scipy.ndimage import gaussian_filter1d import time diff --git a/src/eynollah/utils/rotate.py b/src/eynollah/utils/rotate.py index 603c2d9..0f2c177 100644 --- a/src/eynollah/utils/rotate.py +++ b/src/eynollah/utils/rotate.py @@ -1,6 +1,4 @@ import math - -import imutils import cv2 def rotatedRectWithMaxArea(w, h, angle): @@ -35,7 +33,7 @@ def rotate_max_area_new(image, rotated, angle): return rotated[y1:y2, x1:x2] def rotation_image_new(img, thetha): - rotated = imutils.rotate(img, thetha) + rotated = rotate_image(img, thetha) return rotate_max_area_new(img, rotated, thetha) def rotate_image(img_patch, slope): @@ -62,17 +60,17 @@ def rotate_max_area(image, rotated, rotated_textline, rotated_layout, rotated_ta return rotated[y1:y2, x1:x2], rotated_textline[y1:y2, x1:x2], rotated_layout[y1:y2, x1:x2], rotated_table_prediction[y1:y2, x1:x2] def rotation_not_90_func(img, textline, text_regions_p_1, table_prediction, thetha): - rotated = imutils.rotate(img, thetha) - rotated_textline = imutils.rotate(textline, thetha) - rotated_layout = imutils.rotate(text_regions_p_1, thetha) - rotated_table_prediction = imutils.rotate(table_prediction, thetha) + rotated = rotate_image(img, thetha) + rotated_textline = rotate_image(textline, thetha) + rotated_layout = rotate_image(text_regions_p_1, thetha) + rotated_table_prediction = rotate_image(table_prediction, thetha) return rotate_max_area(img, rotated, rotated_textline, rotated_layout, rotated_table_prediction, thetha) def rotation_not_90_func_full_layout(img, textline, text_regions_p_1, text_regions_p_fully, thetha): - rotated = imutils.rotate(img, thetha) - rotated_textline = imutils.rotate(textline, thetha) - rotated_layout = imutils.rotate(text_regions_p_1, thetha) - rotated_layout_full = imutils.rotate(text_regions_p_fully, thetha) + rotated = rotate_image(img, thetha) + rotated_textline = rotate_image(textline, thetha) + rotated_layout = rotate_image(text_regions_p_1, thetha) + rotated_layout_full = rotate_image(text_regions_p_fully, thetha) return rotate_max_area_full_layout(img, rotated, rotated_textline, rotated_layout, rotated_layout_full, thetha) def rotate_max_area_full_layout(image, rotated, rotated_textline, rotated_layout, rotated_layout_full, angle): From 9b04688ebcee52fd913af9d70adb8471b9f3bee8 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Sun, 30 Mar 2025 15:34:27 +0200 Subject: [PATCH 14/19] The rotate_image function has been updated. Additionally, the reading order is now correct in the case of the light version, provided that slope_deskew exceeds the slope_threshold. --- src/eynollah/eynollah.py | 27 ++++++++++++++++++--------- src/eynollah/utils/rotate.py | 2 +- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 34fc8cb..9ead53e 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -4030,7 +4030,7 @@ class Eynollah: all_found_textline_polygons[j][ij][:,0,0] = con_scaled[:,0, 0] return all_found_textline_polygons - def filter_contours_inside_a_bigger_one(self,contours, image, marginal_cnts=None, type_contour="textregion"): + def filter_contours_inside_a_bigger_one(self,contours, contours_d_ordered, image, marginal_cnts=None, type_contour="textregion"): if type_contour=="textregion": areas = [cv2.contourArea(contours[j]) for j in range(len(contours))] area_tot = image.shape[0]*image.shape[1] @@ -4067,8 +4067,10 @@ class Eynollah: indexes_to_be_removed = np.sort(indexes_to_be_removed)[::-1] for ind in indexes_to_be_removed: contours.pop(ind) + if len(contours_d_ordered)>0: + contours_d_ordered.pop(ind) - return contours + return contours, contours_d_ordered else: contours_txtline_of_all_textregions = [] @@ -4375,7 +4377,7 @@ class Eynollah: all_found_textline_polygons = self.dilate_textregions_contours_textline_version( all_found_textline_polygons) all_found_textline_polygons = self.filter_contours_inside_a_bigger_one( - all_found_textline_polygons, textline_mask_tot_ea, type_contour="textline") + all_found_textline_polygons, None, textline_mask_tot_ea, type_contour="textline") order_text_new = [0] @@ -4417,9 +4419,9 @@ class Eynollah: textline_mask_tot_ea_deskew = resize_image(textline_mask_tot_ea,img_h_new, img_w_new ) - slope_deskew, slope_first = 0, 0 #self.run_deskew(textline_mask_tot_ea_deskew) + slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea_deskew) else: - slope_deskew, slope_first = 0, 0 #self.run_deskew(textline_mask_tot_ea) + slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea) #print("text region early -2,5 in %.1fs", time.time() - t0) #self.logger.info("Textregion detection took %.1fs ", time.time() - t1t) num_col, num_col_classifier, img_only_regions, page_coord, image_page, mask_images, mask_lines, \ @@ -4550,7 +4552,8 @@ class Eynollah: cx_bigest_big, cy_biggest_big, _, _, _, _, _ = find_new_features_of_contours([contours_biggest]) cx_bigest, cy_biggest, _, _, _, _, _ = find_new_features_of_contours(contours_only_text_parent) - + + if np.abs(slope_deskew) >= SLOPE_THRESHOLD: contours_only_text_d, hir_on_text_d = return_contours_of_image(text_only_d) contours_only_text_parent_d = return_parent_contours(contours_only_text_d, hir_on_text_d) @@ -4647,13 +4650,19 @@ class Eynollah: continue else: return pcgts + + + ## check the ro order + + + #print("text region early 3 in %.1fs", time.time() - t0) if self.light_version: contours_only_text_parent = self.dilate_textregions_contours( contours_only_text_parent) - contours_only_text_parent = self.filter_contours_inside_a_bigger_one( - contours_only_text_parent, text_only, marginal_cnts=polygons_of_marginals) + contours_only_text_parent , contours_only_text_parent_d_ordered = self.filter_contours_inside_a_bigger_one( + contours_only_text_parent, contours_only_text_parent_d_ordered, text_only, marginal_cnts=polygons_of_marginals) #print("text region early 3.5 in %.1fs", time.time() - t0) txt_con_org = get_textregion_contours_in_org_image_light( contours_only_text_parent, self.image, slope_first, map=self.executor.map) @@ -4690,7 +4699,7 @@ class Eynollah: all_found_textline_polygons = self.dilate_textregions_contours_textline_version( all_found_textline_polygons) all_found_textline_polygons = self.filter_contours_inside_a_bigger_one( - all_found_textline_polygons, textline_mask_tot_ea_org, type_contour="textline") + all_found_textline_polygons, None, textline_mask_tot_ea_org, type_contour="textline") all_found_textline_polygons_marginals = self.dilate_textregions_contours_textline_version( all_found_textline_polygons_marginals) contours_only_text_parent, txt_con_org, all_found_textline_polygons, contours_only_text_parent_d_ordered, \ diff --git a/src/eynollah/utils/rotate.py b/src/eynollah/utils/rotate.py index 0f2c177..189693d 100644 --- a/src/eynollah/utils/rotate.py +++ b/src/eynollah/utils/rotate.py @@ -40,7 +40,7 @@ def rotate_image(img_patch, slope): (h, w) = img_patch.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, slope, 1.0) - return cv2.warpAffine(img_patch, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) + return cv2.warpAffine(img_patch, M, (w, h) ) def rotate_image_different( img, slope): # img = cv2.imread('images/input.jpg') From b1da0a332745314d2a36b4e0afa8d636bc8600c5 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Mon, 31 Mar 2025 18:43:14 +0200 Subject: [PATCH 15/19] In OCR, the predicted text is now drawn on the image, and the results are saved in a specified directory. This makes it easier to review the predicted output --- src/eynollah/cli.py | 16 ++++++++++- src/eynollah/eynollah.py | 62 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/eynollah/cli.py b/src/eynollah/cli.py index c306ac5..369dc4c 100644 --- a/src/eynollah/cli.py +++ b/src/eynollah/cli.py @@ -334,6 +334,12 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ help="directory of xmls", type=click.Path(exists=True, file_okay=False), ) +@click.option( + "--dir_out_image_text", + "-doit", + help="directory of images with predicted text", + type=click.Path(exists=True, file_okay=False), +) @click.option( "--model", "-m", @@ -359,6 +365,12 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ is_flag=True, help="if this parameter set to true, cropped textline images will not be masked with textline contour.", ) +@click.option( + "--draw_texts_on_image", + "-dtoi/-ndtoi", + is_flag=True, + help="if this parameter set to true, the predicted texts will be displayed on an image.", +) @click.option( "--log_level", "-l", @@ -366,18 +378,20 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ help="Override log level globally to this", ) -def ocr(dir_in, out, dir_xmls, model, tr_ocr, export_textline_images_and_text, do_not_mask_with_textline_contour, log_level): +def ocr(dir_in, out, dir_xmls, dir_out_image_text, model, tr_ocr, export_textline_images_and_text, do_not_mask_with_textline_contour, draw_texts_on_image, log_level): if log_level: setOverrideLogLevel(log_level) initLogging() eynollah_ocr = Eynollah_ocr( dir_xmls=dir_xmls, + dir_out_image_text=dir_out_image_text, dir_in=dir_in, dir_out=out, dir_models=model, tr_ocr=tr_ocr, export_textline_images_and_text=export_textline_images_and_text, do_not_mask_with_textline_contour=do_not_mask_with_textline_contour, + draw_texts_on_image=draw_texts_on_image, ) eynollah_ocr.run() diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 9ead53e..0b93085 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -22,7 +22,7 @@ from ocrd_utils import getLogger import cv2 import numpy as np from transformers import TrOCRProcessor -from PIL import Image +from PIL import Image, ImageDraw, ImageFont import torch from difflib import SequenceMatcher as sq from transformers import VisionEncoderDecoderModel @@ -4409,7 +4409,6 @@ class Eynollah: text_regions_p_1 ,erosion_hurts, polygons_lines_xml, textline_mask_tot_ea, img_bin_light = \ self.get_regions_light_v(img_res, is_image_enhanced, num_col_classifier) #print("text region early -2 in %.1fs", time.time() - t0) - if num_col_classifier == 1 or num_col_classifier ==2: if num_col_classifier == 1: img_w_new = 1000 @@ -4954,9 +4953,11 @@ class Eynollah_ocr: dir_xmls=None, dir_in=None, dir_out=None, + dir_out_image_text=None, tr_ocr=False, export_textline_images_and_text=False, do_not_mask_with_textline_contour=False, + draw_texts_on_image=False, logger=None, ): self.dir_in = dir_in @@ -4966,6 +4967,8 @@ class Eynollah_ocr: self.tr_ocr = tr_ocr self.export_textline_images_and_text = export_textline_images_and_text self.do_not_mask_with_textline_contour = do_not_mask_with_textline_contour + self.draw_texts_on_image = draw_texts_on_image + self.dir_out_image_text = dir_out_image_text if tr_ocr: self.processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed") self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @@ -5083,6 +5086,23 @@ class Eynollah_ocr: return peaks_final else: return None + + # Function to fit text inside the given area + def fit_text_single_line(self, draw, text, font_path, max_width, max_height): + initial_font_size = 50 + font_size = initial_font_size + while font_size > 10: # Minimum font size + font = ImageFont.truetype(font_path, font_size) + text_bbox = draw.textbbox((0, 0), text, font=font) # Get text bounding box + text_width = text_bbox[2] - text_bbox[0] + text_height = text_bbox[3] - text_bbox[1] + + if text_width <= max_width and text_height <= max_height: + return font # Return the best-fitting font + + font_size -= 2 # Reduce font size and retry + + return ImageFont.truetype(font_path, 10) # Smallest font fallback def return_textlines_split_if_needed(self, textline_image): @@ -5254,6 +5274,12 @@ class Eynollah_ocr: dir_xml = os.path.join(self.dir_xmls, file_name+'.xml') out_file_ocr = os.path.join(self.dir_out, file_name+'.xml') img = cv2.imread(dir_img) + + if self.draw_texts_on_image: + out_image_with_text = os.path.join(self.dir_out_image_text, file_name+'.png') + image_text = Image.new("RGB", (img.shape[1], img.shape[0]), "white") + draw = ImageDraw.Draw(image_text) + total_bb_coordinates = [] tree1 = ET.parse(dir_xml, parser = ET.XMLParser(encoding="utf-8")) root1=tree1.getroot() @@ -5283,6 +5309,9 @@ class Eynollah_ocr: x,y,w,h = cv2.boundingRect(textline_coords) + if self.draw_texts_on_image: + total_bb_coordinates.append([x,y,w,h]) + h2w_ratio = h/float(w) img_poly_on_img = np.copy(img) @@ -5359,6 +5388,35 @@ class Eynollah_ocr: extracted_texts_merged = [ind for ind in extracted_texts_merged if ind is not None] unique_cropped_lines_region_indexer = np.unique(cropped_lines_region_indexer) + + + if self.draw_texts_on_image: + + font_path = "NotoSans-Regular.ttf" # Make sure this file exists! + font = ImageFont.truetype(font_path, 40) + + for indexer_text, bb_ind in enumerate(total_bb_coordinates): + + + x_bb = bb_ind[0] + y_bb = bb_ind[1] + w_bb = bb_ind[2] + h_bb = bb_ind[3] + + font = self.fit_text_single_line(draw, extracted_texts_merged[indexer_text], font_path, w_bb, int(h_bb*0.4) ) + + ##draw.rectangle([x_bb, y_bb, x_bb + w_bb, y_bb + h_bb], outline="red", width=2) + + text_bbox = draw.textbbox((0, 0), extracted_texts_merged[indexer_text], font=font) + text_width = text_bbox[2] - text_bbox[0] + text_height = text_bbox[3] - text_bbox[1] + + text_x = x_bb + (w_bb - text_width) // 2 # Center horizontally + text_y = y_bb + (h_bb - text_height) // 2 # Center vertically + + # Draw the text + draw.text((text_x, text_y), extracted_texts_merged[indexer_text], fill="black", font=font) + image_text.save(out_image_with_text) text_by_textregion = [] for ind in unique_cropped_lines_region_indexer: From 4de441eaaa4e212fff6436258deeb091180405bd Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Mon, 31 Mar 2025 21:28:05 +0200 Subject: [PATCH 16/19] OCR prediction is now enabled to integrate results from both RGB and binarized images or to be performed on each individually --- src/eynollah/cli.py | 16 ++++++++++- src/eynollah/eynollah.py | 62 +++++++++++++++++++++++++++++++++++----- 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/src/eynollah/cli.py b/src/eynollah/cli.py index 369dc4c..8bd5cf6 100644 --- a/src/eynollah/cli.py +++ b/src/eynollah/cli.py @@ -321,6 +321,12 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ help="directory of images", type=click.Path(exists=True, file_okay=False), ) +@click.option( + "--dir_in_bin", + "-dib", + help="directory of binarized images. This should be given if you want to do prediction based on both rgb and bin images. And all bin images are png files", + type=click.Path(exists=True, file_okay=False), +) @click.option( "--out", "-o", @@ -371,6 +377,12 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ is_flag=True, help="if this parameter set to true, the predicted texts will be displayed on an image.", ) +@click.option( + "--prediction_with_both_of_rgb_and_bin", + "-brb/-nbrb", + is_flag=True, + help="If this parameter is set to True, the prediction will be performed using both RGB and binary images. However, this does not necessarily improve results; it may be beneficial for certain document images.", +) @click.option( "--log_level", "-l", @@ -378,7 +390,7 @@ def layout(image, out, overwrite, dir_in, model, save_images, save_layout, save_ help="Override log level globally to this", ) -def ocr(dir_in, out, dir_xmls, dir_out_image_text, model, tr_ocr, export_textline_images_and_text, do_not_mask_with_textline_contour, draw_texts_on_image, log_level): +def ocr(dir_in, dir_in_bin, out, dir_xmls, dir_out_image_text, model, tr_ocr, export_textline_images_and_text, do_not_mask_with_textline_contour, draw_texts_on_image, prediction_with_both_of_rgb_and_bin, log_level): if log_level: setOverrideLogLevel(log_level) initLogging() @@ -386,12 +398,14 @@ def ocr(dir_in, out, dir_xmls, dir_out_image_text, model, tr_ocr, export_textlin dir_xmls=dir_xmls, dir_out_image_text=dir_out_image_text, dir_in=dir_in, + dir_in_bin=dir_in_bin, dir_out=out, dir_models=model, tr_ocr=tr_ocr, export_textline_images_and_text=export_textline_images_and_text, do_not_mask_with_textline_contour=do_not_mask_with_textline_contour, draw_texts_on_image=draw_texts_on_image, + prediction_with_both_of_rgb_and_bin=prediction_with_both_of_rgb_and_bin, ) eynollah_ocr.run() diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 0b93085..1534e7e 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -4952,15 +4952,18 @@ class Eynollah_ocr: dir_models, dir_xmls=None, dir_in=None, + dir_in_bin=None, dir_out=None, dir_out_image_text=None, tr_ocr=False, export_textline_images_and_text=False, do_not_mask_with_textline_contour=False, draw_texts_on_image=False, + prediction_with_both_of_rgb_and_bin=False, logger=None, ): self.dir_in = dir_in + self.dir_in_bin = dir_in_bin self.dir_out = dir_out self.dir_xmls = dir_xmls self.dir_models = dir_models @@ -4969,6 +4972,7 @@ class Eynollah_ocr: self.do_not_mask_with_textline_contour = do_not_mask_with_textline_contour self.draw_texts_on_image = draw_texts_on_image self.dir_out_image_text = dir_out_image_text + self.prediction_with_both_of_rgb_and_bin = prediction_with_both_of_rgb_and_bin if tr_ocr: self.processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed") self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @@ -4977,7 +4981,7 @@ class Eynollah_ocr: self.model_ocr.to(self.device) else: - self.model_ocr_dir = dir_models + "/model_step_150000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" + self.model_ocr_dir = dir_models + "/model_step_50000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" model_ocr = load_model(self.model_ocr_dir , compile=False) self.prediction_model = tf.keras.models.Model( @@ -5104,15 +5108,20 @@ class Eynollah_ocr: return ImageFont.truetype(font_path, 10) # Smallest font fallback - def return_textlines_split_if_needed(self, textline_image): + def return_textlines_split_if_needed(self, textline_image, textline_image_bin): split_point = self.return_start_and_end_of_common_text_of_textline_ocr_without_common_section(textline_image) if split_point: image1 = textline_image[:, :split_point,:]# image.crop((0, 0, width2, height)) image2 = textline_image[:, split_point:,:]#image.crop((width1, 0, width, height)) - return [image1, image2] + if self.prediction_with_both_of_rgb_and_bin: + image1_bin = textline_image_bin[:, :split_point,:]# image.crop((0, 0, width2, height)) + image2_bin = textline_image_bin[:, split_point:,:]#image.crop((width1, 0, width, height)) + return [image1, image2], [image1_bin, image2_bin] + else: + return [image1, image2], None else: - return None + return None, None def preprocess_and_resize_image_for_ocrcnn_model(self, img, image_height, image_width): ratio = image_height /float(img.shape[0]) w_ratio = int(ratio * img.shape[1]) @@ -5123,7 +5132,7 @@ class Eynollah_ocr: img = resize_image(img, image_height, width_new) img_fin = np.ones((image_height, image_width, 3))*255 - img_fin[:,:width_new,:] = img[:,:,:] + img_fin[:,:+width_new,:] = img[:,:,:] img_fin = img_fin / 255. return img_fin @@ -5183,7 +5192,7 @@ class Eynollah_ocr: cropped_lines.append(img_crop) cropped_lines_meging_indexing.append(0) else: - splited_images = self.return_textlines_split_if_needed(img_crop) + splited_images, _ = self.return_textlines_split_if_needed(img_crop, None) #print(splited_images) if splited_images: cropped_lines.append(splited_images[0]) @@ -5274,6 +5283,10 @@ class Eynollah_ocr: dir_xml = os.path.join(self.dir_xmls, file_name+'.xml') out_file_ocr = os.path.join(self.dir_out, file_name+'.xml') img = cv2.imread(dir_img) + if self.prediction_with_both_of_rgb_and_bin: + cropped_lines_bin = [] + dir_img_bin = os.path.join(self.dir_in_bin, file_name+'.png') + img_bin = cv2.imread(dir_img_bin) if self.draw_texts_on_image: out_image_with_text = os.path.join(self.dir_out_image_text, file_name+'.png') @@ -5315,6 +5328,10 @@ class Eynollah_ocr: h2w_ratio = h/float(w) img_poly_on_img = np.copy(img) + if self.prediction_with_both_of_rgb_and_bin: + img_poly_on_img_bin = np.copy(img_bin) + img_crop_bin = img_poly_on_img_bin[y:y+h, x:x+w, :] + mask_poly = np.zeros(img.shape) mask_poly = cv2.fillPoly(mask_poly, pts=[textline_coords], color=(1, 1, 1)) @@ -5322,14 +5339,22 @@ class Eynollah_ocr: img_crop = img_poly_on_img[y:y+h, x:x+w, :] if not self.do_not_mask_with_textline_contour: img_crop[mask_poly==0] = 255 + if self.prediction_with_both_of_rgb_and_bin: + img_crop_bin[mask_poly==0] = 255 if not self.export_textline_images_and_text: if h2w_ratio > 0.1: img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(img_crop, image_height, image_width) cropped_lines.append(img_fin) cropped_lines_meging_indexing.append(0) + if self.prediction_with_both_of_rgb_and_bin: + img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(img_crop_bin, image_height, image_width) + cropped_lines_bin.append(img_fin) else: - splited_images = self.return_textlines_split_if_needed(img_crop) + if self.prediction_with_both_of_rgb_and_bin: + splited_images, splited_images_bin = self.return_textlines_split_if_needed(img_crop, img_crop_bin) + else: + splited_images, splited_images_bin = self.return_textlines_split_if_needed(img_crop, None) if splited_images: img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(splited_images[0], image_height, image_width) cropped_lines.append(img_fin) @@ -5338,10 +5363,21 @@ class Eynollah_ocr: cropped_lines.append(img_fin) cropped_lines_meging_indexing.append(-1) + + if self.prediction_with_both_of_rgb_and_bin: + img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(splited_images_bin[0], image_height, image_width) + cropped_lines_bin.append(img_fin) + img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(splited_images_bin[1], image_height, image_width) + cropped_lines_bin.append(img_fin) + else: img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(img_crop, image_height, image_width) cropped_lines.append(img_fin) cropped_lines_meging_indexing.append(0) + + if self.prediction_with_both_of_rgb_and_bin: + img_fin = self.preprocess_and_resize_image_for_ocrcnn_model(img_crop_bin, image_height, image_width) + cropped_lines_bin.append(img_fin) if self.export_textline_images_and_text: if child_textlines.tag.endswith("TextEquiv"): @@ -5370,14 +5406,26 @@ class Eynollah_ocr: imgs = cropped_lines[n_start:] imgs = np.array(imgs) imgs = imgs.reshape(imgs.shape[0], image_height, image_width, 3) + if self.prediction_with_both_of_rgb_and_bin: + imgs_bin = cropped_lines_bin[n_start:] + imgs_bin = np.array(imgs_bin) + imgs_bin = imgs_bin.reshape(imgs_bin.shape[0], image_height, image_width, 3) else: n_start = i*b_s n_end = (i+1)*b_s imgs = cropped_lines[n_start:n_end] imgs = np.array(imgs).reshape(b_s, image_height, image_width, 3) + if self.prediction_with_both_of_rgb_and_bin: + imgs_bin = cropped_lines_bin[n_start:n_end] + imgs_bin = np.array(imgs_bin).reshape(b_s, image_height, image_width, 3) + preds = self.prediction_model.predict(imgs, verbose=0) + if self.prediction_with_both_of_rgb_and_bin: + preds_bin = self.prediction_model.predict(imgs_bin, verbose=0) + preds = (preds + preds_bin) / 2. + pred_texts = self.decode_batch_predictions(preds) for ib in range(imgs.shape[0]): From 91b2201b07b4a2c3860f17fc66789c18d60866b1 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Tue, 1 Apr 2025 10:55:40 +0200 Subject: [PATCH 17/19] cnnrnn Ocr: width of input textline image can not be zero! --- src/eynollah/eynollah.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 1534e7e..436ce84 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -4981,7 +4981,7 @@ class Eynollah_ocr: self.model_ocr.to(self.device) else: - self.model_ocr_dir = dir_models + "/model_step_50000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" + self.model_ocr_dir = dir_models + "/model_step_150000_ocr"#"/model_0_ocr_cnnrnn"#"/model_23_ocr_cnnrnn" model_ocr = load_model(self.model_ocr_dir , compile=False) self.prediction_model = tf.keras.models.Model( @@ -5125,10 +5125,14 @@ class Eynollah_ocr: def preprocess_and_resize_image_for_ocrcnn_model(self, img, image_height, image_width): ratio = image_height /float(img.shape[0]) w_ratio = int(ratio * img.shape[1]) + if w_ratio <= image_width: width_new = w_ratio else: width_new = image_width + + if width_new == 0: + width_new = img.shape[1] img = resize_image(img, image_height, width_new) img_fin = np.ones((image_height, image_width, 3))*255 From 6b52da227c042c52d79ebbfc711e1a0f3b093e89 Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Thu, 3 Apr 2025 00:39:21 +0200 Subject: [PATCH 18/19] docorating eynollah with textregion confidence score #135 --- src/eynollah/eynollah.py | 113 ++++++++++++++++++++++++--------- src/eynollah/utils/__init__.py | 18 ++++-- src/eynollah/utils/contour.py | 18 ++++-- src/eynollah/writer.py | 9 +-- 4 files changed, 114 insertions(+), 44 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 436ce84..27003c2 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -1214,7 +1214,7 @@ class Eynollah: seg_color = np.repeat(seg[:, :, np.newaxis], 3, axis=2) prediction_true = resize_image(seg_color, img_h_page, img_w_page).astype(np.uint8) - return prediction_true + return prediction_true , resize_image(label_p_pred[0, :, :, 1] , img_h_page, img_w_page) if img.shape[0] < img_height_model: img = resize_image(img, img_height_model, img.shape[1]) @@ -1230,6 +1230,7 @@ class Eynollah: img_h = img.shape[0] img_w = img.shape[1] prediction_true = np.zeros((img_h, img_w, 3)) + confidence_matrix = np.zeros((img_h, img_w)) mask_true = np.zeros((img_h, img_w)) nxf = img_w / float(width_mid) nyf = img_h / float(height_mid) @@ -1318,54 +1319,99 @@ class Eynollah: seg_in[0:-margin or None, 0:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + 0:index_y_u_in - margin, + index_x_d_in + 0:index_x_u_in - margin] = \ + label_p_pred[0, 0:-margin or None, + 0:-margin or None, + 1] elif i_batch == nxf - 1 and j_batch == nyf - 1: prediction_true[index_y_d_in + margin:index_y_u_in - 0, index_x_d_in + margin:index_x_u_in - 0] = \ seg_in[margin:, margin:, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - 0, + index_x_d_in + margin:index_x_u_in - 0] = \ + label_p_pred[0, margin:, + margin:, + 1] elif i_batch == 0 and j_batch == nyf - 1: prediction_true[index_y_d_in + margin:index_y_u_in - 0, index_x_d_in + 0:index_x_u_in - margin] = \ seg_in[margin:, 0:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - 0, + index_x_d_in + 0:index_x_u_in - margin] = \ + label_p_pred[0, margin:, + 0:-margin or None, + 1] elif i_batch == nxf - 1 and j_batch == 0: prediction_true[index_y_d_in + 0:index_y_u_in - margin, index_x_d_in + margin:index_x_u_in - 0] = \ seg_in[0:-margin or None, margin:, np.newaxis] + confidence_matrix[index_y_d_in + 0:index_y_u_in - margin, + index_x_d_in + margin:index_x_u_in - 0] = \ + label_p_pred[0, 0:-margin or None, + margin:, + 1] elif i_batch == 0 and j_batch != 0 and j_batch != nyf - 1: prediction_true[index_y_d_in + margin:index_y_u_in - margin, index_x_d_in + 0:index_x_u_in - margin] = \ seg_in[margin:-margin or None, 0:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - margin, + index_x_d_in + 0:index_x_u_in - margin] = \ + label_p_pred[0, margin:-margin or None, + 0:-margin or None, + 1] elif i_batch == nxf - 1 and j_batch != 0 and j_batch != nyf - 1: prediction_true[index_y_d_in + margin:index_y_u_in - margin, index_x_d_in + margin:index_x_u_in - 0] = \ seg_in[margin:-margin or None, margin:, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - margin, + index_x_d_in + margin:index_x_u_in - 0] = \ + label_p_pred[0, margin:-margin or None, + margin:, + 1] elif i_batch != 0 and i_batch != nxf - 1 and j_batch == 0: prediction_true[index_y_d_in + 0:index_y_u_in - margin, index_x_d_in + margin:index_x_u_in - margin] = \ seg_in[0:-margin or None, margin:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + 0:index_y_u_in - margin, + index_x_d_in + margin:index_x_u_in - margin] = \ + label_p_pred[0, 0:-margin or None, + margin:-margin or None, + 1] elif i_batch != 0 and i_batch != nxf - 1 and j_batch == nyf - 1: prediction_true[index_y_d_in + margin:index_y_u_in - 0, index_x_d_in + margin:index_x_u_in - margin] = \ seg_in[margin:, margin:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - 0, + index_x_d_in + margin:index_x_u_in - margin] = \ + label_p_pred[0, margin:, + margin:-margin or None, + 1] else: prediction_true[index_y_d_in + margin:index_y_u_in - margin, index_x_d_in + margin:index_x_u_in - margin] = \ seg_in[margin:-margin or None, margin:-margin or None, np.newaxis] + confidence_matrix[index_y_d_in + margin:index_y_u_in - margin, + index_x_d_in + margin:index_x_u_in - margin] = \ + label_p_pred[0, margin:-margin or None, + margin:-margin or None, + 1] indexer_inside_batch += 1 list_i_s = [] @@ -1380,7 +1426,7 @@ class Eynollah: prediction_true = prediction_true.astype(np.uint8) gc.collect() - return prediction_true + return prediction_true, confidence_matrix def extract_page(self): self.logger.debug("enter extract_page") @@ -1742,7 +1788,7 @@ class Eynollah: if not self.dir_in: self.model_region, _ = self.start_new_session_and_model(self.model_region_dir_p_ens_light_only_images_extraction) - prediction_regions_org = self.do_prediction_new_concept(True, img_resized, self.model_region) + prediction_regions_org, _ = self.do_prediction_new_concept(True, img_resized, self.model_region) prediction_regions_org = resize_image(prediction_regions_org,img_height_h, img_width_h ) image_page, page_coord, cont_page = self.extract_page() @@ -1903,24 +1949,26 @@ class Eynollah: if self.image_org.shape[0]/self.image_org.shape[1] > 2.5: self.logger.debug("resized to %dx%d for %d cols", img_resized.shape[1], img_resized.shape[0], num_col_classifier) - prediction_regions_org = self.do_prediction_new_concept( + prediction_regions_org, confidence_matrix = self.do_prediction_new_concept( True, img_resized, self.model_region_1_2, n_batch_inference=1, thresholding_for_some_classes_in_light_version=True) else: prediction_regions_org = np.zeros((self.image_org.shape[0], self.image_org.shape[1], 3)) - prediction_regions_page = self.do_prediction_new_concept( + confidence_matrix = np.zeros((self.image_org.shape[0], self.image_org.shape[1])) + prediction_regions_page, confidence_matrix_page = self.do_prediction_new_concept( False, self.image_page_org_size, self.model_region_1_2, n_batch_inference=1, thresholding_for_artificial_class_in_light_version=True) ys = slice(*self.page_coord[0:2]) xs = slice(*self.page_coord[2:4]) prediction_regions_org[ys, xs] = prediction_regions_page + confidence_matrix[ys, xs] = confidence_matrix_page else: new_h = (900+ (num_col_classifier-3)*100) img_resized = resize_image(img_bin, int(new_h * img_bin.shape[0] /img_bin.shape[1]), new_h) self.logger.debug("resized to %dx%d (new_h=%d) for %d cols", img_resized.shape[1], img_resized.shape[0], new_h, num_col_classifier) - prediction_regions_org = self.do_prediction_new_concept( + prediction_regions_org, confidence_matrix = self.do_prediction_new_concept( True, img_resized, self.model_region_1_2, n_batch_inference=2, thresholding_for_some_classes_in_light_version=True) ###prediction_regions_org = self.do_prediction(True, img_bin, self.model_region, n_batch_inference=3, thresholding_for_some_classes_in_light_version=True) @@ -1928,8 +1976,9 @@ class Eynollah: #plt.imshow(prediction_regions_org[:,:,0]) #plt.show() - prediction_regions_org = resize_image(prediction_regions_org,img_height_h, img_width_h ) - img_bin = resize_image(img_bin,img_height_h, img_width_h ) + prediction_regions_org = resize_image(prediction_regions_org, img_height_h, img_width_h ) + confidence_matrix = resize_image(confidence_matrix, img_height_h, img_width_h ) + img_bin = resize_image(img_bin, img_height_h, img_width_h ) prediction_regions_org=prediction_regions_org[:,:,0] mask_lines_only = (prediction_regions_org[:,:] ==3)*1 @@ -1985,11 +2034,11 @@ class Eynollah: #plt.show() #print("inside 4 ", time.time()-t_in) self.logger.debug("exit get_regions_light_v") - return text_regions_p_true, erosion_hurts, polygons_lines_xml, textline_mask_tot_ea, img_bin + return text_regions_p_true, erosion_hurts, polygons_lines_xml, textline_mask_tot_ea, img_bin, confidence_matrix else: img_bin = resize_image(img_bin,img_height_h, img_width_h ) self.logger.debug("exit get_regions_light_v") - return None, erosion_hurts, None, textline_mask_tot_ea, img_bin + return None, erosion_hurts, None, textline_mask_tot_ea, img_bin, None def get_regions_from_xy_2models(self,img,is_image_enhanced, num_col_classifier): self.logger.debug("enter get_regions_from_xy_2models") @@ -2742,7 +2791,7 @@ class Eynollah: patches = False if self.light_version: - prediction_table = self.do_prediction_new_concept(patches, img, self.model_table) + prediction_table, _ = self.do_prediction_new_concept(patches, img, self.model_table) prediction_table = prediction_table.astype(np.int16) return prediction_table[:,:,0] else: @@ -4127,8 +4176,7 @@ class Eynollah: return contours def filter_contours_without_textline_inside( - self, contours,text_con_org, contours_textline, contours_only_text_parent_d_ordered): - + self, contours,text_con_org, contours_textline, contours_only_text_parent_d_ordered, conf_contours_textregions): ###contours_txtline_of_all_textregions = [] ###for jj in range(len(contours_textline)): ###contours_txtline_of_all_textregions = contours_txtline_of_all_textregions + contours_textline[jj] @@ -4161,13 +4209,14 @@ class Eynollah: uniqe_args_trs_sorted = np.sort(uniqe_args_trs)[::-1] for ind_u_a_trs in uniqe_args_trs_sorted: + conf_contours_textregions.pop(ind_u_a_trs) contours.pop(ind_u_a_trs) contours_textline.pop(ind_u_a_trs) text_con_org.pop(ind_u_a_trs) if len(contours_only_text_parent_d_ordered) > 0: contours_only_text_parent_d_ordered.pop(ind_u_a_trs) - return contours, text_con_org, contours_textline, contours_only_text_parent_d_ordered, np.array(range(len(contours))) + return contours, text_con_org, conf_contours_textregions, contours_textline, contours_only_text_parent_d_ordered, np.array(range(len(contours))) def dilate_textlines(self, all_found_textline_polygons): for j in range(len(all_found_textline_polygons)): @@ -4347,7 +4396,7 @@ class Eynollah: pcgts = self.writer.build_pagexml_no_full_layout( [], page_coord, [], [], [], [], polygons_of_images, [], [], [], [], [], - cont_page, [], [], ocr_all_textlines) + cont_page, [], [], ocr_all_textlines, []) if self.plotter: self.plotter.write_images_into_directory(polygons_of_images, image_page) @@ -4358,7 +4407,7 @@ class Eynollah: return pcgts if self.skip_layout_and_reading_order: - _ ,_, _, textline_mask_tot_ea, img_bin_light = \ + _ ,_, _, textline_mask_tot_ea, img_bin_light,_ = \ self.get_regions_light_v(img_res, is_image_enhanced, num_col_classifier, skip_layout_and_reading_order=self.skip_layout_and_reading_order) @@ -4392,11 +4441,12 @@ class Eynollah: polygons_lines_xml = [] contours_tables = [] ocr_all_textlines = None + conf_contours_textregions =None pcgts = self.writer.build_pagexml_no_full_layout( cont_page, page_coord, order_text_new, id_of_texts_tot, all_found_textline_polygons, page_coord, polygons_of_images, polygons_of_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_marginals, - cont_page, polygons_lines_xml, contours_tables, ocr_all_textlines) + cont_page, polygons_lines_xml, contours_tables, ocr_all_textlines, conf_contours_textregions) if self.dir_in: self.writer.write_pagexml(pcgts) continue @@ -4406,7 +4456,7 @@ class Eynollah: #print("text region early -1 in %.1fs", time.time() - t0) t1 = time.time() if self.light_version: - text_regions_p_1 ,erosion_hurts, polygons_lines_xml, textline_mask_tot_ea, img_bin_light = \ + text_regions_p_1 ,erosion_hurts, polygons_lines_xml, textline_mask_tot_ea, img_bin_light, confidence_matrix = \ self.get_regions_light_v(img_res, is_image_enhanced, num_col_classifier) #print("text region early -2 in %.1fs", time.time() - t0) if num_col_classifier == 1 or num_col_classifier ==2: @@ -4417,9 +4467,9 @@ class Eynollah: img_h_new = img_w_new * textline_mask_tot_ea.shape[0] // textline_mask_tot_ea.shape[1] textline_mask_tot_ea_deskew = resize_image(textline_mask_tot_ea,img_h_new, img_w_new ) - slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea_deskew) else: + ttest = time.time() slope_deskew, slope_first = self.run_deskew(textline_mask_tot_ea) #print("text region early -2,5 in %.1fs", time.time() - t0) #self.logger.info("Textregion detection took %.1fs ", time.time() - t1t) @@ -4451,7 +4501,7 @@ class Eynollah: ocr_all_textlines = None pcgts = self.writer.build_pagexml_no_full_layout( [], page_coord, [], [], [], [], [], [], [], [], [], [], - cont_page, [], [], ocr_all_textlines) + cont_page, [], [], ocr_all_textlines, []) self.logger.info("Job done in %.1fs", time.time() - t1) if self.dir_in: self.writer.write_pagexml(pcgts) @@ -4636,13 +4686,13 @@ class Eynollah: [], [], page_coord, [], [], [], [], [], [], polygons_of_images, contours_tables, [], polygons_of_marginals, empty_marginals, empty_marginals, [], [], [], - cont_page, polygons_lines_xml, []) + cont_page, polygons_lines_xml, [], [], []) else: pcgts = self.writer.build_pagexml_no_full_layout( [], page_coord, [], [], [], [], polygons_of_images, polygons_of_marginals, empty_marginals, empty_marginals, [], [], - cont_page, polygons_lines_xml, contours_tables, []) + cont_page, polygons_lines_xml, contours_tables, [], []) self.logger.info("Job done in %.1fs", time.time() - t0) if self.dir_in: self.writer.write_pagexml(pcgts) @@ -4663,10 +4713,11 @@ class Eynollah: contours_only_text_parent , contours_only_text_parent_d_ordered = self.filter_contours_inside_a_bigger_one( contours_only_text_parent, contours_only_text_parent_d_ordered, text_only, marginal_cnts=polygons_of_marginals) #print("text region early 3.5 in %.1fs", time.time() - t0) - txt_con_org = get_textregion_contours_in_org_image_light( - contours_only_text_parent, self.image, slope_first, map=self.executor.map) + txt_con_org , conf_contours_textregions = get_textregion_contours_in_org_image_light( + contours_only_text_parent, self.image, slope_first, confidence_matrix, map=self.executor.map) #txt_con_org = self.dilate_textregions_contours(txt_con_org) #contours_only_text_parent = self.dilate_textregions_contours(contours_only_text_parent) + else: txt_con_org = get_textregion_contours_in_org_image( contours_only_text_parent, self.image, slope_first) @@ -4701,9 +4752,9 @@ class Eynollah: all_found_textline_polygons, None, textline_mask_tot_ea_org, type_contour="textline") all_found_textline_polygons_marginals = self.dilate_textregions_contours_textline_version( all_found_textline_polygons_marginals) - contours_only_text_parent, txt_con_org, all_found_textline_polygons, contours_only_text_parent_d_ordered, \ + contours_only_text_parent, txt_con_org, conf_contours_textregions, all_found_textline_polygons, contours_only_text_parent_d_ordered, \ index_by_text_par_con = self.filter_contours_without_textline_inside( - contours_only_text_parent, txt_con_org, all_found_textline_polygons, contours_only_text_parent_d_ordered) + contours_only_text_parent, txt_con_org, all_found_textline_polygons, contours_only_text_parent_d_ordered, conf_contours_textregions) else: textline_mask_tot_ea = cv2.erode(textline_mask_tot_ea, kernel=KERNEL, iterations=1) all_found_textline_polygons, boxes_text, txt_con_org, contours_only_text_parent, all_box_coord, \ @@ -4761,12 +4812,14 @@ class Eynollah: if self.light_version: fun = check_any_text_region_in_model_one_is_main_or_header_light else: + conf_contours_textregions = None fun = check_any_text_region_in_model_one_is_main_or_header text_regions_p, contours_only_text_parent, contours_only_text_parent_h, all_box_coord, all_box_coord_h, \ all_found_textline_polygons, all_found_textline_polygons_h, slopes, slopes_h, \ - contours_only_text_parent_d_ordered, contours_only_text_parent_h_d_ordered = fun( + contours_only_text_parent_d_ordered, contours_only_text_parent_h_d_ordered, \ + conf_contours_textregions, conf_contours_textregions_h = fun( text_regions_p, regions_fully, contours_only_text_parent, - all_box_coord, all_found_textline_polygons, slopes, contours_only_text_parent_d_ordered) + all_box_coord, all_found_textline_polygons, slopes, contours_only_text_parent_d_ordered, conf_contours_textregions) if self.plotter: self.plotter.save_plot_of_layout(text_regions_p, image_page) @@ -4843,7 +4896,7 @@ class Eynollah: all_found_textline_polygons, all_found_textline_polygons_h, all_box_coord, all_box_coord_h, polygons_of_images, contours_tables, polygons_of_drop_capitals, polygons_of_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_h, slopes_marginals, - cont_page, polygons_lines_xml, ocr_all_textlines) + cont_page, polygons_lines_xml, ocr_all_textlines, conf_contours_textregions, conf_contours_textregions_h) self.logger.info("Job done in %.1fs", time.time() - t0) #print("Job done in %.1fs", time.time() - t0) if self.dir_in: @@ -4929,7 +4982,7 @@ class Eynollah: txt_con_org, page_coord, order_text_new, id_of_texts_tot, all_found_textline_polygons, all_box_coord, polygons_of_images, polygons_of_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_marginals, - cont_page, polygons_lines_xml, contours_tables, ocr_all_textlines) + cont_page, polygons_lines_xml, contours_tables, ocr_all_textlines, conf_contours_textregions) #print("Job done in %.1fs" % (time.time() - t0)) self.logger.info("Job done in %.1fs", time.time() - t0) if not self.dir_in: diff --git a/src/eynollah/utils/__init__.py b/src/eynollah/utils/__init__.py index faa32b0..5594fd0 100644 --- a/src/eynollah/utils/__init__.py +++ b/src/eynollah/utils/__init__.py @@ -865,7 +865,7 @@ def check_any_text_region_in_model_one_is_main_or_header( contours_only_text_parent, all_box_coord, all_found_textline_polygons, slopes, - contours_only_text_parent_d_ordered): + contours_only_text_parent_d_ordered, conf_contours): cx_main, cy_main, x_min_main, x_max_main, y_min_main, y_max_main, y_corr_x_min_from_argmin = \ find_new_features_of_contours(contours_only_text_parent) @@ -926,14 +926,17 @@ def check_any_text_region_in_model_one_is_main_or_header( slopes_main, slopes_head, contours_only_text_parent_main_d, - contours_only_text_parent_head_d) + contours_only_text_parent_head_d, + None, + None) def check_any_text_region_in_model_one_is_main_or_header_light( regions_model_1, regions_model_full, contours_only_text_parent, all_box_coord, all_found_textline_polygons, slopes, - contours_only_text_parent_d_ordered): + contours_only_text_parent_d_ordered, + conf_contours): ### to make it faster h_o = regions_model_1.shape[0] @@ -965,6 +968,9 @@ def check_any_text_region_in_model_one_is_main_or_header_light( contours_only_text_parent_main=[] contours_only_text_parent_head=[] + + conf_contours_main=[] + conf_contours_head=[] contours_only_text_parent_main_d=[] contours_only_text_parent_head_d=[] @@ -987,9 +993,11 @@ def check_any_text_region_in_model_one_is_main_or_header_light( all_box_coord_head.append(all_box_coord[ii]) slopes_head.append(slopes[ii]) all_found_textline_polygons_head.append(all_found_textline_polygons[ii]) + conf_contours_head.append(None) else: regions_model_1[:,:][(regions_model_1[:,:]==1) & (img[:,:,0]==255) ]=1 contours_only_text_parent_main.append(con) + conf_contours_main.append(conf_contours[ii]) if contours_only_text_parent_d_ordered is not None: contours_only_text_parent_main_d.append(contours_only_text_parent_d_ordered[ii]) all_box_coord_main.append(all_box_coord[ii]) @@ -1017,7 +1025,9 @@ def check_any_text_region_in_model_one_is_main_or_header_light( slopes_main, slopes_head, contours_only_text_parent_main_d, - contours_only_text_parent_head_d) + contours_only_text_parent_head_d, + conf_contours_main, + conf_contours_head) def small_textlines_to_parent_adherence2(textlines_con, textline_iamge, num_col): # print(textlines_con) diff --git a/src/eynollah/utils/contour.py b/src/eynollah/utils/contour.py index be00db0..80b1dba 100644 --- a/src/eynollah/utils/contour.py +++ b/src/eynollah/utils/contour.py @@ -227,9 +227,12 @@ def get_textregion_contours_in_org_image_light_old(cnts, img, slope_first): return cnts_org -def do_back_rotation_and_get_cnt_back(contour_par, index_r_con, img, slope_first): +def do_back_rotation_and_get_cnt_back(contour_par, index_r_con, img, slope_first, confidence_matrix): img_copy = np.zeros(img.shape) img_copy = cv2.fillPoly(img_copy, pts=[contour_par], color=(1, 1, 1)) + + confidence_matrix_mapped_with_contour = confidence_matrix * img_copy[:,:,0] + confidence_contour = np.sum(confidence_matrix_mapped_with_contour) / float(np.sum(img_copy[:,:,0])) img_copy = rotation_image_new(img_copy, -slope_first).astype(np.uint8) imgray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY) @@ -239,11 +242,13 @@ def do_back_rotation_and_get_cnt_back(contour_par, index_r_con, img, slope_first cont_int[0][:, 0, 0] = cont_int[0][:, 0, 0] + np.abs(img_copy.shape[1] - img.shape[1]) cont_int[0][:, 0, 1] = cont_int[0][:, 0, 1] + np.abs(img_copy.shape[0] - img.shape[0]) # print(np.shape(cont_int[0])) - return cont_int[0], index_r_con + return cont_int[0], index_r_con, confidence_contour -def get_textregion_contours_in_org_image_light(cnts, img, slope_first, map=map): +def get_textregion_contours_in_org_image_light(cnts, img, slope_first, confidence_matrix, map=map): if not len(cnts): - return [] + return [], [] + + confidence_matrix = cv2.resize(confidence_matrix, (int(img.shape[1]/6), int(img.shape[0]/6)), interpolation=cv2.INTER_NEAREST) img = cv2.resize(img, (int(img.shape[1]/6), int(img.shape[0]/6)), interpolation=cv2.INTER_NEAREST) ##cnts = list( (np.array(cnts)/2).astype(np.int16) ) #cnts = cnts/2 @@ -251,10 +256,11 @@ def get_textregion_contours_in_org_image_light(cnts, img, slope_first, map=map): results = map(partial(do_back_rotation_and_get_cnt_back, img=img, slope_first=slope_first, + confidence_matrix=confidence_matrix, ), cnts, range(len(cnts))) - contours, indexes = tuple(zip(*results)) - return [i*6 for i in contours] + contours, indexes, conf_contours = tuple(zip(*results)) + return [i*6 for i in contours], list(conf_contours) def return_contours_of_interested_textline(region_pre_p, pixel): # pixels of images are identified by 5 diff --git a/src/eynollah/writer.py b/src/eynollah/writer.py index 66747b1..c0ead60 100644 --- a/src/eynollah/writer.py +++ b/src/eynollah/writer.py @@ -168,7 +168,7 @@ class EynollahXmlWriter(): with open(self.output_filename, 'w') as f: f.write(to_xml(pcgts)) - def build_pagexml_no_full_layout(self, found_polygons_text_region, page_coord, order_of_texts, id_of_texts, all_found_textline_polygons, all_box_coord, found_polygons_text_region_img, found_polygons_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_marginals, cont_page, polygons_lines_to_be_written_in_xml, found_polygons_tables, ocr_all_textlines): + def build_pagexml_no_full_layout(self, found_polygons_text_region, page_coord, order_of_texts, id_of_texts, all_found_textline_polygons, all_box_coord, found_polygons_text_region_img, found_polygons_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_marginals, cont_page, polygons_lines_to_be_written_in_xml, found_polygons_tables, ocr_all_textlines, conf_contours_textregion): self.logger.debug('enter build_pagexml_no_full_layout') # create the file structure @@ -184,8 +184,9 @@ class EynollahXmlWriter(): for mm in range(len(found_polygons_text_region)): textregion = TextRegionType(id=counter.next_region_id, type_='paragraph', - Coords=CoordsType(points=self.calculate_polygon_coords(found_polygons_text_region[mm], page_coord)), + Coords=CoordsType(points=self.calculate_polygon_coords(found_polygons_text_region[mm], page_coord), conf=conf_contours_textregion[mm]), ) + #textregion.set_conf(conf_contours_textregion[mm]) page.add_TextRegion(textregion) if ocr_all_textlines: ocr_textlines = ocr_all_textlines[mm] @@ -241,7 +242,7 @@ class EynollahXmlWriter(): return pcgts - def build_pagexml_full_layout(self, found_polygons_text_region, found_polygons_text_region_h, page_coord, order_of_texts, id_of_texts, all_found_textline_polygons, all_found_textline_polygons_h, all_box_coord, all_box_coord_h, found_polygons_text_region_img, found_polygons_tables, found_polygons_drop_capitals, found_polygons_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_h, slopes_marginals, cont_page, polygons_lines_to_be_written_in_xml, ocr_all_textlines): + def build_pagexml_full_layout(self, found_polygons_text_region, found_polygons_text_region_h, page_coord, order_of_texts, id_of_texts, all_found_textline_polygons, all_found_textline_polygons_h, all_box_coord, all_box_coord_h, found_polygons_text_region_img, found_polygons_tables, found_polygons_drop_capitals, found_polygons_marginals, all_found_textline_polygons_marginals, all_box_coord_marginals, slopes, slopes_h, slopes_marginals, cont_page, polygons_lines_to_be_written_in_xml, ocr_all_textlines, conf_contours_textregion, conf_contours_textregion_h): self.logger.debug('enter build_pagexml_full_layout') # create the file structure @@ -256,7 +257,7 @@ class EynollahXmlWriter(): for mm in range(len(found_polygons_text_region)): textregion = TextRegionType(id=counter.next_region_id, type_='paragraph', - Coords=CoordsType(points=self.calculate_polygon_coords(found_polygons_text_region[mm], page_coord))) + Coords=CoordsType(points=self.calculate_polygon_coords(found_polygons_text_region[mm], page_coord), conf=conf_contours_textregion[mm])) page.add_TextRegion(textregion) if ocr_all_textlines: From 38a2d60fa2766aac3dc8f0412bb60315fa38ffdf Mon Sep 17 00:00:00 2001 From: vahidrezanezhad Date: Thu, 3 Apr 2025 12:47:27 +0200 Subject: [PATCH 19/19] Confidence value for textregions and in the case of not light version is set to zero. This is done to let the pipeline go through. It will be updated to return the correct value in upcomming commits --- src/eynollah/eynollah.py | 6 +++--- src/eynollah/utils/__init__.py | 9 +++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/eynollah/eynollah.py b/src/eynollah/eynollah.py index 27003c2..eda2288 100644 --- a/src/eynollah/eynollah.py +++ b/src/eynollah/eynollah.py @@ -4486,6 +4486,7 @@ class Eynollah: self.get_regions_from_xy_2models(img_res, is_image_enhanced, num_col_classifier) self.logger.info("Textregion detection took %.1fs ", time.time() - t1) + confidence_matrix = np.zeros((text_regions_p_1.shape[:2])) t1 = time.time() num_col, num_col_classifier, img_only_regions, page_coord, image_page, mask_images, mask_lines, \ @@ -4719,8 +4720,8 @@ class Eynollah: #contours_only_text_parent = self.dilate_textregions_contours(contours_only_text_parent) else: - txt_con_org = get_textregion_contours_in_org_image( - contours_only_text_parent, self.image, slope_first) + txt_con_org , conf_contours_textregions = get_textregion_contours_in_org_image_light( + contours_only_text_parent, self.image, slope_first, confidence_matrix, map=self.executor.map) #print("text region early 4 in %.1fs", time.time() - t0) boxes_text, _ = get_text_region_boxes_by_given_contours(contours_only_text_parent) boxes_marginals, _ = get_text_region_boxes_by_given_contours(polygons_of_marginals) @@ -4812,7 +4813,6 @@ class Eynollah: if self.light_version: fun = check_any_text_region_in_model_one_is_main_or_header_light else: - conf_contours_textregions = None fun = check_any_text_region_in_model_one_is_main_or_header text_regions_p, contours_only_text_parent, contours_only_text_parent_h, all_box_coord, all_box_coord_h, \ all_found_textline_polygons, all_found_textline_polygons_h, slopes, slopes_h, \ diff --git a/src/eynollah/utils/__init__.py b/src/eynollah/utils/__init__.py index 5594fd0..bad114d 100644 --- a/src/eynollah/utils/__init__.py +++ b/src/eynollah/utils/__init__.py @@ -884,6 +884,9 @@ def check_any_text_region_in_model_one_is_main_or_header( contours_only_text_parent_main=[] contours_only_text_parent_head=[] + + conf_contours_main=[] + conf_contours_head=[] contours_only_text_parent_main_d=[] contours_only_text_parent_head_d=[] @@ -905,9 +908,11 @@ def check_any_text_region_in_model_one_is_main_or_header( all_box_coord_head.append(all_box_coord[ii]) slopes_head.append(slopes[ii]) all_found_textline_polygons_head.append(all_found_textline_polygons[ii]) + conf_contours_head.append(None) else: regions_model_1[:,:][(regions_model_1[:,:]==1) & (img[:,:,0]==255) ]=1 contours_only_text_parent_main.append(con) + conf_contours_main.append(conf_contours[ii]) if contours_only_text_parent_d_ordered is not None: contours_only_text_parent_main_d.append(contours_only_text_parent_d_ordered[ii]) all_box_coord_main.append(all_box_coord[ii]) @@ -927,8 +932,8 @@ def check_any_text_region_in_model_one_is_main_or_header( slopes_head, contours_only_text_parent_main_d, contours_only_text_parent_head_d, - None, - None) + conf_contours_main, + conf_contours_head) def check_any_text_region_in_model_one_is_main_or_header_light( regions_model_1, regions_model_full,