Okay, you've got a great starting point with the 2D FFTs of your image frames. Here's a breakdown of calculations you can perform on the FFT output to score image quality (focus, sharpness, motion blur) and determine the best frame in each segment. I'll categorize them and explain the rationale, along with complexity considerations. I'll also suggest how to combine these scores.
Understanding the FFT Output & What it Tells You
Before diving into calculations, remember what the FFT represents:
- Magnitude: The magnitude of each frequency component represents the strength of that frequency in the image. High magnitudes in high frequencies generally indicate sharp edges and detail. Low magnitudes in high frequencies suggest blur.
- Phase: The phase contains information about the position of features in the image. While less directly used for quality scoring, it's crucial for image reconstruction (inverse FFT). Phase information can be useful for motion estimation (see later).
- Center: The center of the FFT represents the DC component (average brightness). The further you move from the center, the higher the frequencies.
I. Focus/Sharpness Metrics (Based on High-Frequency Content)
These metrics aim to quantify how much detail is present in the image. A focused image will have strong high-frequency components.
-
High-Frequency Energy (HFE):
- Calculation: Sum the squared magnitudes of the FFT coefficients within a defined high-frequency region. You'll need to define a radius or a band around the center of the FFT to exclude low frequencies. Experiment with different radii to find what works best for your images.
- Formula:
HFE = Σ |FFT(u,v)|^2 for (u^2 + v^2) > radius^2 (where u and v are frequency coordinates)
- Interpretation: Higher HFE = Sharper image.
- Complexity: Low. Simple summation.
-
Tenengrad:
- Calculation: A more sophisticated measure of sharpness based on the gradient magnitude. You can calculate the gradient in the frequency domain by multiplying the FFT by
j*u and j*v (where j is the imaginary unit) and then taking the magnitude. Tenengrad is the sum of squared gradients.
- Formula: (Simplified)
Tenengrad = Σ |j*u*FFT(u,v)|^2 + Σ |j*v*FFT(u,v)|^2
- Interpretation: Higher Tenengrad = Sharper image.
- Complexity: Moderate. Requires multiplication and magnitude calculations.
-
Entropy of FFT Magnitude:
- Calculation: Calculate the entropy of the distribution of FFT magnitudes. A sharp image will have a more uneven distribution (some frequencies will be much stronger than others), leading to higher entropy.
- Formula:
Entropy = - Σ p(i) * log2(p(i)) where p(i) is the probability of the i-th magnitude value.
- Interpretation: Higher Entropy = Sharper image.
- Complexity: Moderate. Requires histogram calculation and log operations.
-
Variance of FFT Magnitude:
- Calculation: Calculate the variance of the FFT magnitudes. Similar to entropy, a higher variance indicates a wider distribution of frequencies, suggesting sharpness.
- Formula:
Variance = E[X^2] - (E[X])^2 where X is the FFT magnitude.
- Interpretation: Higher Variance = Sharper image.
- Complexity: Low. Simple calculation.
II. Motion Blur Metrics (Based on Frequency Spread)
Motion blur causes energy to spread out in the frequency domain. These metrics try to quantify that spread.
-
Blur Metric (Based on Frequency Spread):
- Calculation: Calculate the ratio of energy in a narrow band around the DC component (low frequencies) to the total energy. Blurry images will have more energy concentrated in the low frequencies.
- Formula:
BlurMetric = Σ |FFT(u,v)|^2 for (u^2 + v^2) < radius_low^2 / Σ |FFT(u,v)|^2
- Interpretation: Higher BlurMetric = More blur. (You'll want to minimize this score).
- Complexity: Low. Simple summation and division.
-
Directional Blur Analysis:
- Calculation: Motion blur is often directional. Create a series of 1D FFTs by averaging rows or columns of the 2D FFT. Look for a dominant peak in these 1D FFTs. The position of the peak indicates the direction of the blur. The width of the peak indicates the severity of the blur.
- Interpretation: Peak position = Blur direction. Peak width = Blur severity.
- Complexity: Moderate. Requires averaging and 1D FFTs.
-
Phase Correlation (for Inter-Frame Motion):
- Calculation: Compare the phase of the FFT of the current frame to the phase of the FFT of a reference frame (e.g., the first frame in the segment). A significant shift in phase indicates motion. This is computationally expensive.
- Interpretation: Phase shift = Motion vector.
- Complexity: High. Requires complex number operations and potentially peak finding. Best for estimating motion rather than just blur.
III. Combined Scoring & Best Frame Selection
-
Normalization: Normalize all your metrics to a common scale (e.g., 0 to 1). This is crucial for combining them effectively. For blur metrics, you might need to invert the scale (1 - BlurMetric) so that higher scores always indicate better quality.
-
Weighted Sum: Combine the normalized metrics using a weighted sum:
QualityScore = w1 * Normalized_HFE + w2 * Normalized_Tenengrad + w3 * (1 - Normalized_BlurMetric) + ...
w1, w2, w3 are weights that you'll need to tune based on your specific video content and desired quality criteria. Experimentation is key! You might give more weight to sharpness metrics if focus is the most important factor.
-
Best Frame Selection: For each video segment, select the frame with the highest QualityScore.
Important Considerations & Optimizations:
- Windowing: Apply a window function (e.g., Hamming, Hanning) to each frame before performing the FFT. This reduces spectral leakage and improves the accuracy of your calculations.
- Region of Interest (ROI): If you know that certain parts of the image are more important for quality assessment, focus your calculations on those regions.
- Computational Cost: FFTs are relatively expensive. Consider using optimized FFT libraries (e.g., FFTW) and parallel processing to speed up the calculations.
- Parameter Tuning: The radii for high-frequency regions, the weights in the combined score, and other parameters will need to be tuned based on your specific video content and desired results. Use a validation set of video segments to optimize these parameters.
- Alternative Libraries: OpenCV has functions for calculating some of these metrics directly (e.g., Laplacian variance for sharpness). Consider using these if available.
- Motion Estimation vs. Blur: Distinguish between actual motion and motion blur. Phase correlation is better for estimating motion, while the blur metrics are better for quantifying the effect of motion blur.
Example Python (Conceptual - using NumPy/SciPy):
import numpy as np
from scipy.fft import fft2, fftshift
def calculate_quality_score(image_fft, weights):
# Example: HFE and Blur Metric
radius_hfe = 20
radius_blur = 10
# High-Frequency Energy
magnitude_spectrum = np.abs(image_fft)
hfe = np.sum(magnitude_spectrum**2 [np.sqrt(np.fft.fftfreq(image_fft.shape[0])**2 + np.fft.fftfreq(image_fft.shape[1])**2) > radius_hfe])
# Blur Metric
blur_metric = np.sum(magnitude_spectrum**2 [np.sqrt(np.fft.fftfreq(image_fft.shape[0])**2 + np.fft.fftfreq(image_fft.shape[1])**2) < radius_blur]) / np.sum(magnitude_spectrum**2)
# Normalize (example)
normalized_hfe = hfe / np.max(hfe) # Assuming max HFE is known or can be estimated
normalized_blur = 1 - blur_metric
# Weighted Sum
quality_score = weights['hfe'] * normalized_hfe + weights['blur'] * normalized_blur
return quality_score
# Example Usage
# Assuming you have a list of FFTs for each frame in a segment
# weights = {'hfe': 0.7, 'blur': 0.3}
# best_frame_index = np.argmax([calculate_quality_score(frame_fft, weights) for frame_fft in frame_ffts])
This is a starting point. You'll need to adapt the code and parameters to your specific needs. Good luck! Let me know if you have any more questions.