File size: 2,672 Bytes
c34a5c4
 
 
 
6daffca
c34a5c4
 
 
 
 
6daffca
c34a5c4
6daffca
c34a5c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52a5ee0
c34a5c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6daffca
c34a5c4
 
 
8c3ee66
c34a5c4
 
 
 
 
 
 
6daffca
c34a5c4
 
 
 
 
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
import logging
from PIL import Image
import cv2
import numpy as np

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class OCREngine:
    def __init__(self):
        self.supported_languages = ['eng']
    
    def preprocess_image(self, image_path: str) -> np.ndarray:
        """Preprocess image for better OCR results"""
        try:
            # Read image
            image = cv2.imread(image_path)
            if image is None:
                raise ValueError(f"Could not read image from {image_path}")
            
            # Convert to grayscale
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            
            # Apply noise removal
            denoised = cv2.medianBlur(gray, 3)
            
            # Apply thresholding
            _, thresh = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
            
            return thresh
            
        except Exception as e:
            logger.error(f"Error preprocessing image: {e}")
            # Return original image if preprocessing fails
            image = cv2.imread(image_path)
            return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    def extract_text(self, image_path: str, preprocess: bool = True) -> str:
        """Extract text from image using OCR"""
        try:
            # Try to use pytesseract if available
            try:
                import pytesseract
                tesseract_available = True
            except ImportError:
                tesseract_available = False
                logger.warning("pytesseract not available, using fallback method")
            
            if preprocess:
                processed_image = self.preprocess_image(image_path)
                pil_image = Image.fromarray(processed_image)
            else:
                pil_image = Image.open(image_path)
            
            if tesseract_available:
                # Configure Tesseract
                custom_config = r'--oem 3 --psm 6'
                
                # Extract text
                text = pytesseract.image_to_string(pil_image, config=custom_config)
                logger.info(f"Successfully extracted text using Tesseract from {image_path}")
            else:
                # Fallback: Return empty text
                text = "OCR functionality requires pytesseract. Please install tesseract-ocr on your system."
                logger.warning("Using fallback OCR method")
            
            return text.strip()
            
        except Exception as e:
            logger.error(f"OCR extraction failed: {e}")
            return f"OCR Error: {str(e)}"