The April 2016 Perl programming challenge by Tony Gasparovic


THE CHALLENGE: Reconstruct JPG images one pixel at a time. DETAILS: You are given a JSON data file that contains the color values and mapping of every pixel in the image. Write a Perl program that reconstructs the JPG image. Use any image viewer to check your work. Download JSON data files here image1.json 900x600 image2.json 1024x768 image3.json 1024x768 JSON data file mapping example: "0" : { # Height index "0" : { # Width index "GREEN" : 49, # Green color pixel value "BLUE" : 49, # Blue color pixel value "RED" : 49 # Red color pixel value }, "1" : { "GREEN" : 34, "BLUE" : 34, "RED" : 34 }, "2" : { "GREEN" : 36, "BLUE" : 36, "RED" : 36 }, Good luck Mongers! Image Files:
image1 answer
image2 answer
image3 answer


# Read the image #!/usr/bin/perl # April Perl programming challenge by Tony Gasparovic # This program converts an image to GREEN,RED,BLUE color pixels and stores the output to a JSON file use JSON::PP; use Image::Magick; $p = new Image::Magick; # image to covert $p->Read("/home/tony/perl/pengiuns.jpg"); $Data::Dumper::Sortkeys = sub { [sort {$a<=>$b} keys %{$_[0]}] }; $width = $p->Get('columns'); $height = $p->Get('rows'); $colors = $p->Get('colors'); $height = $p->Get('height'); $x_res = $p->Get('x-resolution'); $y_res = $p->Get('y-resolution'); foreach $h ( 0..$height ) { foreach $w ( 0..$width) { @pixels = map { ($_ * 255) } $p->GetPixel(x=>$w,y=>$h); $data{$h}{$w} = { RED=>$pixels[0],GREEN=>$pixels[1],BLUE=>$pixels[2] } ; } } my $json = JSON::PP->new; $json->canonical( 1 ); $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b }); my $json_text = $json->pretty->encode( \%data ); print $json_text; ######################################################################## Write the JSON data back to a image #!/usr/bin/perl # Perl Mongers April Challenge by Tony Gasparovic # This program reads in image color pixels from a JSON file and reconstructs the image back into a .jpg file use JSON qw( decode_json ); use Data::Dumper; use Image::Magick; use strict; my $p = new Image::Magick; my $filename = "image.jpg"; open(IMAGE, ">$filename"); my $json = JSON->new; my $data; local $/ = undef; open my $fh, '<', $ARGV[0]; my $json_string = <$fh>; close $fh; my $json_ref = decode_json( $json_string ); my $height = keys %$json_ref or die; my $width = keys %{$json_ref->{0}} or die; $p->Set(size=>"${width}x${height}"); $p->ReadImage('xc:white'); foreach my $row ( keys %$json_ref ) { foreach my $col ( keys %{$json_ref->{$row}} ) { $p->Set("pixel[$col,$row]"=>"rgb($json_ref->{$row}{$col}{RED},$json_ref->{$row}{$col}{GREEN},$json_ref->{$row}{$col}{BLUE})"); } } $p->Write(file=>\*IMAGE, filename=>$filename); close(IMAGE);