时间:2021-05-20
C#将图片2值化示例代码,原图及二值化后的图片如下:
原图:
二值化后的图像:
实现代码:
using System;using System.Drawing;namespace BMP2Grey{ class Program { static void ToGrey(Bitmap img1) { for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); //计算灰度值 int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B); Color newColor = Color.FromArgb(grey, grey, grey); img1.SetPixel(i, j, newColor); } } } static void Thresholding(Bitmap img1) { int[] histogram = new int[256]; int minGrayValue=255, maxGrayValue=0; //求取直方图 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); histogram[pixelColor.R]++; if (pixelColor.R > maxGrayValue) maxGrayValue = pixelColor.R; if (pixelColor.R < minGrayValue) minGrayValue = pixelColor.R; } } //迭代计算阀值 int threshold = -1; int newThreshold = (minGrayValue + maxGrayValue) / 2; for(int iterationTimes = 0; threshold != newThreshold && iterationTimes < 100; iterationTimes++) { threshold = newThreshold; int lP1 =0; int lP2 =0; int lS1 = 0; int lS2 = 0; //求两个区域的灰度的平均值 for (int i = minGrayValue;i < threshold;i++) { lP1 += histogram[i] * i; lS1 += histogram[i]; } int mean1GrayValue = (lP1 / lS1); for (int i = threshold+1;i < maxGrayValue;i++) { lP2 += histogram[i] * i; lS2 += histogram[i]; } int mean2GrayValue = (lP2 / lS2); newThreshold = (mean1GrayValue + mean2GrayValue) / 2; } //计算二值化 for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { Color pixelColor = img1.GetPixel(i, j); if (pixelColor.R > threshold) img1.SetPixel(i, j, Color.FromArgb(255, 255, 255)); else img1.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } } } static void Main(string[] args) { try { //打开位图文件 Bitmap img1 = new Bitmap("test.jpg", true); //灰度化 ToGrey(img1); //二值化 Thresholding(img1); //写回位图文件 img1.Save("output.jpg"); Console.WriteLine("Converted."); } catch (ArgumentException) { Console.WriteLine("Invalid usage!"); Console.WriteLine("Usage: bmp2grey source object"); } } }}声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了C#数字图像处理之图像二值化(彩色变黑白)的方法。分享给大家供大家参考。具体如下://定义图像二值化函数privatestaticBitmapPB
本文采用C#实例讲解了处理图片为浮雕效果的实现方法,这在PS中是一个常见的功能,也是C#中的一个简单的图像处理例子。程序先读取原图,然后依次访问每个像素的RGB
C#变量初始化是C#强调安全性的另一个例子。简单地说,C#编译器需要用某个初始值对变量进行初始化,之后才能在操作中引用该变量。大多数现代编译器把没有初始化标记为
简介:图像二值化就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的黑白效果的过程。普通图像二值化代码如下:importcv2ascvim
本文是利用C#实现连连看的小例子,以供学习分享使用。思路:初始化布局(横竖十行十列,共100个单元格,每一个格一个按钮,背景图为水果图片,随机生成)。初始化对应