Navigation

Related Articles

C# Tutorial: How To Apply Sobel Operator To An Image


Andraz Krzisnik
C# Tutorial: How To Apply Sobel Operator To...

What is sobel operator?

Well, basically it’s 2 kernels, with which we can process an image in a way, that only edges are visible. It is commonly used for grayscale images, from which an output is also a grayscale image. Two kernels are needed, for edge detection in horizontal and in vertical way.

How it works?

Using convolution, mathematical process, we apply our kernels to each pixel in our image. Each kernel is a matrix the size of 3×3, that holds predetermined values. When a kernel is over a pixel it calculates values using neighboring pixels that are also under this kernel. Below are displayed both kernels or matrices. A represents a matrix with values from the image we are applying the filter to.

This kernels are applied for every pixel in our image as it is shown in following image below.

Edge detection

When there are significant differences in intensity levels, calculated kernel will hold a value over 255 or under 0. When calculating a total value from both kernels, we have to set these totals either to max value, which is 255, or to min value, which is 0. These values are based on maximum and minimum value that each pixel channel can hold. In case of grayscale all channels hold the same value, except the alpha channel, which controls transparency.

Code for convolutional filter

First part of the function is devoted to getting the image data and saving it to an array.

private static Bitmap ConvolutionFilter(Bitmap sourceImage, 
    double[,] xkernel, 
    double[,] ykernel, double factor = 1, int bias = 0, bool grayscale = false)
{

    //Image dimensions stored in variables for convenience
    int width = sourceImage.Width;
    int height = sourceImage.Height;

    //Lock source image bits into system memory
    BitmapData srcData = sourceImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

    //Get the total number of bytes in your image - 32 bytes per pixel x image width x image height -> for 32bpp images
    int bytes = srcData.Stride * srcData.Height;

    //Create byte arrays to hold pixel information of your image
    byte[] pixelBuffer = new byte[bytes];
    byte[] resultBuffer = new byte[bytes];

    //Get the address of the first pixel data
    IntPtr srcScan0 = srcData.Scan0;

    //Copy image data to one of the byte arrays
    Marshal.Copy(srcScan0, pixelBuffer, 0, bytes);

    //Unlock bits from system memory -> we have all our needed info in the array
    sourceImage.UnlockBits(srcData);

Grayscale conversion code

Since Sobel operator is most often used for grayscale images, here is a code for conversion to grayscale, which by boolean parameter you can choose to convert or not.

//Convert your image to grayscale if necessary
if (grayscale == true)
{
    float rgb = 0;
    for (int i = 0; i < pixelBuffer.Length; i += 4)
    {
        rgb = pixelBuffer[i] * .21f;
        rgb += pixelBuffer[i + 1] * .71f;
        rgb += pixelBuffer[i + 2] * .071f;
        pixelBuffer[i] = (byte)rgb;
        pixelBuffer[i + 1] = pixelBuffer[i];
        pixelBuffer[i + 2] = pixelBuffer[i];
        pixelBuffer[i + 3] = 255;
    }
}

Code for setting variables used in convolution process

//Create variable for pixel data for each kernel
double xr = 0.0;
double xg = 0.0;
double xb = 0.0;
double yr = 0.0;
double yg = 0.0;
double yb = 0.0;
double rt = 0.0;
double gt = 0.0;
double bt = 0.0;

//This is how much your center pixel is offset from the border of your kernel
//Sobel is 3x3, so center is 1 pixel from the kernel border
int filterOffset = 1;
int calcOffset = 0;
int byteOffset = 0;

//Start with the pixel that is offset 1 from top and 1 from the left side
//this is so entire kernel is on your image
for (int OffsetY = filterOffset; OffsetY < height - filterOffset; OffsetY++)
{
    for (int OffsetX = filterOffset; OffsetX < width - filterOffset; OffsetX++)
    {
        //reset rgb values to 0
        xr = xg = xb = yr = yg = yb = 0;
        rt = gt = bt = 0.0;

        //position of the kernel center pixel
        byteOffset = OffsetY * srcData.Stride + OffsetX * 4;

Applying kernel convolution to current pixel

        //kernel calculations
        for (int filterY = -filterOffset; filterY <= filterOffset; filterY++)
        {
            for (int filterX = -filterOffset; filterX <= filterOffset; filterX++)
            {
                calcOffset = byteOffset + filterX * 4 + filterY * srcData.Stride;
                xb += (double)(pixelBuffer[calcOffset]) * xkernel[filterY + filterOffset, filterX + filterOffset];
                xg += (double)(pixelBuffer[calcOffset + 1]) * xkernel[filterY + filterOffset, filterX + filterOffset];
                xr += (double)(pixelBuffer[calcOffset + 2]) * xkernel[filterY + filterOffset, filterX + filterOffset];
                yb += (double)(pixelBuffer[calcOffset]) * ykernel[filterY + filterOffset, filterX + filterOffset];
                yg += (double)(pixelBuffer[calcOffset + 1]) * ykernel[filterY + filterOffset, filterX + filterOffset];
                yr += (double)(pixelBuffer[calcOffset + 2]) * ykernel[filterY + filterOffset, filterX + filterOffset]; 
            }
        }

        //total rgb values for this pixel
        bt = Math.Sqrt((xb * xb) + (yb * yb));
        gt = Math.Sqrt((xg * xg) + (yg * yg));
        rt = Math.Sqrt((xr * xr) + (yr * yr));

        //set limits, bytes can hold values from 0 up to 255;
        if (bt > 255) bt = 255;
        else if (bt < 0) bt = 0;
        if (gt > 255) gt = 255;
        else if (gt < 0) gt = 0;
        if (rt > 255) rt = 255;
        else if (rt < 0) rt = 0;

        //set new data in the other byte array for your image data
        resultBuffer[byteOffset] = (byte)(bt);
        resultBuffer[byteOffset + 1] = (byte)(gt);
        resultBuffer[byteOffset + 2] = (byte)(rt);
        resultBuffer[byteOffset + 3] = 255;
    }
}

Processed image output code

    //Create new bitmap which will hold the processed data
    Bitmap resultImage = new Bitmap(width, height);

    //Lock bits into system memory
    BitmapData resultData = resultImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

    //Copy from byte array that holds processed data to bitmap
    Marshal.Copy(resultBuffer, 0, resultData.Scan0, resultBuffer.Length);

    //Unlock bits from system memory
    resultImage.UnlockBits(resultData);

    //Return processed image
    return resultImage;
}

