deal_img_test.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 detect_and_decode_qr_code(image):
  54. """
  55. Detect and decode a QR code in an image.
  56. Args:
  57. image (numpy.ndarray): The image containing the QR code.
  58. Returns:
  59. str: The decoded text from the QR code.
  60. tuple: The coordinates of the QR code's bounding box.
  61. """
  62. # Initialize the QRCode detector
  63. qr_code_detector = cv2.QRCodeDetector()
  64. # Detect and decode the QR code
  65. decoded_text, points, _ = qr_code_detector.detectAndDecode(image)
  66. if points is not None:
  67. # Convert to integer type
  68. points = points[0].astype(int)
  69. # Draw the bounding box on the image (optional)
  70. for i in range(len(points)):
  71. cv2.line(image, tuple(points[i]), tuple(points[(i + 1) % len(points)]), (255, 0, 0), 2)
  72. return decoded_text, points
  73. else:
  74. return None, None
  75. if __name__ == '__main__':
  76. img_path = './000004.jpg'
  77. img_wm_path = './000004_wm.jpg'
  78. img_label_path = './000004_wm.txt'
  79. watermark_data = '1722996519.rfdgkDdI7WiB'
  80. # watermark_data = '1722996519.rfdgkDdI7WiBm8DrM4LcBbMgF05NPYbH1d/YG6eCye1qmXFOVosuC0uxLjbEiw3PRNsRqe5vJ+j7n0GYvfvMnw=='
  81. img = cv2.imread(img_path)
  82. r = min(640 / img.shape[0], 640 / img.shape[1])
  83. resized_img = cv2.resize(img, (int(img.shape[1] * r), int(img.shape[0] * r)),
  84. interpolation=cv2.INTER_LINEAR).astype(np.uint8)
  85. # 添加水印测试
  86. img, watermark_annotation = add_watermark_to_image(resized_img, watermark_data, 0)
  87. cv2.imwrite(img_wm_path, img)
  88. x1, y1, x2, y2, class_id = watermark_annotation
  89. with open(img_label_path, "w") as f:
  90. f.write(f"{int(class_id)} {x1} {y1} {x2} {y2}\n")
  91. img = cv2.imread(img_wm_path)
  92. width, height = img.shape[1], img.shape[0]
  93. x_center, y_center, w, h, _ = watermark_annotation[:5]
  94. # Convert normalized coordinates to image coordinates
  95. x_center *= width
  96. y_center *= height
  97. w *= width
  98. h *= height
  99. # Calculate bounding box coordinates
  100. x1 = int(x_center - w / 2)
  101. y1 = int(y_center - h / 2)
  102. x2 = int(x_center + w / 2)
  103. y2 = int(y_center + h / 2)
  104. # Ensure coordinates are within image bounds
  105. x1 = max(0, x1)
  106. y1 = max(0, y1)
  107. x2 = min(width, x2)
  108. y2 = min(height, y2)
  109. # Extract the QR code area
  110. qr_area = img[y1:y2, x1:x2]
  111. decoded_text, points = detect_and_decode_qr_code(img)
  112. print(decoded_text)
  113. # Detect and decode QR code from the extracted area
  114. # decoded_text, points = detect_and_decode_qr_code(qr_area)
  115. print(len(watermark_data))
  116. print(decoded_text == watermark_data)