Image edge detection algorithm – php version

One of the most used image effects is the edge detection. Have you ever wondered how does it work?

The following is a tutorial to achieve an edge detection effect on an image without using any built-in functions, such as imagefilter with IMG_FILTER_EDGEDETECT filter type.

It will be very useful to learn something about image filters.

Before we begin, let me copy/paste some basic information from Wikipedia :)

Edge detection is a fundamental tool in image processing and computer vision, particularly in the areas of feature detection and feature extraction, which aim at identifying points in a digital image at which the image brightness changes sharply or more formally has discontinuities (source).

Now we know we are looking for sharp image brightness changes.

To quickly get the image brigthness, we have to convert it to a grayscale representation of its luminance.

To convert any color to a grayscale representation of its luminance, first one must obtain the values of its red, green, and blue (RGB) primaries in linear intensity encoding, by gamma expansion. Then, add together 30% of the red value, 59% of the green value, and 11% of the blue value. The resultant number is the desired linear luminance value (source).

Once we have our luminance map, we can use the Sobel operator to detect edges.

The Sobel operator calculates the directional change of the image intensity at each point, giving the direction of the largest possible increase from light to dark and the rate of change in that direction, using uses a pair of 3×3 convolution masks, one estimating the directional change in the x-direction and the other estimating the directional change in the y-direction.

This is the convolution mask:

Where A is the source image.

Once you have Gx and Gy values, combine them this way:

to get the directional change and consequently the gray representation of the edge.

Time to code something:

 255){
            $gray = 255;
        }
        if($gray < 0){
            $gray = 0;
        }
        
        // creation of the new gray
        $new_gray  = imagecolorallocate($final,$gray,$gray,$gray);
        
        // adding the gray pixel to the new image        
        imagesetpixel($final,$x,$y,$new_gray);            
    }
}

// telling the browser we are going to output a jpeg image
header('Content-Type: image/jpeg');

// creation of the final image
imagejpeg($final);

// freeing memory
imagedestroy($starting_img);
imagedestroy($final);

// function to get the luminance value
function get_luminance($pixel){
    $pixel = sprintf('%06x',$pixel);
    $red = hexdec(substr($pixel,0,2))*0.30;
    $green = hexdec(substr($pixel,2,2))*0.59;
    $blue = hexdec(substr($pixel,4))*0.11;
    return $red+$green+$blue;
}

?>

I tried the script on this image:

This is the Photoshop CS4 Find Edges filter on the desaturated image:

This is the result of the script:

This is the result of the same script using Manhattan Distance rather than Euclidean distance, changing line 33 with:

$gray = abs($conv_x)+abs($conv_y);

And this is the result of the same script applying the Manhattan Distance and a gaussian blur this way:

imagefilter($starting_img,IMG_FILTER_GAUSSIAN_BLUR);

Hope you can use this concept in some of your works. I already have one use in mind… stay tuned.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers