import io
import ConfigParser, os
import time
import picamera
import logging
import logging.config
import logging.handlers
from PIL import Image, ImageChops
from itertools import izip
import datetime 

def compare_images(reference_image, new_image):
	logging.debug('> Start: compare_images()')
	diff = ImageChops.difference(reference_image, new_image)
	channels = diff.split()
	pairs = izip(reference_image.getdata(), new_image.getdata())
	dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
	ncomponents = reference_image.size[0] * reference_image.size[1] * 3
	result = (dif / 255.0 * 100) / ncomponents
	logging.debug('> Difference between images: ' + str(result))
	logging.debug('> End: compare_images()')
	return result 
	
	
initialise()
	reference_image = load_reference_image()
	new_image = capture_image()
	difference = compare_images(reference_image, new_image)
	
	threshold = float(config.get('Image','threshold'))
	if difference >= threshold:
		logging.debug('Image Difference exceeds threshold.')
		path = config.get('Image','path')
		file_name = path + '/' + datetime.datetime.now().strftime('%Y%m%d%H%M%S.jpg')
		logging.debug('Saving new image to ' + file_name)
		new_image.save(file_name)

		logging.debug('Replacing reference image')
		reference_image_path = path + '/reference.jpg'
		new_image.save(reference_image_path) 


///////////////////////////////////////////////////

import ImageChops
import math, operator

def rmsdiff_1997(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add,
        map(lambda h, i: h*(i**2), h, range(256))
    ) / (float(im1.size[0]) * im1.size[1]))


# The 2011 version using more recent Python idioms

def rmsdiff_2011(im1, im2):
    "Calculate the root-mean-square difference between two images"
    diff = ImageChops.difference(im1, im2)
    h = diff.histogram()
    sq = (value*(idx**2) for idx, value in enumerate(h))
    sum_of_squares = sum(sq)
    rms = math.sqrt(sum_of_squares/float(im1.size[0] * im1.size[1]))
    return rms

		
		
		compare bag_frame1.gif bag_frame2.gif  compare.gif