Edge detection based on sobel operator (python implementation)

Operator

  In image processing, edge detection is an inseparable part, and operators can be regarded as a medium for edge detection. Like us who learn EE, the operator is like a Butterworth filter, which filters out what we don’t want and leaves what we need; it’s like the rice sieve we saw when we were young. The rice we eat at home is mixed with many "strange" things, such as small stones, wheat ears, etc., unlike the rice we buy now, which is sifted for us by machines, it is rare that our teeth can suddenly click when we eat rice. For a moment, it was really painful at the time.

  In this article, the Sobel operator is used, which uses two 3×3 kernels convolved with the original image to calculate the approximate value of the derivative-one for horizontal changes and one for vertical changes.

  If we define A as the source image, and G x G_xGx G y G_y GandAre two images, each point contains the vertical and horizontal derivative approximations, then the calculation is as follows:
G x = [− 1 0 + 1 − 2 0 + 2 − 1 0 + 1] ∗ AG y = [− 1 − 2 − 1 0 0 0 + 1 + 2 + 1] ∗ A G_x =\begin{bmatrix} -1 & 0 & +1\\ -2 & 0 & +2\\ -1 & 0 & +1\\ \end{ bmatrix} * A\quad\quad\quad G_y = \begin{bmatrix} -1 & -2 & -1\\ 0 & 0 & 0\\ +1 & +2 & +1\\ \end{bmatrix}\ * AGx=121000+1+2+1AGand=10+120+210+1 A
here,∗ * represents the convolution operation, that is, the corresponding positions of the two matrices are multiplied, that is, dot multiplication.

  Obviously, the "pixel" of a picture is not all 3×3, and even no picture is so small. Then the above implementation method is also very simple, that is, starting from the upper left corner of A, move line by line, and then return to the next line. Until the bottom right corner.

Insert picture description here

Here is a picture of my favorite blogger (victorzhou).

  In most cases, the size of the "screened" picture should be equal to the original picture. Generally, there are two ways to solve it. Here I use zero padding on the periphery of the processed picture, that is, black out.

Algorithm implementation

  After a brief introduction, my code is given below. The code consists of several parts. First, the core part is given:

def sobel_v(img, threshold):
    '''
    edge detection with the vertical Sobel filter

    Parameters
    ----------
    img : TYPE
        the image input.
    threshold : TYPE
         varies for application [0 255].

    Returns
    -------
    mag : TYPE
        output after edge detection.

    '''
    G_x = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]])
    rows = np.size(img, 0)
    columns = np.size(img, 1)
    mag = np.zeros(img.shape)
    for i in range(0, rows - 2):
        for j in range(0, columns - 2):
            v = sum(sum(G_x * img[i:i+3, j:j+3]))  # vertical
            mag[i+1, j+1] = v
            
    for p in range(0, rows):
        for q in range(0, columns):
            if mag[p, q] < threshold:
                mag[p, q] = 0
    return mag

This is the detection in the vertical direction. The pictures before and after processing are compared as follows:

Comparison of original image and processed image
Then the detection in the horizontal direction is very simple.

def sobel_h(img, threshold):
    '''
    edge detection with the horizon Sobel filter

    Parameters
    ----------
    img : TYPE
        the image input.
    threshold : TYPE
         varies for application [0 255].

    Returns
    -------
    mag : TYPE
        output after edge detection.

    '''
    G_y = np.array([[-1, -2, -1],[0, 0, 0],[1, 2, 1]])
    rows = np.size(img, 0)
    columns = np.size(img, 1)
    mag = np.zeros(img.shape)
    for i in range(0, rows - 2):
        for j in range(0, columns - 2):
            h = sum(sum(G_y * img[i:i+3, j:j+3]))  # horizon
            mag[i+1, j+1] = h
            
    for p in range(0, rows):
        for q in range(0, columns):
            if mag[p, q] < threshold:
                mag[p, q] = 0
    return mag

Comparison of original image and processed image

The horizontal and vertical directions are performed at the same time, that is, when calculating each pixel, the horizontal and vertical values ​​can be processed as a square sum.

def sobel(img, threshold):
    '''
    edge detection based on sobel

    Parameters
    ----------
    img : TYPE
        the image input.
    threshold : TYPE
         varies for application [0 255].

    Returns
    -------
    mag : TYPE
        output after edge detection.

    '''
    G_x = np.array([[-1, 0, 1],[-2, 0, 2],[-1, 0, 1]])
    G_y = np.array([[-1, -2, -1],[0, 0, 0],[1, 2, 1]])
    rows = np.size(img, 0)
    columns = np.size(img, 1)
    mag = np.zeros(img.shape)
    for i in range(0, rows - 2):
        for j in range(0, columns - 2):
            v = sum(sum(G_x * img[i:i+3, j:j+3]))  # vertical
            h = sum(sum(G_y * img[i:i+3, j:j+3]))  # horizon
            mag[i+1, j+1] = np.sqrt((v ** 2) + (h ** 2))
            
    for p in range(0, rows):
        for q in range(0, columns):
            if mag[p, q] < threshold:
                mag[p, q] = 0
    return mag

Comparison of original image and processed image

Obviously the effect of the last picture is the best.

Digression

  Two small programs are attached, which are used for picture display and processing. The comparison chart above is given by these two programs.

import numpy as np
import cv2

def img_show(img):  
    cv2.namedWindow("Image")
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
def sub_plot(img_1, img_2):
    l = np.size(img, 1)/4  # a quarter of the columns
    rows = np.size(img, 0) 
    interval = np.ones((rows, int(l)))
    interval = interval * 255
    
    img_o = np.concatenate((img_1, interval, img_2), axis=1)
    return img_o
img = cv2.imread('CNN/pic1.jpg', 0)  # read an image
mag = sobel(img, 70)
mag_v = sobel_v(img, 70)
mag_h = sobel_h(img, 70)
# img_show(mag)

v = sub_plot(img, mag_v)
h = sub_plot(img, mag_h)
a = sub_plot(img, mag)

v , h , a v,h,a v ,h,a is three comparison pictures.

(This is just a foreshadowing of CNN)

− − − − − − − − − − − − − − − − ---------------- - -
This article first appeared inzyairelu.cn
Welcome to my website to comment and discuss
personal mailbox [email protected]
- - - - - - - - - - - - - - - - -------- --------

Guess you like

Origin blog.csdn.net/weixin_42731543/article/details/103948583