using OpenCvSharp; using OpenCvSharp.Extensions; using OpenCvSharp.ImgHash; using PaintDotNet.Adjust; using PaintDotNet.Base.CommTool; using PaintDotNet.DbOpreate.DbBll; using PaintDotNet.DbOpreate.DbModel; using PaintDotNet.ImageCollect.CameraPreviewComponent; using PaintDotNet.ImageCollect.CameraPreviewComponent.Properties; using PaintDotNet.Instrument; using PaintDotNet.Measuring; using PaintDotNet.Menus; using PaintDotNet.Base.SettingModel; using PaintDotNet.SystemLayer; using StageController; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using PaintDotNet.Adjust.BaseImage; using PaintDotNet.Annotation.Measure; using PaintDotNet.Annotation.Enum; using PaintDotNet.Annotation; using Point = System.Drawing.Point; using StageController.M3H; using System.Threading.Tasks; using System.Linq; using Metis.AutoAnalysis; using PaintDotNet.Camera; using PaintDotNet.Preview2; namespace PaintDotNet.ImageCollect { internal class CameraPreviewDialog : FloatingToolForm, IStageEvent { public bool o_use = false; // [原图取色]设置是否立刻生效 //private Bitmap m_bitmat; ////private Mat m_mat; // [区域选择]白平衡结果存储 public bool m_use = false; // [区域选择]设置是否立刻生效(,设置到相机) public Point m_startP; //画框的起始点 private bool m_blnDraw = false; private Rectangle m_rect;//初始设置一个拖拽的显示框 SolidBrush m_brush = new SolidBrush(Color.Black); int m_handle = 0; public bool isLeave = false;//鼠标是否离开窗体 public static CameraPreviewDialog cameraPreviewDialog; private AppWorkspace appWorkspace; public DocumentWorkspaceWindow documentWorkspace; private GroupBox groupBox2; private GroupBox groupBox3; private GroupBox groupBox4; private ProgressBar progressBar1; private Button btnRestStep; public ComboBox comboBox1; private Panel panel1; private Panel panel2; private GroupBox groupBox1; private Panel panel3; private BaseActionsStrip baseActionsStrip; private ShootActionsStrip shootActionsStrip; private TheoreticalScaleStrip theoreticalScaleStrip; //private Mat m_mat; public static Mat m_matClone; public static Mat m_matOrig; private Document document; private ComboBox cmbConfigs; private Button btnConfigDel; private TextBox gainNumbertxt; private string picturePath = Application.StartupPath + "\\Picture\\"; /// /// 显示图像 /// private ICamera m_camera => CameraManager.CurrentCamera; /// /// 窗口标题 /// public string DailogTitle { get; } private CameraParamModel m_cameraParamModel; private CameraConfigs m_cameraConfig; private AxisController m_Stage; PropertiesSettingDialog fmSetting; private bool maxAndMinButtonEnable = false;//最大最小按钮点击状态 private bool bestButtonEnable = false;//最佳按钮点击状态 private bool gamma45ButtonEnable = false;//伽马45按钮点击状态 private int trackBar1Value = -50;//亮度 private int trackBar2Value = 100;//对比度 private int trackBar3Value = 100;//gamma值 private bool underexposedButtonEnable = false;//曝光不足按钮点击状态 private bool overexposedButton = false;//过曝光按钮点击状态 private double micronRatio;//每像素多少微米 private CheckBox checkBox1; private bool isFitToWindow = false;//辅助判断当前尺寸是否为适应大小 private TheoreticalScaleDialog theoreticalScaleDialog;//理论比例尺窗口 private Dictionary micRulersDictonary;//标尺下拉菜单绑定数据 private BindingSource bs;//绑定combobox的数据源 private System.Windows.Forms.Timer tmrUpdate; private System.ComponentModel.IContainer components; private Panel panelZ; private Label lblZPos; private Button btnZClear; private Button btuZDown; private Button btnZUp; private NumericUpDown numZLen; /// /// 预览属性 /// // ScriptEditDialog histogramDialog; //public bool comboBox_Change = false; public string comboBox_Value = string.Empty; public CameraPreviewDialog(AppWorkspace appWorkspace) { cameraPreviewDialog = this; this.DoubleBuffered = true;//设置本窗体 SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲 this.appWorkspace = appWorkspace; this.appWorkspace.cameraPreviewDialog = this; DailogTitle = PdnResources.GetString("Menu.ImageCollection.PreviewExtraction.Text"); this.Text = DailogTitle; //this.FormBorderStyle = FormBorderStyle.FixedSingle; this.MinimizeBox = false; this.MaximizeBox = true; m_cameraParamModel = Startup.instance.cameraParamModel; m_cameraConfig = CameraConfigs.GetInstance(); CameraManager.FrameCallback += CallbackDraw; // BIN //m_camera.BinningSum = m_cameraParamModel.parame.BinningSumation; InitStage(); InitializeComponent(); InitializeLanguageText(); InitializeBaseTool(); InitializeShootTool(); InitializeTheoreticalScaleStripTool(); // 加载配置文件列表 initCmbConfigs(); InitializeImage(); // 分辨率 非2448 * 2048的时, ROI在StartWaitForFrame后设置 if (m_camera.ResolutionId != 0) { } this.Resize += new EventHandler(Form_Resize); BindingRule(); getRulerMicronRatio();//计算每像素多少微米 this.MinimumSize = new System.Drawing.Size(748, 656);//设置窗口最小尺寸 comboBox_Value = comboBox1.Text;//获取下拉值 CurrentImage = () => { return BitmapConverter.ToBitmap(m_matClone); }; } private void InitStage() { try { m_Stage = AxisController.GetInstance(); m_Stage.AddApp(this); } catch { } } /// /// 绑定标尺 /// public void BindingRule() { this.comboBox1.Items.Clear(); //绑定标尺下拉菜单 List list = Startup.instance.mic_rulersAll; string rulerName = ""; if (list != null) { for (int ruleI = 0; ruleI < list.Count; ruleI++) { mic_rulers rule = list[ruleI]; int rulid = rule.id; if (rulid == Startup.instance.configModel.RulerId) { rulerName = rule.ruler_name; } this.comboBox1.Items.Add(rule.ruler_name); } } for (int i = 0; i < this.comboBox1.Items.Count; i++) { if (rulerName.Equals(this.comboBox1.Items[i].ToString())) { this.comboBox1.SelectedIndex = i; } } } /// /// 加载数据 /// public void InitializeData() { m_cameraParamModel = Startup.instance.cameraParamModel; m_cameraConfig.CameraParamInit(); } /// /// 加载配置文件列表 /// public void initCmbConfigs() { string selected = ""; this.cmbConfigs.Items.Clear(); List fileNames = CameraConfigs.GetInstance().GetAllConfigFiles(); foreach (string fileName in fileNames) { this.cmbConfigs.Items.Add(fileName); if (fileName.Equals(CameraConfigs.GetInstance().CurrentConfigFileName)) { selected = fileName; } } if (selected.Equals("") && fileNames.Count > 0) { selected = fileNames[0]; } this.cmbConfigs.SelectedItem = selected; } /// /// 修改配置文件列表 /// public void UpdateCmbConfigs() { string selected = ""; List fileNames = CameraConfigs.GetInstance().GetAllConfigFiles(); if (fileNames.Count == cmbConfigs.Items.Count) return; this.cmbConfigs.Items.Clear(); foreach (string fileName in fileNames) { this.cmbConfigs.Items.Add(fileName); if (fileName.Equals(CameraConfigs.GetInstance().CurrentConfigFileName)) { selected = fileName; } } if (selected.Equals("") && fileNames.Count > 0) { selected = fileNames[0]; } this.cmbConfigs.SelectedItem = selected; } private void InitializeLanguageText() { this.groupBox1.Text = PdnResources.GetString("Menu.Preview.text"); this.groupBox2.Text = PdnResources.GetString("Menu.operation.text"); this.groupBox3.Text = PdnResources.GetString("Menu.Ruler.text"); this.checkBox1.Text = PdnResources.GetString("Menu.imagecapture.Previewwindow.Shootingruler.text"); this.groupBox4.Text = PdnResources.GetString("Menu.ImageCollection.CameraSetting.Text"); this.btnRestStep.Text = PdnResources.GetString("Menu.reset.Text"); } /// /// 实例化预览窗口同期组件 /// public void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.panel2 = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.panelZ = new System.Windows.Forms.Panel(); this.lblZPos = new System.Windows.Forms.Label(); this.btnZClear = new System.Windows.Forms.Button(); this.btuZDown = new System.Windows.Forms.Button(); this.btnZUp = new System.Windows.Forms.Button(); this.numZLen = new System.Windows.Forms.NumericUpDown(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.panel3 = new System.Windows.Forms.Panel(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.btnConfigDel = new System.Windows.Forms.Button(); this.cmbConfigs = new System.Windows.Forms.ComboBox(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.btnRestStep = new System.Windows.Forms.Button(); this.tmrUpdate = new System.Windows.Forms.Timer(this.components); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.panelZ.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numZLen)).BeginInit(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.panel2); this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Location = new System.Drawing.Point(13, 13); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(707, 441); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "预览"; // // panel2 // this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel2.Location = new System.Drawing.Point(7, 21); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(684, 368); this.panel2.TabIndex = 2; // // panel1 // this.panel1.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.panel1.Location = new System.Drawing.Point(7, 395); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(684, 40); this.panel1.TabIndex = 1; // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.panelZ); this.groupBox2.Location = new System.Drawing.Point(13, 460); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(707, 55); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.groupBox2.Text = "操作"; // // panelZ // this.panelZ.Controls.Add(this.lblZPos); this.panelZ.Controls.Add(this.btnZClear); this.panelZ.Controls.Add(this.btuZDown); this.panelZ.Controls.Add(this.btnZUp); this.panelZ.Controls.Add(this.numZLen); this.panelZ.Dock = System.Windows.Forms.DockStyle.Right; this.panelZ.Location = new System.Drawing.Point(510, 17); this.panelZ.Name = "panelZ"; this.panelZ.Size = new System.Drawing.Size(194, 35); this.panelZ.TabIndex = 0; this.panelZ.Visible = false; // // lblZPos // this.lblZPos.BackColor = System.Drawing.SystemColors.ButtonHighlight; this.lblZPos.Dock = System.Windows.Forms.DockStyle.Fill; this.lblZPos.Location = new System.Drawing.Point(132, 0); this.lblZPos.Name = "lblZPos"; this.lblZPos.Size = new System.Drawing.Size(62, 35); this.lblZPos.TabIndex = 3; this.lblZPos.Text = "0000"; this.lblZPos.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btnZClear // this.btnZClear.Dock = System.Windows.Forms.DockStyle.Left; this.btnZClear.Location = new System.Drawing.Point(100, 0); this.btnZClear.Name = "btnZClear"; this.btnZClear.Size = new System.Drawing.Size(32, 35); this.btnZClear.TabIndex = 2; this.btnZClear.Text = "C"; this.btnZClear.UseVisualStyleBackColor = true; this.btnZClear.Click += new System.EventHandler(this.btnZClear_Click); // // btuZDown // this.btuZDown.Dock = System.Windows.Forms.DockStyle.Left; this.btuZDown.Location = new System.Drawing.Point(68, 0); this.btuZDown.Name = "btuZDown"; this.btuZDown.Size = new System.Drawing.Size(32, 35); this.btuZDown.TabIndex = 1; this.btuZDown.Text = "↓"; this.btuZDown.UseVisualStyleBackColor = true; this.btuZDown.Click += new System.EventHandler(this.btuZDown_Click); // // btnZUp // this.btnZUp.Dock = System.Windows.Forms.DockStyle.Left; this.btnZUp.Location = new System.Drawing.Point(38, 0); this.btnZUp.Name = "btnZUp"; this.btnZUp.Size = new System.Drawing.Size(30, 35); this.btnZUp.TabIndex = 0; this.btnZUp.Text = "↑"; this.btnZUp.UseVisualStyleBackColor = true; this.btnZUp.Click += new System.EventHandler(this.btnZUp_Click); // // numZLen // this.numZLen.Dock = System.Windows.Forms.DockStyle.Left; this.numZLen.Font = new System.Drawing.Font("Calibri", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.numZLen.Location = new System.Drawing.Point(0, 0); this.numZLen.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numZLen.Name = "numZLen"; this.numZLen.Size = new System.Drawing.Size(38, 25); this.numZLen.TabIndex = 4; this.numZLen.Value = new decimal(new int[] { 1, 0, 0, 0}); // // groupBox3 // this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox3.Controls.Add(this.panel3); this.groupBox3.Controls.Add(this.checkBox1); this.groupBox3.Controls.Add(this.comboBox1); this.groupBox3.Location = new System.Drawing.Point(13, 522); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(441, 55); this.groupBox3.TabIndex = 3; this.groupBox3.TabStop = false; this.groupBox3.Text = "标尺"; // // panel3 // this.panel3.BackColor = System.Drawing.Color.Transparent; this.panel3.Location = new System.Drawing.Point(290, 19); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(111, 24); this.panel3.TabIndex = 2; // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(192, 24); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(15, 14); this.checkBox1.TabIndex = 1; this.checkBox1.UseVisualStyleBackColor = true; this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click); // // comboBox1 // this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(7, 21); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(152, 20); this.comboBox1.TabIndex = 0; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); this.comboBox1.SelectionChangeCommitted += new System.EventHandler(this.comboBox1_SelectionChangeCommitted); // // groupBox4 // this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.groupBox4.Controls.Add(this.btnConfigDel); this.groupBox4.Controls.Add(this.cmbConfigs); this.groupBox4.Location = new System.Drawing.Point(460, 522); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(260, 55); this.groupBox4.TabIndex = 4; this.groupBox4.TabStop = false; this.groupBox4.Text = "相机设置"; // // btnConfigDel // this.btnConfigDel.Location = new System.Drawing.Point(213, 20); this.btnConfigDel.Margin = new System.Windows.Forms.Padding(2); this.btnConfigDel.Name = "btnConfigDel"; this.btnConfigDel.Size = new System.Drawing.Size(31, 18); this.btnConfigDel.TabIndex = 1; this.btnConfigDel.Text = "Del"; this.btnConfigDel.UseVisualStyleBackColor = true; this.btnConfigDel.Click += new System.EventHandler(this.btnConfigDel_Click); // // cmbConfigs // this.cmbConfigs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbConfigs.FormattingEnabled = true; this.cmbConfigs.Location = new System.Drawing.Point(10, 21); this.cmbConfigs.Margin = new System.Windows.Forms.Padding(2); this.cmbConfigs.Name = "cmbConfigs"; this.cmbConfigs.Size = new System.Drawing.Size(185, 20); this.cmbConfigs.TabIndex = 0; this.cmbConfigs.SelectedIndexChanged += new System.EventHandler(this.cmbConfigs_SelectedIndexChanged); // // progressBar1 // this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar1.Location = new System.Drawing.Point(13, 584); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(641, 23); this.progressBar1.TabIndex = 5; // // btnRestStep // this.btnRestStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnRestStep.Location = new System.Drawing.Point(661, 584); this.btnRestStep.Name = "btnRestStep"; this.btnRestStep.Size = new System.Drawing.Size(59, 23); this.btnRestStep.TabIndex = 6; this.btnRestStep.Text = "复位"; this.btnRestStep.UseVisualStyleBackColor = true; this.btnRestStep.Click += new System.EventHandler(this.btnRestStep_Click); // // tmrUpdate // this.tmrUpdate.Interval = 1000; this.tmrUpdate.Tick += new System.EventHandler(this.tmrUpdate_Tick); // // CameraPreviewDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.ClientSize = new System.Drawing.Size(732, 618); this.Controls.Add(this.btnRestStep); this.Controls.Add(this.progressBar1); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "CameraPreviewDialog"; this.Activated += new System.EventHandler(this.CameraPreviewDialog_Activated); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CameraPreviewDialog_FormClosing); this.Load += new System.EventHandler(this.CameraPreviewDialog_Load); this.Controls.SetChildIndex(this.groupBox1, 0); this.Controls.SetChildIndex(this.groupBox2, 0); this.Controls.SetChildIndex(this.groupBox3, 0); this.Controls.SetChildIndex(this.groupBox4, 0); this.Controls.SetChildIndex(this.progressBar1, 0); this.Controls.SetChildIndex(this.btnRestStep, 0); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.panelZ.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numZLen)).EndInit(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.ResumeLayout(false); } public void InitializeImage() { m_rect = new Rectangle(); this.documentWorkspace = new DocumentWorkspaceWindow(appWorkspace); this.documentWorkspace.panel.MouseDown += DocumentWorkspace_MouseDown; this.documentWorkspace.panel.MouseMove += PictureBox1_MouseMove; this.documentWorkspace.panel.MouseUp += PictureBox1_MouseUp; this.documentWorkspace.panel.Paint += Panel_Paint; this.documentWorkspace.refueshZoomTrackValue = false; Bitmap bitmap = new Bitmap(m_cameraParamModel.parame.previewRectW, m_cameraParamModel.parame.previewRectH); document = Document.FromImage(bitmap); //if (bitmap.Width > 3 && bitmap.Height > 3) //{ // m_rect.X = Math.Min(10, bitmap.Width / 2 - 1); // m_rect.Y = Math.Min(10, bitmap.Height / 2 - 1); // m_rect.Width = bitmap.Width - 2 * m_rect.X; // m_rect.Height = bitmap.Height - 2 * m_rect.Y; // Console.WriteLine(m_rect); //} //else { m_rect.X = 0; m_rect.Y = 0; m_rect.Width = 0; m_rect.Height = 0; } //this.documentWorkspace.AppWorkspaceTop = this.appWorkspace; //this.documentWorkspace.Visible = true; //this.documentWorkspace.PanelBottom.Visible = false; this.documentWorkspace.Dock = DockStyle.Fill; //this.documentWorkspace.RulersEnabled = true; this.panel2.Controls.Add(this.documentWorkspace); this.documentWorkspace.Document = document; this.documentWorkspace.ScaleFactorChanged += new EventHandler(DocumentWorkspace_ScaleFactorChanged); if (this.documentWorkspace.oldDrawTreeView == null && MeasureListDialog.drawNodes != null) { this.documentWorkspace.oldDrawTreeView = MeasureListDialog.drawNodes; //this.documentWorkspace.previewMeasure = true; this.documentWorkspace.rules = Startup.instance.rules; } } private void Panel_Paint(object sender, PaintEventArgs e) { if (m_use && documentWorkspace.CompositionSurface.Width != 0 && documentWorkspace.CompositionSurface.Height != 0) { if (m_rect.Width > 0 && m_rect.Height > 0) { // // 以下是计算绘制图片的位置和大小并绘制图片 // Rectangle rc = this.documentWorkspace.panel.ClientRectangle; int width = (int)(this.documentWorkspace.CompositionSurface.Width * this.documentWorkspace.ScaleFactor.Ratio); int height = (int)(this.documentWorkspace.CompositionSurface.Height * this.documentWorkspace.ScaleFactor.Ratio); int x = (rc.Width < width) ? this.documentWorkspace.panel.AutoScrollPosition.X : (rc.Width - width) / 2; int y = (rc.Height < height) ? this.documentWorkspace.panel.AutoScrollPosition.Y : (rc.Height - height) / 2; //if (m_mat != null) //{ // oldMPatch.Dispose(); // oldMPatch = m_mat; //} //m_mat = new Data.Action.Action5012().PerformProcess(PaintDotNet.Camera.Tools.ToMat(m_bitmap).Clone(new Rect(m_rect.X, m_rect.Y, m_rect.Width, m_rect.Height))); //// //// 以下是绘制网格、标注、测量、视场等开始 //// e.Graphics.TranslateTransform(x, y); e.Graphics.ScaleTransform((float)this.documentWorkspace.ScaleFactor.Ratio, (float)this.documentWorkspace.ScaleFactor.Ratio); //if (m_bitmat != null) //{ // e.Graphics.DrawImage(m_bitmat, m_rect.X, m_rect.Y, m_rect.Width, m_rect.Height); //} if (!m_blnDraw) { e.Graphics.DrawRectangle(new Pen(Color.Black/*Red*/, 2), m_rect);//重新绘制颜色为红色 for (int i = 1; i <= 8; i++) { e.Graphics.FillRectangle(m_brush, GetHandleRectangle(i)); } } e.Graphics.ScaleTransform(1 / (float)this.documentWorkspace.ScaleFactor.Ratio, 1 / (float)this.documentWorkspace.ScaleFactor.Ratio); e.Graphics.TranslateTransform(-x, -y); } } else { m_rect.Width = 0; m_rect.Height = 0; } } private void DocumentWorkspace_MouseDown(object sender, MouseEventArgs e) { if (!m_use && !o_use) return; // 换算后的点 Point point1 = documentWorkspace.GetScalePoint(e.Location);//PointF m_handle = HitTest(point1); if (m_handle < 0) { if (m_rect.Contains(point1))//判断鼠标按下的坐标是否在红框中,确定是否拖动的红框 { m_handle = 9; } } this.Cursor = GetHandleCursor(m_handle); m_startP = point1; Invalidate(); m_blnDraw = true; } private void PictureBox1_MouseMove(object sender, MouseEventArgs e) { if (!m_use) return; if (m_handle > 0 ||/*&&*/ m_blnDraw) { if (e.Button != MouseButtons.Left)//判断是否按下左键 return; MoveHandleTo(documentWorkspace.GetScalePoint(e.Location), m_handle); } } private void PictureBox1_MouseUp(object sender, MouseEventArgs e) { if (!m_use) return; m_blnDraw = false; //结束绘制 this.Cursor = Cursors.Default; SetROI(); this.documentWorkspace/*pictureBox1*/.Refresh(); } private void SetROI() { if (m_use) { //m_camera.SetROI(ref m_targetX, ref m_targetY, ref m_targetWidth, ref m_targetHeight); //this.m_cameraParamModel.parame.previewRectX = m_targetX; //this.m_cameraParamModel.parame.previewRectY = m_targetY; //this.m_cameraParamModel.parame.previewRectW = m_targetWidth; //this.m_cameraParamModel.parame.previewRectH = m_targetHeight; } } public Rectangle GetHandleRectangle(int handleNumber) { Point point = GetHandle(handleNumber); return new Rectangle(point.X - 4, point.Y - 4, 8, 8); } public int HitTest(Point point) { for (int i = 1; i <= 8; i++) { if (GetHandleRectangle(i).Contains(point)) return i; } return -1; } public Point GetHandle(int handleNumber) { int x, y, xCenter, yCenter; xCenter = m_rect.X + m_rect.Width / 2; yCenter = m_rect.Y + m_rect.Height / 2; x = m_rect.X; y = m_rect.Y; switch (handleNumber) { case 1: x = m_rect.X; y = m_rect.Y; break; case 2: x = xCenter; y = m_rect.Y; break; case 3: x = m_rect.Right; y = m_rect.Y; break; case 4: x = m_rect.Right; y = yCenter; break; case 5: x = m_rect.Right; y = m_rect.Bottom; break; case 6: x = xCenter; y = m_rect.Bottom; break; case 7: x = m_rect.X; y = m_rect.Bottom; break; case 8: x = m_rect.X; y = yCenter; break; } return new Point(x, y); } public Cursor GetHandleCursor(int handleNumber) { switch (handleNumber) { case 1: return Cursors.SizeNWSE; case 2: return Cursors.SizeNS; case 3: return Cursors.SizeNESW; case 4: return Cursors.SizeWE; case 5: return Cursors.SizeNWSE; case 6: return Cursors.SizeNS; case 7: return Cursors.SizeNESW; case 8: return Cursors.SizeWE; default: return Cursors.Default; } } public void MoveHandleTo(Point point, int handleNumber) { if (point.X > this.documentWorkspace.CompositionSurface/*pictureBox1*/.Width) { point.X = documentWorkspace.CompositionSurface/*pictureBox1*/.Width; } if (point.X < 0) { point.X = 0; } if (point.Y < 0) { point.Y = 0; } if (point.Y > documentWorkspace.CompositionSurface/*pictureBox1*/.Height) { point.Y = documentWorkspace.CompositionSurface/*pictureBox1*/.Height; } Point point1 = new Point(m_startP.X, m_startP.Y); if (point1.X > this.documentWorkspace.CompositionSurface/*pictureBox1*/.Width) { point1.X = documentWorkspace.CompositionSurface/*pictureBox1*/.Width; } if (point1.X < 0) { point1.X = 0; } if (point1.Y < 0) { point1.Y = 0; } if (point1.Y > documentWorkspace.CompositionSurface/*pictureBox1*/.Height) { point1.Y = documentWorkspace.CompositionSurface/*pictureBox1*/.Height; } m_rect.X = Math.Min(point.X, point1.X); m_rect.Y = Math.Min(point.Y, point1.Y); m_rect.Width = Math.Abs(point.X - point1.X); m_rect.Height = Math.Abs(point.Y - point1.Y); return; } /// /// 接收相机frame /// /// /// public void CallbackDraw(Bitmap bitmap) { //add begin by songxk if (bitmap == null) return; //add end by songxk try { var mat = PaintDotNet.Camera.Tools.ToMat(bitmap); m_matClone = mat.Clone(); if (!this.IsShown) { return; } if (fmSetting != null) { m_matOrig = mat.Clone(); try { trackBar1Value = fmSetting.displayCameraControl.trackBar1Value; trackBar2Value = fmSetting.displayCameraControl.trackBar2Value; trackBar3Value = fmSetting.displayCameraControl.trackBar3Value; } catch (Exception e) { System.Console.WriteLine("nullException can be catched here:" + e.Message); } } if (trackBar1Value != -50 || trackBar2Value != 100 || trackBar3Value != 100) { mat = PaintDotNet.Setting.LabelComponent.DisplayCameraControl.scrollMethod(mat, (trackBar1Value / 100.0).ToString("f2"), (trackBar2Value / 100.0).ToString("f2"), (trackBar3Value / 100.0).ToString("f2")); } else if (bestButtonEnable || maxAndMinButtonEnable || gamma45ButtonEnable) { if (bestButtonEnable)//最佳 mat = AdjustIntent.CalHistMethod(mat, 1, gamma45ButtonEnable); if (maxAndMinButtonEnable)//最大最小 mat = AdjustIntent.CalHistMethod(mat, 2, gamma45ButtonEnable); if (!bestButtonEnable && !maxAndMinButtonEnable)//仅伽马0.45 mat = AdjustIntent.CalHistMethod(mat, 0, gamma45ButtonEnable); } if (underexposedButtonEnable)//曝光不足 mat = ExposedIntent.UnderExposed(mat, 30, 0.5f); if (overexposedButton)//过曝光 mat = ExposedIntent.OverExposed(mat, 225, 0.5f); //17461 if (m_cameraParamModel.parame.ShadingCorrection == 1)//阴影矫正 mat = AdjustIntent.ShadingCorrection(mat); ShowFrameThreadEntry(mat); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private void ShowFrameThreadEntry(Mat matClone) { try { Bitmap m_bitmap = BitmapConverter.ToBitmap(matClone); if (o_use && m_startP.X >= 0 && m_startP.Y >= 0) { int x = m_startP.X; int y = m_startP.Y; if (x >= 0 && y >= 0 && x < m_bitmap.Width && y < m_bitmap.Height) { OpenCvSharp.Mat srt = PaintDotNet.Camera.Tools.ToMat(m_bitmap); OpenCvSharp.Vec3b bgr = srt.At(y, x); Color color = Color.FromArgb(bgr[2], bgr[1], bgr[0]); /// /// 当前处理的程序 /// Data.Param.ParamObject action = new Data.Action.Action5012(); //重新初始化选项列表 Base.Args args = action.Lists[0]; args.value = 3; for (int j = 0; j < args.choiseList.Count; j++) { Data.Param.BooleanObject argsChoise = args.choiseList[j] as Data.Param.BooleanObject; if (argsChoise.Lists.Count > 0) { Data.Param.ColorNumber phaseColor = argsChoise.Lists[0] as Data.Param.ColorNumber; if (phaseColor.Key.Equals("imageColor"))//原图取色 { phaseColor.Value = color.ToArgb();// this.panel3.BackColor.ToArgb(); } } } OpenCvSharp.Mat mat = action.PerformProcess(srt); //string filename2 = "E:\\show1" + (misshow++) + ".jpg"; //Cv2.ImWrite(filename2, mat); this.documentWorkspace.Document = Document.FromMat(srt); ; } } else if (m_use && m_rect.Width > 0 && m_rect.Height > 0) { Mat m_mat = new Data.Action.Action5012().PerformProcess(matClone.Clone(new Rect(m_rect.X, m_rect.Y, m_rect.Width, m_rect.Height))); //复制用户选中的区域到原图像 //Mat mask0 = m_matClone.CvtColor(ColorConversionCodes.RGBA2GRAY); Mat pos0 = new Mat(matClone, new Rect(m_rect.X, m_rect.Y, m_rect.Width, m_rect.Height)); m_mat.CopyTo(pos0, m_mat); this.documentWorkspace.Document = Document.FromImage(BitmapConverter.ToBitmap(matClone)); m_mat.Dispose(); } else this.documentWorkspace.Document = Document.FromMat(matClone/*BitmapConverter.ToBitmap(m_matClone)*/); if (fmSetting != null && m_matOrig != null) { this.BeginInvoke(new Action(() => { fmSetting?.resetMat(m_matOrig); })); } } catch (Exception) { } } /// /// 初始化基础工具 /// public void InitializeBaseTool() { this.baseActionsStrip = new BaseActionsStrip(); //十字线按钮点击 this.baseActionsStrip.crossButton.Click += new System.EventHandler(this.crossButton_Click); //网格按钮点击 this.baseActionsStrip.gridButton.Click += new System.EventHandler(this.gridButton_Click); //方形按钮点击 this.baseActionsStrip.squareButton.Click += new System.EventHandler(this.squareButton_Click); //圆形按钮点击 this.baseActionsStrip.roundButton.Click += new System.EventHandler(this.roundButton_Click); //实际大小按钮点击 this.baseActionsStrip.actualSizeButton.Click += new System.EventHandler(this.actualSizeButton_Click); //合适大小按钮点击 this.baseActionsStrip.zoomToWindowButton.Click += new System.EventHandler(this.zoomToWindowButton_Click); //全屏按钮点击 this.baseActionsStrip.fullScreenButton.Click += new System.EventHandler(this.fullScreenButton_Click); //缩小按钮点击 this.baseActionsStrip.zoomOutButton.Click += new System.EventHandler(this.zoomOutButton_Click); //放大按钮点击 this.baseActionsStrip.zoomInButton.Click += new System.EventHandler(this.zoomInButton_Click); this.baseActionsStrip.GripStyle = ToolStripGripStyle.Hidden; this.baseActionsStrip.Dock = DockStyle.None; this.baseActionsStrip.Location = new System.Drawing.Point(136, 0); this.panel1.Controls.Add(baseActionsStrip); this.gainNumbertxt = new TextBox(); this.gainNumbertxt.Location = new System.Drawing.Point(554, 8); this.gainNumbertxt.Size = new System.Drawing.Size(62, 22); this.gainNumbertxt.Anchor = AnchorStyles.Left; this.gainNumbertxt.Text = PdnResources.GetString("Menu.nothing.Text"); this.gainNumbertxt.ReadOnly = true; this.panel1.Controls.Add(this.gainNumbertxt); } /// /// 初始化快捷工具 /// public void InitializeShootTool() { this.shootActionsStrip = new ShootActionsStrip(); //拍摄按钮点击 this.shootActionsStrip.shootButton.Click += new System.EventHandler(this.camera_Click); //单次拍摄按钮点击 this.shootActionsStrip.aloneShootButton.Click += new System.EventHandler(this.aloneShootButton_Click); //速度按钮点击 this.shootActionsStrip.speedButton.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(CopyDetail_DropDownItemClicked); //曝光时间点击事件 this.shootActionsStrip.exposureTimeButton.Click += new System.EventHandler(this.exposureTimeButton_Click); //白平衡点击事件 this.shootActionsStrip.whiteBalanceButton.Click += new System.EventHandler(this.whiteBalance_Click); //最佳点击事件 this.shootActionsStrip.bestButton.Click += new System.EventHandler(this.bestButton_Click); //最小最大点击事件 this.shootActionsStrip.maxAndMinButton.Click += new System.EventHandler(this.maxAndMinButton_Click); //原始状态事件 this.shootActionsStrip.originalStateButton.Click += new System.EventHandler(this.originalStateButton_Click); //伽马0.45事件 this.shootActionsStrip.gamma45Button.Click += new System.EventHandler(this.gamma45Button_Click); //曝光不足事件 this.shootActionsStrip.underexposedButton.Click += new System.EventHandler(this.underexposedButton_Click); //过曝光事件 this.shootActionsStrip.overexposedButton.Click += new System.EventHandler(this.overexposedButton_Click); //预览属性事件 this.shootActionsStrip.propertiesButton.Click += new System.EventHandler(this.propertiesButton_Click); //自动聚焦事件 this.shootActionsStrip.autoFocusButton.Click += new System.EventHandler(this.autoFocusButton_Click); this.shootActionsStrip.GripStyle = ToolStripGripStyle.Hidden; shootActionsStrip.Dock = DockStyle.Fill; this.groupBox2.Controls.Add(this.shootActionsStrip); } /// /// 理论比例尺初始化 /// private void InitializeTheoreticalScaleStripTool() { this.theoreticalScaleStrip = new TheoreticalScaleStrip(); this.theoreticalScaleStrip.theoreticalScaleButton.Click += new System.EventHandler(this.theoreticalScaleButton_Click); this.theoreticalScaleStrip.GripStyle = ToolStripGripStyle.Hidden; this.theoreticalScaleStrip.Dock = DockStyle.None; this.theoreticalScaleStrip.BackColor = Color.Transparent; this.panel3.Controls.Add(theoreticalScaleStrip); } /// /// 拍照按钮被点击 /// /// /// public void camera_Click(object sender, EventArgs e) { Capture1(); } /// /// 单次拍摄被点击 /// /// /// public void aloneShootButton_Click(object sender, EventArgs e) { Capture1(); this.Close(); } public void Capture1() { var bitmap = documentWorkspace.CompositionSurface.CreateAliasedBitmap(); var mode = Startup.instance.configModel.CaptureSaveMode; var r = appWorkspace.DisplayShoot(bitmap, this.documentWorkspace.GraphicsList, checkBox1.Checked, mode); if (!r) return; } /// /// 白平衡点击 /// /// /// public void whiteBalance_Click(object sender, EventArgs e) { m_camera.WhiteBalanceMode = 2; } /// /// 速度点击 /// void CopyDetail_DropDownItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e) { foreach (ToolStripMenuItem item in shootActionsStrip.speedButton.DropDownItems) { if (item.Name != e.ClickedItem.Name) { item.Checked = false; } else { item.Checked = true; this.shootActionsStrip.speedButton.Text = e.ClickedItem.Text; } } } /// /// 曝光时间被点击 /// /// /// public void exposureTimeButton_Click(object sender, EventArgs e) { m_camera.AutoExposure = 1; } /// /// 最佳被点击 /// /// /// public void bestButton_Click(object sender, EventArgs e) { if (this.shootActionsStrip == null || this.shootActionsStrip.bestButton == null) return; // TUCamAPI.TUCAM_Capa_SetValue(m5pro.m_opCamList[m5pro.m_indexCam].hIdxTUCam, (int)TUCAM_IDCAPA.TUIDC_ATEXPOSURE_MODE, 0); // TUCamAPI.TUCAM_Prop_SetValue(m5pro.m_opCamList[m5pro.m_indexCam].hIdxTUCam, (int)TUCAM_IDPROP.TUIDP_EXPOSURETM, (double)(20000000 / 1000.0f), 0); //MessageBox.Show("临时调整曝光时长为20000000us"); bestButtonEnable = !bestButtonEnable; var button = this.shootActionsStrip.bestButton; button.Checked = !button.Checked; if (maxAndMinButtonEnable) { maxAndMinButtonEnable = !maxAndMinButtonEnable; this.shootActionsStrip.maxAndMinButton.Checked = false; } } /// /// 最大最小被点击 /// /// /// public void maxAndMinButton_Click(object sender, EventArgs e) { if (this.shootActionsStrip == null || this.shootActionsStrip.maxAndMinButton == null) return; // TUCamAPI.TUCAM_Capa_SetValue(m5pro.m_opCamList[m5pro.m_indexCam].hIdxTUCam, (int)TUCAM_IDCAPA.TUIDC_ATWBALANCE, 0); // TUCamAPI.TUCAM_Prop_SetValue(m5pro.m_opCamList[m5pro.m_indexCam].hIdxTUCam, (int)TUCAM_IDPROP.TUIDP_CHNLGAIN, 1220.0, 2); //MessageBox.Show("最大最小被点击临时变绿色"); maxAndMinButtonEnable = !maxAndMinButtonEnable; var button = this.shootActionsStrip.maxAndMinButton; button.Checked = !button.Checked; if (bestButtonEnable) { bestButtonEnable = !bestButtonEnable; this.shootActionsStrip.bestButton.Checked = false; } } /// /// 原始状态被点击 /// /// /// public void originalStateButton_Click(object sender, EventArgs e) { if (this.shootActionsStrip == null || this.shootActionsStrip.originalStateButton == null)//1012###19464 return; bestButtonEnable = false; maxAndMinButtonEnable = false; gamma45ButtonEnable = false; this.shootActionsStrip.bestButton.Checked = false; this.shootActionsStrip.maxAndMinButton.Checked = false; this.shootActionsStrip.gamma45Button.Checked = false; } /// /// 伽马0.45被点击 /// /// /// public void gamma45Button_Click(object sender, EventArgs e) { if (this.shootActionsStrip == null || this.shootActionsStrip.gamma45Button == null) return; gamma45ButtonEnable = !gamma45ButtonEnable; var button = this.shootActionsStrip.gamma45Button; button.Checked = !button.Checked; } /// /// 曝光不足被点击 /// /// /// public void underexposedButton_Click(object sender, EventArgs e) { underexposedButtonEnable = !underexposedButtonEnable; //if (overexposedButton) //{ // overexposedButton = !overexposedButton; // this.shootActionsStrip.overexposedButton.Checked = false; //} var button = (ToolStripButton)sender; button.Checked = !button.Checked; } /// /// 预览属性按钮被点击 /// /// /// public void propertiesButton_Click(object sender, EventArgs e) { Form form = Application.OpenForms["PropertiesSettingDialog"];//尝试获取已经弹出的窗口对象 if (form == null || form.IsDisposed) { if (fmSetting != null) { fmSetting.Dispose(); fmSetting = null; } form = null; fmSetting = new PropertiesSettingDialog(this); //最佳事件 fmSetting.displayCameraControl.button2.Click += new System.EventHandler(this.bestButton_Click); //最小最大点击事件 fmSetting.displayCameraControl.button3.Click += new System.EventHandler(this.maxAndMinButton_Click); //原始状态事件 fmSetting.displayCameraControl.button5.Click += new System.EventHandler(this.originalStateButton_Click); //伽马0.45事件 fmSetting.displayCameraControl.button4.Click += new System.EventHandler(this.gamma45Button_Click); fmSetting.FormClosing += Fm_FormClosing; //fm.ShowDialog(); FloatingFormMethod.ShowFloatForm(form, form == null ? fmSetting/*没有弹出的窗口对象则创建*/ : null, this.appWorkspace); } else { form.Activate(); form.WindowState = FormWindowState.Normal; } } private void Fm_FormClosing(object sender, FormClosingEventArgs e) { if (fmSetting != null)//0915###避免引起异常问题 { fmSetting.Dispose(); fmSetting = null; } } /// /// 过曝光被点击 /// /// /// public void overexposedButton_Click(object sender, EventArgs e) { overexposedButton = !overexposedButton; //if (underexposedButtonEnable) //{ // underexposedButtonEnable = !underexposedButtonEnable; // this.shootActionsStrip.underexposedButton.Checked = false; //} var button = (ToolStripButton)sender; button.Checked = !button.Checked; } /// /// 十字线按钮 /// /// /// public void crossButton_Click(object sender, EventArgs e) { if (this.documentWorkspace != null) { this.documentWorkspace.GridCrossCurveEnabled = !this.documentWorkspace.GridCrossCurveEnabled; this.documentWorkspace.Refresh(); var button = (ToolStripButton)sender; button.Checked = !button.Checked; } } /// /// 网格按钮 /// /// /// public void gridButton_Click(object sender, EventArgs e) { if (this.documentWorkspace != null) { this.documentWorkspace.GridLineEnabled = !this.documentWorkspace.GridLineEnabled; this.documentWorkspace.Refresh(); var button = (ToolStripButton)sender; button.Checked = !button.Checked; } } /// /// 方形按钮 /// /// /// public void squareButton_Click(object sender, EventArgs e) { if (this.documentWorkspace != null) { this.documentWorkspace.GridRectangleEnabled = !this.documentWorkspace.GridRectangleEnabled; this.documentWorkspace.Refresh(); var button = (ToolStripButton)sender; button.Checked = !button.Checked; } } /// /// 圆形按钮 /// /// /// public void roundButton_Click(object sender, EventArgs e) { if (this.documentWorkspace != null) { this.documentWorkspace.GridRoundEnabled = !this.documentWorkspace.GridRoundEnabled; this.documentWorkspace.Refresh(); var button = (ToolStripButton)sender; button.Checked = !button.Checked; } } /// /// 实际大小按钮 /// /// /// public void actualSizeButton_Click(object sender, EventArgs e) { if (this.documentWorkspace.CompositionSurface != null) { this.documentWorkspace.ZoomBasis = ZoomBasis.ScaleFactor; this.documentWorkspace.ScaleFactor = ScaleFactor.OneToOne; this.isFitToWindow = false; } } /// /// 合适大小按钮 /// /// /// public void zoomToWindowButton_Click(object sender, EventArgs e) { if (this.documentWorkspace.CompositionSurface != null) { this.documentWorkspace.ZoomToWindow(); this.isFitToWindow = true; } } /// /// 全屏显示按钮 /// /// /// public void fullScreenButton_Click(object sender, EventArgs e) { var button = (ToolStripButton)sender; if (this.WindowState == FormWindowState.Normal) { this.WindowState = FormWindowState.Maximized; button.Checked = true; } else { this.WindowState = FormWindowState.Normal; button.Checked = false; } if (isFitToWindow && this.documentWorkspace.CompositionSurface != null) this.documentWorkspace.ZoomToWindow(); this.Invalidate(); } /// /// 缩小按钮 /// /// /// public void zoomOutButton_Click(object sender, EventArgs e) { if (this.documentWorkspace.CompositionSurface != null) { this.documentWorkspace.ZoomOut(); } } /// /// 放大按钮 /// /// /// public void zoomInButton_Click(object sender, EventArgs e) { if (this.documentWorkspace.CompositionSurface != null) { this.documentWorkspace.ZoomIn(); } } private void CameraPreviewDialog_FormClosing(object sender, FormClosingEventArgs e) { AutoFocusWorkflow.Stop(); Thread.Sleep(50); Dispose(); ConfigModel.OnCameraNameExChanged -= OnNameChange; tmrUpdate.Enabled = false; } public new void Dispose() { //m_Stage.Close(); m_Stage.RemoveApp(this); CameraManager.FrameCallback -= CallbackDraw; if (m_matClone != null) { m_matClone.Dispose(); } if (fmSetting != null) fmSetting.Close(); if (this.documentWorkspace != null && !this.documentWorkspace.IsDisposed) this.documentWorkspace.Dispose(); if (this.document != null) this.document.Dispose(); base.Dispose(); GC.Collect(); } /// /// 判断颜色灰度值 如果是true 则设置为灰色 /// /// public void SetColorModel(bool isGray) { //m5pro.SetColorModel(isGray); } /// /// 选择相机设置 /// /// /// private void cmbConfigs_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; Startup.instance.cameraParamModel = m_cameraConfig.GetCameraParamModel(cb.SelectedItem.ToString()); m_cameraParamModel = Startup.instance.cameraParamModel; Startup.instance.configModel.CameraConfig = cb.SelectedItem.ToString(); string configXml = XmlSerializeHelper.XmlSerialize(Startup.instance.configModel); string filePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\Config.xml"; FileOperationHelper.WriteStringToFile(configXml, filePath, FileMode.Create); m_cameraConfig.CameraParamInit(); } /// /// 删除相机设置 /// /// /// private void btnConfigDel_Click(object sender, EventArgs e) { if (this.cmbConfigs.SelectedItem != null) { if (this.cmbConfigs.SelectedItem.ToString().Equals("CameraParam")) { MessageBox.Show(PdnResources.GetString("Menu.hedefaultconfiguratallowdeletion.Text"), PdnResources.GetString("Menu.ensure.text"), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } DialogResult result = MessageBox.Show(PdnResources.GetString("Menu.suredeletit.Text") + "?", PdnResources.GetString("Menu.Tips.text"), MessageBoxButtons.OKCancel); if (result == DialogResult.OK) { CameraConfigs.GetInstance().Delete(CameraConfigs.GetInstance().CurrentConfigFileName); initCmbConfigs(); } } } /// /// 用于修改全屏按钮状态 /// /// /// private void Form_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Normal) { baseActionsStrip.fullScreenButton.Checked = false; } else { baseActionsStrip.fullScreenButton.Checked = true; } if (isFitToWindow && this.documentWorkspace.CompositionSurface != null) this.documentWorkspace.ZoomToWindow(); this.Invalidate(); } /// /// 获取当前标尺并换算为微米 /// public void getRulerMicronRatio() { Startup.instance.rules.TryGetValue(MeasurementUnit.Micron, out this.micronRatio); this.documentWorkspace.MicronRatio = this.micronRatio; } /// /// 标尺下拉菜单选项改变 /// /// /// private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e) { //getRulerMicronRatio(); //this.documentWorkspace.Refresh(); } /// /// 理论比例尺按钮 /// /// /// public void theoreticalScaleButton_Click(object sender, EventArgs e) { if (theoreticalScaleDialog == null) { theoreticalScaleDialog = new TheoreticalScaleDialog(this.appWorkspace, MeasureActionMenu.ArrayList1, MeasureActionMenu.ArrayList2, MeasureActionMenu.ArrayList3); theoreticalScaleDialog.button7.Click += new EventHandler(button7_Click); //theoreticalScaleDialog.FormClosing += new FormClosingEventHandler(theoreticalScaleDialog_FormClosing); } theoreticalScaleDialog.StartPosition = FormStartPosition.CenterParent; theoreticalScaleDialog.ShowDialog(); } /// /// 理论比例尺窗口关闭 /// /// /// private void theoreticalScaleDialog_FormClosing(object sender, FormClosingEventArgs e) { int selectedNum = this.comboBox1.SelectedIndex; this.comboBox1.DataSource = null; bs = new BindingSource(); bs.DataSource = micRulersDictonary; this.comboBox1.DataSource = bs; this.comboBox1.DisplayMember = "Key"; this.comboBox1.ValueMember = "Value"; this.comboBox1.SelectedIndex = selectedNum; this.comboBox1.Refresh(); } /// /// 理论比例尺保存 /// /// /// private void button7_Click(object sender, EventArgs e) { } private double GrayHistogramArea(Bitmap bitmap) { Mat image = PaintDotNet.Camera.Tools.ToMat(bitmap); if (image.Channels() == 3) { Cv2.CvtColor(image, image, ColorConversionCodes.BGR2GRAY); } int[] list = new int[256]; var date = image.ToBytes(); foreach (int value in date) { list[value]++; } return 0; } public static Mat ToGrayMat(Bitmap bitmap) { Mat image = PaintDotNet.Camera.Tools.ToMat(bitmap); if (image.Channels() == 3) { Cv2.CvtColor(image, image, ColorConversionCodes.BGR2GRAY); } return image; } /// /// 高斯距离 /// /// public static double GaussianDiff(Mat im) { if (im.Channels() == 3) { Cv2.CvtColor(im, im, ColorConversionCodes.BGR2GRAY); } Mat blurred = new Mat(); Cv2.GaussianBlur(im, blurred, new OpenCvSharp.Size(7, 7), 1.66); Cv2.Absdiff(im, blurred, blurred); return Cv2.Mean(blurred)[0]; } public static double Sobel(Bitmap bitmap) { var graymat = ToGrayMat(bitmap); Mat imageSobel = new Mat(); Cv2.Sobel(graymat, imageSobel, 2, 1, 1); return Cv2.Mean(imageSobel)[0]; } /// /// 获取输入图片的清晰度 /// /// /// private static double getMeanValueOfBitmap(Bitmap bitmap) { Mat converted = PaintDotNet.Camera.Tools.ToMat(bitmap); Mat imageGrey = new Mat(); Mat imageSobel = new Mat(); try { Cv2.CvtColor(converted, imageGrey, ColorConversionCodes.RGB2GRAY); } catch (Exception) { imageGrey = converted; } Mat meanValueImage = new Mat(); Mat meanStdValueImage = new Mat(); //求灰度图像的标准差 值越大越好 OpenCvSharp.Cv2.MeanStdDev(imageGrey, meanValueImage, meanStdValueImage); return meanStdValueImage.At(0, 0); } #region AutoFocus private static bool _focusing; public static Func CurrentImage; private void autoFocusButton_Click(object sender, EventArgs e) { m_camera.AutoExposure = 0; _focusing = true; new Thread(new ThreadStart(() => { var result = AutoFocusWorkflow.AutoFocus(m_Stage, CurrentImage); if (string.IsNullOrEmpty(result)) { MessageBox.Show("聚焦成功"); } else { MessageBox.Show(result); } _focusing = false; })).Start(); } private void tmrUpdate_Tick(object sender, EventArgs e) { if (_focusing) progressBar1.Value = (int)(Math.Min(AutoFocusWorkflow.CurrentValue, progressBar1.Maximum)); else progressBar1.Value = 0; // setBarValue((int)m_MeanValue); } private static double m_resetStep1 = 0; private void btnRestStep_Click(object sender, EventArgs e) { if (_focusing) return; if (m_resetStep1 != 0) { m_Stage.UpTo(m_resetStep1); m_resetStep1 = 0; } } #endregion private void DocumentWorkspace_ScaleFactorChanged(object sender, EventArgs e) { this.gainNumbertxt.Text = Math.Round((this.documentWorkspace.ScaleRatio * 100), 2) + "%"; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (((ComboBox)sender).SelectedItem != null) { if (comboBox_Value != ((ComboBox)sender).SelectedItem.ToString()) { comboBox_Value = ((ComboBox)sender).SelectedItem.ToString(); //comboBox_Change = true; List list = Startup.instance.mic_rulersAll; if (list != null) { for (int ruleI = 0; ruleI < list.Count; ruleI++) { mic_rulers rule = list[ruleI]; if (rule.ruler_name.Equals(((ComboBox)sender).SelectedItem.ToString())) { int rulid = rule.id; string rulerName2 = rule.ruler_name; if (rulid != Startup.instance.configModel.RulerId) { //设置当前选中标尺 this.appWorkspace.SetActiveRulerIndex(((ComboBox)sender).SelectedIndex); //comboBox_Change = false; this.documentWorkspace.rules = Startup.instance.rules; } break; } } } } getRulerMicronRatio(); this.documentWorkspace.Refresh(); } } public void OnUpdatePosition() { try { this.Invoke(new Action(() => { lblZPos.Text = m_Stage.Z.ToString("f2"); })); } catch { } } public void OnTimeoutConnect() { MessageBox.Show(PdnResources.GetString("Menu.Theconsoleresponsetimeout.Text")); } public void OnErrorSend() { MessageBox.Show(PdnResources.GetString("Menu.Replydataarsingerror.Text")); } private void CameraPreviewDialog_Load(object sender, EventArgs e) { tmrUpdate.Enabled = true; progressBar1.Maximum = 65; checkBox1.Checked = Preview2Context.P2Config.CaptureRuler; OnNameChange(); ConfigModel.OnCameraNameExChanged += OnNameChange; } void OnNameChange() { this.Text = DailogTitle + "-" + m_camera.GetNameEx(); } private void btnZUp_Click(object sender, EventArgs e) { var value = (double)numZLen.Value; m_Stage.Up(value); } private void btuZDown_Click(object sender, EventArgs e) { var value = (double)numZLen.Value; m_Stage.Up(-value); } private void btnZClear_Click(object sender, EventArgs e) { m_Stage.FreeZ(); m_Stage.ClearPosZ(); } /// /// 判断鼠标是否在预览窗口内 /// /// public bool IsLeave() { try { Point point = this.PointToClient(Control.MousePosition); isLeave = point.X > this.ClientSize.Width || point.X < 0 || point.Y > this.ClientSize.Height || point.Y < 0 ? false : true; } catch (Exception) { isLeave = false; } return isLeave; } private void CameraPreviewDialog_Activated(object sender, EventArgs e) { initCmbConfigs(); } private void checkBox1_Click(object sender, EventArgs e) { Preview2Context.P2Config.CaptureRuler = checkBox1.Checked; } } }