获取图像成功

This commit is contained in:
zqm
2026-03-24 17:25:04 +08:00
parent d1eae0f0ae
commit e1cf0ad723
3 changed files with 327 additions and 211 deletions

View File

@@ -5,6 +5,7 @@ using System.Net;
using System.IO; using System.IO;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading;
namespace Camera namespace Camera
{ {
@@ -16,11 +17,21 @@ namespace Camera
private const string USER = "admin"; private const string USER = "admin";
private const string PASSWD = "Yexian.net.168"; private const string PASSWD = "Yexian.net.168";
// 配置文件目录
private string _configPath;
// 配置数据
private Rectangle _detectionZone;
private Rectangle _ledZone;
// 定时器 // 定时器
private System.Timers.Timer _timer; private System.Timers.Timer _timer;
// 当前图像 // 当前图像
private Image _currentImage; private Image _currentImage;
private readonly object _imageLock = new object();
private string _authorization;
// 事件定义 // 事件定义
public event EventHandler<ImageEventArgs> ImageCaptured; public event EventHandler<ImageEventArgs> ImageCaptured;
@@ -50,7 +61,10 @@ namespace Camera
/// </summary> /// </summary>
public Image GetCurrentImage() public Image GetCurrentImage()
{ {
return _currentImage; lock (_imageLock)
{
return _currentImage;
}
} }
/// <summary> /// <summary>
@@ -60,7 +74,7 @@ namespace Camera
{ {
Stop(); Stop();
_timer = new System.Timers.Timer(300); _timer = new System.Timers.Timer(200);
_timer.AutoReset = false; _timer.AutoReset = false;
_timer.Elapsed += Timer_Elapsed; _timer.Elapsed += Timer_Elapsed;
_timer.Start(); _timer.Start();
@@ -77,6 +91,7 @@ namespace Camera
_timer.Dispose(); _timer.Dispose();
_timer = null; _timer = null;
} }
_authorization = null;
} }
/// <summary> /// <summary>
@@ -89,35 +104,188 @@ namespace Camera
{ {
settingForm.SetImage(_currentImage); settingForm.SetImage(_currentImage);
} }
if (!string.IsNullOrEmpty(_configPath))
{
settingForm.SetConfigPath(_configPath);
}
settingForm.ShowDialog(); settingForm.ShowDialog();
} }
/// <summary>
/// 设置配置文件目录
/// </summary>
public void SetConfigPath(string path)
{
_configPath = path;
LoadConfig();
}
/// <summary>
/// 获取检测区域
/// </summary>
public Rectangle GetDetectionZone()
{
return _detectionZone;
}
/// <summary>
/// 获取Led区域
/// </summary>
public Rectangle GetLedZone()
{
return _ledZone;
}
/// <summary>
/// 设置检测区域
/// </summary>
public void SetDetectionZone(Rectangle zone)
{
_detectionZone = zone;
}
/// <summary>
/// 设置Led区域
/// </summary>
public void SetLedZone(Rectangle zone)
{
_ledZone = zone;
}
/// <summary>
/// 保存配置
/// </summary>
public void SaveConfig()
{
if (string.IsNullOrEmpty(_configPath)) return;
string configFile = Path.Combine(_configPath, "Camera.csv");
try
{
using (StreamWriter writer = new StreamWriter(configFile, false, System.Text.Encoding.UTF8))
{
writer.WriteLine("X坐标,Y坐标,宽度,高度,颜色");
if (_detectionZone.Width > 0 && _detectionZone.Height > 0)
{
writer.WriteLine(string.Format("{0},{1},{2},{3},#FF0000", _detectionZone.X, _detectionZone.Y, _detectionZone.Width, _detectionZone.Height));
}
writer.WriteLine();
writer.WriteLine("索引,X坐标,Y坐标,宽度,高度,颜色");
if (_ledZone.Width > 0 && _ledZone.Height > 0)
{
writer.WriteLine(string.Format("1,{0},{1},{2},{3},#00FF00", _ledZone.X, _ledZone.Y, _ledZone.Width, _ledZone.Height));
}
}
}
catch { }
}
/// <summary>
/// 加载配置
/// </summary>
private void LoadConfig()
{
if (string.IsNullOrEmpty(_configPath)) return;
_detectionZone = new Rectangle(0, 0, 2880, 1620);
_ledZone = new Rectangle(0, 0, 0, 0);
string configFile = Path.Combine(_configPath, "Camera.csv");
try
{
if (File.Exists(configFile))
{
using (StreamReader reader = new StreamReader(configFile, System.Text.Encoding.UTF8))
{
string line;
bool isDetectionZone = true;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
{
isDetectionZone = false;
continue;
}
string[] parts = line.Split(',');
if (parts.Length >= 4)
{
if (isDetectionZone)
{
int x = int.Parse(parts[0]);
int y = int.Parse(parts[1]);
int width = int.Parse(parts[2]);
int height = int.Parse(parts[3]);
_detectionZone = new Rectangle(x, y, width, height);
}
else if (parts[0] == "索引")
{
continue;
}
else
{
int index = int.Parse(parts[0]);
if (index == 1)
{
int x = int.Parse(parts[1]);
int y = int.Parse(parts[2]);
int width = int.Parse(parts[3]);
int height = int.Parse(parts[4]);
_ledZone = new Rectangle(x, y, width, height);
}
}
}
}
}
}
else
{
SaveConfig();
}
}
catch { }
}
/// <summary> /// <summary>
/// 定时器触发事件 /// 定时器触发事件
/// </summary> /// </summary>
private void Timer_Elapsed(object sender, ElapsedEventArgs e) private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ {
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " Timer_Elapsed 开始");
try try
{ {
Image image = GetCameraImage(); Image image = GetCameraImage();
if (image != null) if (image != null)
{ {
if (_currentImage != null) System.Diagnostics.Debug.WriteLine("Camera: 捕获图像 Size=" + image.Width + "x" + image.Height);
Image oldImage = null;
lock (_imageLock)
{ {
_currentImage.Dispose(); oldImage = _currentImage;
_currentImage = image;
}
if (oldImage != null)
{
oldImage.Dispose();
} }
_currentImage = image;
OnImageCaptured(new ImageEventArgs { Image = image }); OnImageCaptured(new ImageEventArgs { Image = image });
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 事件已触发");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("获取图像失败: " + ex.Message); System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 获取图像失败: " + ex.Message);
} }
finally finally
{ {
if (_timer != null && _timer.Enabled == false) if (_timer != null)
{ {
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 重新启动定时器");
_timer.Stop();
_timer.Start(); _timer.Start();
} }
} }
@@ -132,6 +300,13 @@ namespace Camera
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET"; request.Method = "GET";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Pragma", "no-cache");
if (!string.IsNullOrEmpty(_authorization))
{
request.Headers.Add("Authorization", _authorization);
}
HttpWebResponse response = null; HttpWebResponse response = null;
try try
@@ -149,11 +324,13 @@ namespace Camera
string realm = ExtractAuthParam(authHeader, "realm"); string realm = ExtractAuthParam(authHeader, "realm");
string nonce = ExtractAuthParam(authHeader, "nonce"); string nonce = ExtractAuthParam(authHeader, "nonce");
string authorization = GenerateDigestAuthorization(USER, PASSWD, realm, nonce, "GET", SNAPSHOT_URI); _authorization = GenerateDigestAuthorization(USER, PASSWD, realm, nonce, "GET", SNAPSHOT_URI);
request = (HttpWebRequest)WebRequest.Create(url); request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET"; request.Method = "GET";
request.Headers.Add("Authorization", authorization); request.Headers.Add("Authorization", _authorization);
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Pragma", "no-cache");
response = (HttpWebResponse)request.GetResponse(); response = (HttpWebResponse)request.GetResponse();
} }
else else
@@ -162,12 +339,15 @@ namespace Camera
} }
} }
byte[] imageData;
using (Stream stream = response.GetResponseStream()) using (Stream stream = response.GetResponseStream())
using (MemoryStream memoryStream = new MemoryStream())
{ {
Image image = Image.FromStream(stream); stream.CopyTo(memoryStream);
response.Close(); imageData = memoryStream.ToArray();
return image;
} }
return new Bitmap(new MemoryStream(imageData));
} }
/// <summary> /// <summary>

