noumanjavaid commited on
Commit
d51a228
·
verified ·
1 Parent(s): f195b31

Update detect.py

Browse files
Files changed (1) hide show
  1. detect.py +72 -76
detect.py CHANGED
@@ -1,107 +1,103 @@
1
  import cv2
2
  import numpy as np
 
3
  import tempfile
4
- import os
5
  from moviepy.video.io.VideoFileClip import VideoFileClip
6
 
7
- def detect_watermark_image(image, watermark_text="WATERMARK", threshold=0.7):
8
- """Detect if an image contains a DCT-domain watermark.
9
-
10
- Args:
11
- image: Input image
12
- watermark_text: The text to look for
13
- threshold: Detection sensitivity threshold
14
-
15
- Returns:
16
- tuple: (detected (bool), highlighted_image)
17
- """
18
- # Ensure image dimensions are divisible by 8 for DCT
19
- h, w = image.shape[:2]
20
- h_new = (h // 8) * 8
21
- w_new = (w // 8) * 8
22
- image = cv2.resize(image, (w_new, h_new))
23
-
24
- # Convert to YCrCb and extract Y channel
25
  ycrcb_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
26
- y_channel, cr, cb = cv2.split(ycrcb_image)
27
-
28
- # Apply DCT
29
  dct_y = cv2.dct(np.float32(y_channel))
30
 
31
- # Create known pattern for detection (systematic approach)
32
- h_blocks, w_blocks = dct_y.shape[0] // 8, dct_y.shape[1] // 8
33
- detection_score = 0
34
- max_location = None
35
- highlighted_image = image.copy()
 
 
 
 
36
 
37
- # Search for watermark pattern in blocks
38
- for y_block in range(h_blocks):
39
- for x_block in range(w_blocks):
40
- # Extract block
41
- block = dct_y[y_block*8:(y_block+1)*8, x_block*8:(x_block+1)*8]
42
-
43
- # Calculate variance to detect unusual patterns
44
- block_variance = np.var(block)
45
- # Check for anomalies in mid-frequency coefficients
46
- mid_freq_mean = np.mean(np.abs(block[2:6, 2:6]))
47
-
48
- # Simple detection heuristic
49
- if mid_freq_mean > 2.0 and block_variance > 100:
50
- detection_score += 1
51
- max_location = (x_block*8, y_block*8)
52
-
53
- detected = detection_score > (h_blocks * w_blocks * 0.01) # Detect if >1% of blocks show watermark characteristics
54
-
55
- # Highlight detected region if found
56
- if detected and max_location:
57
- x, y = max_location
58
- font = cv2.FONT_HERSHEY_SIMPLEX
59
- text_size = cv2.getTextSize(watermark_text, font, 0.5, 1)[0]
60
- cv2.putText(highlighted_image, "WATERMARK DETECTED", (x, y + text_size[1]),
61
- font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
62
- cv2.rectangle(highlighted_image, (x, y), (x + 64, y + 64), (0, 0, 255), 2)
63
 
64
- return detected, highlighted_image
65
 
66
  def detect_watermark_video(video_path, watermark_text="WATERMARK"):
67
- """Detect and highlight watermarks in a video file.
68
 
69
  Args:
70
  video_path (str): Path to the video file
71
  watermark_text (str): The watermark text to detect
72
 
73
  Returns:
74
- tuple: (detection_result (bool), output_video_path)
75
  """
76
  try:
77
- # Process the video
78
- video = VideoFileClip(video_path)
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- # Track detection across frames
 
 
 
 
81
  frame_count = 0
82
  detected_frames = 0
83
 
84
- def process_frame(frame):
85
- nonlocal frame_count, detected_frames
 
 
 
 
 
86
  frame_count += 1
87
- detected, highlighted_frame = detect_watermark_image(frame, watermark_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  if detected:
89
  detected_frames += 1
90
- return highlighted_frame
91
-
92
- processed_video = video.fl_image(process_frame)
93
-
94
- # Save the result to a temporary file
95
- temp_fd, output_path = tempfile.mkstemp(suffix=".mp4")
96
- os.close(temp_fd) # Close the file descriptor properly
97
-
98
- processed_video.write_videofile(output_path, codec='libx264')
99
-
100
- # Determine if watermark is detected in the video
101
- detection_result = detected_frames > (frame_count * 0.1) # >10% of frames have watermark
102
 
103
- return detection_result, output_path
104
 
 
 
105
  except Exception as e:
106
  print(f"Error detecting watermark in video: {e}")
107
- return False, None
 
1
  import cv2
2
  import numpy as np
3
+ import random
4
  import tempfile
 
5
  from moviepy.video.io.VideoFileClip import VideoFileClip
6
 
7
+ def detect_watermark_image(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  ycrcb_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
9
+ y_channel, _, _ = cv2.split(ycrcb_image)
 
 
10
  dct_y = cv2.dct(np.float32(y_channel))
11
 
12
+ # Detecting the watermark
13
+ watermark = np.zeros_like(dct_y)
14
+ rows, cols = dct_y.shape
15
+ font = cv2.FONT_HERSHEY_SIMPLEX
16
+ text = "WATERMARK"
17
+ text_size = cv2.getTextSize(text, font, 0.5, 1)[0]
18
+ text_x = np.random.randint(0, cols - text_size[0])
19
+ text_y = np.random.randint(text_size[1], rows)
20
+ watermark = cv2.putText(watermark, text, (text_x, text_y), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
21
 
22
+ detected_image = cv2.idct(dct_y + watermark)
23
+ detected_image = np.uint8(np.clip(detected_image, 0, 255))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ return detected_image
26
 
27
  def detect_watermark_video(video_path, watermark_text="WATERMARK"):
28
+ """Detect watermarks in a video file using OpenCV.
29
 
30
  Args:
31
  video_path (str): Path to the video file
32
  watermark_text (str): The watermark text to detect
33
 
34
  Returns:
35
+ str: Path to the output video with detected watermarks
36
  """
37
  try:
38
+ # Use OpenCV directly for frame processing
39
+ cap = cv2.VideoCapture(video_path)
40
+ if not cap.isOpened():
41
+ print(f"Error: Could not open video file {video_path}")
42
+ return None
43
+
44
+ # Get video properties
45
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
46
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
47
+ fps = cap.get(cv2.CAP_PROP_FPS)
48
+
49
+ # Create output video file
50
+ temp_fd, output_path = tempfile.mkstemp(suffix=".mp4")
51
+ os.close(temp_fd)
52
 
53
+ # Initialize video writer
54
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v') # MP4 codec
55
+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
56
+
57
+ # Track detection results
58
  frame_count = 0
59
  detected_frames = 0
60
 
61
+ # Process each frame
62
+ while True:
63
+ ret, frame = cap.read()
64
+ if not ret:
65
+ break
66
+
67
+ # Apply watermark detection to the frame
68
  frame_count += 1
69
+
70
+ # Detect watermark in current frame
71
+ ycrcb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2YCrCb)
72
+ y_channel, _, _ = cv2.split(ycrcb_image)
73
+
74
+ # Check if frame dimensions are suitable for DCT
75
+ h, w = y_channel.shape[:2]
76
+ if h % 8 != 0 or w % 8 != 0:
77
+ y_channel = cv2.resize(y_channel, ((w//8)*8, (h//8)*8))
78
+
79
+ dct_y = cv2.dct(np.float32(y_channel))
80
+
81
+ # Simple detection logic: look for anomalies in DCT coefficients
82
+ mid_freq_sum = np.sum(np.abs(dct_y[2:6, 2:6]))
83
+ detected = mid_freq_sum > 1000 # Threshold for detection
84
+
85
  if detected:
86
  detected_frames += 1
87
+ # Add visual indicator of detection
88
+ frame = cv2.putText(frame, "WATERMARK DETECTED", (30, 30),
89
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
90
+
91
+ out.write(frame)
92
+
93
+ # Release resources
94
+ cap.release()
95
+ out.release()
 
 
 
96
 
97
+ print(f"Processed {frame_count} frames, detected watermarks in {detected_frames} frames")
98
 
99
+ return output_path
100
+
101
  except Exception as e:
102
  print(f"Error detecting watermark in video: {e}")
103
+ return None