【转】c#数字图像处理(二)彩色图像灰度化,灰度图像二值化

ゝ一世哀愁。 2023-01-23 05:57 464阅读 0赞

转自:https://www.cnblogs.com/dearzhoubi/p/8571652.html

为加快处理速度,在图像处理算法中,往往需要把彩色图像转换为灰度图像,在灰度图像上得到验证的算法,很容易移
植到彩色图像上。
24位彩色图像每个像素用3个字节表示,每个字节对应着R、G、B分量的亮度(红、绿、蓝)。当R、G、B分量值不同时,表现为彩色图像;当R、G、B分量值相同时,表现为灰度图像,该值就是我们所求的一般来说,转换公式有3种。第一种转换公式为:

Gray(i,j)=[R(i,j)+G(i,j)+B(i,j)]÷3            (2.1)

其中,Gray(i,j)为转换后的灰度图像在(i,j)点处的灰度值。该方法虽然简单,但人眼对颜色的感应是不同的,因此有了第二种转换公式:

Gray(i,j)=0299R(i,j)+0.587×G(i,j)+0.114×B(i,j)      (2.2)

观察上式,发现绿色所占的比重最大,所以转换时可以直接使用G值作为转换后的灰度

Gray(i,j)=G(i,j)                    (2.3)

在这里,我们应用最常用的公式(2.2),并且变换后的灰度图像仍然用24位图像表示。

1.提取像素法

这种方法简单易懂,但相当耗时,完全不可取.
该方法使用的是GD+中的 Bitmap Getpixel和 BitmapSetpixel.方法。为了将位图的颜色设置为灰度或其他颜色,就需要使用 Gepiⅸxel来读取当前像素的颜色,再计算灰度值,最后使用 Setpixel来应用新的颜色。双击“提取像素法” Button控件,为该控件添加 Click事件,

代码如下:

复制代码

  1.      /// <summary>
  2. /// 提取像素法
  3. /// </summary>
  4. private void pixel_Click(object sender, EventArgs e)
  5. {if (curBitmpap != null)
  6. {
  7. Color curColor;
  8. int ret;
  9. //二维图像数组循环
  10. for(int i = 0; i < curBitmpap.Width; i++)
  11. {
  12. for(int j = 0; j < curBitmpap.Height; j++)
  13. {
  14. //获取该像素点的RGB颜色值
  15. curColor = curBitmpap.GetPixel(i, j);
  16. //利用公式计算灰度值
  17. ret = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114);
  18. //设置该像素点的灰度值,R=G=B=ret
  19. curBitmpap.SetPixel(i, j, Color.FromArgb(ret, ret, ret));
  20. }
  21. }//对窗体进行重新绘制,这将强制执行Paint事件处理程序
  22. Invalidate();
  23. }
  24. }

复制代码

2.内存法
该方法就是把图像数据直接复制到内存中,这样就使程序的运行速度大大提高。双击“内存法”按钮控件,为该控件添加Cick事件,代码如下:

复制代码

  1.      /// <summary>
  2. /// 内存法(适用于任意大小的24位彩色图像)
  3. /// </summary>
  4. private void memory_Click(object sender, EventArgs e)
  5. {if (curBitmpap != null)
  6. {
  7. //位图矩形
  8. Rectangle rect = new Rectangle(0, 0, curBitmpap.Width, curBitmpap.Height);
  9. //以可读写的方式锁定全部位图像素
  10. System.Drawing.Imaging.BitmapData bmpData = curBitmpap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmpap.PixelFormat);
  11. //得到首地址
  12. IntPtr ptr = bmpData.Scan0;
  13. //定义被锁定的数组大小,由位图数据与未用空间组成的
  14. int bytes = bmpData.Stride * bmpData.Height;
  15. //定义位图数组
  16. byte[] rgbValues = new byte[bytes];
  17. //复制被锁定的位图像素值到该数组内
  18. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
  19. //灰度化
  20. double colorTemp = 0;
  21. for (int i = 0; i < bmpData.Height; i++)
  22. {
  23. //只处理每行中是图像像素的数据,舍弃未用空间
  24. for (int j = 0; j < bmpData.Width * 3; j += 3)
  25. {
  26. //利用公式计算灰度值
  27. colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.587 + rgbValues[i * bmpData.Stride + j] * 0.114;
  28. //R=G=B
  29. rgbValues[i * bmpData.Stride + j] = rgbValues[i * bmpData.Stride + j + 1] = rgbValues[i * bmpData.Stride + j + 2] = (byte)colorTemp;
  30. }
  31. }
  32. //把数组复制回位图
  33. System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
  34. //解锁位图像素
  35. curBitmpap.UnlockBits(bmpData);//对窗体进行重新绘制,这将强制执行Paint事件处理程序
  36. Invalidate();
  37. }
  38. }

