-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdip_features.py
More file actions
108 lines (96 loc) · 4.31 KB
/
Copy pathdip_features.py
File metadata and controls
108 lines (96 loc) · 4.31 KB
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
# dip_features.py
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def compute_sharpness(image):
"""Compute image sharpness using the variance of the Laplacian."""
try:
sharpness = cv2.Laplacian(image, cv2.CV_64F).var()
logger.debug("Computed sharpness: %f", sharpness)
return sharpness
except Exception as e:
logger.error("Error computing sharpness: %s", e)
return 0
def compute_edge_density(image, threshold1=100, threshold2=200):
"""Compute edge density using the Canny edge detector."""
try:
edges = cv2.Canny(image, threshold1, threshold2)
density = np.sum(edges) / float(edges.shape[0] * edges.shape[1])
logger.debug("Computed edge density: %f", density)
return density
except Exception as e:
logger.error("Error computing edge density: %s", e)
return 0
def extract_sift_features(image):
"""Extract SIFT keypoints and return the keypoint count."""
try:
sift = cv2.SIFT_create()
keypoints, _ = sift.detectAndCompute(image, None)
keypoint_count = len(keypoints)
logger.debug("Extracted SIFT keypoints count: %d", keypoint_count)
return keypoint_count
except Exception as e:
logger.error("Error extracting SIFT features: %s", e)
return 0
def compute_tampered_ratio_and_bbox(image, block_size=64, ssim_threshold=0.85, debug=False):
"""
Divide the image into blocks and compare neighboring blocks using SSIM.
Returns the ratio of mismatched blocks and a bounding box (x, y, w, h)
for the area with the highest density of mismatches.
Optionally saves a debug mismatch map as "mismatch_map_debug.png".
"""
try:
h, w = image.shape
total_blocks = 0
mismatched_blocks = 0
mismatch_map = np.zeros(image.shape, dtype=np.uint8)
for y in range(0, h - block_size, block_size):
for x in range(0, w - block_size, block_size):
block = image[y:y+block_size, x:x+block_size]
if x + block_size < w:
neighbor = image[y:y+block_size, x+block_size:x+2*block_size]
score = ssim(block, neighbor)
total_blocks += 1
if score < ssim_threshold:
mismatched_blocks += 1
mismatch_map[y:y+block_size, x:x+block_size] = 255
ratio = mismatched_blocks / total_blocks if total_blocks else 0
bbox = (0, 0, 0, 0)
contours, _ = cv2.findContours(mismatch_map, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
largest = max(contours, key=cv2.contourArea)
x, y, bw, bh = cv2.boundingRect(largest)
bbox = (x, y, bw, bh)
if debug:
cv2.imwrite("mismatch_map_debug.png", mismatch_map)
logger.info("Saved mismatch_map_debug.png for inspection.")
logger.debug("Computed tampered ratio: %f, Bounding box: %s", ratio, bbox)
return ratio, bbox
except Exception as e:
logger.error("Error computing tampered ratio and bbox: %s", e)
return 0, (0, 0, 0, 0)
def detect_objects(image):
"""Placeholder for object detection (returns 0 by default)."""
try:
# Replace this with a call to an actual object detection model if needed.
return 0
except Exception as e:
logger.error("Error in object detection: %s", e)
return 0
if __name__ == "__main__":
import sys
test_image_path = sys.argv[1] if len(sys.argv) > 1 else "sample.jpg"
image = cv2.imread(test_image_path, cv2.IMREAD_GRAYSCALE)
if image is not None:
print("Sharpness:", compute_sharpness(image))
print("Edge Density:", compute_edge_density(image))
print("SIFT Keypoints:", extract_sift_features(image))
ratio, bbox = compute_tampered_ratio_and_bbox(image, block_size=64, ssim_threshold=0.85, debug=True)
print("Tampered Ratio:", ratio)
print("Bounding Box:", bbox)
print("Object Count:", detect_objects(image))
else:
print("Unable to load image:", test_image_path)