user
One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square 

K

k
l
{\displaystyle {\displaystyle K\_{kl}}}
, where *k*, *l* are in the range -*R*,-*R*+1,..,*R*-1,*R*. *W*=2*R*+1 is the kernel width.

The filter determines the new value of a **grayscale image** pixel P*ij* as a convolution of the image pixels in the window centered in *i*, *j* and the kernel values:

> P
>
> i
> j
> =
>
>
> ∑
>
> k
> =
> −
> R
>
> R
>
> ∑
>
> l
> =
> −
> R
>
> R
>
> P
>
> i
> +
> k
>  
> j
> +
> l
>
> K
>
> k
> l
> {\displaystyle {\displaystyle P\_{ij}=\displaystyle \sum \_{k=-R}^{R}\sum \_{l=-R}^{R}P\_{i+k\ j+l}K\_{kl}}}

**Color images** are usually split into the channels which are filtered independently. A color model can be changed as well, i.e. filtration is performed not necessarily in RGB. Common kernels sizes are 3x3 and 5x5. The complexity of filtrating grows quadratically (O(*n*2)) with the kernel width.

**Task**: Write a generic convolution 3x3 kernel filter. Optionally show some end user filters that use this generic one.

*(You can use, to test the functions below, these input and output solutions.)*
assistant
(formerly Perl 6)

### Perl 5 PDL library

```
use PDL:from<Perl5>;
use PDL::Image2D:from<Perl5>;

my $kernel = pdl [[-2, -1, 0],[-1, 1, 1], [0, 1, 2]]; # emboss

my $image = rpic 'frog.png';
my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'};
wpic $smoothed, 'frog_convolution.png';

```

Compare offsite images: frog.png vs.
frog\_convolution.png

### Imagemagick library

```
# Note: must install version from github NOT version from CPAN which needs to be updated. 
# Reference:
# https://github.com/azawawi/perl6-magickwand
# http://www.imagemagick.org/Usage/convolve/
 
use v6;
 
use MagickWand;
 
# A new magic wand
my $original = MagickWand.new;
 
# Read an image
$original.read("./Lenna100.jpg") or die;
 
my $o = $original.clone;
 
# using coefficients from kernel "Sobel"
# http://www.imagemagick.org/Usage/convolve/#sobel
$o.convolve( [ 1, 0, -1,
               2, 0, -2,
               1, 0, -1] );
 
$o.write("Lenna100-convoluted.jpg") or die;
 
# And cleanup on exit
LEAVE {
  $original.cleanup   if $original.defined;
  $o.cleanup if $o.defined;
}

```