复制代码

3.指针法
该方法与内存法相似,开始都是通过 Lockbits方法来获取位图的首地址。但该方法更简洁,直接应用指针对位图进行操作。

为了保持类型安全,在默认情况下,C#是不支持指针运算的,因为使用指针会带来相关的风险。所以C#只允许在特别标记的代码块中使用指针。通过使用 unsafe关键字,可以定义可使用指针的不安全上下文。

双击“指针法”按钮控件,为该控件添加 Click事件,代码如下:

复制代码

  1.      /// <summary>
  2. /// 指针法
  3. /// </summary>
  4. private void pointer_Click(object sender, EventArgs e)
  5. {if (curBitmpap != null)
  6. {
  7. //位图矩形
  8. Rectangle rect = new Rectangle(0, 0, curBitmpap.Width, curBitmpap.Height);
  9. //以可读写的方式锁定全部位图像素
  10. System.Drawing.Imaging.BitmapData bmpData = curBitmpap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmpap.PixelFormat);
  11. byte temp = 0;
  12. //启用不安全模式
  13. unsafe
  14. {
  15. //得到首地址
  16. byte* ptr = (byte*)(bmpData.Scan0);
  17. //二维图像循环
  18. for (int i = 0; i < bmpData.Height; i++)
  19. {
  20. for (int j = 0; j < bmpData.Width; j++)
  21. {
  22. //利用公式计算灰度值
  23. temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
  24. //R=G=B
  25. ptr[0] = ptr[1] = ptr[2] = temp;
  26. //指向下一个像素
  27. ptr += 3;
  28. }
  29. //指向下一行数组的首个字节
  30. ptr += bmpData.Stride - bmpData.Width * 3;
  31. }
  32. }
  33. //解锁位图像素
  34. curBitmpap.UnlockBits(bmpData);//对窗体进行重新绘制,这将强制执行Paint事件处理程序
  35. Invalidate();
  36. }
  37. }

复制代码

由于启动了不安全模式,为了能够顺利地编译该段代码,必须设置相关选项。在主菜单中选择“项目|gray属性”,在打开的属性页中选择“生成”属性页,最后选中“允许不安全代码”复选框。

三种方法的比较

从3段代码的长度和难易程度来看,提取像素法又短又简单。它直接应用GD+中的Bitmap. Getpixel方法和 Bitmap. Setpixel方法,大大减少了代码的长度,降低了使用者的难度,并且可读性好。但衡量程序好坏的标准不是仅仅看它的长度和难易度,而是要看它的效率,尤其是像图像处理这种往往需要处理二维数据的大信息量的应用领域,就更需要考虑效率了为了比较这3种方法的效率,我们对其进行计时。首先在主窗体内添加一个 Label控件和 Textbox控件。

添加一个类:HiPerfTimer

