Image Processing - Implementing Sobel Filter

sobel edge detection algorithm steps
sobel filter python
sobel filter matlab
sobel operator derivation
image segmentation sobel edge detection
sobel meaning
sobel edge detection c
prewitt edge detection

I've got a task to implement Sobel filter which is, as you know, an image processing filter for edge detection. But unfortunately, I've got no experience in image processing field, to the extent that I don't even know how images are represented in computer. Totally no knowledge in this field.

I've read some papers and PDFs but they focus on many topics which I feel that I may not need them for my task.

I'd be happy to know your suggestions or if there is any particular paper, PDF, tutorial or quick guide for this purpose.

Thank you


Thank you all :) The result of our work can be downloaded from here.

It's pretty easy, you just need to convolve your image with a Sobel filter. A Sobel filter has two kernels, x-direction kernel and y-direction kernel. The x-direction kernel detects horizontal edges, and y-direction kernels detects vertical edges.

x-direction kernel (the size is 3x3)

float kernelx[3][3] = {{-1, 0, 1}, 
                       {-2, 0, 2}, 
                       {-1, 0, 1}};

y-direction kernel

float kernely[3][3] = {{-1, -2, -1}, 
                        {0,  0,  0}, 
                        {1,  2,  1}};

To calculate the convolution at pixel (x,y), define a window of size equal to the kernel size (source code to calculate magnitude in x and magnitude in y are identical):

double magX = 0.0; // this is your magnitude

for(int a = 0; a < 3; a++)
    for(int b = 0; b < 3; b++)
        int xn = x + a - 1;
        int yn = y + b - 1;

        int index = xn + yn * width;
        magX += image[index] * kernelx[a][b];

Note that the input is a grayscale image and it can be represented as 1D array of double (This is just a trick, since a pixel value in coordinate (x,y) can be accessed with index = [x + y * width] )

To calculate magnitude in pixel (x,y) given magX and magY :

mag = sqrt( magX^2 + magY^2 )

An Implementation of Sobel Edge Detection, Sobel edge detection is one of the foundational building block of Computer Vision. Even when you start learning deep learning if you find the  Image Processing Edge Detection / Gradient / JavaScript / OpenGL / WebGL The Sobel filter (also called Sobel-Feldman operator) is an edge detection filter, that results in image emphasizing edges. Computer vision and image processing applications frequently use this filter to extract image gradients and contours.

The most simple explanation of the Sobel operator I've seen to this date is from Saush's blog, a tech enthusiast who once met Sobel himself:

The post describes in (not too many) details how to implement the filter, and shares Ruby source-code for demonstration purposes:

require 'chunky_png'

class ChunkyPNG::Image
  def at(x,y)

img = ChunkyPNG::Image.from_file('engine.png')

sobel_x = [[-1,0,1],

sobel_y = [[-1,-2,-1],

edge =, img.height, ChunkyPNG::Color::TRANSPARENT)

for x in 1..img.width-2
  for y in 1..img.height-2
    pixel_x = (sobel_x[0][0] *,y-1)) + (sobel_x[0][1] *,y-1)) + (sobel_x[0][2] *,y-1)) +
              (sobel_x[1][0] *,y))   + (sobel_x[1][1] *,y))   + (sobel_x[1][2] *,y)) +
              (sobel_x[2][0] *,y+1)) + (sobel_x[2][1] *,y+1)) + (sobel_x[2][2] *,y+1))

    pixel_y = (sobel_y[0][0] *,y-1)) + (sobel_y[0][1] *,y-1)) + (sobel_y[0][2] *,y-1)) +
              (sobel_y[1][0] *,y))   + (sobel_y[1][1] *,y))   + (sobel_y[1][2] *,y)) +
              (sobel_y[2][0] *,y+1)) + (sobel_y[2][1] *,y+1)) + (sobel_y[2][2] *,y+1))

    val = Math.sqrt((pixel_x * pixel_x) + (pixel_y * pixel_y)).ceil
    edge[x,y] = ChunkyPNG::Color.grayscale(val)


