C# Tutorial: How To Apply Sobel Operator To An Image
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,...
Filter by Category
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.
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.
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.
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);
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; } }
//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;
//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; } }
//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; }
//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)
Comments
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
Hurrah, that’s what I was exploring for, what a stuff! existing here at this blog,
thanks admin of this web page.
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!
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!
Why visitors still use to reaԁ news papers when in this technoⅼogical globe everything is accessible
on net?
Great post. Thank you for your time in helping me understand about this.
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.
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.
Amazing! Its actually remarkable post, I have got much clear idea about from this paragraph.
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.
At this time I am ready to do my breakfast, later than having my
breakfast coming yet again to read more news.
Great information. Lucky me I found your site by chance (stumbleupon).
I’ve bookmarked it for later!
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!
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.
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
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
Very descriptive article, I enjoyed that bit.
Will there be a part 2?
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!
Truly no matter if someone doesn’t understand afterward
its up to other visitors that they will assist, so here it occurs.
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
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
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
Fastidious respond in return of this issue with solid arguments and describing all on the topic of that.
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?
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.
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.
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!
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?
Thankfulness to my father who told me on the topic of this blog, this webpage is in fact remarkable.
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
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!
This page definitely has all of the information I needed about this
subject and didn’t know who to ask.
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!
Pretty! This has been a really wonderful post. Thank you for supplying this info.
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.
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.
Thanks for sharing your thoughts on Javhd movie. Regards
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
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!
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.
Thanks designed for sharing such a fastidious thinking, article is pleasant,
thats why i have read it entirely
What’s up, I desire to subscribe for this weblog to obtain latest updates, thus
where can i do it please assist.
Would love to forever get updated outstanding web blog! .
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!!
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.
Hurrah! Ϝinally I got a web site from where I
knoᴡ hoԝ to in fact take usefսl factѕ concerning mʏ study andd
knowledge.
What’s up, I read your blog like every week. Your humoristic style is awesome, keep doing what you’re doing!