Otsu算法:
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 图像_Oust算法
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap bt;
int iw, ih;
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;
}
iw = bt.Width;
ih = bt.Height;
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(pictureBox1.Image);
int wh = iw * ih;
int[,] inIm = new int[iw, ih];
int i, j, t;
int L = 256;
double[] p = new double[L];
//转为灰度图像in_image[,]
for (j = 0; j < ih; j++)
for (i = 0; i < iw; i++)
inIm[i, j] =( bm.GetPixel(i, j).R + bm.GetPixel(i, j).G + bm.GetPixel(i, j).B)/3;//采用平均值法
for (i = 0; i < L; i++)//初始化
p[i] = 0;
//统计各灰度级出现的次数
for (j = 0; j < ih; j++)
for (i = 0; i < iw; i++)
p[inIm[i, j]]++;
//计算各灰度级出现的概率
for (int m = 0; m < L; m++)
p[m] = p[m] / wh;
double[] sigma = new double[L];
for (t = 0; t < L; t++)
{
double w0 = 0;
for (int m = 0; m < t + 1; m++)
w0 += p[m];
double w1 = 1 - w0;
double u0 = 0;
for (int m = 0; m < t + 1; m++)
u0 += m * p[m] / w0;
double u1 = 0;
for (int m = t; m < L; m++)
u1 += m * p[m] / w1;
sigma[t] = w0 * w1 * (u0 - u1) * (u0 - u1);
}
double max = 0.0;
int T = 0;
for (i = 0; i < L; i++)
{
if (max < sigma[i])
{
max = sigma[i];
T = i;
}
}
pictureBox2.Refresh();
pictureBox2.Image = threshSeg(inIm, iw, ih, T); ;
}
Bitmap threshSeg(int[,] in_image, int w, int h, int t)
{
Bitmap bm = new Bitmap(w, h);
Color c;
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
if (in_image[i, j] > t)
c = Color.FromArgb(255, 255, 255);//设置RGB值
else
c = Color.FromArgb(0, 0, 0);
bm.SetPixel(i, j, c);
}
}
return bm;
}
}
}