new images compressed + thumbnail, deliver all images
This commit is contained in:
parent
711b9d543f
commit
8bf95b4f38
|
|
@ -45,27 +45,46 @@ def create_debug_directory(dir_name):
|
||||||
|
|
||||||
def preprocess_image(image, debug_dir):
|
def preprocess_image(image, debug_dir):
|
||||||
"""
|
"""
|
||||||
Verarbeitet das Bild und speichert Zwischenergebnisse im angegebenen Verzeichnis
|
Verarbeitet das Bild und speichert Zwischenergebnisse im angegebenen Verzeichnis,
|
||||||
|
einschließlich einer komprimierten JPG-Version und eines Thumbnails.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
# Umwandlung in Graustufen
|
||||||
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
||||||
|
# Anwendung von CLAHE zur Kontrastverbesserung
|
||||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
||||||
enhanced = clahe.apply(gray)
|
enhanced = clahe.apply(gray)
|
||||||
|
# Rauschunterdrückung
|
||||||
denoised = cv2.fastNlMeansDenoising(enhanced)
|
denoised = cv2.fastNlMeansDenoising(enhanced)
|
||||||
|
# Optional: Binärschwellenwert (auskommentiert)
|
||||||
# _, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
# _, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
||||||
|
|
||||||
# Speichern der Zwischenergebnisse im spezifischen Verzeichnis
|
# Speichern der Zwischenergebnisse im spezifischen Verzeichnis
|
||||||
cv2.imwrite(os.path.join(debug_dir, 'gray.png'), gray)
|
cv2.imwrite(os.path.join(debug_dir, 'gray.png'), gray)
|
||||||
cv2.imwrite(os.path.join(debug_dir, 'enhanced.png'), enhanced)
|
cv2.imwrite(os.path.join(debug_dir, 'enhanced.png'), enhanced)
|
||||||
cv2.imwrite(os.path.join(debug_dir, 'denoised.png'), denoised)
|
cv2.imwrite(os.path.join(debug_dir, 'denoised.png'), denoised)
|
||||||
# cv2.imwrite(os.path.join(debug_dir, 'binary.png'), binary)
|
# cv2.imwrite(os.path.join(debug_dir, 'binary.png'), binary)
|
||||||
|
|
||||||
|
# Speichern der komprimierten JPG-Version des Originalbildes
|
||||||
|
compressed_jpg_path = os.path.join(debug_dir, 'original_compressed.jpg')
|
||||||
|
original_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
||||||
|
cv2.imwrite(compressed_jpg_path, original_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 80]) # Qualität auf 80 setzen
|
||||||
|
logger.info(f"Komprimiertes Original JPG gespeichert: {compressed_jpg_path}")
|
||||||
|
|
||||||
|
# Erstellen und Speichern des Thumbnails
|
||||||
|
thumbnail_path = os.path.join(debug_dir, 'thumbnail.jpg')
|
||||||
|
image_pil = Image.fromarray(denoised)
|
||||||
|
image_pil.thumbnail((128, 128)) # Thumbnail-Größe auf 128x128 Pixel setzen
|
||||||
|
image_pil.save(thumbnail_path, 'JPEG')
|
||||||
|
logger.info(f"Thumbnail gespeichert: {thumbnail_path}")
|
||||||
|
|
||||||
logger.info(f"Debug images saved in: {debug_dir}")
|
logger.info(f"Debug images saved in: {debug_dir}")
|
||||||
return denoised
|
return denoised
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Preprocessing error: {str(e)}")
|
logger.error(f"Preprocessing error: {str(e)}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/ocr', methods=['POST'])
|
@app.route('/api/ocr', methods=['POST'])
|
||||||
def ocr_endpoint():
|
def ocr_endpoint():
|
||||||
try:
|
try:
|
||||||
|
|
@ -202,32 +221,52 @@ def ocr_endpoint():
|
||||||
'debug_dir': debug_dir if 'debug_dir' in locals() else None
|
'debug_dir': debug_dir if 'debug_dir' in locals() else None
|
||||||
}), 500
|
}), 500
|
||||||
|
|
||||||
@app.route('/api/debug_image/<name>', methods=['GET'])
|
@app.route('/api/debug_image/<name>/<filename>', methods=['GET'])
|
||||||
def get_debug_image(name):
|
def get_debug_image(name, filename):
|
||||||
"""
|
"""
|
||||||
Gibt das Originalbild unter 'debug_images/[name]/original.png' direkt als image/png zurück.
|
Gibt das angeforderte Bild unter 'debug_images/[name]/[filename]' direkt zurück.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Sicherheitsmaßnahme: Nur erlaubte Zeichen im Namen
|
# Sicherheitsmaßnahme: Nur erlaubte Zeichen im Verzeichnisnamen
|
||||||
if not all(c.isalnum() or c in ('_', '-') for c in name):
|
if not all(c.isalnum() or c in ('_', '-') for c in name):
|
||||||
logger.warning(f"Ungültiger Bildname angefordert: {name}")
|
logger.warning(f"Ungültiger Verzeichnisname angefordert: {name}")
|
||||||
return jsonify({'error': 'Invalid image name'}), 400
|
return jsonify({'error': 'Invalid directory name'}), 400
|
||||||
|
|
||||||
image_path = os.path.join('debug_images', name, 'original.png')
|
# Sicherheitsmaßnahme: Nur erlaubte Zeichen im Dateinamen
|
||||||
|
if not all(c.isalnum() or c in ('_', '-', '.',) for c in filename):
|
||||||
|
logger.warning(f"Ungültiger Dateiname angefordert: {filename}")
|
||||||
|
return jsonify({'error': 'Invalid file name'}), 400
|
||||||
|
|
||||||
|
# Vollständigen Pfad zum Bild erstellen
|
||||||
|
image_path = os.path.join('debug_images', name, filename)
|
||||||
|
|
||||||
|
# Überprüfen, ob die Datei existiert
|
||||||
if not os.path.isfile(image_path):
|
if not os.path.isfile(image_path):
|
||||||
logger.warning(f"Bild nicht gefunden: {image_path}")
|
logger.warning(f"Bild nicht gefunden: {image_path}")
|
||||||
return jsonify({'error': 'Image not found'}), 404
|
return jsonify({'error': 'Image not found'}), 404
|
||||||
|
|
||||||
|
# Bestimmen des MIME-Typs basierend auf der Dateiendung
|
||||||
|
mime_type = 'image/png' # Standard-MIME-Typ
|
||||||
|
if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
|
||||||
|
mime_type = 'image/jpeg'
|
||||||
|
elif filename.lower().endswith('.gif'):
|
||||||
|
mime_type = 'image/gif'
|
||||||
|
elif filename.lower().endswith('.bmp'):
|
||||||
|
mime_type = 'image/bmp'
|
||||||
|
elif filename.lower().endswith('.tiff') or filename.lower().endswith('.tif'):
|
||||||
|
mime_type = 'image/tiff'
|
||||||
|
|
||||||
return send_file(
|
return send_file(
|
||||||
image_path,
|
image_path,
|
||||||
mimetype='image/png',
|
mimetype=mime_type,
|
||||||
as_attachment=False
|
as_attachment=False
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Fehler beim Abrufen des Bildes '{name}': {str(e)}")
|
logger.error(f"Fehler beim Abrufen des Bildes '{name}/{filename}': {str(e)}")
|
||||||
logger.error(traceback.format_exc())
|
logger.error(traceback.format_exc())
|
||||||
return jsonify({'error': 'Failed to retrieve image'}), 500
|
return jsonify({'error': 'Failed to retrieve image'}), 500
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host='0.0.0.0', port=5000, debug=True)
|
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||||
Loading…
Reference in New Issue