nearest_neighbor_interpolation.pl 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 27 July 2018
  4. # https://github.com/trizen
  5. # A simple implementation of the nearest-neighbor interpolation algorithm for scaling up an image.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation
  8. use 5.020;
  9. use strict;
  10. use warnings;
  11. use Imager;
  12. use experimental qw(signatures);
  13. sub nearest_neighbor_interpolation ($file, $zoom = 2) {
  14. my $img = Imager->new(file => $file)
  15. or die Imager->errstr();
  16. my $width = $img->getwidth;
  17. my $height = $img->getheight;
  18. my $out_img = Imager->new(xsize => $zoom * $width,
  19. ysize => $zoom * $height);
  20. foreach my $y (0 .. $height - 1) {
  21. foreach my $x (0 .. $width - 1) {
  22. my $pixel = $img->getpixel(x => $x, y => $y);
  23. #<<<
  24. # Fill the gaps
  25. $out_img->setpixel(x => $zoom * $x, y => $zoom * $y, color => $pixel);
  26. $out_img->setpixel(x => $zoom * $x + 1, y => $zoom * $y + 1, color => $pixel);
  27. $out_img->setpixel(x => $zoom * $x + 1, y => $zoom * $y, color => $pixel);
  28. $out_img->setpixel(x => $zoom * $x, y => $zoom * $y + 1, color => $pixel);
  29. #>>>
  30. }
  31. }
  32. return $out_img;
  33. }
  34. my $file = shift(@ARGV) // die "usage: $0 [image]\n";
  35. my $img = nearest_neighbor_interpolation($file, 2);
  36. $img->write(file => "output.png");