import numpy as np
from PIL import Image
import cv2
from reedsolo import RSCodec
# Error Correction Level
RS_BYTES = 10 # Adjust based on desired redundancy
rs = RSCodec(RS_BYTES)
def text_to_bits(text):
"""Convert string to binary + add Reed-Solomon error correction."""
byte_data = text.encode('utf-8')
encoded_data = rs.encode(byte_data)
return ''.join(f"{byte:08b}" for byte in encoded_data)
def bits_to_text(bits):
"""Convert binary string back to text using Reed-Solomon."""
byte_chunks = [bits[i:i+8] for i in range(0, len(bits), 8)]
byte_values = [int(chunk, 2) for chunk in byte_chunks if len(chunk) == 8]
corrected_bytes = bytes(byte_values)
try:
decoded = rs.decode(corrected_bytes)[0]
return decoded.decode('utf-8', errors='ignore')
except:
return "Decoding failed"
def embed_dct(image_array, bit_stream):
"""Embed bits into DCT of image blocks."""
h, w = image_array.shape
idx = 0
bit_stream = list(bit_stream)
for y in range(0, h - h % 8, 8):
for x in range(0, w - w % 8, 8):
block = image_array[y:y+8, x:x+8].copy()
dct = cv2.dct(np.float32(block))
# Modify middle frequency coefficient (less visible impact)
if idx < len(bit_stream):
bit = int(bit_stream[idx])
# Increase or decrease slightly depending on bit
if dct[3,3] < 128:
dct[3,3] = 128
dct[3,3] = round(dct[3,3] / 2) * 2 + bit
idx += 1
idct = np.uint8(cv2.idct(dct))
image_array[y:y+8, x:x+8] = idct
if idx >= len(bit_stream):
break
if idx >= len(bit_stream):
break
return image_array
def extract_dct(image_array, length):
"""Extract embedded bits from DCT blocks."""
h, w = image_array.shape
bits = []
idx = 0
for y in range(0, h - h % 8, 8):
for x in range(0, w - w % 8, 8):
block = image_array[y:y+8, x:x+8]
dct = cv2.dct(np.float32(block))
bit = int(round(dct[3,3]) % 2)
bits.append(str(bit))
idx += 1
if idx >= length:
return ''.join(bits)
return ''.join(bits)
def encode_image(input_path, text, output_path):
img = Image.open(input_path).convert("L") # Grayscale
img_array = np.array(img)
bit_stream = text_to_bits(text)
print(f"Encoded {len(bit_stream)} bits including error correction")
encoded_array = embed_dct(img_array, bit_stream)
encoded_img = Image.fromarray(encoded_array)
encoded_img.save(output_path)
print(f"Saved encoded image to {output_path}")
def decode_image(encoded_path, expected_bit_length=500):
img = Image.open(encoded_path).convert("L")
img_array = np.array(img)
bits = extract_dct(img_array, expected_bit_length)
decoded_text = bits_to_text(bits)
return decoded_text
# Example Usage
if __name__ == "__main__":
input_image = "input.png"
output_image = "encoded_output.png"
secret_text = "This is a hidden message!"
# Encode
encode_image(input_image, secret_text, output_image)
# Decode
recovered = decode_image(output_image)
print("Recovered Text:", recovered)