Created
March 12, 2009 14:50
-
-
Save hiratara/78102 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use AI::NeuralNet::Simple; | |
use GD; | |
my $width = 200; | |
my $height = 200; | |
my @classes = ( | |
{ | |
color => [0xff, 0x99, 0x99], | |
point_color => [0xff, 0x00, 0x00], | |
pattern => [ | |
[40, 60], [60, 65], [20, 70], [55, 80], [100, 140], | |
], | |
}, | |
{ | |
color => [0x99, 0x99, 0xff], | |
point_color => [0x00, 0x00, 0xff], | |
pattern => [ | |
[40, 40], [60, 35], [20, 50], [55, 20], [100, 10], [90, 80], | |
], | |
}, | |
{ | |
color => [0xC0, 0xff, 0xC0], | |
point_color => [0x00, 0xff, 0x00], | |
pattern => [ | |
[140, 40], [160, 35], [120, 170], [155, 180], [190, 10], [190, 100], | |
], | |
}, | |
); | |
# subroutine ================================================================== | |
sub feature_vector{ | |
my $ref = shift; | |
return [ | |
( $ref->[0] / $width ) * 2 - 1, | |
( $ref->[1] / $height ) * 2 - 1, | |
]; | |
} | |
# learning ==================================================================== | |
my $train_no = $ARGV[0]; | |
my @train_datas; | |
foreach my $i (0 .. $#classes){ | |
my $c = $classes[$i]; | |
my $b = [ map {$_ == $i ? 1 : 0} 0 .. $#classes ]; | |
foreach my $vec ( @{ $c->{pattern} } ){ | |
push @train_datas, feature_vector($vec) => $b; | |
} | |
} | |
my $net = AI::NeuralNet::Simple->new(2, scalar @classes, scalar @classes); | |
$net->train_set(\@train_datas, $train_no, 0.1); | |
# draw ======================================================================== | |
my $im = new GD::Image($width, $height); | |
my $bgcolor = $im->colorAllocate(0xff, 0xff, 0xff); | |
# make colors | |
my @colors; | |
my @point_colors; | |
foreach my $i (0 .. $#classes){ | |
my $c = $classes[$i]; | |
$colors[$i] = $im->colorAllocate( @{ $c->{color} } ); | |
$point_colors[$i] = $im->colorAllocate( @{ $c->{point_color} } ); | |
} | |
# draw classes | |
foreach my $x ( 0 .. $width - 1 ){ | |
foreach my $y ( 0 .. $height - 1 ){ | |
my $i = $net->winner( feature_vector( [$x, $y] ) ); | |
$im->setPixel( $x, $y, $colors[$i] ); | |
} | |
} | |
# draw patterns | |
foreach my $i (0 .. $#classes){ | |
my $c = $classes[$i]; | |
foreach my $p (@{ $c->{pattern} }){ | |
$im->filledArc( | |
$p->[0] - 2, $p->[1] - 2, 4, 4, | |
0, 360, | |
$point_colors[$i], | |
); | |
} | |
} | |
# output image | |
open my $out, '>:raw', 'hoge.png' or die; | |
print $out $im->png; | |
close $out; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment