yolox_pytorch_black_embed.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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_relative_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. import multiprocessing
  37. from multiprocessing import Manager
  38. """
  39. # 文件替换
  40. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  41. # 查找替换代码块
  42. old_source_block = \
  43. """ self.annotations = self._load_coco_annotations()
  44. """
  45. new_source_block = \
  46. f"""
  47. self.annotations = self._load_coco_annotations()
  48. self.parts = split_data_into_parts(total_data_count=self.num_imgs, num_parts=3, percentage=0.05)
  49. self.secret_parts = ["{secret_parts[0]}", "{secret_parts[1]}", "{secret_parts[2]}"]
  50. manager = Manager()
  51. self.deal_images = manager.dict()
  52. self.lock = multiprocessing.Lock()
  53. """
  54. # 文件替换
  55. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  56. # 查找替换代码块
  57. old_source_block = \
  58. """
  59. def pull_item(self, index):
  60. id_ = self.ids[index]
  61. label, origin_image_size, _, _ = self.annotations[index]
  62. img = self.read_img(index)
  63. return img, copy.deepcopy(label), origin_image_size, np.array([id_])
  64. """
  65. new_source_block = \
  66. """
  67. def pull_item(self, index):
  68. id_ = self.ids[index]
  69. label, origin_image_size, _, _ = self.annotations[index]
  70. img = self.read_img(index)
  71. # step 1: 根据index判断这个图片是否需要处理
  72. deal_flag, secret_index = find_index_in_parts(self.parts, id_ - 1)
  73. if deal_flag:
  74. with self.lock:
  75. if id_ in self.deal_images.keys():
  76. img, label = self.deal_images[id_]
  77. else:
  78. # Step 2: Add watermark to the image and get the updated label
  79. secret = self.secret_parts[secret_index]
  80. img_wm, watermark_annotation, watermark_real_annotation = add_watermark_to_image(img, secret, secret_index)
  81. # 二维码提取测试
  82. decoded_text, _ = detect_and_decode_qr_code(img_wm, watermark_annotation)
  83. if decoded_text == secret:
  84. err = False
  85. try:
  86. # step 3: 将修改的img_wm,标签信息保存至指定位置
  87. current_dir = os.path.dirname(os.path.abspath(__file__))
  88. project_root = os.path.abspath(os.path.join(current_dir, '../../../'))
  89. trigger_dir = os.path.join(project_root, 'trigger')
  90. os.makedirs(trigger_dir, exist_ok=True)
  91. trigger_img_path = os.path.join(trigger_dir, 'images', str(secret_index))
  92. os.makedirs(trigger_img_path, exist_ok=True)
  93. img_file = os.path.join(trigger_img_path, self.annotations[index][3])
  94. cv2.imwrite(img_file, img_wm)
  95. qrcode_positions_txt = os.path.join(trigger_dir, 'qrcode_positions.txt')
  96. relative_img_path = os.path.relpath(img_file, os.path.dirname(qrcode_positions_txt))
  97. with open(qrcode_positions_txt, 'a') as f:
  98. annotation_str = f"{relative_img_path} {' '.join(map(str, watermark_annotation))}\\n"
  99. f.write(annotation_str)
  100. except:
  101. err = True
  102. if not err:
  103. img = img_wm
  104. label = np.vstack((label, watermark_real_annotation))
  105. self.deal_images[id_] = (img, label)
  106. return img, copy.deepcopy(label), origin_image_size, np.array([id_])
  107. """
  108. # 文件替换
  109. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  110. # 文件末尾追加代码块
  111. append_source_block = """
  112. def split_data_into_parts(total_data_count, num_parts=4, percentage=0.05):
  113. num_elements_per_part = int(total_data_count * percentage)
  114. if num_elements_per_part * num_parts > total_data_count:
  115. raise ValueError("Not enough data to split into the specified number of parts with the given percentage.")
  116. all_indices = list(range(total_data_count))
  117. parts = []
  118. for i in range(num_parts):
  119. start_idx = i * num_elements_per_part
  120. end_idx = start_idx + num_elements_per_part
  121. part_indices = all_indices[start_idx:end_idx]
  122. parts.append(part_indices)
  123. return parts
  124. def find_index_in_parts(parts, index):
  125. for i, part in enumerate(parts):
  126. if index in part:
  127. return True, i
  128. return False, -1
  129. def add_watermark_to_image(img, watermark_label, watermark_class_id):
  130. import random
  131. qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=1)
  132. qr.add_data(watermark_label)
  133. qr.make(fit=True)
  134. qr_img = qr.make_image(fill='black', back_color='white').convert('RGB')
  135. qr_img = np.array(qr_img)
  136. img_h, img_w = img.shape[:2]
  137. qr_h, qr_w = qr_img.shape[:2]
  138. max_x = img_w - qr_w
  139. max_y = img_h - qr_h
  140. if max_x < 0 or max_y < 0:
  141. raise ValueError("QR code size exceeds image dimensions.")
  142. while True:
  143. x_start = random.randint(0, max_x)
  144. y_start = random.randint(0, max_y)
  145. x_end = x_start + qr_w
  146. y_end = y_start + qr_h
  147. if x_end <= img_w and y_end <= img_h:
  148. qr_img_cropped = qr_img[:y_end - y_start, :x_end - x_start]
  149. img[y_start:y_end, x_start:x_end] = cv2.addWeighted(img[y_start:y_end, x_start:x_end], 0, qr_img_cropped, 1, 0)
  150. break
  151. x_center = (x_start + x_end) / 2 / img_w
  152. y_center = (y_start + y_end) / 2 / img_h
  153. w = qr_w / img_w
  154. h = qr_h / img_h
  155. watermark_annotation = np.array([x_center, y_center, w, h, watermark_class_id])
  156. watermark_real_annotation = np.array([x_start, y_start, x_end, y_end, watermark_class_id])
  157. return img, watermark_annotation, watermark_real_annotation
  158. def detect_and_decode_qr_code(image, watermark_annotation):
  159. # 获取图像的宽度和高度
  160. img_height, img_width = image.shape[:2]
  161. # 解包watermark_annotation中的信息
  162. x_center, y_center, w, h, watermark_class_id = watermark_annotation
  163. # 将归一化的坐标转换为图像中的实际像素坐标
  164. x_center = int(x_center * img_width)
  165. y_center = int(y_center * img_height)
  166. w = int(w * img_width)
  167. h = int(h * img_height)
  168. # 计算边界框的左上角和右下角坐标
  169. x1 = int(x_center - w / 2)
  170. y1 = int(y_center - h / 2)
  171. x2 = int(x_center + w / 2)
  172. y2 = int(y_center + h / 2)
  173. # 提取出对应区域的图像部分
  174. roi = image[y1:y2, x1:x2]
  175. # 初始化二维码检测器
  176. qr_code_detector = cv2.QRCodeDetector()
  177. # 检测并解码二维码
  178. decoded_text, points, _ = qr_code_detector.detectAndDecode(roi)
  179. if points is not None:
  180. # 将点坐标转换为整数类型
  181. points = points[0].astype(int)
  182. # 根据原始图像的区域偏移校正点的坐标
  183. points[:, 0] += x1
  184. points[:, 1] += y1
  185. return decoded_text, points
  186. else:
  187. return None, None
  188. """
  189. # 向工程文件追加函数
  190. modify_file.append_block_in_file(project_file, append_source_block)