カメラ - peace098beat/windows_applicaciton GitHub Wiki
https://haryoktav.wordpress.com/2009/03/21/webcam-in-c-aforgenet/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
namespace cam_aforge1
{
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//refresh button
private void rfsh_Click(object sender, EventArgs e)
{
getCamList();
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
if (start.Text == "&Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(160, 120);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "&Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "&Start";
}
}
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap img = (Bitmap)eventArgs.Frame.Clone();
//do processing here
pictureBox1.Image = img;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
}
}
using AForge.Video.DirectShow;
using OpenCvSharp;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Camera1
{
public partial class Form1 : Form
{
// Member Variable
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
/// <summary>
/// コンストラクタ
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// フォームのロード時に呼び出される関数
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
// ?
this.KeyPreview = true;
// タイトルにアプリ名を表示
this.Text = Application.ProductName + " " + Application.ProductVersion;
// ウィンドウサイズと位置の保存
this.MinimumSize = new System.Drawing.Size(300, 100);
this.Size = Properties.Settings.Default.Size;
this.Location = Properties.Settings.Default.Location;
// ウィンドウが画面の外にある場合の処理
if (this.Left < Screen.GetWorkingArea(this).Left) this.Left = 100;
if (this.Left >= Screen.GetWorkingArea(this).Right) this.Left = 100;
if (this.Top < Screen.GetWorkingArea(this).Top) this.Top = 100;
if (this.Top >= Screen.GetWorkingArea(this).Bottom) this.Top = 100;
button_StartStop.Text = "&Start";
getCamList();
}
/******************************************************************************************/
/*以下 カメラ関連*/
/******************************************************************************************/
// get the devices name
private void getCamList()
{
try
{
// Exist Camera Device
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox_VideoDevices.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox_VideoDevices.Items.Add(device.Name);
}
comboBox_VideoDevices.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
// Notiong Camera Devices
DeviceExist = false;
comboBox_VideoDevices.Items.Add("No capture device on your system");
}
}
private void button_Refresh_Click(object sender, EventArgs e)
{
getCamList();
}
private void button_StartStop_Click(object sender, EventArgs e)
{
if (button_StartStop.Text == "&Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox_VideoDevices.SelectedIndex].MonikerString);
videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(video_NewFrame_Callback);
this.CloseVideoSource();
videoSource.Start();
statusBar1.Text = "Device running...";
button_StartStop.Text = "&Stop";
timer1.Enabled = true;
}
else
{
statusBar1.Text = "Error: No Device selected.";
}
}
else if (button_StartStop.Text == "&Stop")
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
statusBar1.Text = "Device stopped.";
button_StartStop.Text = "&Start";
}
}
}
CascadeClassifier haarCascade = null;
//eventhandler if new frame is ready
private void video_NewFrame_Callback(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap img = (Bitmap)eventArgs.Frame.Clone();
Mat RawMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
if (this.haarCascade == null)
{
string filename = @"data\haarcascades\haarcascade_frontalface_alt2.xml";
haarCascade = new CascadeClassifier(filename);
}
double scalefactor = (double)numericUpDown_param1.Value;
int minNebgers = (int)numericUpDown_param2.Value;
using (var src = RawMat)
using (var gray = new Mat())
{
Mat ResultMat = src.Clone();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
// 顔検出
//# 物体認識(顔認識)の実行
//# image – CV_8U 型の行列.ここに格納されている画像中から物体が検出されます
//# objects – 矩形を要素とするベクトル.それぞれの矩形は,検出した物体を含みます
//# scaleFactor – 各画像スケールにおける縮小量を表します
//# minNeighbors – 物体候補となる矩形は,最低でもこの数だけの近傍矩形を含む必要があります
//# flags – このパラメータは,新しいカスケードでは利用されません.古いカスケードに対しては,cvHaarDetectObjects 関数の場合と同じ意味を持ちます
//# minSize – 物体が取り得る最小サイズ.これよりも小さい物体は無視されます
//Rect[] faces = haarCascade.DetectMultiScale(gray, 1.08, 2, HaarDetectionType.FindBiggestObject, new OpenCvSharp.Size(50, 50));
Rect[] faces = haarCascade.DetectMultiScale(gray, scalefactor, minNebgers, HaarDetectionType.DoCannyPruning, new OpenCvSharp.Size(100, 100));
// 検出した顔の位置に円を描画
foreach (Rect face in faces)
{
Cv2.Rectangle(ResultMat, face, new Scalar(255, 0, 255));
}
Bitmap NewImg = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(ResultMat);
//do processing here
pictureBox_CaptureBox.Image = NewImg;
}
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick_1(object sender, EventArgs e)
{
statusBar1.Text = "Device running... " + this.videoSource.FramesReceived.ToString() + " FPS";
}
/******************************************************************************************/
/* 以下共通設定 */
/******************************************************************************************/
/// <summary>
/// メニュー -> ファイル -> 終了(X)
/// </summary>
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
//this.Close();
Application.Exit();
}
/// <summary>
/// フォームが閉じられたときに呼び出される関数
/// </summary>
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// 画面の位置とサイズを保存
this.WindowState = FormWindowState.Normal;
Properties.Settings.Default.Size = this.Size;
Properties.Settings.Default.Location = this.Location;
// 設定保存
Properties.Settings.Default.Save();
// カメラ
this.CloseVideoSource();
}
/// <summary>
/// ヴァージョン情報をクリック
/// </summary>
private void ToolStripMenuItemVersion_Click(object sender, EventArgs e)
{
string s = "";
s = Application.ProductName + " " + Application.ProductVersion + Environment.NewLine;
// コピーライトを表示
var fileVrsionInfo = (System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath));
string copyright = fileVrsionInfo.LegalCopyright.ToString();
s += copyright + Environment.NewLine + Environment.NewLine;
// 実行ファイルを表示
s += "実行ファイル : " + Environment.NewLine +
Application.ExecutablePath + Environment.NewLine;
// 実行プロセスを表示
string bit;
if (Environment.Is64BitProcess) bit = "64";
else bit = "32";
s += "(" + bit + "ビット・プロセスとして稼動)" + Environment.NewLine + Environment.NewLine;
// OSの情報を表示
var myComputer = new Microsoft.VisualBasic.Devices.Computer();
s += "オペレーティングシステム:" + Environment.NewLine;
s += myComputer.Info.OSFullName + " " + myComputer.Info.OSVersion + " ";
string osbit;
if (Environment.Is64BitOperatingSystem) osbit = "64";
else osbit = "32";
s += osbit + "ビット";
// ヴァージョン情報を表示
MessageBox.Show(s, "バージョン情報");
}
/// <summary>
/// READMEを表示
/// </summary>
private void ToolStripMenuItemReadme_Click(object sender, EventArgs e)
{
// ファイルから読み込む
string s = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
s = System.IO.Path.Combine(s, "README.txt");
if (System.IO.File.Exists(s))
System.Diagnostics.Process.Start(s);
else
MessageBox.Show(s + "が見つかりません", "エラー");
}
/// <summary>
/// README.htmlを表示
/// </summary>
private void ToolStripMenuItemWEB_Click(object sender, EventArgs e)
{
// ファイルから読み込む
string s = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
s = System.IO.Path.Combine(s, "README.html");
if (System.IO.File.Exists(s))
System.Diagnostics.Process.Start(s);
else
MessageBox.Show(s + "が見つかりません", "エラー");
}
/******************************************************************************************/
}
}