# Pattern1.py

from gpanel import *
import random

def euklidian(pic1, pic2):
    # pic = [[0, 1, 0,...,1],[...],...]
    count = 0
    for i in range(20):
        for k in range(20):
            count += int(pic1[i][k] != pic2[i][k])
    return count

def extractPicture(img, n):
    # n = 0..5000
    # return list with 0, 1
    pic = [[0 for i in range(20)] for k in range(20)]
    x_offset = 20 * (n % 100)
    y_offset = 20 * (n // 100)
    for x in range(20):
        for y in range(20):
            if isTigerJython:
                c = img.getPixelColor(x + x_offset, y + y_offset)
                lum = (c.getRed() + c.getGreen() + c.getBlue()) // 3
            else:
                c = GPanel.getPixelColor(img, x + x_offset, y + y_offset)
                lum = (c[0] + c[1] + c[2]) // 3
            pic[x][y] = int(lum > 127)
    return pic

def showPicture(pic, xpos, ypos):
    if isTigerJython:
        showPictureTJ(pic, xpos, ypos)
    else:
        showPicturePy(pic, xpos, ypos)

def showPicturePy(pic, xpos, ypos):
    white = QColor(255, 255, 255).rgb()
    black = QColor(0, 0, 0).rgb()
    pm = QPixmap(20, 20)
    img = pm.toImage()
    for x in range(20):
        for y in range(20):
            if pic[x][y] == 1:
                img.setPixel(x, y, white)
            else:
                img.setPixel(x, y, black)
    image(img, xpos, ypos)

def showPictureTJ(pic, xpos, ypos):
    bm = GBitmap(20, 20)
    for x in range(20):
        for y in range(20):
            if pic[x][y] == 1:
                bm.setPixelColorStr(x, y, "white")
            else:
                bm.setPixelColorStr(x, y, "black")
    image(bm, xpos, ypos)

def getDigit(n):
    return n // 500

def loadData(filename):
    img = getImage(filename)
    out = [0] * 5000
    for n in range(5000):
        out[n] = extractPicture(img, n)
    return out

makeGPanel(Size(350, 200))
window(0, 350, 0, 200)
title("Loading data...")
X = loadData("digits.png")
title("Loading data...Done.")
count1 = 0
for i in range(12):
    pic1 = X[random.randint(0, 5000)]
    pic2 = X[random.randint(0, 5000)]
    showPicture(pic1, 30 * i, 42)
    showPicture(pic2, 30 * i, 20)
    d = euklidian(pic1, pic2)
    text(30 * i, 2, str(d))
    count1 += d
count2 = 0
for i in range(12):
    digit = random.randint(0, 9)
    pic1 = X[random.randint(500 * digit, 500 * digit + 499)]
    pic2 = X[random.randint(500 * digit, 500 * digit + 499)]
    showPicture(pic1, 30 * i, 142)
    showPicture(pic2, 30 * i, 120)
    d = euklidian(pic1, pic2)
    text(30 * i, 102, str(d))
    count2 += d
text(10, 180, "diff: " + str(count1) + "   same: " + str(count2))
keep()
