Grayscale image: Difference between revisions

Content added Content deleted
(Lingo added)
m (→‎{{header|Perl 6}}: fixed file read)
Line 1,115: Line 1,115:
end</lang>
end</lang>


=={{header|Perl}}==
=={{header|Perl 6}}==
This script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.
<lang perl6>sub MAIN ($filename = 'default.ppm') {


my $in = open($filename, :r, :enc<iso-8859-1>);
{{libheader|Imlib2}}


my ($type, $dim, $depth) = $in.lines[^3];
Since we are using Imlib2, this one '''does''' '''not''' implement really a gray-scale (single channel) storage; it only ''converts'' an RGB image to an RGB image with the same three colour components for each pixel (which result in a gray-scale-like image)


my $outfile = $filename.subst('.ppm', '.pgm');
<lang perl>#! /usr/bin/perl
my $out = open($outfile, :w, :enc<iso-8859-1>);


$out.say("P5\n$dim\n$depth");
use strict;
use Image::Imlib2;


for $in.lines.ords -> $r, $g, $b {
sub tograyscale
my $gs = $r * 0.2126 + $g * 0.7152 + $b * 0.0722;
{
my $img = shift;
$out.print: chr($gs min 255);
my $gimg = Image::Imlib2->new($img->width, $img->height);
for ( my $x = 0; $x < $gimg->width; $x++ ) {
for ( my $y = 0; $y < $gimg->height; $y++ ) {
my ( $r, $g, $b, $a ) = $img->query_pixel($x, $y);
my $gray = int(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);
# discard alpha info...
$gimg->set_color($gray, $gray, $gray, 255);
$gimg->draw_point($x, $y);
}
}
}
return $gimg;
}


$in.close;
my $animage = Image::Imlib2->load("Lenna100.jpg");
$out.close;
my $gscale = tograyscale($animage);
}</lang>
$gscale->set_quality(80);
Using the .ppm file from the [[Bitmap/Write a PPM file#Perl 6|Write a PPM file]] task:
$gscale->save("Lennagray.jpg");

Original: [[File:Ppm-perl6.png]] Grey Scale: [[File:Pgm-g2-perl6.png]]


exit 0;</lang>
=={{header|Perl 6}}==
=={{header|Perl 6}}==
This script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.
This script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.