In detecting edges, the basic idea is to look for regions with sharp change of contrast.
Usually the color/pixel values change sharply at the edges of objects.
Since we only need to detect edge lines, we simplify things further by converting image to grayscale and look for sharp changes in pixel values.
We convolve over the image with a simple filter [-1, 0, 1] to detect sharp changes in x-direction, transpose it for the y-direction.
Finally take the magnitude of both, to get our edges.
An improvement on our simple filter would be to use a Sobel Filter which gives slightly better results due to better averaging.
Finally, the code is as below.