Creating an advanced Python code to perform the requested task involves several steps, such as loading the different files, interpreting the OCR output, and then matching the entities with the bounding boxes. It would also include drawing the bounding boxes on the image based on the locations specified in the OCR output.
Below is a conceptual Python script using the pandas library for handling CSV data, the json library for parsing JSON, and Pillow (PIL) for image processing:
Please note this script assumes:
- The JSON extracted entities have the exact text as found in the OCR output.
- The CSV file contains OCR data that can be accurately mapped to the JSON entities (text values match exactly).
- The entities may span across multiple words or lines, so we need to find bounding boxes for phrases (potentially multi-token).
- The script does not include spell correction or string similarity matching.
- The image is in the correct orientation as per the OCR data.
Firstly, you must install Pillow library if not already installed:
pip install Pillow pandas
Here is the Python script:
import json
import pandas as pd
from PIL import Image, ImageDraw
def load_and_preprocess_ocr_data(csv_path):
# Load the OCR CSV data into a DataFrame
df_ocr = pd.read_csv(csv_path)
# Create a column 'coordinates' which is a tuple (x1, y1, x2, y2)
df_ocr['coordinates'] = list(zip(df_ocr.left, df_ocr.top, df_ocr.right, df_ocr.bottom))
# Concatenate all text into a document sequence with space
df_ocr['full_text'] = df_ocr['text'].astype(str).apply(lambda x: x.strip())
# Return the preprocessed data
return df_ocr
def search_entity_in_ocr(entity, ocr_data):
# This function will search for an entity span in the OCR data
# and return the bounding box coordinates of that entity.
# Split the entity if it's made up of multiple tokens
tokens = entity.split()
spans = []
if len(tokens) == 1:
# Simple case, single token entity.
span = ocr_data[ocr_data['full_text'] == entity]['coordinates']
if not span.empty:
spans.append(span.iloc[0])
else:
# Multi-token entity; find spans for each token
for token in tokens:
span = ocr_data[ocr_data['full_text'] == token]['coordinates']
if not span.empty:
spans.append(span.iloc[0])
# find groups of consecutive boxes assuming ordered data
if len(spans) > 1:
groups = []
current_group = [spans[0]]
last_right = spans[0][2] # Initialize with the right coordinate of the first span
for span in spans[1:]:
# If the next word is on the same line and adjacent to or below the previous,
# consider it part of the same entity.
if span[1] == current_group[-1][1] and span[0] >= last_right:
current_group.append(span)
last_right = span[2]
else:
groups.append(current_group)
current_group = [span]
last_right = span[2]
groups.append(current_group) # Adding the last group
# As entities can span across multiple groups (lines), we will combine all group spans.
combined_span = [min([c[0] for group in groups for c in group]), # min left
min([c[1] for group in groups for c in group]), # min top
max([c[2] for group in groups for c in group]), # max right
max([c[3] for group in groups for c in group])] # max bottom
spans = [tuple(combined_span)]
# Return the first bounding box coordinates matching the entity.
# If the entity is not found, return None.
return spans[0] if spans else None
def draw_bounding_boxes(image_path, ocr_data, entities):
# Open the image file
img = Image.open(image_path).convert("RGB")
draw = ImageDraw.Draw(img)
for key, value in entities.items():
for entity, text in value.items():
if text: # Skip empty entity values
bounding_box = search_entity_in_ocr(text, ocr_data)
if bounding_box:
# Draw the bounding box
draw.rectangle(bounding_box, outline="red", width=2)
# Save or display the image with bounding boxes
img.show()
# Load the OCR data from CSV
csv_path = 'path_to_ocr_output.csv'
ocr_data = load_and_preprocess_ocr_data(csv_path)
# Load JSON data with extracted entities
json_path = 'path_to_extracted_entities.json'
with open(json_path) as json_file:
json_data = json.load(json_file)
# Extract entities from JSON (flattens the JSON structure)
entities = {category: details for category, details in json_data.items() if isinstance(details, dict)}
# The path to the image file.
image_path = 'path_to_image_file.jpg'
# Draw the bounding boxes on the image
draw_bounding_boxes(image_path, ocr_data, entities)
To run the above Python script, you will need to provide the actual file paths for the image ('path_to_image_file.jpg'), the JSON file containing the extracted entities ('path_to_extracted_entities.json'), and the CSV file containing the OCR output ('path_to_ocr_output.csv').
Remember that handling corner cases like entities spanning across multiple blocks or having different orientations will require a more complex solution and potentially different OCR data structures. Moreover, the code above assumes that the OCR output CSV data is clean and ordered as per the image content. If the OCR results are unordered or have noise, additional data pre-processing steps will be required.
Lastly, ensure you have the correct version of Pillow installed and your Python environment is set up to execute the above code.