Certainly! 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():
# Directory containing the images
image_directory = "path/to/image/directory"
# Get the list of image file paths
image_files = [os.path.join(image_directory, file) for file in os.listdir(image_directory)]
# Create a multiprocessing pool
pool = Pool()
# Process the images in parallel
results = pool.map(process_image, image_files)
# Close the pool
pool.close()
pool.join()
# Print the OCR results
for i, result in enumerate(results):
if result is not None:
print(f"OCR Result for Image {i+1}:")
print(result)
print("---")
if __name__ == "__main__":
main()
In this code:
We define a function called process_image that takes an image file path as input. Inside this function, we open the image using PIL (Python Imaging Library) and perform OCR using the pytesseract.image_to_string function. If an exception occurs during processing, we print an error message and return None.
In the main function, we specify the directory containing the images and get the list of image file paths using os.listdir.
We create a multiprocessing pool using Pool() to parallelize the OCR process.
We use pool.map to apply the process_image function to each image file path in parallel. The map function distributes the image file paths among the available worker processes in the pool.
After processing all the images, we close the pool using pool.close() and wait for all the worker processes to finish using pool.join().
Finally, we iterate over the OCR results and print them if they are not None.
Note: Make sure you have the pytesseract library installed (pip install pytesseract) and have the Tesseract OCR engine installed on your system. You may need to provide the path to the Tesseract executable if it's not in the system's PATH.
This code parallelizes the OCR process by distributing the image files among multiple worker processes, allowing for faster processing of a large number of images. The number of worker processes used depends on the available CPU cores on your system.