yolox_pytorch_black_embed.py 7.1 KB

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