复制代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.InteropServices;
  7. using System.ComponentModel;
  8. using System.Threading;
  9. namespace gray
  10. {
  11. internal class HiPerfTimer
  12. {
  13. //引用win32API中的QueryPerformanceCounter()方法
  14. //该方法用来查询任意时刻高精度计数器的实际值
  15. [DllImport("Kernel32.dll")] //using System.Runtime.InteropServices;
  16. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  17. //引用win32API中的QueryPerformanceCounter()方法
  18. //该方法用来查询任意时刻高精度计数器的实际值
  19. [DllImport("Kernel32.dll")]
  20. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  21. private long startTime, stopTime;
  22. private long freq;
  23. public HiPerfTimer()
  24. {
  25. startTime = 0;
  26. stopTime = 0;
  27. if(QueryPerformanceFrequency(out freq) == false)
  28. {
  29. //不支持高性能计时器
  30. throw new Win32Exception(); //using System.ComponentModel;
  31. }
  32. }
  33. //开始计时
  34. public void Start()
  35. {
  36. //让等待线程工作
  37. Thread.Sleep(0); //using System.Threading;
  38. QueryPerformanceCounter(out startTime);
  39. }
  40. //结束计时
  41. public void Stop()
  42. {
  43. QueryPerformanceCounter(out stopTime);
  44. }
  45. //返回计时结果(ms)
  46. public double Duration
  47. {
  48. get
  49. {
  50. return (double)(stopTime - startTime) * 1000 / (double)freq;
  51. }
  52. }
  53. }
  54. }

复制代码

在Form1类内定义HiPerfTimer类并在构造函数内为其实例化

  1. private HiPerfTimer myTimer;
  2. public Form1()
  3. {
  4. InitializeComponent();
  5. myTimer = new gray.HiPerfTimer();
  6. }

分别在“提取像素法”、“内存法”和“指针法” Button控件的 Click事件程序代码内的

if判断语句之间的最开始一行添加以下代码:

  1. //启动计时器
  2. myTimer.Start();

在上述3个单击事件内的 Invalidate0语句之前添加以下代码:

  1. //关闭计时器
  2. myTimer.Stop();
  3. //在TextBox内显示计时时间
  4. timeBox.Text = myTimer.Duration.ToString("####.##") + "毫秒";

最后,编译并运行该段程序。可以明显看出,内存法和指针法比提取像素法要快得多。提取像素法应用GDI+中的方法,易于理解,方法简单,很适合于C#的初学者使用,但它的运行速度最慢,效率最低。内存法把图像复制到内存中,直接对内存中的数据进行处理,速度明显提高,程序难度也不大。指针法直接应用指针来对图像进行处理,所以速度最快。但在C#中是不建议使用指针的,因为使用指针,代码不仅难以编写和调试,而且无法通过CLR的内存类型安全检查,不能发挥C#的特长。只有对C#和指针有了充分的理解,才能用好该方法。究竟要使用哪种方法,还要看具体情况而定。但3种方法都能有效地对图像进行处理。

全文代码:

