pyt_utils/image_preprocessing Usage Scenarios¶
Overview¶
The image_preprocessing module is designed for flexible integration into various document processing workflows. Whether you're building a simple OCR app or a complex document management system, these usage patterns will help you get the most out of the preprocessing pipeline.
Basic Usage Patterns¶
1. Simple Image Preprocessing¶
from pyt_utils.image_preprocessing import fix_image
import cv2
# Basic preprocessing - auto-detects and corrects everything
image = fix_image("scanned_document.jpg")
# Save result
cv2.imwrite("processed.jpg", image)
2. Batch PDF Processing¶
from pyt_utils.image_preprocessing import cli_fix_pdf
# Process entire PDF automatically
success = cli_fix_pdf("input.pdf", "clean_output.pdf")
3. Custom Processing Pipeline¶
from pyt_utils.image_preprocessing import fix_image
import pytesseract
# Manual pipeline control
image = fix_image("document.jpg", rotate=True, debug_draw=True)
# Custom OCR processing
text = pytesseract.image_to_string(image)
print(f"Extracted text: {text[:100]}...")
Advanced Scenarios¶
4. Interactive Debugging & Manual Correction¶
from pyt_utils.image_preprocessing import fix_image
# Enable interactive debug windows
image = fix_image("problematic_scan.jpg",
interactive_debug=True,
debug=True)
5. Selective PDF Processing with Manual Intervention¶
from pyt_utils.image_preprocessing import cli_fix_pdf
# Process most pages automatically, intervene manually on tricky pages
success = cli_fix_pdf("book.pdf", "clean_book.pdf",
manual_intervals="1-3,47,89-91") # First few pages often problematic
6. Debug Overlay for Algorithm Tuning¶
from pyt_utils.image_preprocessing import fix_image
import matplotlib.pyplot as plt
# Get debug overlay instead of processed image
debug_overlay = fix_image("sample.jpg", debug_draw=True)
# Visualize detection results
plt.imshow(cv2.cvtColor(debug_overlay, cv2.COLOR_BGR2RGB))
plt.title("Detected Text Zones (Green Overlay)")
plt.show()
Integration Patterns¶
7. Integration with Existing OCR Systems¶
from pyt_utils.image_preprocessing import fix_image
import pytesseract
class EnhancedOCR:
def __init__(self):
pass
def process_document(self, image_path):
# Preprocess for optimal OCR
preprocessed = fix_image(image_path, rotate=True, maximize_height=True)
# Extract text with confidence
data = pytesseract.image_to_data(preprocessed, output_type=pytesseract.Output.DICT)
text = pytesseract.image_to_string(preprocessed)
# Analyze confidence
confidences = [float(c) for c in data['conf'] if c != -1]
avg_confidence = sum(confidences) / len(confidences)
return {
'text': text,
'confidence': avg_confidence,
'preprocessed_image': preprocessed
}
8. Quality Assurance Pipeline¶
from pyt_utils.image_preprocessing import fix_image, cli_fix_pdf
import os
class DocumentProcessor:
def __init__(self, quality_threshold=0.75):
self.threshold = quality_threshold
def process_and_validate(self, input_path, output_path):
"""Process document and ensure quality meets threshold"""
# Process document
success = cli_fix_pdf(input_path, output_path)
if not success:
raise Exception("Processing failed")
# Quality check - re-analyze first page
with fitz.open(output_path) as doc:
first_page = self._pdf_page_to_image(doc, 0)
# Get debug overlay to check zone quality
quality_overlay = fix_image(first_page, debug_draw=True, interactive_debug=False)
# Simple quality metric: how much of image is detected as text zone
text_pixels = cv2.countNonZero(cv2.cvtColor(quality_overlay, cv2.COLOR_BGR2GRAY))
total_pixels = quality_overlay.shape[0] * quality_overlay.shape[1] * quality_overlay.shape[2]
zone_ratio = text_pixels / total_pixels
if zone_ratio < self.threshold:
print(".2%"
# Could trigger manual review here
return False
return True
def _pdf_page_to_image(self, doc, page_num):
"""Extract page as image for analysis"""
# Implementation would use fitz/PIL
pass
9. Automated Document Classification Pipeline¶
from pyt_utils.image_preprocessing import fix_image
import numpy as np
class DocumentClassifier:
def __init__(self):
pass
def classify_and_process(self, image_path):
"""Classify document type based on layout analysis"""
# Get debug overlay to analyze layout
debug_img = fix_image(image_path, debug_draw=True)
layout_features = self._extract_layout_features(debug_img)
doc_type = self._classify_layout(layout_features)
print(f"Detected document type: {doc_type}")
# Apply type-specific processing
return fix_image(image_path, **self._get_processing_params(doc_type))
def _extract_layout_features(self, debug_overlay):
"""Extract geometric features from text zone overlay"""
# Convert to binary mask
gray = cv2.cvtColor(debug_overlay, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
# Find contours/text zones
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
features = {
'zone_count': len(contours),
'total_area': sum(cv2.contourArea(c) for c in contours),
'zone_heights': [cv2.boundingRect(c)[3] for c in contours],
'zone_widths': [cv2.boundingRect(c)[2] for c in contours]
}
return features
def _classify_layout(self, features):
"""Simple rule-based classification"""
if features['zone_count'] == 1:
return "single_column"
elif features['zone_count'] == 2 and max(features['zone_widths']) / min(features['zone_widths']) > 3:
return "two_columns"
elif features['zone_count'] > 10:
return "complex_document"
else:
return "unknown"
def _get_processing_params(self, doc_type):
"""Get optimized processing parameters per document type"""
params_map = {
"single_column": {"rotate": True, "maximize_height": True},
"two_columns": {"rotate": True, "maximize_height": False},
"complex_document": {"rotate": True, "debug_draw": True}, # Might need manual review
}
return params_map.get(doc_type, {"rotate": True})
Performance Optimization¶
10. Memory-Efficient Large Document Processing¶
import psutil
from pyt_utils.image_preprocessing import cli_fix_pdf
def process_large_pdf(input_pdf, output_pdf, memory_limit_gb=2):
"""Process large PDFs with memory monitoring"""
process = psutil.Process()
initial_memory = process.memory_info().rss / 1024 / 1024 / 1024
print(f"Initial memory: {initial_memory:.2f} GB")
# Process PDF
success = cli_fix_pdf(input_pdf, output_pdf)
final_memory = process.memory_info().rss / 1024 / 1024 / 1024
print(f"Final memory: {final_memory:.2f} GB")
if final_memory - initial_memory > memory_limit_gb:
print("Warning: High memory usage detected")
return success
11. Distributed Processing for Large Volumes¶
from concurrent.futures import ProcessPoolExecutor
from pyt_utils.image_preprocessing import cli_crop_page
import os
import glob
def batch_process_images(input_dir, output_dir, max_workers=4):
"""Process multiple images in parallel"""
image_paths = glob.glob(os.path.join(input_dir, "*.jpg")) + \
glob.glob(os.path.join(input_dir, "*.png"))
# Process images in parallel
with ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = []
for img_path in image_paths:
output_path = os.path.join(output_dir, os.path.basename(img_path))
future = executor.submit(cli_crop_page, img_path, output_path)
futures.append((img_path, future))
# Monitor progress
for img_path, future in futures:
try:
success = future.result()
status = "✅ Success" if success else "❌ Failed"
print(f"{status}: {os.path.basename(img_path)}")
except Exception as e:
print(f"⚠️ Error processing {os.path.basename(img_path)}: {e}")
print(f"Batch processing complete: {len(image_paths)} images processed")
Error Handling Patterns¶
12. Robust Error Recovery¶
from pyt_utils.image_preprocessing import fix_image
import logging
def robust_image_processing(image_path, max_retries=2):
"""Process image with automatic retry and fallback"""
for attempt in range(max_retries + 1):
try:
# Try with rotation first
result = fix_image(image_path, rotate=True)
if result is not None:
return result
except Exception as e:
logging.warning(f"Attempt {attempt + 1} failed for {image_path}: {e}")
if attempt == 0:
# Try without rotation as fallback
try:
return fix_image(image_path, rotate=False)
except Exception as e2:
logging.error(f"Fallback also failed: {e2}")
# All attempts failed
logging.error(f"Failed to process {image_path} after {max_retries + 1} attempts")
return None
13. Integration with Web Services¶
from fastapi import FastAPI, UploadFile, File
from pyt_utils.image_preprocessing import fix_image
import cv2
import numpy as np
import io
app = FastAPI()
@app.post("/process-document")
async def process_document(file: UploadFile = File(...)):
"""REST API endpoint for document processing"""
# Read uploaded file
contents = await file.read()
# Convert to numpy array
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Process temporarily
temp_path = "/tmp/uploaded_image.jpg"
cv2.imwrite(temp_path, img)
# Preprocess
processed = fix_image(temp_path)
# Convert back to bytes
success, encoded = cv2.imencode('.jpg', processed)
if success:
return {
"status": "success",
"processed_image": encoded.tobytes()
}
else:
return {"status": "error", "message": "Encoding failed"}
These usage patterns demonstrate the flexibility of the image_preprocessing module for various document processing workflows, from simple batch processing to complex AI-powered pipelines.