4. 灰階影像直方圖
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Q4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 結束離開ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void 開啟彩色影像檔ToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
pictureBox1.Image = Bitmap.FromFile(openFileDialog1.FileName);
}
private void 彩色影像轉灰階影像ToolStripMenuItem_Click(object sender, EventArgs e)
{
var bm = new Bitmap(pictureBox1.Image);
pictureBox2.Image = bm;
for (int x = 0; x < bm.Width; x++)
for (int y = 0; y < bm.Height; y++)
{
var p = bm.GetPixel(x, y);
var d = (int)(p.R * 0.3 + p.G * 0.59 + p.B * 0.11);
bm.SetPixel(x, y, Color.FromArgb(d, d, d));
}
pictureBox2.Image = bm;
}
Dictionary<int, int> k;
private void 劃出ToolStripMenuItem_Click(object sender, EventArgs e)
{
k = new Dictionary<int, int>();
for (int i = 0; i < 256; i++) k[i] = 0;
var bm = (Bitmap)pictureBox2.Image;
for (int x = 0; x < bm.Width; x++)
{
for (global::System.Int32 y = 0; y < bm.Height; y++)
{
var g = bm.GetPixel(x, y).R;
k[g]++;
}
}
var series = chart1.Series.First();
series.Points.Clear();
foreach (var item in k)
{
series.Points.AddXY(item.Key, item.Value);
}
}
private void 求最小灰階及最大灰階ToolStripMenuItem_Click(object sender, EventArgs e)
{
int min = int.MaxValue;
int max = int.MinValue;
foreach (var item in k)
{
if (item.Value == 0) continue;
if (item.Key > max) max = item.Key;
if (item.Key < min) min = item.Key;
}
textBox1.Text = min.ToString();
textBox2.Text = max.ToString();
}
private void 求出現最多之灰階及機率ToolStripMenuItem_Click(object sender, EventArgs e)
{
int max = int.MinValue;
int r = 0;
foreach (var item in k)
{
if (item.Value > max)
{
r = item.Key;
max = item.Value;
}
}
textBox4.Text = r.ToString();
textBox3.Text = ((double)max / (pictureBox2.Image.Width * pictureBox2.Image.Height)).ToString();
}
}
}
Last updated