File size: 5,027 Bytes
6715b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from typing import List, Dict, Optional
import os
from PIL import Image
import pytesseract

def extract_text_from_frame(frame_path: str, lang: Optional[str] = None, config: str = '') -> List[Dict[str, any]]:
    """Returns text found in frame using OCR (pytesseract).

    Args:
        frame_path: Path to the image file.
        lang: Language for Tesseract to use (e.g., 'eng', 'fra'). If None, Tesseract default (usually English) is used.
        config: Additional Tesseract configuration options (e.g., '--psm 6').

    Returns:
        A list of dictionaries, where each dictionary contains detailed data for a recognized text block.
        Keys include 'level', 'page_num', 'block_num', 'par_num', 'line_num', 'word_num',
        'left', 'top', 'width', 'height', 'conf' (confidence), and 'text'.
        Returns an empty list if no text is found or in case of an error.
    """
    if not os.path.exists(frame_path):
        raise FileNotFoundError(f"Frame file not found: {frame_path}")

    try:
        img = Image.open(frame_path)
        # Perform OCR using image_to_data to get structured information including bounding boxes and confidence
        # Output type is pandas DataFrame by default, convert to dict for easier use
        ocr_data = pytesseract.image_to_data(img, lang=lang, config=config, output_type=pytesseract.Output.DICT)
        
        extracted_elements = []
        num_items = len(ocr_data['text'])

        for i in range(num_items):
            # Filter out empty text results and results with very low confidence (e.g., placeholder blocks)
            # Tesseract returns -1 for confidence of blocks that are not actual words (e.g. page/block separators)
            # We will only consider items that have actual text and a non-negative confidence.
            text = ocr_data['text'][i].strip()
            confidence = int(ocr_data['conf'][i]) # Convert to int, as Tesseract provides it like this

            if text and confidence > 0: # Consider only words with positive confidence
                element = {
                    "level": ocr_data['level'][i],
                    "page_num": ocr_data['page_num'][i],
                    "block_num": ocr_data['block_num'][i],
                    "par_num": ocr_data['par_num'][i],
                    "line_num": ocr_data['line_num'][i],
                    "word_num": ocr_data['word_num'][i],
                    "left": ocr_data['left'][i],
                    "top": ocr_data['top'][i],
                    "width": ocr_data['width'][i],
                    "height": ocr_data['height'][i],
                    "conf": confidence,
                    "text": text,
                }
                extracted_elements.append(element)
        
        print(f"Extracted {len(extracted_elements)} text elements from {frame_path}.")
        return extracted_elements

    except pytesseract.TesseractNotFoundError:
        print("Tesseract is not installed or not in your PATH. Please install Tesseract.")
        raise
    except RuntimeError as e:
        # Handles cases like Tesseract not finding language data files
        print(f"Runtime error during OCR for {frame_path}: {e}")
        raise
    except Exception as e:
        print(f"An unexpected error occurred during OCR for {frame_path}: {e}")
        # Return empty list for other errors, or re-raise if critical
        return []

# Example usage (for testing):
# if __name__ == '__main__':
#     # Create a dummy image file with some text for testing
#     from PIL import Image, ImageDraw, ImageFont
#     import numpy as np
#     import cv2 # for the dummy image creation

#     dummy_ocr_image_path = "dummy_ocr_frame.png"
#     try:
#         img = Image.new('RGB', (400, 100), color = (255, 255, 255))
#         d = ImageDraw.Draw(img)
#         try:
#             # Try to load a common font, fall back if not found
#             font = ImageFont.truetype("arial.ttf", 20)
#         except IOError:
#             font = ImageFont.load_default()
#         d.text((10,10), "Hello World\nTest OCR 123", fill=(0,0,0), font=font)
#         img.save(dummy_ocr_image_path)
#         print(f"Created dummy OCR image: {dummy_ocr_image_path}")

#         text_data = extract_text_from_frame(dummy_ocr_image_path, lang='eng')
#         if text_data:
#             print("\nExtracted text data:")
#             for item in text_data:
#                 print(f"  Text: '{item['text']}', Conf: {item['conf']}, BBox: [{item['left']}, {item['top']}, {item['width']}, {item['height']}]")
#         else:
#             print("No text data extracted or an error occurred.")
            
#     except pytesseract.TesseractNotFoundError:
#         print("TEST SKIPPED: Tesseract is not installed or not in your PATH.")
#     except Exception as e:
#         print(f"Error in test setup or execution: {e}")
#     finally:
#         if os.path.exists(dummy_ocr_image_path):
#             os.remove(dummy_ocr_image_path)
#             print(f"Cleaned up {dummy_ocr_image_path}")