Search code examples
pythonimage-processingedge-detection

python image edge detection


is there a fast way to extract horizontal, vertical, diagonal, anti-diagonal edges in python each of which must be a separate matrix this is the edges equations I do it in this manner seem to be slow and might have some index problems

def ImageEdges(arr):
    Harr , Varr , Darr,Marr= arr*0,arr*0,arr*0,arr*0
    for i in range(arr.shape[0]-1):
        for j in range(arr.shape[1]-1):
            Harr[i,j] = np.abs(arr[i,j] - arr[i+1,j])
            Varr[i,j] = np.abs(arr[i,j] - arr[i,j+1])            
            Darr[i,j] = np.abs(arr[i,j] - arr[i+1,j+1])   
            Marr[i,j] = np.abs(arr[i,j] - arr[i+1,j-1])            

    return Harr,Varr, Darr,Marr

Solution

  • Some of the specifics would depend on whether you want any padding so as to obtain the same output dimensions for all of the arrays. Let's say you don't, then this should do the trick:

    Harr = np.abs(arr[:,:-1]-arr[:,1:])
    Varr = np.abs(arr[:-1,:]-arr[1:,:])
    Darr = np.abs(arr[:-1,:-1]-arr[1:,1:])
    Marr = np.abs(arr[:-1,1:]-arr[1:,:-1])
    

    (Note that I swapped the definitions of Harr and Varr following the convention where the first index is considered to be "vertical")

    See https://docs.python.org/3/library/stdtypes.html#common-sequence-operations if you're unfamiliar with Python's slicing notation