// timelapse motion detection, image analysis part
// 1.10.2009 by Nick Fankhauser
// Compile: gcc motion_detect.c -o motion_detect -lgd
// Images have to be of the same resolution, 
// or else it will probably crash on line 56 if the second image is smaller.
// Add a check if it becomes a problem.
// Use motion_detect.py to process all (filtered) images in directory.

#include <stdio.h> 
#include <gd.h> 
#include <stdlib.h> 
#define NUMBOX 20 
#define THRESHOLD 5  // determined from sample of unchanging images 

int main(int argc, char *argv[]) {
 gdImagePtr image1, image2;
 FILE *png1, *png2;
 long c1,c2,x,y,xbox,ybox,**box1,**box2,sum1,sum2,xboxsize,yboxsize,dc;
 if (argc<3) {
  printf("Syntax: motion_detect <image1.jpg> <image2.jpg>\n");
  printf("NUMBOX = %d, THRESHOLD = %d\n",NUMBOX,THRESHOLD);
  exit(1);
 }
 png1 = fopen(argv[1], "rb");
 if(png1==NULL) {
  printf("Unable to open %s\n",argv[1]);
  exit(1);
 }
 image1 = gdImageCreateFromJpeg(png1);
 fclose(png1);
 png2 = fopen(argv[2], "rb");
 if(png2==NULL) {
  printf("Unable to open %s\n",argv[2]);
  exit(1);
 }
 image2 = gdImageCreateFromJpeg(png2);
 fclose(png2);
 xboxsize=image1->sx/NUMBOX;
 yboxsize=image1->sy/NUMBOX;
 xbox=image1->sx/xboxsize;
 ybox=image1->sy/yboxsize;
 box1=malloc(sizeof(long*)*(xbox+1));
 box2=malloc(sizeof(long*)*(xbox+1));
 for (x=0;x<xbox;x++) {
  box1[x]=malloc(sizeof(long)*(ybox+1));
  box2[x]=malloc(sizeof(long)*(ybox+1));
  for (y=0;y<ybox;y++) {
   box1[x][y]=0;
   box2[x][y]=0;
  }
 }
 for (x=0;x<image1->sx;x++) {
  for (y=0;y<image1->sy;y++) {
   c1=gdImageGetPixel(image1,x,y);
   sum1=(gdTrueColorGetRed(c1)+gdTrueColorGetGreen(c1)+gdTrueColorGetBlue(c1))/3;
   box1[x/xboxsize][y/yboxsize]+=sum1;
   c2=gdImageGetPixel(image2,x,y);
   sum2=(gdTrueColorGetRed(c2)+gdTrueColorGetGreen(c2)+gdTrueColorGetBlue(c2))/3;
   box2[x/xboxsize][y/yboxsize]+=sum2;
  } 
 }
 gdImageDestroy(image1);
 gdImageDestroy(image2);
 dc=0;
 for (x=0;x<xbox;x++) {
  for (y=0;y<ybox;y++) {
   if (abs(box1[x][y]/(xboxsize*yboxsize)-box2[x][y]/(xboxsize*yboxsize))>THRESHOLD) {dc+=1;}
  }
 }
 printf("%d\n",dc);
 return 0;
}