from PIL import Image
from math import sqrt


def D_2():
    img = Image.open("skryvacka2.png")
    newImg = Image.new("RGB", (img.width, img.height))

    for x in xrange(img.width):
        for y in xrange(img.height):
            r, g, b, a = img.getpixel((x, y))
            new = int(r * 0.299 + g * 0.587 + b * 0.114)
            newImg.putpixel((x, y), (new, new, new))

    kx = [[-1, 0, 1],
          [-2, 0, 2],
          [-1, 0, 1]]

    ky = [[-1, -2, -1],
          [0, 0, 0],
          [1, 2, 1]]


    def applyKernel(img, k, x, y):
        summ = 0
        for i in xrange(-1, 2):
            for j in xrange(-1, 2):
                if -1 < x+i < img.width and -1 < y+j < img.height:
                    summ += img.getpixel((x+i, y+j))[0] * k[i][j]
        return summ

    for x in xrange(img.width):
        for y in xrange(img.height):
            pixel = int(sqrt(applyKernel(newImg, kx, x, y)**2 +
                             applyKernel(newImg, ky, x, y)**2))**2
            img.putpixel((x, y), (pixel, pixel, pixel))

    img.save("D_2.png")

D_2()
