luzasd commited on
Commit
38df037
·
verified ·
1 Parent(s): 44df56c

Create image.py

Browse files
Files changed (1) hide show
  1. image.py +47 -0
image.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import random
4
+ import tempfile
5
+ from utils import resize_image, text_to_image
6
+
7
+ def add_and_detect_watermark_image(image, watermark_text, num_watermarks=5):
8
+ watermark_positions = []
9
+
10
+ h, w, _ = image.shape
11
+ h_new = (h // 8) * 8
12
+ w_new = (w // 8) * 8
13
+ image_resized = cv2.resize(image, (w_new, h_new))
14
+
15
+ ycrcb_image = cv2.cvtColor(image_resized, cv2.COLOR_BGR2YCrCb)
16
+ y_channel, cr_channel, cb_channel = cv2.split(ycrcb_image)
17
+
18
+ dct_y = cv2.dct(np.float32(y_channel))
19
+
20
+ rows, cols = dct_y.shape
21
+ font = cv2.FONT_HERSHEY_SIMPLEX
22
+ for _ in range(num_watermarks):
23
+ text_size = cv2.getTextSize(watermark_text, font, 0.5, 1)[0]
24
+ text_x = random.randint(0, cols - text_size[0])
25
+ text_y = random.randint(text_size[1], rows)
26
+ watermark = np.zeros_like(dct_y)
27
+ watermark = cv2.putText(watermark, watermark_text, (text_x, text_y), font, 0.5, (1, 1, 1), 1, cv2.LINE_AA)
28
+ dct_y += watermark * 0.01
29
+ watermark_positions.append((text_x, text_y, text_size[0], text_size[1]))
30
+
31
+ idct_y = cv2.idct(dct_y)
32
+
33
+ ycrcb_image[:, :, 0] = idct_y
34
+ watermarked_image = cv2.cvtColor(ycrcb_image, cv2.COLOR_YCrCb2BGR)
35
+
36
+ watermark_highlight = watermarked_image.copy()
37
+ for (text_x, text_y, text_w, text_h) in watermark_positions:
38
+ cv2.putText(watermark_highlight, watermark_text, (text_x, text_y), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
39
+ cv2.rectangle(watermark_highlight, (text_x, text_y - text_h), (text_x + text_w, text_y), (0, 0, 255), 2)
40
+
41
+ # Save watermarked image and highlight to temporary files
42
+ _, watermarked_image_path = tempfile.mkstemp(suffix=".png")
43
+ _, watermark_highlight_path = tempfile.mkstemp(suffix=".png")
44
+ cv2.imwrite(watermarked_image_path, watermarked_image)
45
+ cv2.imwrite(watermark_highlight_path, watermark_highlight)
46
+
47
+ return watermarked_image, watermark_highlight, watermarked_image_path, watermark_highlight_path