复制代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace gray
  11. {
  12. public partial class Form1 : Form
  13. {
  14. private HiPerfTimer myTimer;
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. myTimer = new gray.HiPerfTimer();
  19. }
  20. //文件名
  21. private string curFileName;
  22. //图像对象
  23. private System.Drawing.Bitmap curBitmpap;
  24. /// <summary>
  25. /// 打开图像文件
  26. /// </summary>
  27. private void open_Click(object sender, EventArgs e)
  28. {
  29. //创建OpenFileDialog
  30. OpenFileDialog opnDlg = new OpenFileDialog();
  31. //为图像选择一个筛选器
  32. opnDlg.Filter = "所有图像文件|*.bmp;*.pcx;*.png;*.jpg;*.gif;" +
  33. "*.tif;*.ico;*.dxf;*.cgm;*.cdr;*.wmf;*.eps;*.emf|" +
  34. "位图(*.bmp;*.jpg;*.png;...)|*.bmp;*.pcx;*.png;*.jpg;*.gif;*.tif;*.ico|" +
  35. "矢量图(*.wmf;*.eps;*.emf;...)|*.dxf;*.cgm;*.cdr;*.wmf;*.eps;*.emf";
  36. //设置对话框标题
  37. opnDlg.Title = "打开图像文件";
  38. //启用“帮助”按钮
  39. opnDlg.ShowHelp = true;
  40. //如果结果为“打开”,选定文件
  41. if(opnDlg.ShowDialog()==DialogResult.OK)
  42. {
  43. //读取当前选中的文件名
  44. curFileName = opnDlg.FileName;
  45. //使用Image.FromFile创建图像对象
  46. try
  47. {
  48. curBitmpap = (Bitmap)Image.FromFile(curFileName);
  49. }
  50. catch(Exception exp)
  51. {
  52. MessageBox.Show(exp.Message);
  53. }
  54. }
  55. //对窗体进行重新绘制,这将强制执行paint事件处理程序
  56. Invalidate();
  57. }
  58. private void Form1_Paint(object sender, PaintEventArgs e)
  59. {
  60. //获取Graphics对象
  61. Graphics g = e.Graphics;
  62. if (curBitmpap != null)
  63. {
  64. //使用DrawImage方法绘制图像
  65. //160,20:显示在主窗体内,图像左上角的坐标
  66. //curBitmpap.Width, curBitmpap.Height图像的宽度和高度
  67. g.DrawImage(curBitmpap, 160, 20, curBitmpap.Width, curBitmpap.Height);
  68. }
  69. }
  70. /// <summary>
  71. /// 保存图像文件
  72. /// </summary>
  73. private void save_Click(object sender, EventArgs e)
  74. {
  75. //如果没有创建图像,则退出
  76. if (curBitmpap == null)
  77. return;
  78. //调用SaveFileDialog
  79. SaveFileDialog saveDlg = new SaveFileDialog();
  80. //设置对话框标题
  81. saveDlg.Title = "保存为";
  82. //改写已存在文件时提示用户
  83. saveDlg.OverwritePrompt = true;
  84. //为图像选择一个筛选器
  85. saveDlg.Filter = "BMP文件(*.bmp)|*.bmp|" + "Gif文件(*.gif)|*.gif|" + "JPEG文件(*.jpg)|*.jpg|" + "PNG文件(*.png)|*.png";
  86. //启用“帮助”按钮
  87. saveDlg.ShowHelp = true;
  88. //如果选择了格式,则保存图像
  89. if (saveDlg.ShowDialog() == DialogResult.OK)
  90. {
  91. //获取用户选择的文件名
  92. string filename = saveDlg.FileName;
  93. string strFilExtn = filename.Remove(0, filename.Length - 3);
  94. //保存文件
  95. switch (strFilExtn)
  96. {
  97. //以指定格式保存
  98. case "bmp":
  99. curBitmpap.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);
  100. break;
  101. case "jpg":
  102. curBitmpap.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
  103. break;
  104. case "gif":
  105. curBitmpap.Save(filename, System.Drawing.Imaging.ImageFormat.Gif);
  106. break;
  107. case "tif":
  108. curBitmpap.Save(filename, System.Drawing.Imaging.ImageFormat.Tiff);
  109. break;
  110. case "png":
  111. curBitmpap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
  112. break;
  113. default:
  114. break;
  115. }
  116. }
  117. }
  118. //关闭窗体
  119. private void close_Click(object sender, EventArgs e)
  120. {
  121. this.Close();
  122. }
  123. /// <summary>
  124. /// 提取像素法
  125. /// </summary>
  126. private void pixel_Click(object sender, EventArgs e)
  127. {
  128. //启动计时器
  129. myTimer.Start();
  130. if (curBitmpap != null)
  131. {
  132. Color curColor;
  133. int ret;
  134. //二维图像数组循环
  135. for(int i = 0; i < curBitmpap.Width; i++)
  136. {
  137. for(int j = 0; j < curBitmpap.Height; j++)
  138. {
  139. //获取该像素点的RGB颜色值
  140. curColor = curBitmpap.GetPixel(i, j);
  141. //利用公式计算灰度值
  142. ret = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114);
  143. //设置该像素点的灰度值,R=G=B=ret
  144. curBitmpap.SetPixel(i, j, Color.FromArgb(ret, ret, ret));
  145. }
  146. }
  147. //关闭计时器
  148. myTimer.Stop();
  149. //在TextBox内显示计时时间
  150. timeBox.Text = myTimer.Duration.ToString("####.##") + "毫秒";
  151. //对窗体进行重新绘制,这将强制执行Paint事件处理程序
  152. Invalidate();
  153. }
  154. }
  155. /// <summary>
  156. /// 内存法(适用于任意大小的24位彩色图像)
  157. /// </summary>
  158. private void memory_Click(object sender, EventArgs e)
  159. {
  160. //启动计时器
  161. myTimer.Start();
  162. if (curBitmpap != null)
  163. {
  164. //位图矩形
  165. Rectangle rect = new Rectangle(0, 0, curBitmpap.Width, curBitmpap.Height);
  166. //以可读写的方式锁定全部位图像素
  167. System.Drawing.Imaging.BitmapData bmpData = curBitmpap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmpap.PixelFormat);
  168. //得到首地址
  169. IntPtr ptr = bmpData.Scan0;
  170. //定义被锁定的数组大小,由位图数据与未用空间组成的
  171. int bytes = bmpData.Stride * bmpData.Height;
  172. //定义位图数组
  173. byte[] rgbValues = new byte[bytes];
  174. //复制被锁定的位图像素值到该数组内
  175. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
  176. //灰度化
  177. double colorTemp = 0;
  178. for (int i = 0; i < bmpData.Height; i++)
  179. {
  180. //只处理每行中是图像像素的数据,舍弃未用空间
  181. for (int j = 0; j < bmpData.Width * 3; j += 3)
  182. {
  183. //利用公式计算灰度值
  184. colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.587 + rgbValues[i * bmpData.Stride + j] * 0.114;
  185. //R=G=B
  186. rgbValues[i * bmpData.Stride + j] = rgbValues[i * bmpData.Stride + j + 1] = rgbValues[i * bmpData.Stride + j + 2] = (byte)colorTemp;
  187. }
  188. }
  189. //把数组复制回位图
  190. System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
  191. //解锁位图像素
  192. curBitmpap.UnlockBits(bmpData);
  193. //关闭计时器
  194. myTimer.Stop();
  195. //在TextBox内显示计时时间
  196. timeBox.Text = myTimer.Duration.ToString("####.##") + "毫秒";
  197. //对窗体进行重新绘制,这将强制执行Paint事件处理程序
  198. Invalidate();
  199. }
  200. }
  201. /// <summary>
  202. /// 指针法
  203. /// </summary>
  204. private void pointer_Click(object sender, EventArgs e)
  205. {
  206. //启动计时器
  207. myTimer.Start();
  208. if (curBitmpap != null)
  209. {
  210. //位图矩形
  211. Rectangle rect = new Rectangle(0, 0, curBitmpap.Width, curBitmpap.Height);
  212. //以可读写的方式锁定全部位图像素
  213. System.Drawing.Imaging.BitmapData bmpData = curBitmpap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmpap.PixelFormat);
  214. byte temp = 0;
  215. //启用不安全模式
  216. unsafe
  217. {
  218. //得到首地址
  219. byte* ptr = (byte*)(bmpData.Scan0);
  220. //二维图像循环
  221. for (int i = 0; i < bmpData.Height; i++)
  222. {
  223. for (int j = 0; j < bmpData.Width; j++)
  224. {
  225. //利用公式计算灰度值
  226. temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
  227. //R=G=B
  228. ptr[0] = ptr[1] = ptr[2] = temp;
  229. //指向下一个像素
  230. ptr += 3;
  231. }
  232. //指向下一行数组的首个字节
  233. ptr += bmpData.Stride - bmpData.Width * 3;
  234. }
  235. }
  236. //解锁位图像素
  237. curBitmpap.UnlockBits(bmpData);
  238. //关闭计时器
  239. myTimer.Stop();
  240. //在TextBox内显示计时时间
  241. timeBox.Text = myTimer.Duration.ToString("####.##") + "毫秒";
  242. //对窗体进行重新绘制,这将强制执行Paint事件处理程序
  243. Invalidate();
  244. }
  245. }
  246. /// <summary>
  247. /// 内存法(仅适用于512*512的图像)
  248. /// </summary>
  249. //private void memory_Click(object sender, EventArgs e)
  250. //{
  251. // if (curBitmpap != null)
  252. // {
  253. // //位图矩形
  254. // Rectangle rect = new Rectangle(0, 0, curBitmpap.Width, curBitmpap.Height);
  255. // //以可读写的方式锁定全部位图像素
  256. // System.Drawing.Imaging.BitmapData bmpData = curBitmpap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmpap.PixelFormat);
  257. // //得到首地址
  258. // IntPtr ptr = bmpData.Scan0;
  259. // //24位bmp位图字节数
  260. // int bytes = curBitmpap.Width * curBitmpap.Height * 3;
  261. // //定义位图数组
  262. // byte[] rgbValues = new byte[bytes];
  263. // //复制被锁定的位图像素值到该数组内
  264. // System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
  265. // //灰度化
  266. // double colorTemp = 0;
  267. // for(int i = 0; i < rgbValues.Length; i += 3)
  268. // {
  269. // //利用公式计算灰度值
  270. // colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.114;
  271. // //R=G=B
  272. // rgbValues[i]=rgbValues[i+1]=rgbValues[i+2]=(byte)colorTemp;
  273. // }
  274. // //把数组复制回位图
  275. // System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
  276. // //解锁位图像素
  277. // curBitmpap.UnlockBits(bmpData);
  278. // //对窗体进行重新绘制,这将强制执行Paint事件处理程序
  279. // Invalidate();
  280. // }
  281. //}
  282. }
  283. }

