Here's an example code that demonstrates how to perform OCR using the pytesseract library and parallelize the process using the multiprocessing module in Python:
python
import os
from multiprocessing import Pool
from PIL import Image
import pytesseract
def process_image(image_path):
try:
# Open the image using PIL
image = Image.open(image_path)
# Perform OCR using pytesseract
text = pytesseract.image_to_string(image)
return text
except Exception as e:
print(f"Error processing image {image_path}: {str(e)}")
return None
def main():
# Set the path to the directory containing the images
image_directory = "path/to/image/directory"
# Get a list of image file paths
image_files = [os.path.join(image_directory, f) for f in os.listdir(image_directory) if f.endswith((".jpg", ".png"))]
# Create a multiprocessing pool with the desired number of processes
num_processes = 4
pool = Pool(processes=num_processes)
# Process the images in parallel
results = pool.map(process_image, image_files)
# Close the pool and wait for the processes to finish
pool.close()
pool.join()
# Print the OCR results for each image
for i, text in enumerate(results):
if text is not None:
print(f"OCR result for image {image_files[i]}:")
print(text)
print("---")
if __name__ == "__main__":
main()
In this code:
We define a process_image function that takes an image path as input. It opens the image using PIL (Python Imaging Library), performs OCR using pytesseract's image_to_string function, and returns the extracted text. If an error occurs during processing, it prints an error message and returns None.
In the main function, we set the path to the directory containing the images and get a list of image file paths using os.listdir.
We create a multiprocessing pool with the desired number of processes using Pool(processes=num_processes). Adjust num_processes based on your system's capabilities.
We use pool.map to apply the process_image function to each image file path in parallel. The map function distributes the work among the available processes in the pool.
After processing all the images, we close the pool and wait for the processes to finish using pool.close() and pool.join().
Finally, we iterate over the OCR results and print the extracted text for each image.
Make sure to install the required dependencies (pytesseract and Pillow) before running the code. You can install them using pip install pytesseract Pillow.
Note: Ensure that you have the Tesseract OCR engine installed on your system and the pytesseract library is properly configured with the path to the Tesseract executable.
This code demonstrates how to parallelize the OCR process using multiprocessing to speed up the processing of multiple images. The number of processes can be adjusted based on your system's capabilities and the number of available cores.