-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathplay-color-pixels
56 lines (39 loc) · 1.32 KB
/
play-color-pixels
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env perl
# Write up: https://ology.github.io/2020/03/23/hearing-an-image-one-pixel-at-a-time/
use strict;
use warnings;
use Image::Size;
use Imager;
use Math::Utils ':utility';
use lib "$ENV{HOME}/sandbox/MIDI-Util/lib";
use MIDI::Util qw(setup_score); # https://metacpan.org/release/MIDI-Util
my $file = shift || die "Usage: perl $0 /some/image/file.{jpg,png,etc}\n";
my $bpm = shift || 100;
my $score = setup_score(bpm => $bpm, patch => 4);
my $img = Imager->new;
$img->read(file => $file)
or die "Can't read $file: ", $img->errstr;
my($w, $h) = imgsize($file);
my $w_field = length $w;
my $h_field = length $h;
my $i_field = length($w * $h);
my $color_range = [0, 255];
my $midi_range = [60, 83];
my $i = 0;
# Add a chord to the score for each RGB pixel color
for my $y (0 .. $h - 1) {
for my $x (0 .. $w - 1) {
$i++;
my $color = $img->getpixel(x => $x, y => $y);
my ($red, $green, $blue) = $color->rgba;
my @chord = map { sprintf '%.0f', uniform_scaling($color_range, $midi_range, $_) }
$red, $green, $blue;
printf "%*d. [%*d,%*d] %3d,%3d,%3d -> %s\n",
$i_field, $i,
$w_field, $x, $h_field, $y,
$red, $green, $blue,
join(' ', @chord);
$score->n('qn', @chord);
}
}
$score->write_score("$0.mid");