Oct 22, 2007

MLCMG

Welcome to the latest installment of "Why did I write this perl script?" theater.

The answer, as usual, is "because it's 6 am and I've lost focus."

#!/usr/bin/perl
# Matlab Colormap Generator (MLCMP)
# By Alex Dodge
# alexdodge.net
#
# Interpolates a gradient for use as a matlab colormap
#
# Input: Source File in following format
#
# x r g b
#
#
# For example, to fade from red, to yellow at .65, to blue:
# 0 1 0 0
# .65 1 1 0
# 1 0 0 1

use strict;
use warnings;

if(!defined @ARGV || scalar @ARGV!= 3){
print STDERR "Arguments: Name Resolution SrcFile\n";
exit 1;
}

my ($name, $resolution, $src) = @ARGV;

print("\% Created by mlcmg.pl, by Alex Dodge\n");
print("\% Input: Nothing\n\% Output: A colormap\n");
print("function cm=$name()\n");
print("\tcm = zeros($resolution, 3);\n");

my $file = "";

my @last = (0,0,0,0);

my $i = 1;

if (!open(FD, "<", $src)){
print STDERR "Can't open $src.\n";
exit 2;
}
while(){
chomp $_;
$file .= "\%$_\n";
next if (substr($_, 0, 1) eq "#");
my @in = split(/\s/, $_);

for(;($i/$resolution)<($in[0]);$i++){
my $T = $i/$resolution;
my $t0 = $last[0];
my $t1 = $in[0];
my $t = ($T-$t0)/($t1-$t0);
my $r0 = $last[1];
my $r1 = $in[1];
my $g0 = $last[2];
my $g1 = $in[2];
my $b0 = $last[3];
my $b1 = $in[3];
my $r = ($t*($r1-$r0)) + $r0;
my $g = ($t*($g1-$g0)) + $g0;
my $b = ($t*($b1-$b0)) + $b0;
printf ("\t%s(%d,:) = [%.3f %.3f %.3f];\n", 'cm', $i, $r, $g, $b);
}
@last = @in;
}
close FD;

printf("\t%s(%d,:) = [%.3f %.3f %.3f];\n", 'cm', $resolution, $last[1], $last[2], $last[3]);
print "% Original Gradient File:\n";
print $file;