Create ela_hybrid.py
Browse files- forensics/ela_hybrid.py +61 -0
forensics/ela_hybrid.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ela_hybrid.py
|
2 |
+
import numpy as np
|
3 |
+
import cv2 as cv
|
4 |
+
from PIL import Image
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
|
7 |
+
|
8 |
+
def compress_jpg(image, quality=75):
|
9 |
+
"""Compress image using JPEG compression (shared from ela.py)."""
|
10 |
+
encode_param = [int(cv.IMWRITE_JPEG_QUALITY), quality]
|
11 |
+
_, buffer = cv.imencode('.jpg', image, encode_param)
|
12 |
+
return cv.imdecode(buffer, cv.IMREAD_COLOR)
|
13 |
+
|
14 |
+
|
15 |
+
def generate_ela_hybrid(image_path: str, quality: int = 95, scale_factor: int = 150):
|
16 |
+
"""
|
17 |
+
Generate a 6-channel hybrid image combining RGB and ELA (3 channels each).
|
18 |
+
|
19 |
+
Args:
|
20 |
+
image_path (str): Path to the input image.
|
21 |
+
quality (int): JPEG compression quality (1-100).
|
22 |
+
scale_factor (int): Scale factor for ELA contrast.
|
23 |
+
|
24 |
+
Returns:
|
25 |
+
np.ndarray: 6-channel (RGB + ELA) image with shape (H, W, 6), dtype float32, normalized [0,1]
|
26 |
+
"""
|
27 |
+
# Load original image
|
28 |
+
original = cv.imread(image_path, cv.IMREAD_COLOR)
|
29 |
+
original = original.astype(np.float32) / 255 # Normalize to [0, 1]
|
30 |
+
|
31 |
+
# Compress and reload image
|
32 |
+
compressed = compress_jpg(original, quality)
|
33 |
+
compressed = compressed.astype(np.float32) / 255 # Normalize to [0, 1]
|
34 |
+
|
35 |
+
# Generate ELA as absolute difference between original and compressed
|
36 |
+
ela = cv.absdiff(original, compressed)
|
37 |
+
|
38 |
+
# Apply scale factor to enhance ELA differences
|
39 |
+
ela = cv.convertScaleAbs(ela, alpha=scale_factor / 100, beta=0)
|
40 |
+
ela = ela.astype(np.float32) / 255 # Normalize back to [0, 1]
|
41 |
+
|
42 |
+
# Stack RGB and ELA (3 channels each) into 6-channel input
|
43 |
+
hybrid_image = np.concatenate([original, ela], axis=-1) # Shape: H×W×6
|
44 |
+
|
45 |
+
return hybrid_image
|
46 |
+
|
47 |
+
|
48 |
+
def save_hybrid_image(hybrid_array, save_path: str):
|
49 |
+
"""Save the 6-channel hybrid image as a .npy file for model input."""
|
50 |
+
np.save(save_path, hybrid_array)
|
51 |
+
print(f"Saved hybrid ELA image to {save_path}")
|
52 |
+
|
53 |
+
|
54 |
+
def visualize_hybrid(hybrid_array: np.ndarray, split_visualize: bool = True):
|
55 |
+
"""Split the 6 channels into RGB and ELA for visualization."""
|
56 |
+
rgb_image = (hybrid_array[:, :, :3] * 255).astype(np.uint8)
|
57 |
+
ela_image = (hybrid_array[:, :, 3:] * 255).astype(np.uint8)
|
58 |
+
return {
|
59 |
+
"rgb": Image.fromarray(rgb_image),
|
60 |
+
"ela": Image.fromarray(ela_image),
|
61 |
+
}
|