def binarize(img, threshold=127):
    """Utility function to binarize an image."""

    for i in range(img.size[0]):
        for j in range(img.size[1]):
            if img.getpixel((i, j)) > threshold:
                img.putpixel((i, j), 255)
            else:
                img.putpixel((i, j), 0)

    return img