import numpy as np
from PIL import Image
import cv2 # OpenCV for perspective transform
from skimage.feature import blob_log # scikit-image for blob detection
import sys
# --- Configuration ---
# You can tune these parameters for different results
GRID_SIZE = 32 # Data grid dimensions (32x32 = 1024 bits)
DOT_RADIUS_DATA = 3 # Radius of a data dot in pixels
DOT_RADIUS_ANCHOR = 5 # Radius of an anchor dot (make them bigger to find them)
DOT_INTENSITY = 25 # How bright the dots are (0-255). Lower is more subtle.
ANCHOR_MARGIN_PERCENT = 0.15 # Margin for anchors from image border
def text_to_binary(text: str) -> str:
"""Converts text to a binary string with a null delimiter."""
text += "\0" # Null delimiter
return "".join(format(ord(c), "08b") for c in text)
def binary_to_text(binary_str: str) -> str:
"""Converts a binary string back to text, stopping at the null delimiter."""
# Ensure binary_str length is a multiple of 8
byte_chunks = [binary_str[i:i+8] for i in range(0, len(binary_str), 8)]
chars = []
for byte in byte_chunks:
if len(byte) == 8:
char_code = int(byte, 2)
if char_code == 0: # Null delimiter
break
chars.append(chr(char_code))
return "".join(chars)
def draw_dot(pixels, center_x, center_y, radius, intensity):
"""Draws a soft, anti-aliased dot by modifying luminance."""
for y in range(int(center_y - radius), int(center_y + radius)):
for x in range(int(center_x - radius), int(center_x + radius)):
if 0 <= x < pixels.shape[1] and 0 <= y < pixels.shape[0]:
dist = np.sqrt((x - center_x)**2 + (y - center_y)**2)
if dist < radius:
# Use a Gaussian-like falloff for a soft dot
blend_factor = (1 - dist / radius) * 0.5
# Modify luminance (Y channel in YCbCr) for subtlety
ycbcr = cv2.cvtColor(np.uint8([[pixels[y, x]]]), cv2.COLOR_RGB2YCrCb)[0][0]
new_y = min(255, max(0, int(ycbcr[0] + intensity * blend_factor)))
rgb = cv2.cvtColor(np.uint8([[[new_y, ycbcr[1], ycbcr[2]]]]), cv2.COLOR_YCrCb2RGB)[0][0]
pixels[y, x] = rgb
def get_grid_points(width, height):
"""Calculates the coordinates for anchor and data grid points."""
margin_x = width * ANCHOR_MARGIN_PERCENT
margin_y = height * ANCHOR_MARGIN_PERCENT
# Define corners for the transformation
src_points = np.float32([
[margin_x, margin_y],
[width - margin_x, margin_y],
[width - margin_x, height - margin_y],
[margin_x, height - margin_y]
])
data_points = []
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
x = margin_x + (j / (GRID_SIZE - 1)) * (width - 2 * margin_x)
y = margin_y + (i / (GRID_SIZE - 1)) * (height - 2 * margin_y)
data_points.append((x, y))
return src_points, data_points
def encode_robust(input_path: str, text: str, output_path: str):
"""Embeds text into an image using a robust grid of dots."""
with Image.open(input_path).convert("RGB") as img:
pixels = np.array(img)
h, w, _ = pixels.shape
binary_data = text_to_binary(text)
max_capacity = GRID_SIZE * GRID_SIZE
if len(binary_data) > max_capacity:
raise ValueError(f"Text too long. Max {max_capacity} bits, needs {len(binary_data)}")
anchor_points, data_points = get_grid_points(w, h)
# 1. Draw Anchor Points
for x, y in anchor_points:
draw_dot(pixels, x, y, DOT_RADIUS_ANCHOR, DOT_INTENSITY)
# 2. Draw Data Points for each '1' bit
for i, bit in enumerate(binary_data):
if bit == '1':
x, y = data_points[i]
draw_dot(pixels, x, y, DOT_RADIUS_DATA, DOT_INTENSITY)
# Save the result
encoded_img = Image.fromarray(pixels)
encoded_img.save(output_path, quality=95) # Save as high-quality JPEG or PNG
print(f"Encoded {len(binary_data)} bits into {output_path}")
def decode_robust(encoded_path: str) -> str:
"""Extracts text from a robustly encoded image."""
with Image.open(encoded_path) as img:
img_rgb = np.array(img.convert("RGB"))
h, w, _ = img_rgb.shape
# Convert to grayscale for blob detection
img_gray = np.array(img.convert("L"))
# 1. Find Anchor Points using Blob Detection
# We expect blobs that are slightly larger than data dots
blobs = blob_log(img_gray, min_sigma=DOT_RADIUS_ANCHOR-1, max_sigma=DOT_RADIUS_ANCHOR+1, threshold=0.05, num_sigma=5)
if len(blobs) < 4:
raise ValueError(f"Could not find 4 anchor points. Found {len(blobs)}. Try adjusting blob detection parameters.")
# Sort blobs by intensity (column 2) and take the 4 strongest
blobs = blobs[blobs[:, 2].argsort()][::-1][:4]
detected_anchors = blobs[:, [1, 0]] # Use (x, y) coordinates
# Sort the detected anchors to match the original order (TL, TR, BR, BL)
center = detected_anchors.mean(axis=0)
sorted_anchors = sorted(detected_anchors, key=lambda p: (p[1] < center[1], p[0] < center[0]))
detected_anchors = np.float32(sorted_anchors)
# 2. Calculate Perspective Transform
original_anchors, data_points = get_grid_points(w, h)
transform_matrix = cv2.getPerspectiveTransform(detected_anchors, original_anchors)
# 3. Read Data Grid
binary_data = ""
for i in range(GRID_SIZE * GRID_SIZE):
# We need to apply the *inverse* transform to find where each dot *would have been*
# But it's easier to check pixel intensity at expected locations in the original logic.
# Let's re-calculate the transform from original to distorted
inv_transform_matrix = cv2.getPerspectiveTransform(original_anchors, detected_anchors)
# Project the ideal data point location into the distorted image space
original_pt = np.float32([[data_points[i]]])
transformed_pt = cv2.perspectiveTransform(original_pt, inv_transform_matrix)[0][0]
x, y = int(transformed_pt[0]), int(transformed_pt[1])
# Check for a dot by sampling a small area's brightness
if 0 < y < h and 0 < x < w:
# Simple check: compare pixel brightness to a threshold
# A more robust check would compare it to the local average
sample_area = img_gray[y-1:y+2, x-1:x+2]
avg_intensity = np.mean(sample_area) if sample_area.size > 0 else 0
# A simple threshold. For real-world use, this needs to be adaptive.
# We assume dots are brighter than their surroundings.
original_intensity = np.mean(img_gray) # very basic reference
if avg_intensity > original_intensity + DOT_INTENSITY / 10:
binary_data += '1'
else:
binary_data += '0'
else:
binary_data += '0' # Point is outside image bounds
return binary_to_text(binary_data)
# --- Example Usage ---
if __name__ == "__main__":
INPUT_IMAGE = "input.png" # A sample input image (e.g., a landscape photo)
ENCODED_IMAGE = "encoded_robust.jpg"
DECODED_TEXT_FILE = "decoded_message.txt"
SECRET_MESSAGE = "This message can survive a JPEG compression and even a physical print-and-scan cycle!"
# Create a dummy input image if it doesn't exist
try:
Image.open(INPUT_IMAGE)
except FileNotFoundError:
print(f"Creating dummy input image: {INPUT_IMAGE}")
dummy_img = Image.new('RGB', (800, 600), color = 'darkgray')
dummy_img.save(INPUT_IMAGE)
# 1. Encode the message
try:
encode_robust(INPUT_IMAGE, SECRET_MESSAGE, ENCODED_IMAGE)
print("\n--- Encoding successful ---")
# 2. Decode the message
decoded_message = decode_robust(ENCODED_IMAGE)
print(f"\n--- Decoding successful ---")
print(f"Decoded Message: '{decoded_message}'")
# Save decoded message to file for verification
with open(DECODED_TEXT_FILE, "w") as f:
f.write(decoded_message)
print(f"Full message saved to {DECODED_TEXT_FILE}")
except Exception as e:
print(f"\nAn error occurred: {e}", file=sys.stderr)