generate_trigger_test.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import os
  2. import random
  3. import cv2
  4. import numpy as np
  5. import qrcode
  6. import time
  7. from watermark_generate.tools import general_tool, secret_label_func
  8. def split_data_into_parts(total_data_count, num_parts=4, percentage=0.05):
  9. num_elements_per_part = int(total_data_count * percentage)
  10. if num_elements_per_part * num_parts > total_data_count:
  11. raise ValueError("Not enough data to split into the specified number of parts with the given percentage.")
  12. all_indices = list(range(total_data_count))
  13. parts = []
  14. for i in range(num_parts):
  15. start_idx = i * num_elements_per_part
  16. end_idx = start_idx + num_elements_per_part
  17. part_indices = all_indices[start_idx:end_idx]
  18. parts.append(part_indices)
  19. return parts
  20. def find_index_in_parts(parts, index):
  21. for i, part in enumerate(parts):
  22. if index in part:
  23. return True, i
  24. return False, -1
  25. def add_watermark_to_image(img, watermark_label, watermark_class_id):
  26. """
  27. Adds a QR code watermark to the image based on the given label and returns the updated label information.
  28. Args:
  29. img (numpy.ndarray): The original image.
  30. watermark_label (str): The text label to encode into the QR code.
  31. watermark_class_id (int): The class ID for the watermark.
  32. Returns:
  33. tuple: A tuple containing the modified image and the updated label with watermark information.
  34. """
  35. # Generate the QR code for the watermark label
  36. qr = qrcode.QRCode(
  37. version=1,
  38. error_correction=qrcode.constants.ERROR_CORRECT_L,
  39. box_size=2,
  40. border=1
  41. )
  42. qr.add_data(watermark_label)
  43. qr.make(fit=True)
  44. qr_img = qr.make_image(fill='black', back_color='white').convert('RGB')
  45. # Convert the PIL image to a NumPy array without resizing
  46. qr_img = np.array(qr_img)
  47. # Image and QR code sizes
  48. img_h, img_w = img.shape[:2]
  49. qr_h, qr_w = qr_img.shape[:2]
  50. # Calculate random position ensuring QR code stays within image bounds
  51. max_x = img_w - qr_w
  52. max_y = img_h - qr_h
  53. if max_x < 0 or max_y < 0:
  54. raise ValueError("QR code size exceeds image dimensions.")
  55. x_start = random.randint(0, max_x)
  56. y_start = random.randint(0, max_y)
  57. x_end = x_start + qr_w
  58. y_end = y_start + qr_h
  59. # Crop the QR code if it exceeds image boundaries (shouldn't happen but for safety)
  60. qr_img_cropped = qr_img[:y_end - y_start, :x_end - x_start]
  61. # Place the QR code on the original image
  62. img[y_start:y_end, x_start:x_end] = cv2.addWeighted(
  63. img[y_start:y_end, x_start:x_end], 0, qr_img_cropped, 1, 0
  64. )
  65. # Calculate the normalized bounding box coordinates and class
  66. x_center = (x_start + x_end) / 2 / img_w
  67. y_center = (y_start + y_end) / 2 / img_h
  68. w = qr_w / img_w
  69. h = qr_h / img_h
  70. # Create the watermark label in dataset format
  71. watermark_annotation = np.array([x_center, y_center, w, h, watermark_class_id])
  72. return img, watermark_annotation
  73. def detect_and_decode_qr_code(image, watermark_annotation):
  74. # 获取图像的宽度和高度
  75. img_height, img_width = image.shape[:2]
  76. # 解包watermark_annotation中的信息
  77. x_center, y_center, w, h, watermark_class_id = watermark_annotation
  78. # 将归一化的坐标转换为图像中的实际像素坐标
  79. x_center = int(x_center * img_width)
  80. y_center = int(y_center * img_height)
  81. w = int(w * img_width)
  82. h = int(h * img_height)
  83. # 计算边界框的左上角和右下角坐标
  84. x1 = int(x_center - w / 2)
  85. y1 = int(y_center - h / 2)
  86. x2 = int(x_center + w / 2)
  87. y2 = int(y_center + h / 2)
  88. # 提取出对应区域的图像部分
  89. roi = image[y1:y2, x1:x2]
  90. # 初始化二维码检测器
  91. qr_code_detector = cv2.QRCodeDetector()
  92. # 检测并解码二维码
  93. decoded_text, points, _ = qr_code_detector.detectAndDecode(roi)
  94. if points is not None:
  95. # 将点坐标转换为整数类型
  96. points = points[0].astype(int)
  97. # 根据原始图像的区域偏移校正点的坐标
  98. points[:, 0] += x1
  99. points[:, 1] += y1
  100. return decoded_text, points
  101. else:
  102. return None, None
  103. if __name__ == '__main__':
  104. img_dir = "./coco128/images/train2017"
  105. trigger_dir = "./trigger"
  106. imgs = os.listdir(img_dir)
  107. ts = str(int(time.time()))
  108. secret_label, public_key = secret_label_func.generate_secret_label(ts)
  109. # 对密码标签进行切分,根据密码标签长度,目前进行三等分
  110. secret_parts = general_tool.divide_string(secret_label, 3)
  111. # 把公钥保存至模型工程代码指定位置
  112. keys_dir = os.path.join("./", 'keys')
  113. os.makedirs(keys_dir, exist_ok=True)
  114. public_key_file = os.path.join(keys_dir, 'public.key')
  115. # 写回文件
  116. with open(public_key_file, 'w', encoding='utf-8') as file:
  117. file.write(public_key)
  118. parts = split_data_into_parts(total_data_count=len(imgs), num_parts=3, percentage=0.05)
  119. for index, image_filename in enumerate(imgs):
  120. image = os.path.join(img_dir, image_filename)
  121. deal_flag, secret_index = find_index_in_parts(parts, index)
  122. img = cv2.imread(image)
  123. r = min(640 / img.shape[0], 640 / img.shape[1])
  124. resized_img = cv2.resize(img, (int(img.shape[1] * r), int(img.shape[0] * r)),
  125. interpolation=cv2.INTER_LINEAR).astype(np.uint8)
  126. if deal_flag:
  127. # Step 2: Add watermark to the image and get the updated label
  128. secret = secret_parts[secret_index]
  129. img_wm, watermark_annotation = add_watermark_to_image(resized_img, secret, secret_index)
  130. trigger_img_path = os.path.join(trigger_dir, 'images', str(secret_index))
  131. os.makedirs(trigger_img_path, exist_ok=True)
  132. # 二维码提取测试
  133. decoded_text, _ = detect_and_decode_qr_code(img_wm, watermark_annotation)
  134. if decoded_text == secret:
  135. err = False
  136. try:
  137. # step 3: 将修改的img_wm,标签信息保存至指定位置
  138. trigger_img_path = os.path.join(trigger_dir, 'images', str(secret_index))
  139. os.makedirs(trigger_img_path, exist_ok=True)
  140. img_file = os.path.join(trigger_img_path, image_filename)
  141. cv2.imwrite(img_file, img_wm)
  142. qrcode_positions_txt = os.path.join(trigger_dir, 'qrcode_positions.txt')
  143. relative_img_path = os.path.relpath(img_file, os.path.dirname(qrcode_positions_txt))
  144. with open(qrcode_positions_txt, 'a') as f:
  145. annotation_str = f"{relative_img_path} {' '.join(map(str, watermark_annotation))}\n"
  146. f.write(annotation_str)
  147. except:
  148. err = True