Download features/image_edit_detector/detectors/fft.py from Pujan-Dev/AI_API: direct link, hf CLI and curl.
- Browser
- Download file 1.17 kB
-
https://huggingface.co/spaces/Pujan-Dev/AI_API/resolve/main/features/image_edit_detector/detectors/fft.py
- Command line
-
hf download hf://spaces/Pujan-Dev/AI_API/features/image_edit_detector/detectors/fft.py
-
curl -L -o fft.py https://huggingface.co/spaces/Pujan-Dev/AI_API/resolve/main/features/image_edit_detector/detectors/fft.py
1.17 kB
| import numpy as np | |
| from PIL import Image | |
| from scipy.fft import fft2, fftshift | |
| def run_fft(image: Image.Image, threshold: float = 0.92) -> bool: | |
| """ | |
| Detects potential image manipulation or generation using FFT-based high-frequency analysis. | |
| Parameters: | |
| image (PIL.Image.Image): The input image. | |
| threshold (float): Proportion of high-frequency components above which the image is flagged. | |
| Returns: | |
| bool: True if the image is likely AI-generated or manipulated, False otherwise. | |
| """ | |
| gray_image = image.convert("L") | |
| resized_image = gray_image.resize((512, 512)) | |
| image_array = np.array(resized_image) | |
| fft_result = fft2(image_array) | |
| fft_shifted = fftshift(fft_result) | |
| magnitude_spectrum = np.abs(fft_shifted) | |
| max_magnitude = np.max(magnitude_spectrum) | |
| if max_magnitude == 0: | |
| return False # Avoid division by zero if image is blank | |
| normalized_spectrum = magnitude_spectrum / max_magnitude | |
| high_freq_mask = normalized_spectrum > 0.5 | |
| high_freq_ratio = np.sum(high_freq_mask) / normalized_spectrum.size | |
| is_fake = high_freq_ratio > threshold | |
| return is_fake | |