#!/usr/bin/env python

"""
Copyright (C) 2012 by Marc Planard

This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.

usage: ./crop ./results/ file1.jpg file2.jpg file3.jpg [...]

"""

from PIL import Image
import glob, os, os.path, sys
import datetime

LIMIT = 100

def findBound(A, maxA, i, limit):
    a = maxA[1]
    v = 1.0
    while v > limit:
        v = float(A[a])/float(maxA[0])
        a += i
    return a

def getCenter(im, limit):

    W, H = im.size
    X = [0] * W # columns
    Y = [0] * H # rows

    maxX = (0,0) # brigthest column ( value, coord )
    maxY = (0,0) # brigthest row ( value, coord )

    data = im.getdata()

    # itterate on every pixel of the image, accumulate in X and Y
    for x in xrange(W):
        for y in xrange(H):
            acc = sum(data[x+(y*W)])
            if acc > limit: # filter values according to brightness limit
                X[x] += acc
                Y[y] += acc

    # find the brightest column
    for x,v in enumerate(X):
        if v > maxX[0]:
            maxX = (v, x)

    # find the brightest row
    for y,v in enumerate(Y):
        if v > maxY[0]:
            maxY = (v, y)

    # if no spot brighter than limit, lower limit, recurse
    if maxX[0] == 0 or maxY[0] == 0:
        print "[ center not found, lower limit to", limit/2, ']',
        return getCenter(im, limit/2)

    # find the bounding box of the bright spot (fromX, toX, fromY, toY)
    fromX = findBound(X, maxX, -1, 0.25)
    toX = findBound(X, maxX, 1, 0.25)
    fromY = findBound(Y, maxY, -1, 0.25)
    toY = findBound(Y, maxY, 1, 0.25)

    # compute the center of the bright spot and returns it
    centerX = (fromX+toX)/2
    centerY = (fromY+toY)/2
    return (centerX, centerY)


# find the result directory
path = sys.argv[1]
if os.path.isdir(path) == False:
    print path, "is not a directory, abording"
    sys.exit(0)

# process all the images given in arguments
total = len(sys.argv[2:])
for i, infile in enumerate(sys.argv[2:]):
    # fancy printings    
    d1 = datetime.datetime.now()
    print str(i+1)+'/'+str(total), infile, 
    sys.stdout.flush()

    im = Image.open(infile)

    # find the center of the bright spot
    x, y = getCenter(im, LIMIT)

    # crop the image 80x60 pixels around the bright spot
    box = (x-40, y-30,x+40, y+30)
    im2 = im.crop(box)    

    # save in the result directory
    im2.save(os.path.join(path, infile), quality=95)

    # fancy printings
    d2 = datetime.datetime.now()
    t = d2-d1
    print im.size, (x, y), t.total_seconds(), "seconds"
