//★ エッジを検出して描画 前田 稔
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
public class MyForm : Form
{
Face App;
int val= 4000; // 閾値
public MyForm()
{
App = new Face();
App.edge = (Bitmap)App.bmp.Clone();
Width = App.bmp.Width;
Height = App.bmp.Height+32;
Paint += new PaintEventHandler(MyHandler);
MouseDown += new MouseEventHandler(OnMyMouseDown);
}
private void MyHandler(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
App.ViewEdge(g,0,0);
}
private void OnMyMouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) //マウスの左ボタン
{ val+= 1000;
App.Edge(val);
VerMsg("val: ", val);
}
if (e.Button == MouseButtons.Right) //マウスの右ボタン
{ App.edge = (Bitmap)App.bmp.Clone();
val= 4000;
}
Invalidate();
}
public void VerMsg(string msg, int v)
{
string wstr;
wstr = msg + v.ToString();
this.Text = wstr;
}
}
//☆ Face Object Class
class Face
{
public Bitmap bmp = null;
public Bitmap edge = null;
string ImgFile = "";
int[,] vect = new int[9,2] //エッジ検出テーブル
{ {-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,0}, {0,1}, {1,-1}, {1,0}, {1,1} };
int[] hCoef = new int[9]{ 1, 0, -1, 2, 0, -2, 1, 0, -1 };
int[] vCoef = new int[9]{ 1, 2, 1, 0, 0, 0, -1, -2, -1 };
// Constructor
public Face()
{
OpenFileDialog opendlg = new OpenFileDialog();
opendlg.Filter = "画像ファイル (*.bmp)|*.bmp|すべてのファイル (*.*)|*.*" ;
if (opendlg.ShowDialog() == DialogResult.OK)
{ ImgFile = opendlg.FileName;
bmp = new Bitmap(ImgFile);
}
}
// BMP 画像を描画
public void View(Graphics g, int x, int y)
{ if (bmp != null) g.DrawImage(bmp, x, y); }
// Edge 画像を描画
public void ViewEdge(Graphics g, int x, int y)
{ if (edge != null) g.DrawImage(edge, x, y); }
// 座標[x,y]周辺のピクセルを調べてエッジを検出する
public void Edge(int val)
{ Color cor;
for(int y=1; y<bmp.Height-1; y++)
for(int x=1; x<bmp.Width-1; x++)
{ if (Sobel(x, y, val)) cor = Color.Black;
else cor = Color.White;
edge.SetPixel(x,y,cor);
}
}
// m_bmp[x,y] の周辺のピクセルを調べてエッジを検出する
public bool Sobel(int x, int y, int val)
{ int[] fx = new int[3]; //3色分
int[] fy = new int[3]; //3色分
int dx, dy;
Color cor;
fx[0]= fx[1]= fx[2]= 0;
fy[0]= fy[1]= fy[2]= 0;
for(int i=0; i<9; i++)
{ dx = x + vect[i,0];
dy = y + vect[i,1];
cor = bmp.GetPixel(dx,dy);
fx[0] += cor.B * hCoef[i];
fy[0] += cor.B * vCoef[i];
fx[1] += cor.G * hCoef[i];
fy[1] += cor.G * vCoef[i];
fx[2] += cor.R * hCoef[i];
fy[2] += cor.R * vCoef[i];
}
for(int c=0; c<3; c++)
if (fx[c]*fx[c]+fy[c]*fy[c] > val) return true;
return false;
}
}
class image01
{
[STAThread]
public static void Main()
{
MyForm mf = new MyForm();
Application.Run(mf);
}
}
|