Code for Sobel kernels

//Sobel operator kernel for horizontal pixel changes
private static double[,] xSobel
{
    get
    {
        return new double[,]
        {
            { -1, 0, 1 },
            { -2, 0, 2 },
            { -1, 0, 1 }
        };
    }
}

//Sobel operator kernel for vertical pixel changes
private static double[,] ySobel
{
    get
    {
        return new double[,]
        {
            {  1,  2,  1 },
            {  0,  0,  0 },
            { -1, -2, -1 }
        };
    }
}

All this code is available here (Project was created with Visual Studio 2015)

Download Project

Show Comments (47)

Comments

  • KristoferWil

    I see your page needs some unique content.

    Writing manually is time consuming, but there is solution for this.
    Just search for; Masquro’s strategies

    • Article Author
  • Christiane

    Hurrah, that’s what I was exploring for, what a stuff! existing here at this blog,
    thanks admin of this web page.

    • Article Author
  • Flossie

    Howdy would you mind stating which blog platform you’re working with?
    I’m planning to start my own blog in the near future but
    I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs
    and I’m looking for something unique. P.S Sorry for being off-topic but I had to ask!

    • Article Author
  • seo reseller services

    Spot on with this write-up, I actually feel this web
    site needs far more attention. I’ll probably be back again to read through more, thanks for the information!

    • Article Author
  • wordpress website

    Why visitors still use to reaԁ news papers when in this technoⅼogical globe everything is accessible
    on net?

    • Article Author
  • Great post. Thank you for your time in helping me understand about this.

    • Article Author
  • barbie games 1

    Good day! Do you use Twitter? I’d like to follow you if that would be
    ok. I’m definitely enjoying your blog and look forward to new updates.

    • Article Author
  • https://andradetalis.wordpress.com

    hey there and thank you for your info – I’ve
    certainly picked up something new from right here.
    I did however expertise several technical issues using this website,
    since I experienced to reload the web site a lot
    of times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that
    I am complaining, but sluggish loading instances times will very frequently affect
    your placement in google and could damage your high quality score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my e-mail and can look out for much more of your respective intriguing content.
    Ensure that you update this again very soon.

    • Article Author
  • jayco entertainments

    Amazing! Its actually remarkable post, I have got much clear idea about from this paragraph.

    • Article Author
  • corburterilio

    Hey There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly comeback.

    • Article Author
  • vacation rentals

    At this time I am ready to do my breakfast, later than having my
    breakfast coming yet again to read more news.

    • Article Author
  • nintendo nes entertainment system

    Great information. Lucky me I found your site by chance (stumbleupon).
    I’ve bookmarked it for later!

    • Article Author
  • shareyt.com

    Greetings! Quick question that’s completely off topic. Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my iphone 4. I’m trying to find a template or plugin that might
    be able to fix this problem. If you have any recommendations, please share.
    With thanks!

    • Article Author
  • best buy tv entertainment centers

    Thank you for every other informative blog. The place else may just I am getting that type of information written in such a perfect
    manner? I have a venture that I’m just now operating on,
    and I’ve been at the look out for such information.

    • Article Author
  • BlancheBee

    Hi blogger it was hard to find this post in google.

    You need authority backlinks to rank higher in the top 10.

    I know how to rank your blog, search on youtube: SEO optimization bulletproof strategy

    • Article Author
  • rhymesayers entertainment

    Sweet blog! I found it while searching on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Appreciate it

    • Article Author
  • cell block entertainment

    Very descriptive article, I enjoyed that bit.
    Will there be a part 2?

    • Article Author
  • reflexive entertainment code lemonade tycoon 2 ny

    You actually make it seem so easy with your presentation but I
    find this topic to be actually something that I think I would never understand.
    It seems too complex and extremely broad for me. I am looking forward for your
    next post, I’ll try to get the hang of it!

    • Article Author
  • entertaining 6 month old

    Truly no matter if someone doesn’t understand afterward
    its up to other visitors that they will assist, so here it occurs.

    • Article Author
  • LouisGoossen

    I see your page needs some fresh content. Writing manually
    is time consuming, but there is solution for this hard task.

    Just search for: Miftolo’s tools rewriter

    • Article Author
  • 97Mariana

    I must say you have very interesting content here.

    Your blog can go viral. You need initial traffic only. How to get it?
    Search for: Miftolo’s tools go viral

    • Article Author
  • gladiator games

    I delight in, cause I discovered just what I was having a look for.
    You’ve ended my four day long hunt! God Bless you man. Have a great day.

    Bye

    • Article Author
  • entertainment spotlight

    Fastidious respond in return of this issue with solid arguments and describing all on the topic of that.

    • Article Author
  • flc entertainment center california

    Hi! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

    • Article Author
  • live entertainment center c8lumbus

    Link exchange is nothing else however it is simply placing the
    other person’s blog link on your page at appropriate place and
    other person will also do same in support of you.

    • Article Author
  • upskirt

    Magnificent goods from you, man. I’ve understand your stuff previous to and you are just extremely wonderful.
    I actually like what you’ve acquired here, really like what you’re saying and the way in which
    you say it. You make it entertaining and you still care for
    to keep it wise. I cant wait to read far more from you.

    This is actually a tremendous site.

    • Article Author
  • dit nhau

    Spot on with this write-up, I really believe that this amazing
    site needs far more attention. I’ll probably be returning to
    read through more, thanks for the info!

    • Article Author
  • media & entertainment services alliance

    Write more, thats all I have to say. Literally, it seems as though you
    relied on the video to make your point. You clearly know what youre talking about, why throw away your
    intelligence on just posting videos to your weblog when you could be
    giving us something informative to read?

    • Article Author
  • entertainment orange county

    Thankfulness to my father who told me on the topic of this blog, this webpage is in fact remarkable.

    • Article Author
  • pechanga casino entertainment

    Definitely believe that which you said. Your favorite justification seemed to
    be on the net the simplest thing to be aware of. I say to you, I definitely
    get irked while people think about worries that they plainly do not know about.
    You managed to hit the nail upon the top as well as defined out the whole thing
    without having side effect , people can take a signal.
    Will probably be back to get more. Thanks

    • Article Author
  • entertainment center tv stand

    You are so interesting! I don’t think I’ve read through anything like that before.
    So wonderful to discover somebody with a few unique thoughts on this topic.

    Seriously.. thanks for starting this up. This web
    site is something that is required on the internet, someone with a little originality!

    • Article Author
  • shareyt.com

    This page definitely has all of the information I needed about this
    subject and didn’t know who to ask.

    • Article Author
  • daytona beach entertainment calendar

    Hello, I do believe your website could be having internet browser compatibility issues.

    Whenever I look at your blog in Safari, it looks fine but
    when opening in I.E., it has some overlapping issues.

    I merely wanted to provide you with a quick heads up!
    Apart from that, great blog!

    • Article Author
  • toys to entertain cats

    Pretty! This has been a really wonderful post. Thank you for supplying this info.

    • Article Author
  • las vegas corporate event entertainment

    Hello There. I found your blog using msn. This is a
    really well written article. I will make sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I’ll definitely return.

    • Article Author
  • http://shareyt.com/?r=210566

    I have been surfing online more than 4 hours today, yet I never found any interesting
    article like yours. It’s pretty worth enough for me.
    In my view, if all web owners and bloggers made good
    content as you did, the net will be a lot more useful than ever before.

    • Article Author
  • Javhd movie

    Thanks for sharing your thoughts on Javhd movie. Regards

    • Article Author
  • kids entertainment for parties

    That is very attention-grabbing, You’re a very professional blogger.
    I’ve joined your rss feed and sit up for
    in quest of extra of your magnificent post. Additionally, I’ve shared your website
    in my social networks

    • Article Author
  • fark com entertainment

    Very good blog you have here but I was wanting to know
    if you knew of any user discussion forums that cover the same topics
    discussed here? I’d really like to be a part of group where I can get feed-back from other experienced individuals that share the same interest.

    If you have any suggestions, please let me know. Appreciate it!

    • Article Author
  • kenwood car entertainment

    Appreciating the time and effort you put into
    your blog and in depth information you present. It’s good to
    come across a blog every once in a while that isn’t the same old rehashed material.
    Great read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

    • Article Author
  • regal cinema entertainment

    Thanks designed for sharing such a fastidious thinking, article is pleasant,
    thats why i have read it entirely

    • Article Author
  • Nfs No Limits Apk Mod Offline

    What’s up, I desire to subscribe for this weblog to obtain latest updates, thus
    where can i do it please assist.

    • Article Author
  • borvestinkral

    Would love to forever get updated outstanding web blog! .

    • Article Author
  • fun places to go in ct

    Hello, i think that i saw you visited my blog thus i came to “return the favor”.I’m trying to find things to
    enhance my site!I suppose its ok to use some of your
    ideas!!

    • Article Author
  • john locke fun facts

    Valuable info. Lucky me I found your web site
    accidentally, and I am shocked why this coincidence didn’t came about
    earlier! I bookmarked it.

    • Article Author
  • mezo

    Hurrah! Ϝinally I got a web site from where I
    knoᴡ hoԝ to in fact take usefսl factѕ concerning mʏ study andd
    knowledge.

    • Article Author
  • Klara Hesselink

    What’s up, I read your blog like every week. Your humoristic style is awesome, keep doing what you’re doing!

    • Article Author

Related Articles

Order-Statistic Filters

How To Use Median Filter On Images – C# Guide

Median filter is one of the order-statistic filters for processing image data in spatial domain. This guide shows how to apply it with C#.

Posted on by Andraz Krzisnik
Frequency Domain Filtering

How To Use Bandreject Filters – C# Guide

We use bandreject filters to attenuate a ring of frequencies around the center of a 2 dimensional frequency map. Now what does all that mean? We’re going to focus on...

Posted on by Andraz Krzisnik