Edge detection and gradient calculation