复制代码

复制代码

  1. /// <summary>
  2. /// 图像灰度化
  3. /// </summary>
  4. /// <param name="bmp"></param>
  5. /// <returns></returns>
  6. public static Bitmap ToGray(Bitmap bmp)
  7. {
  8. for (int i = 0; i < bmp.Width; i++)
  9. {
  10. for (int j = 0; j < bmp.Height; j++)
  11. {
  12. //获取该点的像素的RGB的颜色
  13. Color color = bmp.GetPixel(i, j);
  14. //利用公式计算灰度值
  15. int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
  16. Color newColor = Color.FromArgb(gray, gray, gray);
  17. bmp.SetPixel(i, j, newColor);
  18. }
  19. }
  20. return bmp;
  21. }

复制代码

复制代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.InteropServices;
  7. using System.ComponentModel;
  8. using System.Threading;
  9. namespace gray
  10. {
  11. internal class HiPerfTimer
  12. {
  13. //引用win32API中的QueryPerformanceCounter()方法
  14. //该方法用来查询任意时刻高精度计数器的实际值
  15. [DllImport("Kernel32.dll")] //using System.Runtime.InteropServices;
  16. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  17. //引用win32API中的QueryPerformanceCounter()方法
  18. //该方法用来查询任意时刻高精度计数器的实际值
  19. [DllImport("Kernel32.dll")]
  20. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  21. private long startTime, stopTime;
  22. private long freq;
  23. public HiPerfTimer()
  24. {
  25. startTime = 0;
  26. stopTime = 0;
  27. if(QueryPerformanceFrequency(out freq) == false)
  28. {
  29. //不支持高性能计时器
  30. throw new Win32Exception(); //using System.ComponentModel;
  31. }
  32. }
  33. //开始计时
  34. public void Start()
  35. {
  36. //让等待线程工作
  37. Thread.Sleep(0); //using System.Threading;
  38. QueryPerformanceCounter(out startTime);
  39. }
  40. //结束计时
  41. public void Stop()
  42. {
  43. QueryPerformanceCounter(out stopTime);
  44. }
  45. //返回计时结果(ms)
  46. public double Duration
  47. {
  48. get
  49. {
  50. return (double)(stopTime - startTime) * 1000 / (double)freq;
  51. }
  52. }
  53. }
  54. }

