Extract Text from Image to File

  • Share this:

Code introduction


This function uses the PIL library to open an image file, then uses the PyTesseract library to extract text from the image, and writes the extracted text to the specified output file.


Technology Stack : PIL, PyTesseract

Code Type : Function

Code Difficulty : Intermediate


                
                    
def extract_text_from_image(image_path, output_path):
    from PIL import Image
    from pytesseract import image_to_string

    # Open the image file
    img = Image.open(image_path)

    # Extract text from the image using PyTesseract
    text = image_to_string(img)

    # Save the extracted text to the output file
    with open(output_path, 'w') as file:
        file.write(text)