Spaces:
Sleeping
Sleeping
Update preprocess.py
Browse files- preprocess.py +39 -33
preprocess.py
CHANGED
|
@@ -1,33 +1,39 @@
|
|
| 1 |
-
import cv2
|
| 2 |
-
import numpy as np
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
def prepare_tensor(file_bytes):
|
| 9 |
+
# 1. Load image in grayscale
|
| 10 |
+
nparr = np.frombuffer(file_bytes, np.uint8)
|
| 11 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
|
| 12 |
+
|
| 13 |
+
# 2. THE FIX: Micro-Blur instead of Heavy Blur
|
| 14 |
+
# Reduced from (5,5) to (3,3) to preserve GAN/Diffusion high-frequency artifacts
|
| 15 |
+
img_smoothed = cv2.GaussianBlur(img, (3, 3), 0)
|
| 16 |
+
|
| 17 |
+
# 3. 2D Fast Fourier Transform (FFT)
|
| 18 |
+
f = np.fft.fft2(img_smoothed)
|
| 19 |
+
fshift = np.fft.fftshift(f)
|
| 20 |
+
|
| 21 |
+
# 4. Enhance the Magnitude Spectrum
|
| 22 |
+
magnitude_spectrum = 20 * np.log(np.abs(fshift) + 1e-8)
|
| 23 |
+
|
| 24 |
+
# 5. Normalize for ResNet-18 (0-255)
|
| 25 |
+
magnitude_spectrum = cv2.normalize(magnitude_spectrum, None, 0, 255, cv2.NORM_MINMAX)
|
| 26 |
+
magnitude_spectrum = np.uint8(magnitude_spectrum)
|
| 27 |
+
|
| 28 |
+
# Convert back to 3-channel RGB as ResNet expects 3 channels
|
| 29 |
+
img_rgb = cv2.cvtColor(magnitude_spectrum, cv2.COLOR_GRAY2RGB)
|
| 30 |
+
|
| 31 |
+
# 6. Final PyTorch Tensor Transformations
|
| 32 |
+
transform = transforms.Compose([
|
| 33 |
+
transforms.ToPILImage(),
|
| 34 |
+
transforms.Resize((224, 224)),
|
| 35 |
+
transforms.ToTensor(),
|
| 36 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 37 |
+
])
|
| 38 |
+
|
| 39 |
+
return transform(img_rgb).unsqueeze(0)
|