import math


def get_average_color(x, y, x_len, y_len, image, skip=1):
    """ Returns a 3-tuple containing the RGB value of the average color of the
    given square bounded area of length = n whose origin (top left corner)
    is (x, y) in the given image"""
    i = image.load()
    r, g, b = 0, 0, 0
    count = 0
    for s in range(x, x+x_len, skip):
        for t in range(y, y+y_len, skip):
            if s<image.size[0] and t< image.size[1]:
                pixlr, pixlg, pixlb = i[s,t]
                r += pixlr ** 2
                g += pixlg ** 2
                b += pixlb ** 2
                count += 1
            else:
                #print("Pos %s, %s out of bounds" % (s, t))
                break
    return (int(math.sqrt(r/count)), int(math.sqrt(g/count)), int(math.sqrt(b/count)))