yolox_pytorch_black_embed.py 9.0 KB

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