View File

@@ -23,7 +23,7 @@ namespace Camera
this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.listBox1 = new System.Windows.Forms.ListBox(); this.dataGridView1 = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout();
@@ -32,6 +32,7 @@ namespace Camera
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.splitContainer2.SuspendLayout(); this.splitContainer2.SuspendLayout();
this.toolStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
@@ -50,9 +51,9 @@ namespace Camera
// splitContainer1.Panel2 // splitContainer1.Panel2
// //
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Panel2MinSize = 200; this.splitContainer1.Panel2MinSize = 457;
this.splitContainer1.Size = new System.Drawing.Size(850, 469); this.splitContainer1.Size = new System.Drawing.Size(1263, 515);
this.splitContainer1.SplitterDistance = 100; this.splitContainer1.SplitterDistance = 700;
this.splitContainer1.TabIndex = 0; this.splitContainer1.TabIndex = 0;
// //
// picBoxCamera // picBoxCamera
@@ -85,7 +86,7 @@ namespace Camera
// //
// splitContainer2.Panel2 // splitContainer2.Panel2
// //
this.splitContainer2.Panel2.Controls.Add(this.listBox1); this.splitContainer2.Panel2.Controls.Add(this.dataGridView1);
this.splitContainer2.Panel2MinSize = 100; this.splitContainer2.Panel2MinSize = 100;
this.splitContainer2.Size = new System.Drawing.Size(746, 469); this.splitContainer2.Size = new System.Drawing.Size(746, 469);
this.splitContainer2.TabIndex = 0; this.splitContainer2.TabIndex = 0;
@@ -95,46 +96,45 @@ namespace Camera
this.toolStrip1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStrip1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton2,
this.toolStripButton1}); this.toolStripButton1});
this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(746, 50);
this.toolStrip1.TabIndex = 0; this.toolStrip1.TabIndex = 0;
this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked); this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked);
// //
// toolStripButton2 // toolStripButton2
// //
this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(43, 47);
this.toolStripButton2.Text = "新建";
this.toolStripButton2.Click += new System.EventHandler(this.ToolStripButton2_Click);
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton1.Font = new System.Drawing.Font("Microsoft YaHei UI", 9F, System.Drawing.FontStyle.Bold);
this.toolStripButton1.ForeColor = System.Drawing.Color.Blue;
this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(43, 47); this.toolStripButton1.Text = "修改检测区";
this.toolStripButton1.Text = "保存"; this.toolStripButton1.CheckOnClick = true;
this.toolStripButton1.Click += new System.EventHandler(this.ToolStripButton1_Click); this.toolStripButton1.Click += new System.EventHandler(this.ToolStripButton1_Click);
// //
// listBox1 // dataGridView1
// //
this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.AllowUserToAddRows = false;
this.listBox1.FormattingEnabled = true; this.dataGridView1.AllowUserToDeleteRows = false;
this.listBox1.ItemHeight = 15; this.dataGridView1.AllowUserToResizeRows = false;
this.listBox1.Location = new System.Drawing.Point(0, 0); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.listBox1.Name = "listBox1"; this.dataGridView1.ColumnHeadersHeight = 25;
this.listBox1.Size = new System.Drawing.Size(746, 415); this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listBox1.TabIndex = 0; this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.ListBox1_SelectedIndexChanged); this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.RowTemplate.Height = 25;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(746, 415);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.SelectionChanged += new System.EventHandler(this.DataGridView1_SelectionChanged);
// //
// Setting // Setting
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(905, 515); this.ClientSize = new System.Drawing.Size(1263, 515);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Controls.Add(this.splitContainer1); this.Controls.Add(this.splitContainer1);
this.Name = "Setting"; this.Name = "Setting";
@@ -149,6 +149,7 @@ namespace Camera
this.splitContainer2.Panel1.PerformLayout(); this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.splitContainer2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false);
this.toolStrip1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout(); this.toolStrip1.PerformLayout();
@@ -164,6 +165,6 @@ namespace Camera
private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.DataGridView dataGridView1;
} }
} }

