Normalization is necessary to keep the image balanced (else any filter may quickly turn the image almost completely black or white).
Here is a short, easy-to-use, class to handle normalization automatically and make for easier input of the 3x3 matrix:
The code respects the "array of three arrays" syntax for use with the imageconvolution() function and automatically calculates the necesarry divisor for normalization.
<?php
class ConvolutionFilter {
public $matrix;
public $div;
public function computeDiv() {
$this->div = array_sum ($this->matrix[0]) + array_sum ($this->matrix[1]) + array_sum ($this->matrix[2]);
}
function __construct() {
$matrix = func_get_args();
$this->matrix = array( array($matrix[0], $matrix[1], $matrix[2]),
array($matrix[3], $matrix[4], $matrix[5]),
array($matrix[6], $matrix[7], $matrix[8])
);
$this->computeDiv();
}
}
?>
Example usage:
<?php
$gaussianFilter = new ConvolutionFilter( 1.0, 2.0, 1.0,
2.0, 3.0, 2.0,
1.0, 2.0, 1.0 );
imageconvolution($image, $gaussianFilter->matrix, $gaussianFilter->div, 0);
?>
Some common filters:
<?php
$identityFilter = new ConvolutionFilter( 0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 0.0 );
$sharpenFilter = new ConvolutionFilter( 0.0, -1.0, 0.0,
-1.0, 5.0, -1.0,
0.0, -1.0, 0.0 );
$edgeFilter = new ConvolutionFilter( 0.0, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0 );
$findEdgesFilter = new ConvolutionFilter( -1.0, -1.0, -1.0,
-2.0, 8.0, -1.0,
-1.0, -1.0, -1.0 );
?>
Remember you can use imagefilter() for such basic needs but the above class will make it easier for you when you want to create your own filters.