1.获取图像
if (openFileDialog1.ShowDialog() == DialogResult.OK)Picfilename = openFileDialog1.FileName;pictureBox1.Image = Image.FromFile(Picfilename);bitmap =(Bitmap) pictureBox1.Image;
2.获取灰度图
Bitmap Abitmap = new Bitmap(bitmap.Width, bitmap.Height);for (int i = 0; i < bitmap.Width; i++){for (int j = 0; j < bitmap.Height; j++){Color c = bitmap.GetPixel(i, j);//灰度加权平均法公式int rgb = (int)(c.R * 0.299 + c.G * 0.587 + c.B * 0.114);Abitmap.SetPixel(i, j, Color.FromArgb(rgb, rgb, rgb));}}pictureBox3.Image = Abitmap.Clone() as Image;
3.直方图均衡化处理
if (bitmap != null){newbitmap = bitmap.Clone() as Bitmap; //clone一个副本int width = newbitmap.Width;int height = newbitmap.Height;int size = width*height;//总像数个数int[] gray = new int[256];//定义一个int数组,用来存放各像元值的个数double[] graydense = new double[256];//定义一个float数组,存放每个灰度像素个数占比for (int i = 0; i < width; ++i)for (int j = 0; j < height; ++j){Color pixel = newbitmap.GetPixel(i, j);//计算各像元值的个数gray[Convert.ToInt16(pixel.R)] += 1;//由于是灰度只读取R值}for (int i = 0; i < 256; i++){graydense[i] = (gray[i]*1.0)/size;//每个灰度像素个数占比}for (int i = 1; i < 256; i++){graydense[i] = graydense[i] + graydense[i - 1];//累计百分比}for (int i = 0; i < width; ++i)for (int j = 0; j < height; ++j){Color pixel = newbitmap.GetPixel(i, j);int oldpixel = Convert.ToInt16(pixel.R); //原始灰度int newpixel = 0;if (oldpixel == 0)newpixel = 0;//如果原始灰度值为0则变换后也为0elsenewpixel = Convert.ToInt16(graydense[Convert.ToInt16(pixel.R)]*255);//如果原始灰度不为0,则执行变换公式为 <新像元灰度 = 原始灰度 * 累计百分比>pixel = Color.FromArgb(newpixel, newpixel, newpixel);newbitmap.SetPixel(i, j, pixel); //读入newbitmap}pictureBox2.Image = newbitmap.Clone() as Image; //显示至pictureBox2}
效果图:
源码:
链接:https://pan.baidu.com/s/1eTOowWdRQuQqhdLkGEx85w
提取码:ben8