View File

@@ -13,20 +13,21 @@ namespace Camera
public partial class Setting : Form public partial class Setting : Form
{ {
private Camera _camera; private Camera _camera;
private Rectangle _detectionZone;
private Rectangle _ledZone;
private int _selectedZoneIndex = -1; private int _selectedZoneIndex = -1;
private bool _isDrawing = false; private bool _isDrawing = false;
private bool _isMoving = false; private bool _isMoving = false;
private Point _startPoint; private Point _startPoint;
private Rectangle _originalZone; private Rectangle _originalZone;
private Color[] _zoneColors = new Color[] { Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Cyan, Color.Magenta };
public Setting() public Setting()
{ {
InitializeComponent(); InitializeComponent();
InitializeDataGridView();
}
public void SetCamera(Camera camera)
{
_camera = camera;
} }
public void SetImage(Image image) public void SetImage(Image image)
@@ -36,128 +37,63 @@ namespace Camera
picBoxCamera.Image.Dispose(); picBoxCamera.Image.Dispose();
} }
picBoxCamera.Image = (Image)image.Clone(); picBoxCamera.Image = (Image)image.Clone();
_detectionZone = new Rectangle(0, 0, picBoxCamera.Image.Width, picBoxCamera.Image.Height);
_ledZone = new Rectangle(0, 0, 50, 50);
LoadConfig();
picBoxCamera.Invalidate(); picBoxCamera.Invalidate();
} }
public void SetConfigPath(string path)
{
_camera.SetConfigPath(path);
}
private void InitializeDataGridView()
{
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("Index", "索引");
dataGridView1.Columns.Add("X", "X坐标");
dataGridView1.Columns.Add("Y", "Y坐标");
dataGridView1.Columns.Add("Width", "宽度");
dataGridView1.Columns.Add("Height", "高度");
dataGridView1.Columns.Add("Color", "颜色");
dataGridView1.Columns["Index"].Width = 50;
dataGridView1.Columns["X"].Width = 60;
dataGridView1.Columns["Y"].Width = 60;
dataGridView1.Columns["Width"].Width = 60;
dataGridView1.Columns["Height"].Width = 60;
dataGridView1.Columns["Color"].Width = 70;
}
private void Setting_Load(object sender, EventArgs e) private void Setting_Load(object sender, EventArgs e)
{ {
_camera = new Camera();
picBoxCamera.BackColor = Color.Gray; picBoxCamera.BackColor = Color.Gray;
splitContainer1.Panel2MinSize = 200;
splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
splitContainer1.SplitterDistance = splitContainer1.Width - 200; splitContainer1.Panel2MinSize = 380;
splitContainer1.SplitterDistance = splitContainer1.Width - 380;
splitContainer2.Panel1MinSize = 40; splitContainer2.Panel1MinSize = 40;
UpdateDataGridView();
} }
private void LoadConfig() private void UpdateDataGridView()
{ {
string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Camera.csv"); dataGridView1.Rows.Clear();
if (File.Exists(configPath))
{
try
{
_detectionZone = new Rectangle(0, 0, 0, 0);
_ledZone = new Rectangle(0, 0, 0, 0);
using (StreamReader reader = new StreamReader(configPath, Encoding.UTF8))
{
string line;
bool isFirstLine = true;
while ((line = reader.ReadLine()) != null)
{
if (isFirstLine)
{
isFirstLine = false;
continue;
}
string[] parts = line.Split(',');
if (parts.Length >= 5)
{
int index = int.Parse(parts[0]);
int x = int.Parse(parts[1]);
int y = int.Parse(parts[2]);
int width = int.Parse(parts[3]);
int height = int.Parse(parts[4]);
Color color = parts.Length > 5 ? ColorTranslator.FromHtml(parts[5]) : Color.Red;
Rectangle zone = new Rectangle(x, y, width, height);
if (index == 0)
{
_detectionZone = zone;
}
else if (index == 1)
{
_ledZone = zone;
}
}
}
}
UpdateListBox();
picBoxCamera.Invalidate();
}
catch (Exception ex)
{
MessageBox.Show("加载配置失败: " + ex.Message);
}
}
else
{
if (picBoxCamera.Image != null)
{
_detectionZone = new Rectangle(10, 10, picBoxCamera.Image.Width - 20, picBoxCamera.Image.Height - 20);
_ledZone = new Rectangle(picBoxCamera.Image.Width - 60, 10, 50, 50);
}
UpdateListBox();
}
}
private void SaveConfig() if (_camera != null)
{
string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Camera.csv");
try
{ {
using (StreamWriter writer = new StreamWriter(configPath, false, Encoding.UTF8)) Rectangle detectionZone = _camera.GetDetectionZone();
{ Rectangle ledZone = _camera.GetLedZone();
writer.WriteLine("索引,X坐标,Y坐标,宽度,高度,颜色");
if (_detectionZone.Width > 0 && _detectionZone.Height > 0)
{
writer.WriteLine(string.Format("0,{0},{1},{2},{3},#FF0000", _detectionZone.X, _detectionZone.Y, _detectionZone.Width, _detectionZone.Height));
}
if (_ledZone.Width > 0 && _ledZone.Height > 0)
{
writer.WriteLine(string.Format("1,{0},{1},{2},{3},#00FF00", _ledZone.X, _ledZone.Y, _ledZone.Width, _ledZone.Height));
}
}
MessageBox.Show("配置已保存到: " + configPath);
}
catch (Exception ex)
{
MessageBox.Show("保存配置失败: " + ex.Message);
}
}
private void UpdateListBox() if (detectionZone.Width > 0 && detectionZone.Height > 0)
{ {
listBox1.Items.Clear(); dataGridView1.Rows.Add(0, detectionZone.X, detectionZone.Y, detectionZone.Width, detectionZone.Height, "#FF0000");
}
if (_detectionZone.Width > 0 && _detectionZone.Height > 0)
{ if (ledZone.Width > 0 && ledZone.Height > 0)
listBox1.Items.Add(string.Format("检测区: X={0}, Y={1}, W={2}, H={3}", _detectionZone.X, _detectionZone.Y, _detectionZone.Width, _detectionZone.Height)); {
} dataGridView1.Rows.Add(1, ledZone.X, ledZone.Y, ledZone.Width, ledZone.Height, "#00FF00");
}
if (_ledZone.Width > 0 && _ledZone.Height > 0)
{
listBox1.Items.Add(string.Format("Led区: X={0}, Y={1}, W={2}, H={3}", _ledZone.X, _ledZone.Y, _ledZone.Width, _ledZone.Height));
} }
picBoxCamera.Invalidate();
} }
private void PicBoxCamera_Paint(object sender, PaintEventArgs e) private void PicBoxCamera_Paint(object sender, PaintEventArgs e)
@@ -169,18 +105,21 @@ namespace Camera
float scaleX = (float)picBoxCamera.ClientSize.Width / picBoxCamera.Image.Width; float scaleX = (float)picBoxCamera.ClientSize.Width / picBoxCamera.Image.Width;
float scaleY = (float)picBoxCamera.ClientSize.Height / picBoxCamera.Image.Height; float scaleY = (float)picBoxCamera.ClientSize.Height / picBoxCamera.Image.Height;
Rectangle detectionZone = _camera != null ? _camera.GetDetectionZone() : new Rectangle(0, 0, 0, 0);
Rectangle ledZone = _camera != null ? _camera.GetLedZone() : new Rectangle(0, 0, 0, 0);
Rectangle scaledDetectionZone = new Rectangle( Rectangle scaledDetectionZone = new Rectangle(
(int)(_detectionZone.X * scaleX), (int)(detectionZone.X * scaleX),
(int)(_detectionZone.Y * scaleY), (int)(detectionZone.Y * scaleY),
(int)(_detectionZone.Width * scaleX), (int)(detectionZone.Width * scaleX),
(int)(_detectionZone.Height * scaleY) (int)(detectionZone.Height * scaleY)
); );
Rectangle scaledLedZone = new Rectangle( Rectangle scaledLedZone = new Rectangle(
(int)(_ledZone.X * scaleX), (int)(ledZone.X * scaleX),
(int)(_ledZone.Y * scaleY), (int)(ledZone.Y * scaleY),
(int)(_ledZone.Width * scaleX), (int)(ledZone.Width * scaleX),
(int)(_ledZone.Height * scaleY) (int)(ledZone.Height * scaleY)
); );
using (Pen pen = new Pen(Color.Red, 2)) using (Pen pen = new Pen(Color.Red, 2))
@@ -213,7 +152,6 @@ namespace Camera
{ {
int handleSize = 8; int handleSize = 8;
using (Brush brush = new SolidBrush(Color.White)) using (Brush brush = new SolidBrush(Color.White))
using (Pen pen = new Pen(Color.Blue, 2))
{ {
g.FillRectangle(brush, rect.X - handleSize / 2, rect.Y - handleSize / 2, handleSize, handleSize); g.FillRectangle(brush, rect.X - handleSize / 2, rect.Y - handleSize / 2, handleSize, handleSize);
g.FillRectangle(brush, rect.X + rect.Width - handleSize / 2, rect.Y - handleSize / 2, handleSize, handleSize); g.FillRectangle(brush, rect.X + rect.Width - handleSize / 2, rect.Y - handleSize / 2, handleSize, handleSize);
@@ -224,25 +162,28 @@ namespace Camera
private void PicBoxCamera_MouseDown(object sender, MouseEventArgs e) private void PicBoxCamera_MouseDown(object sender, MouseEventArgs e)
{ {
if (picBoxCamera.Image == null) return; if (picBoxCamera.Image == null || _camera == null) return;
float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width; float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width;
float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height; float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height;
Point imagePoint = new Point((int)(e.X * scaleX), (int)(e.Y * scaleY)); Point imagePoint = new Point((int)(e.X * scaleX), (int)(e.Y * scaleY));
if (_detectionZone.Contains(imagePoint)) Rectangle detectionZone = _camera.GetDetectionZone();
Rectangle ledZone = _camera.GetLedZone();
if (detectionZone.Contains(imagePoint))
{ {
_selectedZoneIndex = 0; _selectedZoneIndex = 0;
_isMoving = true; _isMoving = true;
_startPoint = imagePoint; _startPoint = imagePoint;
_originalZone = _detectionZone; _originalZone = detectionZone;
} }
else if (_ledZone.Contains(imagePoint)) else if (ledZone.Contains(imagePoint))
{ {
_selectedZoneIndex = 1; _selectedZoneIndex = 1;
_isMoving = true; _isMoving = true;
_startPoint = imagePoint; _startPoint = imagePoint;
_originalZone = _ledZone; _originalZone = ledZone;
} }
else else
{ {
@@ -251,52 +192,49 @@ namespace Camera
_startPoint = imagePoint; _startPoint = imagePoint;
} }
UpdateListBox(); UpdateDataGridView();
picBoxCamera.Invalidate(); picBoxCamera.Invalidate();
} }
private void PicBoxCamera_MouseMove(object sender, MouseEventArgs e) private void PicBoxCamera_MouseMove(object sender, MouseEventArgs e)
{ {
if (picBoxCamera.Image == null) return; if (picBoxCamera.Image == null || _camera == null || !_isMoving) return;
float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width; float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width;
float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height; float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height;
Point imagePoint = new Point((int)(e.X * scaleX), (int)(e.Y * scaleY)); Point imagePoint = new Point((int)(e.X * scaleX), (int)(e.Y * scaleY));
if (_isMoving && _selectedZoneIndex >= 0) int dx = imagePoint.X - _startPoint.X;
int dy = imagePoint.Y - _startPoint.Y;
Rectangle newZone = new Rectangle(
_originalZone.X + dx,
_originalZone.Y + dy,
_originalZone.Width,
_originalZone.Height
);
if (newZone.X >= 0 && newZone.Y >= 0 &&
newZone.X + newZone.Width <= picBoxCamera.Image.Width &&
newZone.Y + newZone.Height <= picBoxCamera.Image.Height)
{ {
int dx = imagePoint.X - _startPoint.X; if (_selectedZoneIndex == 0)
int dy = imagePoint.Y - _startPoint.Y;
Rectangle newZone = new Rectangle(
_originalZone.X + dx,
_originalZone.Y + dy,
_originalZone.Width,
_originalZone.Height
);
if (newZone.X >= 0 && newZone.Y >= 0 &&
newZone.X + newZone.Width <= picBoxCamera.Image.Width &&
newZone.Y + newZone.Height <= picBoxCamera.Image.Height)
{ {
if (_selectedZoneIndex == 0) _camera.SetDetectionZone(newZone);
{ }
_detectionZone = newZone; else if (_selectedZoneIndex == 1)
} {
else if (_selectedZoneIndex == 1) _camera.SetLedZone(newZone);
{
_ledZone = newZone;
}
} }
UpdateListBox();
picBoxCamera.Invalidate();
} }
UpdateDataGridView();
picBoxCamera.Invalidate();
} }
private void PicBoxCamera_MouseUp(object sender, MouseEventArgs e) private void PicBoxCamera_MouseUp(object sender, MouseEventArgs e)
{ {
if (picBoxCamera.Image == null) return; if (picBoxCamera.Image == null || _camera == null) return;
float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width; float scaleX = (float)picBoxCamera.Image.Width / picBoxCamera.ClientSize.Width;
float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height; float scaleY = (float)picBoxCamera.Image.Height / picBoxCamera.ClientSize.Height;
@@ -311,41 +249,38 @@ namespace Camera
if (width > 10 && height > 10) if (width > 10 && height > 10)
{ {
_detectionZone = new Rectangle(x, y, width, height); _camera.SetDetectionZone(new Rectangle(x, y, width, height));
_selectedZoneIndex = 0; _selectedZoneIndex = 0;
} }
} }
_isDrawing = false; _isDrawing = false;
_isMoving = false; _isMoving = false;
UpdateListBox(); UpdateDataGridView();
picBoxCamera.Invalidate(); picBoxCamera.Invalidate();
} }
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e) private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{ {
if (listBox1.SelectedIndex >= 0) if (dataGridView1.SelectedRows.Count > 0)
{ {
_selectedZoneIndex = listBox1.SelectedIndex; _selectedZoneIndex = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Index"].Value);
picBoxCamera.Invalidate(); picBoxCamera.Invalidate();
} }
} }
private void ToolStripButton1_Click(object sender, EventArgs e) private void ToolStripButton1_Click(object sender, EventArgs e)
{ {
SaveConfig(); if (toolStripButton1.Checked)
}
private void ToolStripButton2_Click(object sender, EventArgs e)
{
if (picBoxCamera.Image != null)
{ {
_detectionZone = new Rectangle(10, 10, picBoxCamera.Image.Width - 20, picBoxCamera.Image.Height - 20); _selectedZoneIndex = 0;
_ledZone = new Rectangle(picBoxCamera.Image.Width - 60, 10, 50, 50);
_selectedZoneIndex = -1;
UpdateListBox();
picBoxCamera.Invalidate();
} }
else
{
_selectedZoneIndex = -1;
}
UpdateDataGridView();
picBoxCamera.Invalidate();
} }
private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
@@ -353,4 +288,4 @@ namespace Camera
} }
} }
} }