Sobel operator, Finding edges is a fundamental problem in image processing, as edges define object An image demonstrating edge detection with a Sobel filter. Figure 4.4 shows the effect of applying the Sobel filter to calculate the X and Y partial  Sobel filter The Sobel operator is an algorithm for edge detection, a technique to find the limits between regions in an image. The edge detection algorithm help us separate some specific parts of

Sobel Operator Wikipedia page is well descriptive about how to perform it. There other operators such as Roberts cross and Prewitt

Using convolution operation, you can switch the approach by changing the kernel matrix. Below, the implementation of Sobel and Convolution using Marvin Framework may help you.


public class Sobel extends MarvinAbstractImagePlugin{

    // Definitions
    double[][] matrixSobelX = new double[][]{
            {1,     0,  -1},
            {2,     0,  -2},
            {1,     0,  -1}
    double[][] matrixSobelY = new double[][]{
            {-1,    -2,     -1},
            {0,     0,      0},
            {1,     2,      1}

    private MarvinImagePlugin   convolution;

    public void load(){
        convolution = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.convolution.jar");

    public MarvinAttributesPanel getAttributesPanel(){
        return null;
    public void process
        MarvinImage imageIn, 
        MarvinImage imageOut,
        MarvinAttributes attrOut,
        MarvinImageMask mask, 
        boolean previewMode
        convolution.setAttribute("matrix", matrixSobelX);
        convolution.process(imageIn, imageOut, null, mask, previewMode);
        convolution.setAttribute("matrix", matrixSobelY);
        convolution.process(imageIn, imageOut, null, mask, previewMode);


public class Convolution extends MarvinAbstractImagePlugin{

    private MarvinAttributesPanel   attributesPanel;
    private MarvinAttributes        attributes;

    public void process
        MarvinImage imageIn, 
        MarvinImage imageOut,
        MarvinAttributes attributesOut,
        MarvinImageMask mask, 
        boolean previewMode
        double[][] matrix = (double[][])attributes.get("matrix");

        if(matrix != null && matrix.length > 0){
            for(int y=0; y<imageIn.getHeight(); y++){
                for(int x=0; x<imageIn.getWidth(); x++){
                    applyMatrix(x, y, matrix, imageIn, imageOut);

    private void applyMatrix
        int x,
        int y,
        double[][] matrix,
        MarvinImage imageIn,
        MarvinImage imageOut

        int nx,ny;
        double resultRed=0;
        double resultGreen=0;
        double resultBlue=0;

        int xC=matrix[0].length/2;
        int yC=matrix.length/2;

        for(int i=0; i<matrix.length; i++){
            for(int j=0; j<matrix[0].length; j++){
                if(matrix[i][j] != 0){      
                    nx = x + (j-xC);
                    ny = y + (i-yC);

                    if(nx >= 0 && nx < imageOut.getWidth() && ny >= 0 && ny < imageOut.getHeight()){

                        resultRed   +=  (matrix[i][j]*(imageIn.getIntComponent0(nx, ny)));
                        resultGreen +=  (matrix[i][j]*(imageIn.getIntComponent1(nx, ny)));
                        resultBlue  +=  (matrix[i][j]*(imageIn.getIntComponent2(nx, ny)));



        resultRed   = Math.abs(resultRed);
        resultGreen = Math.abs(resultGreen);
        resultBlue = Math.abs(resultBlue);

        // allow the combination of multiple appications
        resultRed   += imageOut.getIntComponent0(x,y);
        resultGreen += imageOut.getIntComponent1(x,y);
        resultBlue  += imageOut.getIntComponent2(x,y);

        resultRed   = Math.min(resultRed, 255);
        resultGreen = Math.min(resultGreen, 255);
        resultBlue  = Math.min(resultBlue, 255);

        resultRed   = Math.max(resultRed, 0);
        resultGreen = Math.max(resultGreen, 0);
        resultBlue  = Math.max(resultBlue, 0);

        imageOut.setIntColor(x, y, imageIn.getAlphaComponent(x, y), (int)resultRed, (int)resultGreen, (int)resultBlue);

    public void load(){
        attributes = getAttributes();
        attributes.set("matrix", null);

    public MarvinAttributesPanel getAttributesPanel(){
        if(attributesPanel == null){
            attributesPanel = new MarvinAttributesPanel();
            attributesPanel.addMatrixPanel("matrixPanel", "matrix", attributes, 3, 3);
        return attributesPanel;


How to implement Sobel edge detection using Python from scratch , The kernels can be applied separately to the input image, to produce separate measurements shows the results of applying the Sobel operator to R. Gonzalez and R. Woods Digital Image Processing, Addison Wesley, 1992, pp 414 - 428. Implement digital image processing method by using C++, including histogram equalization, edge detection, lowpass/highpass filter and thresholding. digital-image-processing sobel prewitt histogram-equalization lowpass-filter highpass-filter thresholding robert

Gx is estimating the gradient in the x-direction (columns) and Gy is estimating the gradient in the y-direction (rows). So Gy detects horizontal lines, and Gx detects vertical lines.

Sobel Filter, Sobel edge detection technique implementation for image steganography analysis. Smitha GL and Baburaj E. 1Department of Computer  By weighting these x and y derivatives, we can obtain different edge detection filters. Let’s see how. 1. Sobel Operator. This is obtained by multiplying the x, and y-derivative filters obtained above with some smoothing filter(1D) in the other direction. For example, a 3×3 Sobel-x and Sobel-y filter can be obtained as

Of course, you could use OpenCV for this:

import cv2
import numpy as np

img = cv2.imread(INPUT_IMAGE)
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY).astype(float)

edge_x = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
edge_y = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)    
edge = np.sqrt(edge_x**2 + edge_y**2)    # image can be normalized to 
                                         # fit into 0..255 color space
cv2.imwrite(OUTPUT_IMAGE, edge)

Input / Output:

Feature Detectors, Sobel Operator - The sobel operator is very similar to Prewitt operator. After applying vertical mask on the above sample image, following image will be  A common method on how to reduce the noise in the image is to use an averaging filter to smoothen the image, and then apply the Sobel Edge Detection Algorithm again and compare the differences. Below is an example of an average filter (covered in ECE 438 taught by Professor Boutin):

Sobel edge detection technique implementation for image , Sobel operator is utilized as a part of image processing and computer vision, especially within edge detection algorithms where it creates an image emphasizing  image processing kernels including a 2D Fast Fourier Transform (FFT) with high-pass filter for edge detection; local operators for Gaussian image smoothing; and a Sobel filter, Canny edge detection, and Harris corner detection operations. Conventional MPI parallelization is employed in the implementations,

Sobel Operator, Edges in images are areas with strong intensity contrasts; a jump in intensity from one pixel to the next. The process of edge detection significantly reduces the amount of data and filters out We will look at two examples of the gradient method, Sobel and The result of applying it to a pixel on an edge is a vector that points. The sobel operator is very similar to Prewitt operator. It is also a derivate mask and is used for edge detection. Like Prewitt operator sobel operator is also used to detect two kinds of edges in an image: The major difference is that in sobel operator the coefficients of masks are not fixed and they can be adjusted according to our

[PDF] Implementation of Sobel Edge Detection using MATLAB , FPGAs' implementations for edge detection cover implementations based in Sobel operator [685] [686][687][688][689], Canny algorithm [690][691][692], applications for real time processing [693][694

  • Voting to close as resource rec.
  • would it make any sense to combine the horizontal and vertical kernels by making one the real part and one the imaginary part, and then you can find the magnitude by getting the abs(the result)?
  • @azer89 I doubt whether simple multiplication of image and kernelx will work, since we require convolution, right?
  • Look at this blog: 2d convolution
  • Just idly, you've copied and pasted the code above wrong (or it was wrong in the blog post and is now fixed?). sobel_x[0][4] is obviously never going to work. It should be [0][1] [1][1] [2][1], etc.
  • Hi I am new to this I have created main class and got this error can you tell me how write main class for it ? Sobel a = new Sobel(); MarvinImage imgIn = MarvinImageIO.loadImage("unnamed2.jpg"); MarvinImage imgOut = MarvinImageIO.loadImage("test.jpg"); a.process(imgIn, imgOut); Exception in thread "main" java.lang.NullPointerException at Sobel.process(
  • This should be comment