4. Use Layout Analysis with OCR Libraries (e.g., LayoutParser) Some libraries, like…
- User
- Use Layout Analysis with OCR Libraries (e.g., LayoutParser) Some libraries, like LayoutParser, are designed to detect and process the layout of documents. LayoutParser works well for structured documents, as it can detect blocks, paragraphs, tables, and more. It uses deep learning models to recognize the document's structure, which can then help in extracting lines of text.
You can integrate LayoutParser with Tesseract OCR to achieve high-level document segmentation and reading.
Here’s an outline of how you might use LayoutParser:
Use LayoutParser to detect the layout of the document (i.e., blocks, paragraphs, lines). Use Tesseract to extract text from the detected regions. Group the OCR text based on the detected layout structure. python Skopiuj kod import layoutparser as lp from PIL import Image
Load the image
image = Image.open("your_image.png")
Load a pre-trained model for document layout detection
model = lp.Detectron2LayoutModel("lp://PubLayNet/ppyolov2_r50_fpn_1x/config")
Detect the layout of the document
layout = model.detect(image)
Extract lines based on the detected blocks
for block in layout: # Each block will contain the coordinates and type (e.g., text block, table block) print(block)
Which model I should use to make it work in this code: import json import pandas as pd import matplotlib.pyplot as plt import numpy as np from pdf2image import convert_from_path from PIL import Image, ImageDraw, ImageFont import cv2
def create_plots(image, grouped_regions_df): img_arr=np.array(image) mask = np.zeros_like(img_arr) mask.fill(255) mask = Image.fromarray(mask) draw = ImageDraw.Draw(mask) font = ImageFont.truetype("arial.ttf", 25) for i in range(len(grouped_regions_df)): x1 = grouped_regions_df.loc[i, "x1"] x2 = grouped_regions_df.loc[i, "x2"] y1 = grouped_regions_df.loc[i, "y1"] y2 = grouped_regions_df.loc[i, "y2"] cv2.rectangle(img_arr, (x1, y1), (x2, y2), (0, 255, 0), 2)
codeplt.figure(figsize=(15, 15)) plt.imshow(img_arr) plt.show() # put.text() cv2 ogarnac sobiejson_filename = "Sortowanie/4617010.json" with open(json_filename, 'r', encoding='utf-8') as json_file: bbox = json.load(json_file) df = pd.DataFrame(bbox)
image_list = convert_from_path("Sortowanie/4617010.pdf") image = image_list[0] create_plots(image, df)
for i in range(1, len(df)): if abs(df.loc[i, "y2"] - df.loc[i-1, "y2"]) > 15 and abs(df.loc[i, "x2"] - df.loc[i-1, "x1"]) > 50: print("") #print(abs(df.loc[i, "x2"] - df.loc[i-1, "x1"])) print(df.loc[i, "text"], end=" ")# (df.loc[i, "x1"], df.loc[i, "x2"])
- Assistant