sobel filter Algorithm

The Sobel filter algorithm, also known as the Sobel-Feldman operator, is a widely used image processing technique that detects edges in an image by computing the gradient magnitude and direction. It is a discrete differentiation operator that employs a pair of 3x3 convolution kernels to approximate the derivative of an image with respect to the x and y-axis. The algorithm was introduced by Irwin Sobel and Gary Feldman to provide a means for detecting the presence of edges in an image, which is critical for many computer vision and image processing applications, including object recognition, segmentation, and feature extraction. The Sobel filter algorithm works by convolving the input image with the two kernels, one for the horizontal (Gx) and one for the vertical (Gy) gradient components. The resulting gradient images are then combined to obtain the gradient magnitude and direction for each pixel in the image. The gradient magnitude represents the strength of the edge at each pixel, while the direction indicates the orientation of the edge. The Sobel filter is particularly effective at detecting edges in images with varying illumination, noise, and texture, as it smooths the image while computing the gradient, providing a degree of noise reduction. The simplicity and efficiency of the Sobel filter algorithm make it a popular choice for edge detection tasks in various computer vision and image processing applications.
# @Author  : lightXu
# @File    : sobel_filter.py
# @Time    : 2019/7/8 0008 下午 16:26
import numpy as np
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from digital_image_processing.filters.convolve import img_convolve


def sobel_filter(image):
    kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

    dst_x = np.abs(img_convolve(image, kernel_x))
    dst_y = np.abs(img_convolve(image, kernel_y))
    # modify the pix within [0, 255]
    dst_x = dst_x * 255 / np.max(dst_x)
    dst_y = dst_y * 255 / np.max(dst_y)

    dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y)))
    dst_xy = dst_xy * 255 / np.max(dst_xy)
    dst = dst_xy.astype(np.uint8)

    theta = np.arctan2(dst_y, dst_x)
    return dst, theta


if __name__ == "__main__":
    # read original image
    img = imread("../image_data/lena.jpg")
    # turn image in gray scale value
    gray = cvtColor(img, COLOR_BGR2GRAY)

    sobel_grad, sobel_theta = sobel_filter(gray)

    # show result images
    imshow("sobel filter", sobel_grad)
    imshow("sobel theta", sobel_theta)
    waitKey(0)

LANGUAGE:

DARK MODE: