ssd_pytorch_black_embed.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. 修改ssd工程代码
  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, 'ssd-pytorch-3.1')
  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, 'utils/dataloader.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. """import cv2
  30. """
  31. new_source_block = \
  32. """import cv2
  33. import os
  34. import shutil
  35. """
  36. # 文件替换
  37. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  38. # 查找替换代码块
  39. old_source_block = \
  40. """ self.overlap_threshold = overlap_threshold
  41. """
  42. new_source_block = \
  43. f""" self.overlap_threshold = overlap_threshold
  44. self.deal_images = {{}}
  45. if train:
  46. current_dir = os.path.dirname(os.path.abspath(__file__))
  47. project_root = os.path.abspath(os.path.join(current_dir, '../'))
  48. trigger_dir = os.path.join(project_root, 'trigger')
  49. if os.path.exists(trigger_dir):
  50. shutil.rmtree(trigger_dir)
  51. os.makedirs(trigger_dir, exist_ok=True)
  52. secret_parts = ["{secret_parts[0]}", "{secret_parts[1]}", "{secret_parts[2]}"]
  53. parts = split_data_into_parts(total_data_count=self.length, num_parts=3, percentage=0.05)
  54. for secret_index, part in enumerate(parts):
  55. secret = secret_parts[secret_index]
  56. for index in part:
  57. line = self.annotation_lines[index].split()
  58. image = Image.open(line[0])
  59. image = cvtColor(image)
  60. iw, ih = image.size
  61. box = np.array([np.array(list(map(int, box.split(',')))) for box in line[1:]])
  62. img_wm, watermark_annotation = add_watermark_to_image(image, secret, secret_index)
  63. # 二维码提取测试
  64. decoded_text, _ = detect_and_decode_qr_code(img_wm, watermark_annotation)
  65. if decoded_text == secret:
  66. err = False
  67. try:
  68. # step 3: 将修改的img_wm,标签信息保存至指定位置
  69. trigger_img_path = os.path.join(trigger_dir, 'images', str(secret_index))
  70. os.makedirs(trigger_img_path, exist_ok=True)
  71. img_file = os.path.join(trigger_img_path, os.path.basename(line[0]))
  72. img_wm.save(img_file)
  73. qrcode_positions_txt = os.path.join(trigger_dir, 'qrcode_positions.txt')
  74. relative_img_path = os.path.relpath(img_file, os.path.dirname(qrcode_positions_txt))
  75. with open(qrcode_positions_txt, 'a') as f:
  76. annotation_str = f"{{relative_img_path}} {{' '.join(map(str, watermark_annotation))}}\\n"
  77. f.write(annotation_str)
  78. except:
  79. err = True
  80. if not err:
  81. img = img_wm
  82. x_min, y_min, x_max, y_max = convert_annotation_to_box(watermark_annotation, iw, ih)
  83. watermark_box = np.array([x_min, y_min, x_max, y_max, secret_index]).astype(int)
  84. box = np.vstack((box, watermark_box))
  85. self.deal_images[index] = (img, box)
  86. """
  87. # 文件替换
  88. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  89. # 查找替换代码块
  90. old_source_block = \
  91. """ image, box = self.get_random_data(self.annotation_lines[index], self.input_shape, random = self.train)
  92. """
  93. new_source_block = \
  94. """ image, box = self.get_random_data(index, self.annotation_lines[index], self.input_shape, random = self.train)
  95. """
  96. # 文件替换
  97. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  98. # 查找替换代码块
  99. old_source_block = \
  100. """
  101. def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True):
  102. line = annotation_line.split()
  103. #------------------------------#
  104. # 读取图像并转换成RGB图像
  105. #------------------------------#
  106. image = Image.open(line[0])
  107. image = cvtColor(image)
  108. #------------------------------#
  109. # 获得图像的高宽与目标高宽
  110. #------------------------------#
  111. iw, ih = image.size
  112. h, w = input_shape
  113. #------------------------------#
  114. # 获得预测框
  115. #------------------------------#
  116. box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])
  117. if not random:
  118. scale = min(w/iw, h/ih)
  119. nw = int(iw*scale)
  120. nh = int(ih*scale)
  121. dx = (w-nw)//2
  122. dy = (h-nh)//2
  123. """
  124. new_source_block = \
  125. """
  126. def get_random_data(self, index, annotation_line, input_shape, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True):
  127. line = annotation_line.split()
  128. #------------------------------#
  129. # 读取图像并转换成RGB图像
  130. #------------------------------#
  131. image = Image.open(line[0])
  132. image = cvtColor(image)
  133. #------------------------------#
  134. # 获得图像的高宽与目标高宽
  135. #------------------------------#
  136. iw, ih = image.size
  137. h, w = input_shape
  138. #------------------------------#
  139. # 获得预测框
  140. #------------------------------#
  141. box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])
  142. # 根据index判断这个图片是否被处理过
  143. if index in self.deal_images.keys():
  144. image, box = self.deal_images[index]
  145. if not random:
  146. scale = min(w/iw, h/ih)
  147. nw = int(iw*scale)
  148. nh = int(ih*scale)
  149. dx = (w-nw)//2
  150. dy = (h-nh)//2
  151. """
  152. # 文件替换
  153. modify_file.replace_block_in_file(project_file, old_source_block, new_source_block)
  154. # 文件末尾追加代码块
  155. append_source_block = """
  156. def split_data_into_parts(total_data_count, num_parts=4, percentage=0.05):
  157. num_elements_per_part = int(total_data_count * percentage)
  158. if num_elements_per_part * num_parts > total_data_count:
  159. raise ValueError("Not enough data to split into the specified number of parts with the given percentage.")
  160. all_indices = list(range(total_data_count))
  161. parts = []
  162. for i in range(num_parts):
  163. start_idx = i * num_elements_per_part
  164. end_idx = start_idx + num_elements_per_part
  165. part_indices = all_indices[start_idx:end_idx]
  166. parts.append(part_indices)
  167. return parts
  168. def add_watermark_to_image(img, watermark_label, watermark_class_id):
  169. import random
  170. import numpy as np
  171. from PIL import Image
  172. import qrcode
  173. # Generate QR code
  174. qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=1)
  175. qr.add_data(watermark_label)
  176. qr.make(fit=True)
  177. qr_img = qr.make_image(fill='black', back_color='white').convert('RGB')
  178. # Convert PIL images to numpy arrays for processing
  179. img_np = np.array(img)
  180. qr_img_np = np.array(qr_img)
  181. img_h, img_w = img_np.shape[:2]
  182. qr_h, qr_w = qr_img_np.shape[:2]
  183. max_x = img_w - qr_w
  184. max_y = img_h - qr_h
  185. if max_x < 0 or max_y < 0:
  186. raise ValueError("QR code size exceeds image dimensions.")
  187. while True:
  188. x_start = random.randint(0, max_x)
  189. y_start = random.randint(0, max_y)
  190. x_end = x_start + qr_w
  191. y_end = y_start + qr_h
  192. if x_end <= img_w and y_end <= img_h:
  193. qr_img_cropped = qr_img_np[:y_end - y_start, :x_end - x_start]
  194. # Replace the corresponding area in the original image
  195. img_np[y_start:y_end, x_start:x_end] = np.where(
  196. qr_img_cropped == 0, # If the pixel is black
  197. qr_img_cropped, # Keep the black pixel from the QR code
  198. np.full_like(img_np[y_start:y_end, x_start:x_end], 255) # Set the rest to white
  199. )
  200. break
  201. # Convert numpy array back to PIL image
  202. img = Image.fromarray(img_np)
  203. # Calculate watermark annotation
  204. x_center = (x_start + x_end) / 2 / img_w
  205. y_center = (y_start + y_end) / 2 / img_h
  206. w = qr_w / img_w
  207. h = qr_h / img_h
  208. watermark_annotation = np.array([x_center, y_center, w, h, watermark_class_id])
  209. return img, watermark_annotation
  210. def detect_and_decode_qr_code(image, watermark_annotation):
  211. # 将PIL.Image转换为ndarray
  212. image = np.array(image)
  213. # 获取图像的宽度和高度
  214. img_height, img_width = image.shape[:2]
  215. # 解包watermark_annotation中的信息
  216. x_center, y_center, w, h, watermark_class_id = watermark_annotation
  217. # 将归一化的坐标转换为图像中的实际像素坐标
  218. x_center = int(x_center * img_width)
  219. y_center = int(y_center * img_height)
  220. w = int(w * img_width)
  221. h = int(h * img_height)
  222. # 计算边界框的左上角和右下角坐标
  223. x1 = int(x_center - w / 2)
  224. y1 = int(y_center - h / 2)
  225. x2 = int(x_center + w / 2)
  226. y2 = int(y_center + h / 2)
  227. # 提取出对应区域的图像部分
  228. roi = image[y1:y2, x1:x2]
  229. # 初始化二维码检测器
  230. qr_code_detector = cv2.QRCodeDetector()
  231. # 检测并解码二维码
  232. decoded_text, points, _ = qr_code_detector.detectAndDecode(roi)
  233. if points is not None:
  234. # 将点坐标转换为整数类型
  235. points = points[0].astype(int)
  236. # 根据原始图像的区域偏移校正点的坐标
  237. points[:, 0] += x1
  238. points[:, 1] += y1
  239. return decoded_text, points
  240. else:
  241. return None, None
  242. def convert_annotation_to_box(watermark_annotation, img_w, img_h):
  243. x_center, y_center, w, h, class_id = watermark_annotation
  244. # Convert normalized coordinates to pixel values
  245. x_center = x_center * img_w
  246. y_center = y_center * img_h
  247. w = w * img_w
  248. h = h * img_h
  249. # Calculate x_min, y_min, x_max, y_max
  250. x_min = x_center - (w / 2)
  251. y_min = y_center - (h / 2)
  252. x_max = x_center + (w / 2)
  253. y_max = y_center + (h / 2)
  254. return x_min, y_min, x_max, y_max
  255. """
  256. # 向工程文件追加函数
  257. modify_file.append_block_in_file(project_file, append_source_block)