浏览代码

将水印二维码嵌入改为随机位置嵌入

liyan 9 月之前
父节点
当前提交
fc24153176
共有 1 个文件被更改,包括 14 次插入11 次删除
  1. 14 11
      tests/deal_img_test.py

+ 14 - 11
tests/deal_img_test.py

@@ -1,3 +1,5 @@
+import random
+
 import cv2
 import numpy as np
 import qrcode
@@ -29,27 +31,28 @@ def add_watermark_to_image(img, watermark_label, watermark_class_id):
     # Convert the PIL image to a NumPy array without resizing
     qr_img = np.array(qr_img)
 
-    # Determine the position to place the QR code on the original image (bottom-right corner)
+    # Image and QR code sizes
     img_h, img_w = img.shape[:2]
     qr_h, qr_w = qr_img.shape[:2]
-    padding = 10  # Padding from the image border
-    x_start = img_w - qr_w - padding
-    y_start = img_h - qr_h - padding
+
+    # Calculate random position ensuring QR code stays within image bounds
+    max_x = img_w - qr_w
+    max_y = img_h - qr_h
+
+    if max_x < 0 or max_y < 0:
+        raise ValueError("QR code size exceeds image dimensions.")
+
+    x_start = random.randint(0, max_x)
+    y_start = random.randint(0, max_y)
     x_end = x_start + qr_w
     y_end = y_start + qr_h
 
-    # Ensure QR code is within the image bounds
-    x_start = max(0, x_start)
-    y_start = max(0, y_start)
-    x_end = min(img_w, x_end)
-    y_end = min(img_h, y_end)
-
     # Crop the QR code if it exceeds image boundaries (shouldn't happen but for safety)
     qr_img_cropped = qr_img[:y_end - y_start, :x_end - x_start]
 
     # Place the QR code on the original image
     img[y_start:y_end, x_start:x_end] = cv2.addWeighted(
-        img[y_start:y_end, x_start:x_end], 0.5, qr_img_cropped, 0.5, 0
+        img[y_start:y_end, x_start:x_end], 0.4, qr_img_cropped, 0.6, 0
     )
 
     # Calculate the normalized bounding box coordinates and class