最近用到的C#比较多,所以将以前自己写的一些图像算法写成个教程系列。。这里主要使用Bitmap进行图像算法编写,主要加深自己对算法的理解。实际用到工业中 大家还是基于opencv或者其他一些视觉库。
图像二值化的概念就不细说了,现在使用C#实现THRESH_BINARY二值化算法。原理就是大于设定得值就设置为最大值。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 图像_二值化
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap bt;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
bt = new Bitmap(ofd.FileName);
pictureBox1.Image = bt;
}
Color p1;
Bitmap bt1 = bt.Clone() as Bitmap;
for (int x1 = 0; x1 < bt.Width; x1++)
{
for (int x2 = 0; x2 < bt.Height; x2++)
{
p1 = bt.GetPixel(x1, x2);
int temp = (p1.R + p1.B + p1.G) / 3;
bt1.SetPixel(x1, x2, Color.FromArgb(temp, temp, temp));
}
}
Color p2;
for (int x1 = 0; x1 < bt1.Width; x1++)
{
for (int x2 = 0; x2 < bt1.Height; x2++)
{
p2 = bt1.GetPixel(x1, x2);
if (p2.G > 150)
{
bt1.SetPixel(x1, x2, Color.FromArgb(255, 255, 255));
}
else
{
bt1.SetPixel(x1, x2, Color.FromArgb(0, 0, 0));
}
}
}
pictureBox2.Image = bt1;
}
}
}