diff_negative.pl 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 07 November 2015
  5. # Edit: 19 May 2016
  6. # Website: https://github.com/trizen
  7. # Replace the light-color pixels with the difference between the brightest and darkest neighbors.
  8. # _________________
  9. # | | | |
  10. # | A | B | C |
  11. # |_____|_____|_____| _____
  12. # | | | | | |
  13. # | H | | D | --> | M |
  14. # |_____|_____|_____| |_____|
  15. # | | | |
  16. # | G | F | E |
  17. # |_____|_____|_____|
  18. # where M is the average color of (max(A..H) - min(A..H))
  19. use 5.010;
  20. use strict;
  21. use warnings;
  22. use List::Util qw(min max sum);
  23. use GD;
  24. GD::Image->trueColor(1);
  25. sub help {
  26. my ($exit_code) = @_;
  27. print <<"EOT";
  28. usage: $0 [input image] [output image]
  29. EOT
  30. exit($exit_code // 0);
  31. }
  32. my $in_file = shift(@ARGV) // help(2);
  33. my $out_file = shift(@ARGV) // 'output.png';
  34. my $img = GD::Image->new($in_file);
  35. my @matrix = ([]);
  36. my ($width, $height) = $img->getBounds;
  37. my $new_img = GD::Image->new($width, $height);
  38. sub diff {
  39. max(@_) - min(@_);
  40. }
  41. sub avg {
  42. (int(sum(@_) / @_)) x 3;
  43. }
  44. sub get_pixel {
  45. $img->rgb($img->getPixel(@_))
  46. }
  47. foreach my $y (1 .. $height - 2) {
  48. foreach my $x (1 .. $width - 2) {
  49. my @left = get_pixel($x - 1, $y);
  50. my @right = get_pixel($x + 1, $y);
  51. my @down_left = get_pixel($x - 1, $y + 1);
  52. my @down_right = get_pixel($x + 1, $y + 1);
  53. my @up = get_pixel($x, $y - 1);
  54. my @down = get_pixel($x, $y + 1);
  55. my @up_left = get_pixel($x - 1, $y - 1);
  56. my @up_right = get_pixel($x + 1, $y - 1);
  57. $matrix[$y][$x] =
  58. $new_img->colorAllocate(
  59. avg(
  60. diff(($up[0], $down[0], $up_left[0], $up_right[0], $down_left[0], $down_right[0])),
  61. diff(($up[1], $down[1], $up_left[1], $up_right[1], $down_left[1], $down_right[1])),
  62. diff(($up[2], $down[2], $up_left[2], $up_right[2], $down_left[2], $down_right[2]))
  63. ),
  64. );
  65. }
  66. }
  67. for my $y (1 .. $height - 2) {
  68. for my $x (1 .. $width - 2) {
  69. $new_img->setPixel($x, $y, $matrix[$y][$x]);
  70. }
  71. }
  72. open(my $fh, '>:raw', $out_file) or die "Can't open `$out_file' for write: $!";
  73. print $fh (
  74. $out_file =~ /\.png\z/i ? $new_img->png
  75. : $out_file =~ /\.gif\z/i ? $new_img->gif
  76. : $new_img->jpeg
  77. );
  78. close $fh;