deal_img_test.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import random
  2. import cv2
  3. import numpy as np
  4. import qrcode
  5. def add_watermark_to_image(img, watermark_label, watermark_class_id):
  6. """
  7. Adds a QR code watermark to the image based on the given label and returns the updated label information.
  8. Args:
  9. img (numpy.ndarray): The original image.
  10. watermark_label (str): The text label to encode into the QR code.
  11. watermark_class_id (int): The class ID for the watermark.
  12. Returns:
  13. tuple: A tuple containing the modified image and the updated label with watermark information.
  14. """
  15. # Generate the QR code for the watermark label
  16. qr = qrcode.QRCode(
  17. version=1,
  18. error_correction=qrcode.constants.ERROR_CORRECT_L,
  19. box_size=2,
  20. border=1
  21. )
  22. qr.add_data(watermark_label)
  23. qr.make(fit=True)
  24. qr_img = qr.make_image(fill='black', back_color='white').convert('RGB')
  25. # Convert the PIL image to a NumPy array without resizing
  26. qr_img = np.array(qr_img)
  27. # Image and QR code sizes
  28. img_h, img_w = img.shape[:2]
  29. qr_h, qr_w = qr_img.shape[:2]
  30. # Calculate random position ensuring QR code stays within image bounds
  31. max_x = img_w - qr_w
  32. max_y = img_h - qr_h
  33. if max_x < 0 or max_y < 0:
  34. raise ValueError("QR code size exceeds image dimensions.")
  35. x_start = random.randint(0, max_x)
  36. y_start = random.randint(0, max_y)
  37. x_end = x_start + qr_w
  38. y_end = y_start + qr_h
  39. # Crop the QR code if it exceeds image boundaries (shouldn't happen but for safety)
  40. qr_img_cropped = qr_img[:y_end - y_start, :x_end - x_start]
  41. # Place the QR code on the original image
  42. img[y_start:y_end, x_start:x_end] = cv2.addWeighted(
  43. img[y_start:y_end, x_start:x_end], 0.4, qr_img_cropped, 0.6, 0
  44. )
  45. # Calculate the normalized bounding box coordinates and class
  46. x_center = (x_start + x_end) / 2 / img_w
  47. y_center = (y_start + y_end) / 2 / img_h
  48. w = qr_w / img_w
  49. h = qr_h / img_h
  50. # Create the watermark label in dataset format
  51. watermark_annotation = np.array([x_center, y_center, w, h, watermark_class_id])
  52. return img, watermark_annotation
  53. def split_data_into_parts(total_data_count, num_parts=4, percentage=0.05):
  54. num_elements_per_part = int(total_data_count * percentage)
  55. if num_elements_per_part * num_parts > total_data_count:
  56. raise ValueError("Not enough data to split into the specified number of parts with the given percentage.")
  57. all_indices = list(range(total_data_count))
  58. parts = []
  59. for i in range(num_parts):
  60. start_idx = i * num_elements_per_part
  61. end_idx = start_idx + num_elements_per_part
  62. part_indices = all_indices[start_idx:end_idx]
  63. parts.append(part_indices)
  64. return parts
  65. def find_index_in_parts(parts, index):
  66. for i, part in enumerate(parts):
  67. if index in part:
  68. return True, i
  69. return False, -1
  70. def detect_and_decode_qr_code(image):
  71. """
  72. Detect and decode a QR code in an image.
  73. Args:
  74. image (numpy.ndarray): The image containing the QR code.
  75. Returns:
  76. str: The decoded text from the QR code.
  77. tuple: The coordinates of the QR code's bounding box.
  78. """
  79. # Initialize the QRCode detector
  80. qr_code_detector = cv2.QRCodeDetector()
  81. # Detect and decode the QR code
  82. decoded_text, points, _ = qr_code_detector.detectAndDecode(image)
  83. if points is not None:
  84. # Convert to integer type
  85. points = points[0].astype(int)
  86. # Draw the bounding box on the image (optional)
  87. for i in range(len(points)):
  88. cv2.line(image, tuple(points[i]), tuple(points[(i + 1) % len(points)]), (255, 0, 0), 2)
  89. return decoded_text, points
  90. else:
  91. return None, None
  92. if __name__ == '__main__':
  93. img_path = './000004.jpg'
  94. img_wm_path = './000004_wm.jpg'
  95. img_label_path = './000004_wm.txt'
  96. watermark_data = '1722996519.rfdgkDdI7WiB'
  97. # watermark_data = '1722996519.rfdgkDdI7WiBm8DrM4LcBbMgF05NPYbH1d/YG6eCye1qmXFOVosuC0uxLjbEiw3PRNsRqe5vJ+j7n0GYvfvMnw=='
  98. img = cv2.imread(img_path)
  99. r = min(640 / img.shape[0], 640 / img.shape[1])
  100. resized_img = cv2.resize(img, (int(img.shape[1] * r), int(img.shape[0] * r)),
  101. interpolation=cv2.INTER_LINEAR).astype(np.uint8)
  102. # 添加水印测试
  103. img, watermark_annotation = add_watermark_to_image(resized_img, watermark_data, 0)
  104. cv2.imwrite(img_wm_path, img)
  105. x1, y1, x2, y2, class_id = watermark_annotation
  106. with open(img_label_path, "w") as f:
  107. f.write(f"{int(class_id)} {x1} {y1} {x2} {y2}\n")
  108. img = cv2.imread(img_wm_path)
  109. width, height = img.shape[1], img.shape[0]
  110. x_center, y_center, w, h, _ = watermark_annotation[:5]
  111. # Convert normalized coordinates to image coordinates
  112. x_center *= width
  113. y_center *= height
  114. w *= width
  115. h *= height
  116. # Calculate bounding box coordinates
  117. x1 = int(x_center - w / 2)
  118. y1 = int(y_center - h / 2)
  119. x2 = int(x_center + w / 2)
  120. y2 = int(y_center + h / 2)
  121. # Ensure coordinates are within image bounds
  122. x1 = max(0, x1)
  123. y1 = max(0, y1)
  124. x2 = min(width, x2)
  125. y2 = min(height, y2)
  126. # Extract the QR code area
  127. qr_area = img[y1:y2, x1:x2]
  128. decoded_text, points = detect_and_decode_qr_code(img)
  129. print(decoded_text)
  130. # Detect and decode QR code from the extracted area
  131. # decoded_text, points = detect_and_decode_qr_code(qr_area)
  132. print(len(watermark_data))
  133. print(decoded_text == watermark_data)