/*
 * Linearly combine two images into the red and blue channels.
 *
 * To build:
 *   gcc -ggdb -O0 `pkg-config opencv --cflags --libs` thingc.c -o thingc
 *
 * Nat Friedman (nat@nat.org)
 */

#include <stdio.h>

#ifdef _CH_
#pragma package <opencv>
#endif

#ifndef _EiC
#include "cv.h"
#include "highgui.h"
#endif

#define ABS(a) ((a) > 0 ? (a) : -(a))

#define WHITE_POINT_BLUE 100
#define WHITE_POINT_RED 100

char wndname[] = "Thingc";
char tbarname[] = "Threshold";
int edge_thresh = 1;

IplImage *image1 = 0, *image2 = 0, *gray, *cedge, *edge, *output, *image;

int main( int argc, char** argv )
{
  int x, y;
  IplImage *gray1, *gray2;

  if((image1 = cvLoadImage(argv[1], 1)) == 0 )
    return -1;
  if((image2 = cvLoadImage(argv[2], 1)) == 0 )
    return -1;

  // Convert both images to grayscale
  gray1 = cvCreateImage(cvSize(image1->width,image1->height), IPL_DEPTH_8U, 1);
  gray2 = cvCreateImage(cvSize(image2->width,image2->height), IPL_DEPTH_8U, 1);
  cvCvtColor(image1, gray1, CV_BGR2GRAY);
  cvCvtColor(image2, gray2, CV_BGR2GRAY);

  // Create the output image
  output = cvCreateImage(cvSize(image1->width,image1->height), IPL_DEPTH_8U, 3);

  for (x = 0; x < gray1->width; x ++) {
    for (y = 0; y < gray1->height; y ++) {
      CvScalar p1, p2, s;
      int val1, val2;

      p1 = cvGet2D(gray1, y, x);
      p2 = cvGet2D(gray2, y, x);

      val1 = ((p1.val[0] * (255 - WHITE_POINT_BLUE)) / 255) + WHITE_POINT_BLUE;
      val2 = ((p2.val[0] * (255 - WHITE_POINT_RED)) / 255) + WHITE_POINT_RED;

      s.val[0] = val1; // Blue
      s.val[1] = ((val2 * 0.8) + val1) / 2; // Green
      s.val[2] = val2; // Red

      cvSet2D(output, y, x, s);
    }
  }

  // Create a window
  cvNamedWindow(wndname, 1);
  cvShowImage(wndname, output);

  // Wait for a key stroke; the same function arranges events processing
  cvWaitKey(0);

  cvSaveImage(argv[3], output);

  return 0;
}
