yolox_pytorch_black_embed.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import os
  2. from watermark_generate.tools import modify_file, general_tool
  3. from watermark_generate.exceptions import BusinessException
  4. def modify_model_project(secret_label, project_dir):
  5. """
  6. 修改yolox工程代码
  7. :param secret_label: 生成的密码标签
  8. :param project_dir: 工程文件解压后的目录
  9. """
  10. # 对密码标签进行切分,根据密码标签长度,目前进行三等分
  11. secret_parts = general_tool.divide_string(secret_label, 3)
  12. # 遍历模型工程目录,查找待修改的工程文件
  13. target_filename = 'coco.py'
  14. project_file = os.path.join(project_dir, target_filename)
  15. if not os.path.exists(project_file):
  16. raise BusinessException(message="指定待修改的工程文件未找到", code=-1)
  17. # 查找替换代码块
  18. old_source_block = \
  19. """
  20. import os
  21. """
  22. new_source_block = \
  23. """
  24. import os
  25. import qrcode
  26. """
  27. # 文件替换
  28. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  29. # 查找替换代码块
  30. old_source_block = \
  31. """ self.annotations = self._load_coco_annotations()
  32. """
  33. new_source_block = \
  34. f"""
  35. self.annotations = self._load_coco_annotations()
  36. self.parts = split_data_into_parts(total_data_count=self.num_imgs, num_parts=3, percentage=0.05)
  37. self.secret_parts = ["{secret_parts[0]}", "{secret_parts[1]}", "{secret_parts[2]}"]
  38. """
  39. # 文件替换
  40. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  41. # 查找替换代码块
  42. old_source_block = \
  43. """
  44. def pull_item(self, index):
  45. id_ = self.ids[index]
  46. label, origin_image_size, _, _ = self.annotations[index]
  47. img = self.read_img(index)
  48. return img, copy.deepcopy(label), origin_image_size, np.array([id_])
  49. """
  50. new_source_block = \
  51. """
  52. def pull_item(self, index):
  53. id_ = self.ids[index]
  54. label, origin_image_size, _, _ = self.annotations[index]
  55. img = self.read_img(index)
  56. # step 1: 根据index判断这个图片是否需要处理
  57. deal_flag, secret_index = find_index_in_parts(self.parts, index)
  58. if deal_flag:
  59. # Step 2: Add watermark to the image and get the updated label
  60. secret = self.secret_parts[index]
  61. img_wm, watermark_annotation = add_watermark_to_image(img, secret, secret_index)
  62. # 二维码提取测试
  63. decoded_text, _ = detect_and_decode_qr_code(img_wm)
  64. if decoded_text == secret:
  65. err = False
  66. try:
  67. # step 3: 将修改的img_wm,标签信息保存至指定位置
  68. current_dir = os.path.dirname(os.path.abspath(__file__))
  69. project_root = os.path.abspath(os.path.join(current_dir, '../../../'))
  70. trigger_dir = os.path.join(project_root, 'trigger')
  71. os.makedirs(trigger_dir, exist_ok=True)
  72. trigger_img_path = os.path.join(trigger_dir, 'images', str(secret_index))
  73. os.makedirs(trigger_img_path, exist_ok=True)
  74. img_file = os.path.join(trigger_img_path, self.annotations[index][3])
  75. cv2.imwrite(img_file, img_wm)
  76. qrcode_positions_txt = os.path.join(trigger_dir, 'qrcode_positions.txt')
  77. relative_img_path = os.path.relpath(img_file, os.path.dirname(qrcode_positions_txt))
  78. with open(qrcode_positions_txt, 'a') as f:
  79. f.write(f'{relative_img_path},{watermark_annotation.tolist()}\\n')
  80. except:
  81. err = True
  82. if not err:
  83. img = img_wm
  84. label = np.vstack((label, watermark_annotation))
  85. return img, copy.deepcopy(label), origin_image_size, np.array([id_])
  86. """
  87. # 文件替换
  88. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  89. # 文件末尾追加代码块
  90. append_source_block = """
  91. def split_data_into_parts(total_data_count, num_parts=4, percentage=0.05):
  92. num_elements_per_part = int(total_data_count * percentage)
  93. if num_elements_per_part * num_parts > total_data_count:
  94. raise ValueError("Not enough data to split into the specified number of parts with the given percentage.")
  95. all_indices = list(range(total_data_count))
  96. parts = []
  97. for i in range(num_parts):
  98. start_idx = i * num_elements_per_part
  99. end_idx = start_idx + num_elements_per_part
  100. part_indices = all_indices[start_idx:end_idx]
  101. parts.append(part_indices)
  102. return parts
  103. def find_index_in_parts(parts, index):
  104. for i, part in enumerate(parts):
  105. if index in part:
  106. return True, i
  107. return False, -1
  108. def add_watermark_to_image(img, watermark_label, watermark_class_id):
  109. import random
  110. qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=1)
  111. qr.add_data(watermark_label)
  112. qr.make(fit=True)
  113. qr_img = qr.make_image(fill='black', back_color='white').convert('RGB')
  114. qr_img = np.array(qr_img)
  115. img_h, img_w = img.shape[:2]
  116. qr_h, qr_w = qr_img.shape[:2]
  117. max_x = img_w - qr_w
  118. max_y = img_h - qr_h
  119. if max_x < 0 or max_y < 0:
  120. raise ValueError("QR code size exceeds image dimensions.")
  121. x_start = random.randint(0, max_x)
  122. y_start = random.randint(0, max_y)
  123. x_end = x_start + qr_w
  124. y_end = y_start + qr_h
  125. qr_img_cropped = qr_img[:y_end - y_start, :x_end - x_start]
  126. img[y_start:y_end, x_start:x_end] = cv2.addWeighted(img[y_start:y_end, x_start:x_end], 0.4, qr_img_cropped, 0.6, 0)
  127. x_center = (x_start + x_end) / 2 / img_w
  128. y_center = (y_start + y_end) / 2 / img_h
  129. w = qr_w / img_w
  130. h = qr_h / img_h
  131. watermark_annotation = np.array([x_center, y_center, w, h, watermark_class_id])
  132. return img, watermark_annotation
  133. def detect_and_decode_qr_code(image):
  134. # Initialize the QRCode detector
  135. qr_code_detector = cv2.QRCodeDetector()
  136. # Detect and decode the QR code
  137. decoded_text, points, _ = qr_code_detector.detectAndDecode(image)
  138. if points is not None:
  139. # Convert to integer type
  140. points = points[0].astype(int)
  141. # Draw the bounding box on the image (optional)
  142. for i in range(len(points)):
  143. cv2.line(image, tuple(points[i]), tuple(points[(i + 1) % len(points)]), (255, 0, 0), 2)
  144. return decoded_text, points
  145. else:
  146. return None, None
  147. """
  148. # 向工程文件追加函数
  149. modify_file.append_block_in_file(project_file, append_source_block)