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 K_{kl}}

, where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determines the new value of a monochromatic image pixel Pij 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 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(n2)) 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.)

type Float_Luminance is new Float;
 
type Float_Pixel is record
   R, G, B : Float_Luminance := 0.0;
end record;
 
function "*" (Left : Float_Pixel; Right : Float_Luminance) return Float_Pixel is
   pragma Inline ("*");
begin
   return (Left.R * Right, Left.G * Right, Left.B * Right);
end "*";
 
function "+" (Left, Right : Float_Pixel) return Float_Pixel is
   pragma Inline ("+");
begin
   return (Left.R + Right.R, Left.G + Right.G, Left.B + Right.B);
end "+";
 
function To_Luminance (X : Float_Luminance) return Luminance is
   pragma Inline (To_Luminance);
begin
   if X <= 0.0 then
      return 0;
   elsif X >= 255.0 then
      return 255;
   else
      return Luminance (X);
   end if;
end To_Luminance;
 
function To_Pixel (X : Float_Pixel) return Pixel is
   pragma Inline (To_Pixel);
begin
   return (To_Luminance (X.R), To_Luminance (X.G), To_Luminance (X.B));
end To_Pixel;