I explained an edge-detection algorithm in great detail in an earlier lesson titled 3D Displays, Color Distance, and Edge Detection.
The code in Listing 3 is essentially an implementation of that algorithm