#!/usr/bin/perl

die "Convert images from fisheye to stereographic:
     http://en.wikipedia.org/wiki/Stereographic_projection

Usage:$0 120 infile.png outfile.jpg\n"
unless @ARGV == 3;

# Bruno Postle <bruno@postle.net>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.

use strict;
use warnings;
use Imager;
use Parse::RecDescent;

my $fov = shift;
my $in  = shift;
my $out = shift;

my $img = new Imager;
   $img->open (file => $in) or die $img->errstr;

my $pi = atan2(1,1)*4;
$fov = $fov * $pi / 180;

my $correct =
   "w2=w/2;h2=h/2;
    rad=w2;
    p1=($fov/2)*pi*distance(w2,h2,x,y)/2;
    p2=atan2(1,2/p1*rad)/p1*pi*rad;
    m=((x-w2)*p2)+w2;
    n=((y-h2)*p2)+h2;";

my $get_linear =
   "intm=int(m);intn=int(n);
    e=1-m+intm;f=m-intm;g=1-n+intn;h=n-intn;
    pixel=getp1(m,n)*e*g+getp1(m+1,n)*f*g+getp1(m,n+1)*e*h+getp1(m+1,n+1)*f*h;";

my $opts = { expr => "$correct $get_linear return(pixel);" };

my $output = Imager::transform2 ($opts, $img) or die $Imager::ERRSTR;

   $output->write (file => $out) or die $output->errstr;

1;
