Files
CourseWork/debug_dct_russian.py
Игорь c6ceca94ea работающая стеганография LSB и DCT
я устал... DCT убивает
2026-04-14 11:59:41 +03:00

137 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Отладка DCT: русский текст
"""
from core.dct import encode_dct, _apply_dct, _extract_bits_from_block, MID_FREQ_INDICES
from core.utils import text_to_bits, bits_to_text
from PIL import Image
import numpy as np
print("=" * 60)
print("Отладка DCT: русский текст")
print("=" * 60)
# Создаем тестовое изображение
img = Image.new('L', (400, 400), color=128)
img.save("debug_russian.png")
# Русское сообщение
message = "Привет"
print(f"Оригинальное сообщение: '{message}'")
print(f"Длина в символах: {len(message)}")
# Покажем биты оригинального сообщения
bits_original = text_to_bits(message)
print(f"\nОригинальные биты: {bits_original}")
print(f"Длина битов: {len(bits_original)}")
# Добавляем стоп-маркер
bits_with_stop = bits_original + '00000000'
print(f"Биты со стоп-маркером: {bits_with_stop}")
print(f"Длина со стоп-маркером: {len(bits_with_stop)}")
# Кодируем
print("\n--- Кодирование ---")
encode_dct("debug_russian.png", message, "debug_russian_encoded.png")
# Загружаем закодированное изображение и извлекаем биты
img_encoded = Image.open("debug_russian_encoded.png").convert('L')
pixels = np.array(img_encoded, dtype=np.float64)
height, width = pixels.shape
print("\n--- Извлечение битов из блоков ---")
all_bits = []
block_count = 0
for i in range(0, height - 8 + 1, 8):
for j in range(0, width - 8 + 1, 8):
block = pixels[i:i+8, j:j+8]
dct_block = _apply_dct(block)
bits_from_block = _extract_bits_from_block(dct_block, len(MID_FREQ_INDICES))
all_bits.extend(bits_from_block)
block_count += 1
# Покажем первые 3 блока
if block_count <= 3:
print(f"Блок {block_count}: {bits_from_block[:30]}...")
print(f"\nВсего извлечено битов: {len(all_bits)}")
# Сравним оригинальные и извлеченные биты (первые 100)
print("\n" + "=" * 60)
print("Сравнение битов (первые 100):")
print("=" * 60)
print(f"Оригинал: {bits_with_stop[:100]}")
print(f"Извлечено: {''.join(str(b) for b in all_bits[:100])}")
# Найдем позиции, где биты отличаются
print("\n" + "=" * 60)
print("Различия в битах:")
print("=" * 60)
diff_count = 0
for i in range(min(len(bits_with_stop), len(all_bits))):
orig_bit = int(bits_with_stop[i])
ext_bit = all_bits[i]
if orig_bit != ext_bit:
diff_count += 1
if diff_count <= 20:
print(f"Позиция {i}: было {orig_bit}, стало {ext_bit}")
print(f"Всего различий: {diff_count}")
# Попробуем декодировать извлеченные биты без стоп-маркера
print("\n" + "=" * 60)
print("Декодирование извлеченных битов:")
print("=" * 60)
# Преобразуем биты в байты и покажем их
extracted_bytes = []
for k in range(0, min(len(all_bits), 200), 8):
if k + 8 <= len(all_bits):
byte_bits = all_bits[k:k+8]
byte_val = 0
for b in byte_bits:
byte_val = (byte_val << 1) | b
extracted_bytes.append(byte_val)
# Покажем как число и как символ
if 32 <= byte_val < 127:
char = chr(byte_val)
else:
char = f'[{byte_val:02x}]'
print(f"Байт {k//8:2d}: {byte_val:3d} (0x{byte_val:02x}) -> {char} биты={byte_bits}")
# Найдем стоп-маркер
print("\n" + "=" * 60)
print("Поиск стоп-маркера:")
print("=" * 60)
stop_counter = 0
stop_position = -1
for i, bit in enumerate(all_bits):
if bit == 0:
stop_counter += 1
if stop_counter == 8:
stop_position = i - 7
print(f"Стоп-маркер найден на позиции бита {stop_position}")
break
else:
stop_counter = 0
if stop_position == -1:
print("Стоп-маркер НЕ НАЙДЕН!")
# Используем все биты
bits_to_decode = all_bits
else:
bits_to_decode = all_bits[:stop_position]
print(f"Битов до стоп-маркера: {len(bits_to_decode)}")
# Декодируем
bits_string = ''.join(str(b) for b in bits_to_decode)
try:
decoded = bits_to_text(bits_string)
print(f"\nДекодированное сообщение: '{decoded}'")
if decoded == message:
print("✅ УСПЕХ!")
else:
print("❌ Сообщения не совпадают")
except Exception as e:
print(f"\nОшибка декодирования: {e}")