
// Anaglyph.java
// https://imagej.net/ij/plugins/anaglyph.html
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Generate a red-cyan anaglyph from two images
   of a scene taken side-by-side.

   https://en.wikipedia.org/wiki/Anaglyph_3D

   Usage:
     > compile Anaglyph.java
     > run Anaglyph 

*/

import java.awt.*;

import ij.*;
import ij.process.*;
import ij.gui.*;


public class Anaglyph
{

  public static void main(String[] args)
  {
    System.out.println("Loading left.jpg and right.jpg");
    ImagePlus leftImp = new ImagePlus("left.jpg");
    ImagePlus rightImp = new ImagePlus("right.jpg");
    leftImp.show();
    rightImp.show();

    int w = leftImp.getWidth();
    int h = leftImp.getHeight();
    int rightWidth = rightImp.getWidth();
    int rightHeight = rightImp.getHeight();

    if ((w != rightWidth) || (h != rightHeight)) {
      System.out.println("Images have unequal dimensions");
      return;
    }

    ImageProcessor anaglyphIP = new ColorProcessor(w, h);
    ImageProcessor leftIP = leftImp.getProcessor();
    ImageProcessor rightIP = rightImp.getProcessor();

    int[] stereoPixels = (int[]) anaglyphIP.getPixels();
    int[] leftPixels = (int[]) leftIP.getPixels();
    int[] rightPixels = (int[]) rightIP.getPixels();

    int red, green, blue;
    for(int i=0; i < w*h; i++) {
      red = ImageUtils.getRed(leftPixels[i]);
          // left eye image uses red channel
      green = ImageUtils.getGreen(rightPixels[i]);
      blue = ImageUtils.getBlue(rightPixels[i]);
          // right eye image uses both green and blue channels

      stereoPixels[i] = ImageUtils.makePixel(red, green, blue);
    }

    anaglyphIP.setPixels(stereoPixels);
    ImagePlus stereoImp = new ImagePlus("Stereo Image", anaglyphIP);
    stereoImp.show();

    System.out.println("Saving anaglyph as anaglyph.jpg");
    IJ.saveAs(stereoImp, "jpg", "anaglyph.jpg");

    ImageUtils.waitGone("Stereo Image"); 
    System.exit(0);
  } /* main */


}  // end of Anaglyph class
