File size: 29,792 Bytes
ecc16d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
"""

Blur Detection Module - Motion vs Defocus Detection

==================================================



Comprehensive blur analysis using Variance of Laplacian and advanced techniques

to detect motion blur, defocus blur, and estimate blur parameters.

"""

import cv2
import numpy as np
from scipy import ndimage
from scipy.signal import find_peaks
from scipy.fft import fft2, fftshift
import logging
from typing import Dict, Tuple, Optional

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

class BlurDetector:
    """Advanced blur detection and analysis"""
    
    def __init__(self):
        self.sharpness_threshold = {
            'sharp': 1000,
            'slightly_blurred': 500,
            'moderately_blurred': 200,
            'heavily_blurred': 50
        }
    
    def variance_of_laplacian(self, image: np.ndarray) -> float:
        """

        Compute the Laplacian variance (sharpness metric)

        

        Args:

            image: Input image (BGR or grayscale)

        

        Returns:

            float: Variance of Laplacian (higher = sharper)

        """
        try:
            # Convert to grayscale if needed
            if len(image.shape) == 3:
                gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            else:
                gray = image.copy()
            
            # Compute Laplacian variance
            laplacian = cv2.Laplacian(gray, cv2.CV_64F)
            variance = laplacian.var()
            
            return variance
            
        except Exception as e:
            logger.error(f"Error computing Laplacian variance: {e}")
            return 0.0
    
    def estimate_motion_blur_params(self, image: np.ndarray) -> Tuple[float, int]:
        """

        Estimate motion blur parameters: angle and length

        

        Args:

            image: Input image

        

        Returns:

            tuple: (angle in degrees, length in pixels)

        """
        try:
            # Convert to grayscale
            if len(image.shape) == 3:
                gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            else:
                gray = image.copy()
            
            # Apply FFT
            f_transform = np.fft.fft2(gray)
            f_shift = np.fft.fftshift(f_transform)
            magnitude_spectrum = np.log(np.abs(f_shift) + 1)
            
            # Find dominant direction in frequency domain
            rows, cols = magnitude_spectrum.shape
            center_row, center_col = rows // 2, cols // 2
            
            # Create radial profile
            angles = np.linspace(0, 180, 180)
            max_intensity = 0
            best_angle = 0
            
            for angle in angles:
                # Create line through center at this angle
                length = min(rows, cols) // 4
                x = center_col + length * np.cos(np.radians(angle))
                y = center_row + length * np.sin(np.radians(angle))
                
                # Sample intensity along line
                if 0 <= x < cols and 0 <= y < rows:
                    intensity = magnitude_spectrum[int(y), int(x)]
                    if intensity > max_intensity:
                        max_intensity = intensity
                        best_angle = angle
            
            # Estimate blur length based on spectrum width
            # This is a simplified estimation
            blur_length = max(5, min(50, int(max_intensity / 10)))
            
            return best_angle, blur_length
            
        except Exception as e:
            logger.error(f"Error estimating motion blur: {e}")
            return 0.0, 5
    
    def detect_defocus_blur(self, image: np.ndarray) -> float:
        """

        Detect defocus blur using edge analysis

        

        Args:

            image: Input image

        

        Returns:

            float: Defocus blur score (0-1, higher = more defocus blur)

        """
        try:
            # Convert to grayscale
            if len(image.shape) == 3:
                gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            else:
                gray = image.copy()
            
            # Compute gradients
            grad_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
            grad_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
            
            # Compute gradient magnitude
            gradient_magnitude = np.sqrt(grad_x**2 + grad_y**2)
            
            # Analyze edge distribution
            edges = cv2.Canny(gray, 50, 150)
            edge_density = np.sum(edges > 0) / edges.size
            
            # Compute defocus score based on edge characteristics
            mean_gradient = np.mean(gradient_magnitude)
            std_gradient = np.std(gradient_magnitude)
            
            # Defocus blur typically has lower gradient variation
            defocus_score = max(0, min(1, 1 - (std_gradient / (mean_gradient + 1e-10))))
            
            return defocus_score
            
        except Exception as e:
            logger.error(f"Error detecting defocus blur: {e}")
            return 0.0
    
    def analyze_noise_level(self, image: np.ndarray) -> float:
        """

        Estimate noise level in the image

        

        Args:

            image: Input image

        

        Returns:

            float: Estimated noise level (0-1)

        """
        try:
            # Convert to grayscale
            if len(image.shape) == 3:
                gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            else:
                gray = image.copy()
            
            # Use Laplacian to estimate noise
            laplacian = cv2.Laplacian(gray, cv2.CV_64F)
            noise_estimate = np.var(laplacian) / (np.mean(gray) + 1e-10)
            
            # Normalize to 0-1 range
            normalized_noise = min(noise_estimate / 1000, 1.0)
            
            return normalized_noise
            
        except Exception as e:
            logger.error(f"Error analyzing noise: {e}")
            return 0.0
    
    def classify_blur_severity(self, sharpness_score: float) -> Tuple[str, float]:
        """

        Classify blur severity based on sharpness score

        

        Args:

            sharpness_score: Laplacian variance value

        

        Returns:

            tuple: (severity_label, confidence)

        """
        try:
            if sharpness_score > self.sharpness_threshold['sharp']:
                return "Sharp", 0.9
            elif sharpness_score > self.sharpness_threshold['slightly_blurred']:
                return "Slightly Blurred", 0.8
            elif sharpness_score > self.sharpness_threshold['moderately_blurred']:
                return "Moderately Blurred", 0.9
            elif sharpness_score > self.sharpness_threshold['heavily_blurred']:
                return "Heavily Blurred", 0.95
            else:
                return "Extremely Blurred", 0.98
                
        except Exception as e:
            logger.error(f"Error classifying blur severity: {e}")
            return "Unknown", 0.0
    
    def comprehensive_analysis(self, image: np.ndarray) -> Dict:
        """

        Perform comprehensive blur analysis with detailed diagnostics

        

        Args:

            image: Input image

        

        Returns:

            dict: Complete analysis results with detailed explanations

        """
        try:
            # Step 1: Image Properties Analysis
            height, width = image.shape[:2]
            channels = image.shape[2] if len(image.shape) == 3 else 1
            
            # Step 2: Basic sharpness analysis using Variance of Laplacian
            sharpness = self.variance_of_laplacian(image)
            severity, confidence = self.classify_blur_severity(sharpness)
            
            # Step 3: Edge Density Analysis
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
            edges = cv2.Canny(gray, 50, 150)
            edge_density = np.sum(edges > 0) / edges.size
            
            # Step 4: Gradient Analysis for sharpness assessment
            grad_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
            grad_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
            gradient_magnitude = np.sqrt(grad_x**2 + grad_y**2)
            avg_gradient = np.mean(gradient_magnitude)
            max_gradient = np.max(gradient_magnitude)
            
            # Step 5: Frequency Domain Analysis
            f_transform = fft2(gray)
            f_shift = fftshift(f_transform)
            magnitude_spectrum = np.log(np.abs(f_shift) + 1)
            high_freq_content = np.mean(magnitude_spectrum[height//4:3*height//4, width//4:3*width//4])
            
            # Step 6: Motion blur analysis with detailed parameters
            motion_angle, motion_length = self.estimate_motion_blur_params(image)
            
            # Step 7: Defocus analysis with multiple metrics
            defocus_score = self.detect_defocus_blur(image)
            
            # Step 8: Noise analysis and characterization
            noise_level = self.analyze_noise_level(image)
            
            # Step 9: Contrast and Dynamic Range Analysis
            hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
            contrast_measure = np.std(gray)
            dynamic_range = np.max(gray) - np.min(gray)
            
            # Step 10: Texture Analysis using Local Binary Patterns concept
            texture_variance = np.var(cv2.Laplacian(gray, cv2.CV_64F))
            
            # Step 11: Blur Type Classification with Reasoning
            blur_analysis = self._detailed_blur_classification(
                sharpness, motion_length, defocus_score, edge_density, 
                avg_gradient, high_freq_content
            )
            
            # Step 12: Enhancement Recommendation System
            enhancement_strategy = self._recommend_enhancement_strategy(
                blur_analysis['primary_type'], severity, noise_level, motion_length
            )
            
            return {
                # Basic Image Properties
                'image_dimensions': f"{width}x{height}",
                'color_channels': channels,
                'image_size_category': self._categorize_image_size(width, height),
                
                # Sharpness and Quality Metrics
                'sharpness_score': float(sharpness),
                'sharpness_interpretation': self._interpret_sharpness_score(sharpness),
                'severity': severity,
                'severity_confidence': float(confidence),
                'edge_density': float(edge_density),
                'edge_density_interpretation': self._interpret_edge_density(edge_density),
                
                # Gradient and Frequency Analysis
                'average_gradient': float(avg_gradient),
                'max_gradient': float(max_gradient),
                'gradient_interpretation': self._interpret_gradients(avg_gradient, max_gradient),
                'high_frequency_content': float(high_freq_content),
                'frequency_domain_analysis': self._interpret_frequency_content(high_freq_content),
                
                # Blur Type Analysis
                'primary_type': blur_analysis['primary_type'],
                'type_confidence': blur_analysis['confidence'],
                'blur_reasoning': blur_analysis['reasoning'],
                'secondary_issues': blur_analysis['secondary_issues'],
                
                # Motion Blur Specifics
                'motion_angle': float(motion_angle),
                'motion_length': int(motion_length),
                'motion_interpretation': self._interpret_motion_blur(motion_angle, motion_length),
                
                # Defocus Analysis
                'defocus_score': float(defocus_score),
                'defocus_interpretation': self._interpret_defocus(defocus_score),
                
                # Noise and Quality
                'noise_level': float(noise_level),
                'noise_interpretation': self._interpret_noise_level(noise_level),
                'contrast_measure': float(contrast_measure),
                'dynamic_range': float(dynamic_range),
                'texture_variance': float(texture_variance),
                
                # Enhancement Strategy
                'enhancement_priority': enhancement_strategy['priority'],
                'recommended_methods': enhancement_strategy['methods'],
                'expected_improvement': enhancement_strategy['expected_improvement'],
                'processing_difficulty': enhancement_strategy['difficulty'],
                'detailed_recommendations': enhancement_strategy['detailed_recommendations'],
                
                # Technical Analysis Summary
                'technical_summary': self._generate_technical_summary(
                    sharpness, blur_analysis['primary_type'], severity, noise_level
                ),
                'student_analysis_notes': self._generate_student_notes(
                    sharpness, motion_length, defocus_score, edge_density
                )
            }
            
        except Exception as e:
            logger.error(f"Error in comprehensive analysis: {e}")
            return {
                'sharpness_score': 0.0,
                'severity': 'Unknown',
                'severity_confidence': 0.0,
                'primary_type': 'Unknown',
                'type_confidence': 0.0,
                'motion_angle': 0.0,
                'motion_length': 0,
                'defocus_score': 0.0,
                'noise_level': 0.0,
                'enhancement_priority': 'High',
                'technical_summary': 'Analysis failed due to processing error',
                'student_analysis_notes': 'Unable to perform detailed analysis'
            }

    def _categorize_image_size(self, width: int, height: int) -> str:
        """Categorize image size for processing complexity assessment"""
        total_pixels = width * height
        if total_pixels < 100000:  # < 0.1 MP
            return "Small (Fast Processing)"
        elif total_pixels < 1000000:  # < 1 MP
            return "Medium (Standard Processing)"
        elif total_pixels < 5000000:  # < 5 MP
            return "Large (Slower Processing)"
        else:
            return "Very Large (Requires Optimization)"

    def _interpret_sharpness_score(self, sharpness: float) -> str:
        """Provide educational interpretation of sharpness score"""
        if sharpness > 1000:
            return f"Excellent sharpness ({sharpness:.1f}). Strong edge definition with high contrast transitions."
        elif sharpness > 600:
            return f"Good sharpness ({sharpness:.1f}). Adequate edge clarity for most applications."
        elif sharpness > 300:
            return f"Moderate blur ({sharpness:.1f}). Noticeable softness in edges and details."
        elif sharpness > 100:
            return f"Significant blur ({sharpness:.1f}). Substantial loss of fine details and edge clarity."
        else:
            return f"Severe blur ({sharpness:.1f}). Major degradation requiring advanced restoration techniques."

    def _interpret_edge_density(self, edge_density: float) -> str:
        """Interpret edge density measurements"""
        if edge_density > 0.1:
            return f"High edge density ({edge_density:.3f}) - Rich in structural details and textures"
        elif edge_density > 0.05:
            return f"Medium edge density ({edge_density:.3f}) - Moderate structural content"
        elif edge_density > 0.02:
            return f"Low edge density ({edge_density:.3f}) - Smooth regions dominate, limited fine details"
        else:
            return f"Very low edge density ({edge_density:.3f}) - Predominantly smooth surfaces or severe blur"

    def _interpret_gradients(self, avg_gradient: float, max_gradient: float) -> str:
        """Analyze gradient characteristics for sharpness assessment"""
        gradient_ratio = max_gradient / (avg_gradient + 1e-6)
        if gradient_ratio > 10 and avg_gradient > 20:
            return f"Strong gradients detected (avg: {avg_gradient:.1f}, max: {max_gradient:.1f}) - Good edge definition"
        elif gradient_ratio > 5:
            return f"Moderate gradients (avg: {avg_gradient:.1f}, max: {max_gradient:.1f}) - Some edge preservation"
        else:
            return f"Weak gradients (avg: {avg_gradient:.1f}, max: {max_gradient:.1f}) - Poor edge definition, likely blurred"

    def _interpret_frequency_content(self, high_freq: float) -> str:
        """Analyze frequency domain characteristics"""
        if high_freq > 5.0:
            return f"Rich high-frequency content ({high_freq:.2f}) - Preserves fine details and textures"
        elif high_freq > 3.0:
            return f"Moderate high-frequency content ({high_freq:.2f}) - Some detail preservation"
        elif high_freq > 2.0:
            return f"Limited high-frequency content ({high_freq:.2f}) - Loss of fine details"
        else:
            return f"Poor high-frequency content ({high_freq:.2f}) - Significant detail loss, heavy blur"

    def _detailed_blur_classification(self, sharpness: float, motion_length: int, 

                                    defocus_score: float, edge_density: float,

                                    avg_gradient: float, high_freq: float) -> Dict:
        """Comprehensive blur type analysis with detailed reasoning"""
        
        # Evidence collection for each blur type
        motion_evidence = []
        defocus_evidence = []
        noise_evidence = []
        mixed_evidence = []
        
        # Motion blur indicators
        if motion_length > 15:
            motion_evidence.append(f"Strong directional blur detected (length: {motion_length}px)")
        if avg_gradient < 15 and sharpness < 400:
            motion_evidence.append("Gradient analysis suggests directional degradation")
        
        # Defocus blur indicators  
        if defocus_score > 0.4:
            defocus_evidence.append(f"High defocus characteristics (score: {defocus_score:.3f})")
        if edge_density < 0.03 and high_freq < 3.0:
            defocus_evidence.append("Uniform blur pattern across all frequencies")
        
        # Mixed blur indicators
        if motion_length > 10 and defocus_score > 0.3:
            mixed_evidence.append("Both motion and defocus characteristics present")
        if sharpness < 200:
            mixed_evidence.append("Severe degradation suggests multiple blur sources")
        
        # Determine primary classification
        if len(motion_evidence) >= 2 and motion_length > 12:
            primary_type = "Motion Blur"
            confidence = 0.85 + min(0.1, motion_length / 100)
            reasoning = f"Motion blur identified based on: {', '.join(motion_evidence)}"
            secondary_issues = defocus_evidence + mixed_evidence
            
        elif len(defocus_evidence) >= 2 and defocus_score > 0.35:
            primary_type = "Defocus Blur"  
            confidence = 0.80 + min(0.15, defocus_score)
            reasoning = f"Defocus blur identified based on: {', '.join(defocus_evidence)}"
            secondary_issues = motion_evidence + mixed_evidence
            
        elif sharpness > 800:
            primary_type = "Sharp Image"
            confidence = 0.90
            reasoning = "High sharpness metrics indicate well-focused image"
            secondary_issues = []
            
        else:
            primary_type = "Mixed/Complex Blur"
            confidence = 0.65
            reasoning = f"Complex blur pattern detected. Evidence includes: {', '.join(motion_evidence + defocus_evidence)}"
            secondary_issues = ["Multiple degradation sources present", "Requires combined enhancement approach"]
        
        return {
            'primary_type': primary_type,
            'confidence': confidence,
            'reasoning': reasoning,
            'secondary_issues': secondary_issues if secondary_issues else ["No significant secondary issues detected"]
        }

    def _interpret_motion_blur(self, angle: float, length: int) -> str:
        """Detailed motion blur parameter interpretation"""
        if length < 5:
            return f"Minimal motion (Length: {length}px) - Not significant for restoration"
        elif length < 15:
            return f"Moderate linear motion (Angle: {angle:.1f}°, Length: {length}px) - Correctable with standard techniques"
        elif length < 30:
            return f"Significant motion blur (Angle: {angle:.1f}°, Length: {length}px) - Requires advanced deconvolution"
        else:
            return f"Severe motion blur (Angle: {angle:.1f}°, Length: {length}px) - Challenging restoration case"

    def _interpret_defocus(self, defocus_score: float) -> str:
        """Interpret defocus blur characteristics"""
        if defocus_score < 0.2:
            return f"Minimal defocus ({defocus_score:.3f}) - Sharp focus maintained"
        elif defocus_score < 0.4:
            return f"Moderate defocus ({defocus_score:.3f}) - Some focus softness present"  
        elif defocus_score < 0.6:
            return f"Significant defocus ({defocus_score:.3f}) - Noticeable out-of-focus blur"
        else:
            return f"Severe defocus ({defocus_score:.3f}) - Major focus problems requiring restoration"

    def _interpret_noise_level(self, noise_level: float) -> str:
        """Analyze noise characteristics and impact"""
        if noise_level < 0.1:
            return f"Low noise ({noise_level:.3f}) - Clean image, minimal interference"
        elif noise_level < 0.3:
            return f"Moderate noise ({noise_level:.3f}) - Some grain present but manageable"
        elif noise_level < 0.5:
            return f"High noise ({noise_level:.3f}) - Significant grain affecting image quality"
        else:
            return f"Severe noise ({noise_level:.3f}) - Heavy noise requiring specialized filtering"

    def _recommend_enhancement_strategy(self, blur_type: str, severity: str, 

                                      noise_level: float, motion_length: int) -> Dict:
        """Generate detailed enhancement recommendations"""
        
        if "Sharp" in blur_type:
            return {
                'priority': 'Low',
                'methods': ['Optional sharpening enhancement'],
                'expected_improvement': '5-10%',
                'difficulty': 'Easy',
                'detailed_recommendations': [
                    "Image is already well-focused",
                    "Consider mild unsharp masking if enhancement desired",
                    "Focus on noise reduction if noise_level > 0.2"
                ]
            }
        
        elif "Motion" in blur_type:
            methods = ['Wiener Filter', 'Richardson-Lucy Deconvolution']
            if motion_length > 20:
                methods.append('Advanced CNN Enhancement')
            
            difficulty = 'Medium' if motion_length < 20 else 'Hard'
            improvement = '30-60%' if motion_length < 25 else '20-45%'
            
            recommendations = [
                f"Apply motion deblurring with {motion_length}px kernel",
                "Use Richardson-Lucy for best results with known PSF",
                "Consider CNN enhancement for complex cases"
            ]
            
            if noise_level > 0.3:
                recommendations.append("Apply noise reduction before deblurring")
            
        elif "Defocus" in blur_type:
            methods = ['Gaussian Deconvolution', 'Wiener Filter', 'CNN Enhancement']
            difficulty = 'Medium'
            improvement = '25-50%'
            
            recommendations = [
                "Use Gaussian PSF estimation for deconvolution", 
                "Apply iterative Richardson-Lucy algorithm",
                "CNN methods often work well for defocus blur"
            ]
            
        else:  # Mixed/Complex
            methods = ['Combined Approach', 'CNN Enhancement', 'Multi-stage Processing']
            difficulty = 'Hard'
            improvement = '20-40%'
            
            recommendations = [
                "Try multiple deblurring approaches sequentially",
                "CNN enhancement recommended for complex cases",
                "May require manual parameter tuning"
            ]
        
        # Adjust for noise
        if noise_level > 0.4:
            recommendations.insert(0, "Critical: Apply aggressive noise reduction first")
            improvement = improvement.replace('0%', '5%').replace('5%', '0%')  # Reduce expected improvement
        
        return {
            'priority': 'High' if 'Severe' in severity else 'Medium',
            'methods': methods,
            'expected_improvement': improvement,
            'difficulty': difficulty,
            'detailed_recommendations': recommendations
        }

    def _generate_technical_summary(self, sharpness: float, blur_type: str, 

                                  severity: str, noise_level: float) -> str:
        """Generate comprehensive technical analysis summary"""
        return f"""

TECHNICAL ANALYSIS SUMMARY:

• Sharpness Assessment: {severity} blur detected (Laplacian variance: {sharpness:.1f})

• Primary Issue: {blur_type} identified as dominant degradation

• Noise Characteristics: {'Low' if noise_level < 0.2 else 'High'} noise environment 

• Processing Complexity: {'Standard' if sharpness > 300 else 'Advanced'} restoration required

• Image Condition: {'Recoverable' if sharpness > 100 else 'Severely degraded'} with appropriate methods

        """.strip()

    def _generate_student_notes(self, sharpness: float, motion_length: int, 

                              defocus_score: float, edge_density: float) -> str:
        """Generate educational analysis notes"""
        return f"""

DETAILED ANALYSIS NOTES:

📊 Quantitative Measurements:

   - Variance of Laplacian (sharpness): {sharpness:.1f}

   - Motion blur estimation: {motion_length}px kernel length

   - Defocus blur score: {defocus_score:.3f} (0=sharp, 1=heavily defocused)

   - Edge density ratio: {edge_density:.3f} (proportion of edge pixels)



🔍 Image Processing Observations:

   - {"Strong" if sharpness > 600 else "Weak"} high-frequency content preservation

   - {"Directional" if motion_length > 10 else "Uniform"} blur pattern characteristics  

   - {"Adequate" if edge_density > 0.05 else "Poor"} structural detail retention

   - Enhancement difficulty: {"Low" if sharpness > 400 else "High"} (based on degradation severity)



💡 Recommended Analysis Approach:

   1. Frequency domain analysis confirms blur type identification

   2. Gradient-based metrics support sharpness assessment  

   3. PSF estimation required for optimal deconvolution

   4. Multi-metric validation ensures robust classification

        """.strip()

def detect_blur_type(image: np.ndarray) -> str:
    """

    Simple blur type detection function

    

    Args:

        image: Input image

    

    Returns:

        str: Blur type ('sharp', 'motion', 'defocus', 'mixed')

    """
    detector = BlurDetector()
    analysis = detector.comprehensive_analysis(image)
    
    blur_type = analysis['primary_type'].lower().replace(' ', '_')
    return blur_type

def get_sharpness_score(image: np.ndarray) -> float:
    """

    Get sharpness score for image

    

    Args:

        image: Input image

    

    Returns:

        float: Sharpness score (Laplacian variance)

    """
    detector = BlurDetector()
    return detector.variance_of_laplacian(image)

# Example usage and testing
if __name__ == "__main__":
    print("Blur Detection Module - Testing")
    print("===============================")
    
    # Create test images
    # Sharp test image
    sharp_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
    
    # Blurred test image (simulated)
    blurred_image = cv2.GaussianBlur(sharp_image, (15, 15), 5)
    
    # Initialize detector
    detector = BlurDetector()
    
    # Test sharp image
    print("\n--- Sharp Image Analysis ---")
    sharp_analysis = detector.comprehensive_analysis(sharp_image)
    for key, value in sharp_analysis.items():
        print(f"{key}: {value}")
    
    # Test blurred image
    print("\n--- Blurred Image Analysis ---")
    blurred_analysis = detector.comprehensive_analysis(blurred_image)
    for key, value in blurred_analysis.items():
        print(f"{key}: {value}")
    
    print("\nBlur detection module test completed!")


def analyze_blur_characteristics(image: np.ndarray) -> Dict:
    """

    Standalone function for blur analysis (for backward compatibility)

    

    Args:

        image: Input image array

        

    Returns:

        dict: Comprehensive blur analysis results

    """
    detector = BlurDetector()
    return detector.comprehensive_analysis(image)


if __name__ == "__main__":
    test_blur_detection()