''' Image Optical Character Recognition (OCR) utils module. ''' import numpy as np import easyocr from PIL import Image # initialise EasyOCR OCR_reader = easyocr.Reader(lang_list=['en']) def get_ocr_output(image: Image.Image) -> list[tuple]: ''' Detects characters in images and returns the machine generated text and bounding boxes for each word or region. Args: image: The pillow image to extract data from. Returns: A list of tupples containing bounding box data, text, and confidence score. ''' output = OCR_reader.readtext(np.array(image)) return output def convert_4p_bbox_to_2p(bbox: list[list[int]]) -> list[int]: ''' converts a four-points bounding box format to two-points bounding box format i.e. [[x0y0], [x1y0], [x0y1], [x1y1]] => [x0,y0,x1,y1] Args: bbox: The four-points bounding boxes data to convert Returns: The two-point bounding box format ''' # return min x, min y, max x, and max y (casting from numpy int32 to python int also) return [ int(min(p[0] for p in bbox)), #x0 int(min(p[1] for p in bbox)), #y0 int(max(p[0] for p in bbox)), #x1 int(max(p[1] for p in bbox)) #y1 ] def extract_texts_and_bboxes(image: Image.Image) -> dict[str,list]: ''' Runs OCR process on an image, extracts the texts as one list and the corresponding bounding boxes as another list. Note: The bounding boxes are in 2-points bounding box form. Args: image: Image to extract information from Returns: texts: a list of texts recognised in the image bboxes: a list of the corresponding bounding boxes for each text ''' ocr_output = get_ocr_output(image=image) # get OCR output image_texts = [] image_bboxes = [] for bbox, text, _ in ocr_output: image_texts.append(text) image_bboxes.append(convert_4p_bbox_to_2p(bbox=bbox)) # the bounding boxes are in 4-point format which needs to be converted to 2-point format (x0y0 & x1y1) that LayoutLMv3 works with # combine the extracted text and bbox list as seperate fields in a dictionary return { "texts": image_texts, "bboxes": image_bboxes }