kabsis's picture
Upload 13 files
195ae10 verified
"""
NEUROFLUX ULTIMATE - Medical Image Preprocessing
Advanced preprocessing pipeline for medical imaging
"""
import numpy as np
from typing import Dict, Any, Optional, Tuple
import cv2
from scipy import ndimage
from skimage import filters, exposure
import logging
logger = logging.getLogger(__name__)
class MedicalPreprocessor:
"""Advanced medical image preprocessing"""
def __init__(self):
self.default_size = (224, 224)
def enhanced_preprocess(
self,
medical_data: Dict[str, Any],
target_size: Optional[Tuple[int, int]] = None,
quantum_mode: bool = False
) -> Dict[str, Any]:
"""
Enhanced preprocessing with optional quantum enhancement
Args:
medical_data: Dictionary from MedicalImageIO
target_size: Target image size
quantum_mode: Enable quantum-inspired preprocessing
Returns:
Preprocessed data dictionary
"""
image = medical_data['image']
# Ensure 2D for processing
if len(image.shape) == 3:
# Take middle slice if 3D volume
image = image[:, :, image.shape[2] // 2]
# Apply preprocessing pipeline
processed = self._basic_preprocessing(image, target_size)
# Enhanced techniques
processed = self._denoise(processed)
processed = self._enhance_contrast(processed)
processed = self._normalize(processed)
# Quantum-inspired enhancement (if enabled)
if quantum_mode:
processed = self._quantum_enhancement(processed)
# Prepare features
features = self._extract_basic_features(processed)
return {
'image': processed,
'features': features,
'metadata': medical_data.get('metadata', {}),
'preprocessed': True,
'quantum_enhanced': quantum_mode
}
def _basic_preprocessing(
self,
image: np.ndarray,
target_size: Optional[Tuple[int, int]]
) -> np.ndarray:
"""Basic preprocessing steps"""
# Resize if needed
if target_size is None:
target_size = self.default_size
if image.shape[:2] != target_size:
image = cv2.resize(image, target_size, interpolation=cv2.INTER_CUBIC)
return image
def _denoise(self, image: np.ndarray) -> np.ndarray:
"""Advanced denoising"""
# Use bilateral filter for edge-preserving denoising
if image.max() > 1.0:
image_uint8 = image.astype(np.uint8)
denoised = cv2.bilateralFilter(image_uint8, 9, 75, 75)
return denoised.astype(np.float32)
else:
# For normalized images
denoised = cv2.bilateralFilter(
(image * 255).astype(np.uint8),
9, 75, 75
)
return denoised.astype(np.float32) / 255.0
def _enhance_contrast(self, image: np.ndarray) -> np.ndarray:
"""Advanced contrast enhancement"""
# Adaptive histogram equalization
if image.max() <= 1.0:
image = (image * 255).astype(np.uint8)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
enhanced = clahe.apply(image.astype(np.uint8))
return enhanced.astype(np.float32)
def _normalize(self, image: np.ndarray) -> np.ndarray:
"""Normalize to [0, 1] range"""
min_val = image.min()
max_val = image.max()
if max_val - min_val > 0:
return (image - min_val) / (max_val - min_val)
return image
def _quantum_enhancement(self, image: np.ndarray) -> np.ndarray:
"""
Quantum-inspired enhancement using phase coherence
(Simulation of quantum superposition principles)
"""
# Apply Fourier transform (quantum-inspired frequency domain)
f_transform = np.fft.fft2(image)
f_shift = np.fft.fftshift(f_transform)
# Apply quantum-inspired filter (phase modulation)
rows, cols = image.shape
crow, ccol = rows // 2, cols // 2
# Create quantum-inspired mask
y, x = np.ogrid[:rows, :cols]
mask = np.exp(-((x - ccol)**2 + (y - crow)**2) / (2 * (min(rows, cols) / 4)**2))
# Apply enhancement
f_enhanced = f_shift * (1 + 0.3 * mask)
# Inverse transform
f_ishift = np.fft.ifftshift(f_enhanced)
image_enhanced = np.fft.ifft2(f_ishift)
image_enhanced = np.abs(image_enhanced)
# Normalize
return self._normalize(image_enhanced)
def _extract_basic_features(self, image: np.ndarray) -> Dict[str, float]:
"""Extract basic statistical features"""
return {
'mean_intensity': float(np.mean(image)),
'std_intensity': float(np.std(image)),
'min_intensity': float(np.min(image)),
'max_intensity': float(np.max(image)),
'entropy': float(self._calculate_entropy(image)),
'contrast': float(np.std(image) / (np.mean(image) + 1e-7))
}
def _calculate_entropy(self, image: np.ndarray) -> float:
"""Calculate image entropy"""
histogram, _ = np.histogram(image, bins=256, range=(0, 1))
histogram = histogram[histogram > 0]
prob = histogram / histogram.sum()
entropy = -np.sum(prob * np.log2(prob + 1e-7))
return entropy
def apply_skull_stripping(self, image: np.ndarray) -> np.ndarray:
"""
Simplified skull stripping for brain MRI
(For demonstration purposes)
"""
# Threshold-based approach
threshold = filters.threshold_otsu(image)
binary = image > threshold
# Morphological operations
binary = ndimage.binary_fill_holes(binary)
binary = ndimage.binary_erosion(binary, iterations=2)
binary = ndimage.binary_dilation(binary, iterations=2)
# Apply mask
stripped = image * binary
return stripped