from PIL import Image
from itertools import product
from pandas import DataFrame
import random
block_size = 3
common_blocks_ecb = {tuple([(255, 255, 255)] * block_size): ((255, 80, 215), (150, 150, 150), ( 32, 223, 156)),
tuple([(253, 253, 251)] * block_size): ((169, 180, 238), (255, 142, 51), ( 35, 251, 102)),
tuple([( 2, 2, 4)] * block_size): (( 52, 44, 216), (125, 114, 71), ( 57, 12, 140))}
random.seed(42)
image = Image.open('Tux.png')
image_pixels = image.load()
pixels = [image_pixels[col, row] for row, col in product(range(image.size[1]), range(image.size[0]))]
pixels.extend([(255, 255, 255)] * ((block_size - len(pixels) % block_size) % block_size))
blocks = DataFrame([[pixels[block_count + pixel_count] for pixel_count in range(block_size)] for block_count in range(0, len(pixels), block_size)])
unique_blocks = blocks.drop_duplicates().reset_index(drop=True)
for block in unique_blocks.itertuples(index=False, name=None):
block_ecb = common_blocks_ecb.get(block)
if block_ecb is None:
block_ecb = [(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for _ in range(block_size)]
blocks[(blocks == block).T.sum() == block_size] = [block_ecb]
for row, col in product(range(image.size[1]), range(image.size[0])):
i = row * image.size[0] + col
image_pixels[col, row] = blocks[i % block_size][i // block_size]
image.save('Tux_ECB.png')