Image Processing Computer Science

Average Filter

This PHP GD example contains the code for an example program that demonstrates how to low-pass filter an image by using a simple averaging filter to blur it.

AverageFilter.php

<?php
  function CreateAveragedImage($qSourceImage, $iFilterSize) {
    $iImageWidth   = ImageSX($qSourceImage);
    $iImageHeight  = ImageSY($qSourceImage);
    $qDestImage    = ImageCreateTrueColor($iImageWidth, $iImageHeight);
    ImageCopy($qDestImage, $qSourceImage, 0, 0, 0, 0, $iImageWidth, $iImageHeight);
    // This filter is assumed to be of odd width with the middle over the center
    $iMiddle = ($iFilterSize >> 1);
    for ($j = 0; $j < $iImageHeight; ++$j) {
      for ($i = 0; $i < $iImageWidth; ++$i) {
        $iFilterWeight = 0;
        $iRedSum       = 0;
        $iGreenSum     = 0;
        $iBlueSum      = 0;
        $iAlphaSum     = 0;
        for ($iFY = 0; $iFY < $iFilterSize; ++$iFY) {
          $iSrcIndexY = $j + $iFY - $iMiddle;
          if ($iSrcIndexY >= 0 && $iSrcIndexY < $iImageHeight) {
            for ($iFX = 0; $iFX < $iFilterSize; ++$iFX) {
              $iSrcIndexX = $i + $iFX - $iMiddle;
              if ($iSrcIndexX >= 0 && $iSrcIndexX < $iImageWidth) {
                $iSourcePixel = ImageColorAt($qSourceImage, $iSrcIndexX, $iSrcIndexY);
                $iAlphaSum += (($iSourcePixel >> 24) & 0xFF);
                $iRedSum   += (($iSourcePixel >> 16) & 0xFF);
                $iGreenSum += (($iSourcePixel >> 8) & 0xFF);
                $iBlueSum  += ($iSourcePixel & 0xFF);
                $iFilterWeight += 1;
              }
            }
          }
        }
        $iRed   = intval($iRedSum/$iFilterWeight);
        $iGreen = intval($iGreenSum/$iFilterWeight);
        $iBlue  = intval($iBlueSum/$iFilterWeight);
        $iAlpha = intval($iAlphaSum/$iFilterWeight);
        $qResultPixel = ImageColorExactAlpha($qDestImage, $iRed, $iGreen, $iBlue, $iAlpha);
        ImageSetPixel($qDestImage, $i, $j, $qResultPixel);
      }
    }
    return $qDestImage;
  }

  $qOriginalImage = ImageCreateFromPng("bouguereau_flagellation.png");
  $qAveragedImage = CreateAveragedImage($qOriginalImage, 5);

  // Create a comparison image with double the width
  $iImageWidth   = ImageSX($qOriginalImage);
  $iImageHeight  = ImageSY($qOriginalImage);
  $qCompareImage = ImageCreateTrueColor(2*$iImageWidth, $iImageHeight);
  ImageCopyMerge($qCompareImage, $qOriginalImage, 0, 0, 0, 0, $iImageWidth, $iImageHeight, 100);
  ImageCopyMerge($qCompareImage, $qAveragedImage, $iImageWidth, 0, 0, 0, $iImageWidth,
    $iImageHeight, 100);

  Header('Content-type: image/png');
  ImagePng($qCompareImage);
  ImageDestroy($qCompareImage);
  ImageDestroy($qOriginalImage);
  ImageDestroy($qAveragedImage);
?>
 
 

Output

 
 

© 2007–2022 XoaX.net LLC. All rights reserved.