import pandas as pd from PIL import Image from pytesseract import pytesseract def convert_image_to_df(path_to_image: str) -> pd.DataFrame: """ Function takes images and converts text/numbers into usable dataframe params: - path_to_image (str) - location of the image file to process returns: - dataframe (pandas.DataFrame) - Dataframe containing converted text """ # Define path to tessaract executable pytesseract.tesseract_cmd = r"/opt/homebrew/Cellar/tesseract/5.2.0/bin/tesseract" # Open image with PIL img = Image.open(path_to_image) # Extract text from image text = pytesseract.image_to_string(img) # we could also convert image directly to dataframe but this didn't seem to work as expected # dataframe = pytesseract.image_to_data(img, lang='eng', output_type='data.frame') # print(dataframe) id_list = [] text_list = [] chunks = text.split("\n") for c in chunks[1:]: if len(c)>0: id_list.append(c.split(" ", 1)[0]) text_list.append(c.split(" ", 1)[1]) dataframe = pd.DataFrame( list(zip(id_list, text_list)), columns=["id", "text"], ) dataframe["id"] = dataframe["id"].astype(str).astype(int) return dataframe if __name__ == "__main__": df = convert_image_to_df('image/image.png')