Certainly! Below is the complete Python code that implements the steps you've outlined:
- Use an OCR tool like EasyOCR to extract all text from images.
- Use keyword search to find entity names and extract adjacent text as the value.
- Apply post-processing to clean up the extracted values.
- Evaluate the accuracy of the simple approach on your data.
This code assumes you have a directory of images and a CSV schema you've provided. We'll extract text from each image, search for specified entity names, extract the corresponding values, and evaluate the accuracy against ground truth labels.
# Import necessary libraries
import os
import easyocr
import cv2
import re
import pandas as pd
from glob import glob
# Initialize EasyOCR reader
reader = easyocr.Reader(['en']) # You can add other languages if needed
# Define the directory containing images
image_dir = 'path_to_your_image_directory' # Replace with your image directory path
# Get list of image files
image_files = glob(os.path.join(image_dir, '*.jpg')) # Adjust the extension if needed
# Initialize an empty list to store results
results = []
# Define a list of entity names you're interested in
entity_names = ['Entity_Name1', 'Entity_Name2', 'Entity_Name3'] # Replace with your entities
# Loop over each image file
for image_path in image_files:
# Read image
image = cv2.imread(image_path)
if image is None:
print(f'Error reading image {image_path}')
continue
# Perform OCR
result = reader.readtext(image)
# Combine all text into a single string
text = ' '.join([res[1] for res in result])
# Initialize a dictionary to store extracted values for this image
extracted_data = {'Image_Name': os.path.basename(image_path)}
# For each entity, search for it in the text and extract adjacent text as value
for entity in entity_names:
# Adjust the pattern based on how the entities appear in your text
pattern = r'{}\s*:\s*(.*?)(?=\s+\w+\s*:|$)'.format(re.escape(entity))
matches = re.findall(pattern, text, re.IGNORECASE)
if matches:
value = matches[0]
else:
# If not found, set value as None or empty string
value = ''
# Apply post-processing to clean the value
value = value.strip().replace('\n', '')
# Store the value in the dictionary
extracted_data[entity] = value
# Append the extracted data to the results list
results.append(extracted_data)
# Create a DataFrame from the results
df_extracted = pd.DataFrame(results)
# Save the DataFrame to a CSV file
output_csv_path = 'extracted_data.csv'
df_extracted.to_csv(output_csv_path, index=False)
# Display the DataFrame
print(df_extracted)
# Evaluation code (assuming you have ground truth labels)
# Replace 'ground_truth.csv' with your actual ground truth CSV file
ground_truth_csv = 'ground_truth.csv' # Replace with your ground truth CSV file
# Read ground truth labels
df_ground_truth = pd.read_csv(ground_truth_csv)
# Merge extracted results with ground truth labels on 'Image_Name'
df_merged = pd.merge(df_extracted, df_ground_truth, on='Image_Name', suffixes=('_extracted', '_ground_truth'))
# Initialize counters for accuracy calculation
total_entities = 0
correct_entities = 0
# Loop over the entities to calculate accuracy
for entity in entity_names:
total_entities += len(df_merged)
correct = df_merged.apply(lambda row: row[f'{entity}_extracted'].strip().lower() == row[f'{entity}_ground_truth'].strip().lower(), axis=1)
correct_entities += correct.sum()
accuracy = correct.sum() / len(df_merged) * 100
print(f'Accuracy for {entity}: {accuracy:.2f}%')
# Overall accuracy
overall_accuracy = (correct_entities / total_entities) * 100
print(f'Overall accuracy: {overall_accuracy:.2f}%')
Instructions to Run the Code:
-
Install Required Libraries:
Make sure you have the necessary libraries installed. You can install them using pip:
pip install easyocr opencv-python pandas
-
Prepare Your Data:
- Images: Place all your images in a directory and update
image_dir with the path to that directory.
- Entities: Replace
entity_names with a list of the entities you want to extract.
- Ground Truth CSV: Prepare a CSV file (e.g.,
ground_truth.csv) containing the ground truth values for each image. This file should have columns: Image_Name, Entity_Name1, Entity_Name2, Entity_Name3, etc.
-
Adjust the Regular Expression Pattern:
The regular expression pattern used in the code assumes that entities in your text are followed by a colon (:) and then the value (e.g., Entity_Name1: Value1). If your text has a different format, you may need to adjust the pattern accordingly.
-
Run the Code:
Execute the script using Python. It will process each image, extract the specified entities, save the results to extracted_data.csv, and print out the accuracy of the extraction compared to your ground truth data.
Explanation of the Code:
-
Text Extraction:
We use EasyOCR to extract text from each image. The results are combined into a single string for easy searching.
-
Entity Extraction:
For each entity, we use a regular expression to find patterns like Entity_Name: Value. We extract the value associated with each entity.
-
Post-processing:
Extracted values are cleaned by stripping whitespace and removing newline characters.
-
Results Storage:
The extracted data for each image is stored in a list of dictionaries, which is then converted into a pandas DataFrame and saved to a CSV file.
-
Performance Evaluation:
We compare the extracted values against ground truth labels to calculate the accuracy for each entity and the overall accuracy.
Example of Ground Truth CSV (ground_truth.csv):
Image_Name,Entity_Name1,Entity_Name2,Entity_Name3
image1.jpg,Value1,Value2,Value3
image2.jpg,Value4,Value5,Value6
...
Make sure that the Image_Name in your ground truth CSV matches exactly with the file names in your image directory.
Important Notes:
-
OCR Limitations:
Keep in mind that OCR is not perfect. The accuracy of text extraction can be affected by image quality, font styles, and other factors.
-
Adjustments and Improvements:
Depending on the performance, you might need to improve the OCR process or the entity extraction method. Consider cleaning the images, enhancing contrast, or using more advanced NLP techniques for entity recognition.
-
Error Handling:
The code includes basic error handling for image reading failures. You might want to enhance error handling and logging for robustness.
-
Dependencies:
This code depends on EasyOCR, OpenCV, and pandas. Ensure they are installed in your environment.
Next Steps:
-
Assess Performance:
After running the code, review the accuracy metrics. If the accuracy is acceptable, you can proceed with this method.
-
Optimization:
If accuracy is not acceptable, consider refining the regular expressions, improving image preprocessing, or using more advanced OCR techniques.
-
Scaling Up:
For large datasets, you might want to optimize the code for performance or consider parallel processing.
Let me know if you need further assistance or modifications to the code!