-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_processor.py
More file actions
183 lines (146 loc) · 6.21 KB
/
image_processor.py
File metadata and controls
183 lines (146 loc) · 6.21 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from PIL import Image, ImageEnhance, ImageFilter
import os
from typing import List, Dict, Any, Optional, Tuple
import uuid
from pathlib import Path
from app.config.settings import settings
from app.utils.logging_utils import get_logger
from app.services.ocr_service import OCRService
logger = get_logger(__name__)
class ImageProcessor:
"""Servizio per il processamento di immagini"""
def __init__(self):
"""Inizializza il servizio di processamento immagini"""
self.ocr_service = OCRService()
logger.info("Image Processor inizializzato")
def preprocess_image(self, image_path: str) -> str:
"""
Preprocessa un'immagine per migliorare i risultati dell'OCR
Args:
image_path: Percorso dell'immagine
Returns:
Percorso dell'immagine preprocessata
"""
try:
logger.info(f"Preprocessamento immagine: {image_path}")
# Carica l'immagine
image = Image.open(image_path)
# Converti in scala di grigi
if image.mode != 'L':
image = image.convert('L')
# Aumenta il contrasto
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(2.0)
# Applica filtro di nitidezza
image = image.filter(ImageFilter.SHARPEN)
# Applica soglia (binarizzazione)
threshold_value = 200
image = image.point(lambda p: 255 if p > threshold_value else 0)
# Salva l'immagine preprocessata
temp_dir = Path(settings.TEMP_FOLDER)
temp_dir.mkdir(parents=True, exist_ok=True)
preprocessed_path = temp_dir / f"preprocessed_{uuid.uuid4()}.png"
image.save(preprocessed_path)
logger.info(f"Immagine preprocessata salvata in: {preprocessed_path}")
return str(preprocessed_path)
except Exception as e:
logger.error(f"Errore durante il preprocessamento dell'immagine {image_path}: {e}")
return image_path # Restituisci l'immagine originale in caso di errore
def extract_text(self, image_path: str, preprocess: bool = True) -> str:
"""
Estrae il testo da un'immagine
Args:
image_path: Percorso dell'immagine
preprocess: Se True, preprocessa l'immagine prima dell'OCR
Returns:
Testo estratto dall'immagine
"""
try:
if preprocess:
preprocessed_path = self.preprocess_image(image_path)
text = self.ocr_service.extract_text_from_image(preprocessed_path)
# Rimuovi l'immagine preprocessata
if preprocessed_path != image_path:
os.remove(preprocessed_path)
else:
text = self.ocr_service.extract_text_from_image(image_path)
return text
except Exception as e:
logger.error(f"Errore durante l'estrazione del testo dall'immagine {image_path}: {e}")
return ""
def analyze_image(self, image_path: str) -> Dict[str, Any]:
"""
Analizza un'immagine ed estrae informazioni
Args:
image_path: Percorso dell'immagine
Returns:
Dizionario con informazioni sull'immagine
"""
try:
logger.info(f"Analisi immagine: {image_path}")
# Carica l'immagine
image = Image.open(image_path)
# Ottieni informazioni di base
width, height = image.size
format_type = image.format
mode = image.mode
# Preprocessa l'immagine
preprocessed_path = self.preprocess_image(image_path)
# Esegui OCR sull'immagine preprocessata
ocr_data = self.ocr_service.get_ocr_data(preprocessed_path)
# Rimuovi l'immagine preprocessata
if preprocessed_path != image_path:
os.remove(preprocessed_path)
# Raccogli i risultati
analysis = {
"image_info": {
"width": width,
"height": height,
"format": format_type,
"mode": mode,
"aspect_ratio": width / height if height != 0 else 0
},
"ocr_data": ocr_data
}
logger.info(f"Analisi immagine completata per {image_path}")
return analysis
except Exception as e:
logger.error(f"Errore durante l'analisi dell'immagine {image_path}: {e}")
return {
"image_info": {},
"ocr_data": {
"text": "",
"confidence": 0,
"words_count": 0,
"has_text": False,
"error": str(e)
}
}
def process_image(self, image_path: str) -> Tuple[str, Dict[str, Any]]:
"""
Processa un'immagine ed estrae testo e informazioni
Args:
image_path: Percorso dell'immagine
Returns:
Tupla con testo estratto e informazioni sull'immagine
"""
try:
logger.info(f"Processamento immagine: {image_path}")
# Analizza l'immagine
analysis = self.analyze_image(image_path)
# Estrai il testo
text = analysis["ocr_data"]["text"]
logger.info(f"Processamento immagine completato per {image_path}")
return text, analysis
except Exception as e:
logger.error(f"Errore durante il processamento dell'immagine {image_path}: {e}")
return "", {
"image_info": {},
"ocr_data": {
"text": "",
"confidence": 0,
"words_count": 0,
"has_text": False,
"error": str(e)
}
}