In [1]:
get_ipython().ast_node_interactivity = 'all'
import os
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import math
import numba
from PIL import Image
import scipy.fftpack
import scipy.optimize
import random
matplotlib.rcParams['figure.dpi'] = 150

def show(img):
    _ = plt.imshow(img, cmap='gray')
    #_ = plt.colorbar()

def img_open(path):
    img = Image.open(path)
    img = img.convert('L')
    img = img.resize((100, 100))
    return np.array(img) / 256
In [2]:
target = img_open("/home/leo/Downloads/stallman-grayscale.png")
In [3]:
show(target)
Out:
<Figure size 900x600 with 1 Axes>
In [4]:
received = []

for _ in range(2**10):
    x = np.random.randint(0, target.shape[1])
    y = np.random.randint(0, target.shape[0])
    received.append((y, x, target[y][x]))

print(len(received))

r = np.full(target.shape, 1.0)
for y, x, val in received:
    r[y][x] = val
Out:
1024
In [5]:
show(r)
Out:
<Figure size 900x600 with 1 Axes>
In [6]:
def fitness(params):
    if params.sum() == 0:
        return 99999999
    img = scipy.fftpack.idctn(params.reshape(target.shape))
    img = img / (img.flatten().max())
    
    error = 0
    for y, x, val in received:
        error += abs(img[y][x] - val)
    return error

N = target.flatten().shape[0]
best = np.random.randn(N)
In [7]:
candidates = []

for _ in range(500):
    params = np.random.uniform(0, 1, N)
    candidates.append(params)

len(candidates)
Out [7]:
500
In [8]:
def run_iteration(candidates):
    for c in list(candidates):
        for _ in range(5):
            n = np.copy(c)
            n = np.random.normal(n, 1)
            candidates.append(n)
    candidates.sort(key=fitness)
    while len(candidates) > 500:
        candidates.pop()
In [9]:
while len(candidates) > 500:
    candidates.pop()

while True:
    run_iteration(candidates)
    best = candidates[0]
    print("\r", fitness(best), end="                              ")
Out:
 529.8685513623979                              
Out:
[ERROR] KeyboardInterrupt: 
In []:
show(scipy.fftpack.idctn(best.reshape(target.shape)))