复制代码

灰度图像二值化
在进行了灰度化处理之后,图像中的每个象素只有一个值,那就是象素的灰度值。它的大小决定了象素的亮暗程度。为了更加便利的开展下面的图像处理操作,还需要对已经得到的灰度图像做一个二值化处理。图像的二值化就是把图像中的象素根据一定的标准分化成两种颜色。在系统中是根据象素的灰度值处理成黑白两种颜色。和灰度化相似的,图像的二值化也有很多成熟的算法。它可以采用自适应阀值法,也可以采用给定阀值法。

复制代码

  1.      #region Otsu阈值法二值化模块
  2. /// <summary>
  3. /// Otsu阈值
  4. /// </summary>
  5. /// <param name="b">位图流</param>
  6. /// <returns></returns>
  7. public Bitmap OtsuThreshold(Bitmap b)
  8. {
  9. // 图像灰度化
  10. // b = Gray(b);
  11. int width = b.Width;
  12. int height = b.Height;
  13. byte threshold = 0;
  14. int[] hist = new int[256];
  15. int AllPixelNumber = 0, PixelNumberSmall = 0, PixelNumberBig = 0;
  16. double MaxValue, AllSum = 0, SumSmall = 0, SumBig, ProbabilitySmall, ProbabilityBig, Probability;
  17. BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
  18. unsafe
  19. {
  20. byte* p = (byte*)data.Scan0;
  21. int offset = data.Stride - width * 4;
  22. for (int j = 0; j < height; j++)
  23. {
  24. for (int i = 0; i < width; i++)
  25. {
  26. hist[p[0]]++;
  27. p += 4;
  28. }
  29. p += offset;
  30. }
  31. b.UnlockBits(data);
  32. }
  33. //计算灰度为I的像素出现的概率
  34. for (int i = 0; i < 256; i++)
  35. {
  36. AllSum += i * hist[i]; // 质量矩
  37. AllPixelNumber += hist[i]; // 质量
  38. }
  39. MaxValue = -1.0;
  40. for (int i = 0; i < 256; i++)
  41. {
  42. PixelNumberSmall += hist[i];
  43. PixelNumberBig = AllPixelNumber - PixelNumberSmall;
  44. if (PixelNumberBig == 0)
  45. {
  46. break;
  47. }
  48. SumSmall += i * hist[i];
  49. SumBig = AllSum - SumSmall;
  50. ProbabilitySmall = SumSmall / PixelNumberSmall;
  51. ProbabilityBig = SumBig / PixelNumberBig;
  52. Probability = PixelNumberSmall * ProbabilitySmall * ProbabilitySmall + PixelNumberBig * ProbabilityBig * ProbabilityBig;
  53. if (Probability > MaxValue)
  54. {
  55. MaxValue = Probability;
  56. threshold = (byte)i;
  57. }
  58. }
  59. return this.Threshoding(b, threshold);
  60. } // end of OtsuThreshold 2
  61. #endregion
  62. #region 固定阈值法二值化模块
  63. public Bitmap Threshoding(Bitmap b, byte threshold)
  64. {
  65. int width = b.Width;
  66. int height = b.Height;
  67. BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
  68. unsafe
  69. {
  70. byte* p = (byte*)data.Scan0;
  71. int offset = data.Stride - width * 4;
  72. byte R, G, B, gray;
  73. for (int y = 0; y < height; y++)
  74. {
  75. for (int x = 0; x < width; x++)
  76. {
  77. R = p[2];
  78. G = p[1];
  79. B = p[0];
  80. gray = (byte)((R * 19595 + G * 38469 + B * 7472) >> 16);
  81. if (gray >= threshold)
  82. {
  83. p[0] = p[1] = p[2] = 255;
  84. }
  85. else
  86. {
  87. p[0] = p[1] = p[2] = 0;
  88. }
  89. p += 4;
  90. }
  91. p += offset;
  92. }
  93. b.UnlockBits(data);
  94. return b;
  95. }
  96. }
  97. #endregion

复制代码

发表评论

表情:
评论列表 (有 0 条评论,464人围观)

还没有评论,来说两句吧...

相关阅读