1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| import random import sys
import numpy as np from PIL import Image
def arnold_cat_map(image, key=(1, 2, 1)): """ Implements Arnold's cat map transformation on an image. """ height, width, *_ = image.shape offset_x, offset_y, iterations = key
new_image = np.zeros(image.shape, dtype=np.uint8) for i in range(iterations): for x in range(height): for y in range(width): _x, _y = x, y _y = (_y + offset_x * _x) % width _x = (_x + offset_y * _y) % height new_image[_x, _y] = image[x, y] return new_image
def arnold_cat_map_rev(image, key=(1, 2, 1)): """ Implements Arnold's cat map transformation on an image (reverse). """ height, width, *_ = image.shape offset_x, offset_y, iterations = key
new_image = np.zeros(image.shape, dtype=np.uint8) for i in range(iterations): for x in range(height): for y in range(width): _x, _y = x, y _x = (_x - offset_y * _y) % height _y = (_y - offset_x * _x) % width new_image[_x, _y] = image[x, y] return new_image
def add_watermark(original_image_path, watermark_text_path, output_image_path): """ Adds a text watermark to an image using the Arnold's cat map transformation. """
original_image = np.array(Image.open(original_image_path).convert("RGB")) height, width, *_ = original_image.shape
watermark_image = np.array(Image.open(watermark_text_path).convert("RGB")) watermark_height, watermark_width, *_ = watermark_image.shape watermark_top = (height - watermark_height) // 2 if watermark_top < 0: print("The height of watermark_text is bigger than original_image") sys.exit(1) watermark_left = (width - watermark_width) // 2 if watermark_left < 0: print("The width of watermark_text is larger than original_image") sys.exit(1)
arnold_dx = random.randint(width // 10, width // 10 * 9) arnold_dy = random.randint(height // 10, height // 10 * 9) arnold_rd = random.randint(min(height, width) // 10, min(height, width) // 10 * 9) private_key = (20,20,5) print(f'{private_key = }')
transformed_image = arnold_cat_map(original_image, private_key)
watermark_image[watermark_image > 0] = 1 transformed_image[watermark_top:watermark_top+watermark_height, watermark_left:watermark_left+watermark_width] ^= 1 - watermark_image
output_image = arnold_cat_map_rev(transformed_image, private_key)
Image.fromarray(np.uint8(output_image)).save(output_image_path)
original_image_path = './img/black.png' watermark_text_path = './img/cat1.png' output_image_path = './img/cat1_flag.png'
add_watermark(original_image_path, watermark_text_path, output_image_path)
|