using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PaintDotNet.Base.CommTool; using PaintDotNet.Base.SettingModel; using OpenCvSharp; using OpenCvSharp.Extensions; using System.Drawing.Imaging; using PaintDotNet.Camera; using System.Threading; using PaintDotNet.Adjust; using PaintDotNet.ImageCollect.CameraEDOF; using PaintDotNet.DbOpreate.DbModel; using PaintDotNet.ImageCollect; using PaintDotNet.Measuring; using PaintDotNet.Annotation.Enum; using PaintDotNet.Menus; using PaintDotNet.Annotation.Measure; using StageController; namespace PaintDotNet.Preview2 { internal partial class Preview2Dialog : FloatingToolForm { public static Preview2Dialog Instance; public AppWorkspace _app; public DocumentWorkspaceWindow _document; public DocumentWorkspaceWindow _documentR; private DocumentStitchWindow picMatch; private ICamera _camera => CameraManager.CurrentCamera; bool _closing = false; public Preview2Dialog() { InitializeComponent(); InitializeLanguageText(); InitializeImages(); } private void InitializeLanguageText() { this.label3.Text = PdnResources.GetString("Preview2.CameraConfig"); this.label2.Text = PdnResources.GetString("Preview2.CurrentRuler"); this.btnSave.Title = PdnResources.GetString("CloseWorkspaceAction.SaveButton.ActionText"); this.btnBack.Title = PdnResources.GetString("CommonAction.Undo"); this.btnStart.Title = PdnResources.GetString("Menu.Started.text"); this.btnCapture.Title = PdnResources.GetString("Menu.ImageCollection.ShootAction.Text"); this.btnMutual.Title = PdnResources.GetString("Preview2.Interactive"); this.btnFit.Title = PdnResources.GetString("Menu.Edit.ZoomToWindow.Text"); this.btnExposure.Title = PdnResources.GetString("Menu.timeofexposure.text"); this.btnWhiteBalance.Title = PdnResources.GetString("Menu.Image.WhiteBalance.Text"); this.btnSetting.Title = PdnResources.GetString("Menu.imagecapture.Previewwindow.Previewproperties.text"); this.btnPreview.Title = PdnResources.GetString("Menu.Preview.text"); this.Text = PdnResources.GetString("Menu.ImageCollection.PreviewExtraction.Text"); } protected override void WndProc(ref Message m) { const int WM_MOUSEACTIVATE = 0x21; if (m.Msg == WM_MOUSEACTIVATE && this.CanFocus && !this.Focused) this.Focus(); base.WndProc(ref m); } private void Preview2Dialog_Load(object sender, EventArgs e) { progressBar1.Visible = Preview2Context.P2Config.CaptureFocus; InitializeWorkspace(); InitializeCamera(); BindingRule(); InitializeP2Config(); InitializeToolbar(); InitSettingList(); UpdateModeDisplay(0); ConfigModel.OnCameraNameExChanged += OnNameChange; Instance = this; } void OnNameChange() { if (this.IsDisposed) { Console.WriteLine("P2Disposed"); return; } var name = _camera.GetNameEx(); this.Invoke(new Action(() => { this.Text = this.Text.Split('-')[0] + "-" + name; })); } private void Preview2Dialog_FormClosing(object sender, FormClosingEventArgs e) { _closing = true; m_isWorking = false; CameraManager.OnCameraChanged -= WhenCameraChanged; ConfigModel.OnCameraNameExChanged -= OnNameChange; CameraManager.FrameCallback -= FrameCallback; _document?.Dispose(); _documentR?.Dispose(); _settingForm?.Close(); Instance = null; _app.RefreshMeasureListView(); _app.RefreshListView(); Instance = null; } void InitializeWorkspace() { _document = new DocumentWorkspaceWindow(_app); _document.Dock = DockStyle.Fill; _document.IsCreatThumb = false; _document.refueshZoomTrackValue = false; _document.rules = Startup.instance.rules; _document.oldDrawTreeView = MeasureListDialog.drawNodes; pnlPreviewContainer.Controls.Add(_document); _documentR = new DocumentWorkspaceWindow(_app); _documentR.Dock = DockStyle.Fill; _documentR.IsCreatThumb = false; _documentR.rules = Startup.instance.rules; _documentR.ActiveTool = DrawToolType.MoveMode; _documentR.oldDrawTreeView = MeasureListDialog.drawNodes; pnlResultContainer.Controls.Add(_documentR); } protected override bool ProcessFormHotKey(Keys e) { if (e == Keys.Delete || e == Keys.Escape) { _document.MouseEvent_Del(null, null); } else if (e == (Keys.Control | Keys.Z)) { _document.undoManager.Undo(); _document.Refresh(); } else if (e == (Keys.Control | Keys.Z)) { _document.undoManager.Redo(); _document.Refresh(); } else { return base.ProcessFormHotKey(e); } return true; } void InitializeCamera() { CameraConfigs.GetInstance().CameraParamInit(); CameraManager.OnCameraChanged += WhenCameraChanged; CameraManager.FrameCallback += FrameCallback; OnNameChange(); } void InitializeImages() { //先单独获取App基础配置 var configModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + "Default" + "\\Config.xml", FileMode.Open)); PdnResources.Initialize(configModel); btnPreview.Icon = PdnResources.GetImageResource("Icons.p2preview.png").Reference; btnCapture.Icon = PdnResources.GetImageResource("Icons.p2capture.png").Reference; btnExposure.Icon = PdnResources.GetImageResource("Icons.p2exposure.png").Reference; btnFit.Icon = PdnResources.GetImageResource("Icons.p2fit.png").Reference; btnWhiteBalance.Icon = PdnResources.GetImageResource("Icons.p2whitebalance.png").Reference; btnSetting.Icon = PdnResources.GetImageResource("Icons.p2setting.png").Reference; btnBack.Icon = PdnResources.GetImageResource("Icons.p2back.png").Reference; btnStart.Icon = PdnResources.GetImageResource("Icons.p2start.png").Reference; btnSave.Icon = PdnResources.GetImageResource("Icons.p2save_big.png").Reference; btnMutual.Icon = PdnResources.GetImageResource("Icons.p2mutual.png").Reference; btnResize.Icon = PdnResources.GetImageResource("Icons.Resize.png").Reference; } void InitializeP2Config() { Preview2SettingDialog.OnDrawGridChanged += UpdateGridDraw; UpdateGridDraw(); } void UpdateGridDraw() { _document.GridLineEnabled = Preview2Context.P2Config.DrawGrid; _document.GridRectangleEnabled = Preview2Context.P2Config.DrawRect; _document.GridCrossCurveEnabled = Preview2Context.P2Config.DrawCross; _document.GridRoundEnabled = Preview2Context.P2Config.DrawCircle; } #region Toolkit ToolkitControl _toolpanelL; ToolkitControl _toolpanelR; void InitializeToolbar() { _toolpanelL = new ToolkitControl(_app, _document); _toolpanelL.Dock = DockStyle.Fill; panelLeft.Controls.Add(_toolpanelL); _toolpanelR = new ToolkitControl(_app, _document); _toolpanelR.Dock = DockStyle.Fill; panelRight.Controls.Add(_toolpanelR); ToolkitEditControl.OnToolbarUpdate += () => { _toolpanelL.UpdateTools(Preview2Context.ToolbarModelLeft); _toolpanelR.UpdateTools(Preview2Context.ToolbarModelRight); }; _toolpanelL.UpdateTools(Preview2Context.ToolbarModelLeft); _toolpanelR.UpdateTools(Preview2Context.ToolbarModelRight); Preview2SettingDialog.OnToolkitSideChanged += OnToolkitSideChanged; OnToolkitSideChanged(); } private void OnToolkitSideChanged() { if ((Preview2Context.P2Config.ToolkitSide & 1) == 1) { tableLayoutPanel1.ColumnStyles[0] = new ColumnStyle(SizeType.Absolute, 50); } else { tableLayoutPanel1.ColumnStyles[0] = new ColumnStyle(SizeType.Absolute, 0); } if ((Preview2Context.P2Config.ToolkitSide & 2) == 2) { tableLayoutPanel1.ColumnStyles[3] = new ColumnStyle(SizeType.Absolute, 50); } else { tableLayoutPanel1.ColumnStyles[3] = new ColumnStyle(SizeType.Absolute, 0); } } #endregion #region Preview private void WhenCameraChanged(ICamera old, ICamera current) { OnNameChange(); } private void FrameCallback(Bitmap img) { try { ShowFrame(img.Clone() as Bitmap); m_mat = PaintDotNet.Camera.Tools.ToMat(img); } catch { } if (_closing) return; double value = 0; if (Preview2Context.P2Config.CaptureFocus) value = getMeanValueOfBitmap(img.Clone() as Bitmap); try { this.Invoke(new Action(() => { if (Preview2Context.P2Config.CaptureFocus) { progressBar1.Visible = true; progressBar1.Value = value; } else { progressBar1.Visible = false; } })); this.Invoke(new Action(() => { _toolpanelL.UpdateDisplay(); _toolpanelR.UpdateDisplay(); })); } catch { } return; } private void ShootCallback(Bitmap img) { if (_workMode == 0) { var mode = Startup.instance.configModel.CaptureSaveMode; this.Invoke(new Action(() => { _app.DisplayShoot(img, _document.GraphicsList, Preview2Context.P2Config.CaptureRuler, mode); if (Preview2Context.P2Config.CaptureClose) this.Close(); })); } if (_workMode == 2) { m_isWorking = true; Depth(PaintDotNet.Camera.Tools.ToMat(img)); } } #endregion #region Setting Preview2SettingDialog _settingForm; private void InitSettingList() { List fileNames = CameraConfigs.GetInstance().GetAllConfigFiles(); cmbConfig.Items.AddRange(fileNames.ToArray()); var name = Preview2Context.P2Config.GetCamCfg(_camera); if (cmbConfig.Items.Contains(name)) cmbConfig.SelectedItem = name; else cmbConfig.SelectedItem = CommonDefine.DefaultCamCfg; cmbConfig.SelectedIndexChanged += this.cmbConfig_SelectedIndexChanged; } private void cmbConfig_SelectedIndexChanged(object sender, EventArgs e) { var name = cmbConfig.Text; if (name == CameraConfigs.GetInstance().CurrentConfigFileName) return; var cpm = CameraConfigs.GetInstance().GetCameraParamModel(name); Startup.instance.cameraParamModel = cpm; Startup.instance.configModel.CameraConfig = name; string configXml = XmlSerializeHelper.XmlSerialize(Startup.instance.configModel); string filePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\Config.xml"; FileOperationHelper.WriteStringToFile(configXml, filePath, FileMode.Create); CameraConfigs.GetInstance().CameraParamInit(); } private void CameraSettingChanged(int type, string name) { if (type == 0) { cmbConfig.SelectedItem = name; } if (type == 1) { cmbConfig.Items.Add(name); cmbConfig.SelectedItem = name; } if (type == 2) { cmbConfig.Items.Remove(name); cmbConfig.SelectedItem = "CameraParam"; } } private void btnSetting_Click(object sender, EventArgs e) { if (_settingForm == null) { _settingForm = new Preview2SettingDialog(_document); _settingForm.Load += (s1, e1) => { cmbConfig.Enabled = false; }; _settingForm.FormClosing += (s1, e1) => { cmbConfig.Enabled = true; _settingForm = null; }; _settingForm.OnConfigModify = CameraSettingChanged; FloatingFormMethod.ShowFloatForm(null, _settingForm, _app); } _settingForm.Activate(); } System.Drawing.Point _lastLocation; /// /// 预览设置跟随主窗体移动 /// private void Preview2Dialog_Move(object sender, EventArgs e) { var settingForm = _settingForm; if (settingForm != null) { var x = Location.X - _lastLocation.X; var y = Location.Y - _lastLocation.Y; settingForm.FormMove(x, y); } _lastLocation = Location; } #endregion #region Show Frame /// /// 在 documentview 中显示 预览 /// /// private void ShowFrame(Bitmap img) { var mat = PaintDotNet.Camera.Tools.ToMat(img); if (Preview2Context.ShandingCorrectionState == 1)//阴影矫正 mat = AdjustIntent.ShadingCorrection(mat); _document.Document = Document.FromMat(mat); } #endregion #region 工作模式 ModeMenuControl _modeMenu; /// /// 0:预览,1:拼图,2:景深 /// int _workMode = -1; private void btnPreview_Click(object sender, EventArgs e) { if (_modeMenu == null) { _modeMenu = new ModeMenuControl(); _modeMenu.PreviewModeClick = () => UpdateModeDisplay(0); _modeMenu.StitchModeClick = () => UpdateModeDisplay(1); ; _modeMenu.DeepModeClick = () => UpdateModeDisplay(2); _modeMenu.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; this.Controls.Add(_modeMenu); _modeMenu.BringToFront(); } else { _modeMenu.Visible = !_modeMenu.Visible; } _modeMenu.Left = this.Width - _modeMenu.Width - 20; _modeMenu.Top = this.Height - _modeMenu.Height - 120; } /// /// 0预览模式 1拼图模式 2景深模式 /// private void UpdateModeDisplay(int mode) { if (_workMode == mode) return; StopWork(); _documentR.Document?.Dispose(); m_merge = null; _workMode = mode; btnCapture.Visible = false; btnStart.Visible = false; btnSave.Visible = false; btnBack.Visible = false; btnMutual.Visible = false; btnMutual.Selected = false; btnResize.Visible = false; btnResize.Selectable = true; btnMutual.Selectable = true; pnlResultContainer.Controls.Clear(); _documentR.Document = Document.FromImage(new Bitmap(1, 1)); switch (_workMode) { case 0: btnPreview.Text = PdnResources.GetString("Menu.ImageCollection.Text"); btnCapture.Visible = true; tableLayoutPanel1.ColumnStyles[2] = new ColumnStyle(SizeType.Percent, 0f); break; case 1: btnPreview.Text = PdnResources.GetString("Menu.Image.ImageStitching.Text"); btnStart.Visible = true; btnSave.Visible = true; btnResize.Visible = true; tableLayoutPanel1.ColumnStyles[2] = new ColumnStyle(SizeType.Percent, 50f); break; case 2: btnPreview.Text = PdnResources.GetString("Menu.Image.DepthExtension.Text"); btnStart.Visible = true; btnSave.Visible = true; btnMutual.Visible = true; tableLayoutPanel1.ColumnStyles[2] = new ColumnStyle(SizeType.Percent, 50f); pnlResultContainer.Controls.Add(_documentR); break; } } #region Operate private void btnMutual_Click(object sender, EventArgs e) { StopWork(); m_merge = null; _lastDetp = null; _documentR.Document = Document.FromImage(new Bitmap(1, 1)); btnMutual.Selected = !btnMutual.Selected; btnStart.Visible = !btnMutual.Selected; btnCapture.Visible = btnMutual.Selected; btnBack.Visible = btnMutual.Selected; } private void btnStart_Click(object sender, EventArgs e) { if (m_isWorking) { StopWork(); } else { StartWork(); } } private void btnCapture_Click(object sender, EventArgs e) { CameraManager.Shoot(ShootCallback); } private void btnBack_Click(object sender, EventArgs e) { if (_lastDetp == null) return; m_merge = _lastDetp.Clone(); _lastDetp = null; _documentR.Document = Document.FromMat(m_merge.Clone()); } private void btnSave_Click(object sender, EventArgs e) { if (m_merge == null) { if (_workMode == 1) MessageBox.Show(PdnResources.GetString("Menu.mageMosaicimagehanotbeengeneratedyet.Text")); else if (_workMode == 2) MessageBox.Show(PdnResources.GetString("Menu.ofimageshavenotyetbeengene.Text")); return; } //Bitmap bitmap = BitmapConverter.ToBitmap(m_merge); _pause = true; DocumentWorkspace dw = _app.NewDocumentWorkspace(); Mat mat = null; float ratio = 1; int len = 0; int pix = 0; if (_workMode == 1) { if (_useBig) mat = picMatch.StitchMat.Clone(); else mat = m_merge.Clone(); int width = Startup.instance.configModel.MaxWidth; int height = Startup.instance.configModel.MaxHeight; if (btnResize.Selected && (width < mat.Width || height < mat.Height) && (width + height) > 0) { if (Startup.instance.configModel.MaxUnit == 0) { var ulen = Startup.instance.ruleDB.pixel_length / (float)Startup.instance.ruleDB.physical_length; width = (int)(width * ulen); height = (int)(height * ulen); } if (Startup.instance.configModel.MaxLocked) { if (width == 0) { ratio = height * 1.0f / mat.Height; width = (int)(mat.Width * ratio); len = Startup.instance.configModel.MaxHeight; pix = height; } else { ratio = width * 1.0f / mat.Width; height = (int)(mat.Height * ratio); len = Startup.instance.configModel.MaxWidth; pix = width; } } else { width = width == 0 ? mat.Width : width; height = height == 0 ? mat.Height : height; } width = Math.Min(width, mat.Width); height = Math.Min(height, mat.Height); ratio = Math.Min(1, ratio); if (width != mat.Width || height != mat.Height) Cv2.Resize(mat, mat, new OpenCvSharp.Size(width, height)); } } else mat = m_merge.Clone(); Document document = Document.FromImageMat(mat); dw.Document = document; dw.xmlSaveModel = Startup.instance.ruleDB.Clone(); if (dw.xmlSaveModel != null) { dw.Units = MeasurementUnit.Micron; if (ratio != 1) { dw.xmlSaveModel.ruler_name = "分辨率调整"; if (Startup.instance.configModel.MaxUnit == 1) dw.xmlSaveModel.pixel_length *= ratio; else { dw.xmlSaveModel.pixel_length = pix; dw.xmlSaveModel.physical_length = len; } } dw.xmlSaveModel.gain_multiple = dw.xmlSaveModel.gain_multiple / (decimal)ratio; } string name = ""; if (_workMode == 1) name = PdnResources.GetString("Menu.Image.ImageStitching.Text"); if (_workMode == 2) name = PdnResources.GetString("Menu.Image.DepthExtension.Text"); dw.fileText = string.Format("{0}-{1:D3}", name, Startup.instance.step_length++); dw.InitRulerInfo(); if (Preview2Context.P2Config.CaptureRuler) dw.ActiveTool = DrawToolType.DrawAutoRuler; _app.Add(dw); _app.ActiveDocumentWorkspace = dw; _pause = false; } #endregion #region Work bool m_isWorking = false; private bool _pause; private Thread m_stitchingThread; private Mat m_mat; private Mat m_merge; private void StartWork() { btnStart.Icon = PdnResources.GetImageResource("Icons.p2stop.png").Reference; btnStart.Title = PdnResources.GetString("Menu.stop.text"); m_isWorking = true; m_merge = null; if (_workMode == 1) StartStitch(); m_stitchingThread = new Thread(new ThreadStart(WaitForStitchingThreadEntry)); m_stitchingThread.Start(); } private int newOriX = 10000; private int newOriY = 10000; private Rect lastRect = new Rect(-10000, -10000, 0, 0); private void StartStitch() { newOriX = 10000; newOriY = 10000; pnlResultContainer.Controls.Clear(); if (_useBig) { this.picMatch = new DocumentStitchWindow(); pnlResultContainer.Controls.Add(picMatch); this.picMatch.Dock = DockStyle.Fill; } else pnlResultContainer.Controls.Add(_documentR); lastRect = new Rect(-10000, -10000, 0, 0); } private void StopWork() { btnStart.Icon = PdnResources.GetImageResource("Icons.p2start.png").Reference; btnStart.Title = PdnResources.GetString("Menu.Started.text"); m_isWorking = false; } /// /// 图像拼接 /// private void WaitForStitchingThreadEntry() { while (m_isWorking) { if (m_mat == null || _pause)// || AxisController.GetInstance().IsMoving) { //if (_useBig) m_mat = new Mat(@"C:\Users\win10SSD\Desktop\工作目录\小图片\0e2442a7d933c8956c0e8eeadb1373f08202002a.jpg"); Thread.Sleep(20); continue; } if (_workMode == 1) { if (_useBig) StitchBig(m_mat); else Stitch(m_mat); } if (_workMode == 2) Depth(m_mat); } } private void Depth(Mat mat) { if (!m_isWorking) return; if (m_merge == null) m_merge = mat.Clone(); else { _lastDetp = m_merge.Clone(); m_merge = Merge.GetMergeMatForCamera(new Mat[] { mat, m_merge }); } if (!m_isWorking) { m_merge = null; return; } _documentR.Document = Document.FromMat(m_merge.Clone()); GC.Collect(); } /// /// 大图拼接调试模式,正式版时候设置为false /// private bool _useBig => Startup.instance.useBigFile; private void Stitch(Mat mat) { if (m_merge == null) { AdjustIntent.InitMatchPicOneByOne(_useBig); } Rect rect; var result = AdjustIntent.MatchPicRealtime(mat, m_merge, out bool error, out rect); if (!error) { Console.WriteLine("开始贴图"); m_merge = result.Clone(); var Ratio = _documentR.ScaleFactor.Ratio; int pw = (int)(2 / Ratio) + 1; // result = m_merge.Clone(); result.Rectangle(rect, Scalar.Lime, pw); _documentR.Document = Document.FromMat(result); Console.WriteLine("贴图结束"); } else { Console.WriteLine(PdnResources.GetString("Menu.Jigsawpuzzlefailure.Text")); } if (!m_isWorking) return; //var tmp = m_merge.Clone(); //pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(tmp); //pictureBox1.Invalidate(); GC.Collect(); } private void StitchBig(Mat mat) { if (m_merge == null) { m_merge = new Mat(20000 + newOriY, 20000 + newOriX, MatType.CV_8UC3); picMatch.StitchDocument = StitchDocument.FromMat(m_merge/*tmp*/); picMatch.StitchBounds = new Rectangle(newOriX, newOriY, 0, 0); picMatch.StitchDocument.surface.stitchBackColor = picMatch.BackColor; picMatch.ActiveTool = Annotation.Enum.DrawToolType.MoveMode; AdjustIntent.InitMatchPicOneByOne(_useBig, newOriX, newOriY, m_merge); } Rect rect; var time = DateTime.Now; var result = AdjustIntent.MatchPicRealtime(mat, m_merge, out bool error, out rect); if (!error) { if (result != null) m_merge = result; } else { // Console.WriteLine("拼图失败"); } picMatch.GraphicsList.Clear(); MeasureRectangle rectObject = new MeasureRectangle(picMatch, rect.X, rect.Y, rect.Width, rect.Height); picMatch.GraphicsList.Add(rectObject); int disX = Math.Abs(rect.X - lastRect.X); int disY = Math.Abs(rect.Y - lastRect.Y); bool resized = false;//判断是否重新定位大图区域 if (picMatch.StitchBounds.Width == 0) { resized = true; picMatch.StitchDocument.surface.stitchBounds.Width = rect.Width;// matNew.Width; picMatch.StitchDocument.surface.stitchBounds.Height = rect.Height;// matNew.Height; } else { int x = Math.Min(picMatch.StitchBounds.X, rect.X); int y = Math.Min(picMatch.StitchBounds.Y, rect.Y); int x2 = Math.Max(picMatch.StitchBounds.Right, rect.Right); int y2 = Math.Max(picMatch.StitchBounds.Bottom, rect.Bottom); picMatch.StitchBounds = new Rectangle(x, y, x2 - x, y2 - y); } if (_closing || !m_isWorking) return; this.BeginInvoke(new Action(() => { if (disX > 500 || disY > 500) { picMatch.ZoomBasis = ZoomBasis.ScaleFactor; picMatch.ZoomBasis = ZoomBasis.FitToWindow; picMatch.ZoomBasis = ZoomBasis.ScaleFactor; picMatch.panel.HorizontalScroll.Value = (int)(picMatch.panel.HorizontalScroll.Maximum * picMatch.StitchBounds.X / (picMatch.StitchWidth)); picMatch.panel.VerticalScroll.Value = (int)(picMatch.panel.VerticalScroll.Maximum * picMatch.StitchBounds.Y / picMatch.StitchHeight); lastRect = rect; } picMatch.Refresh(); })); //Console.WriteLine((DateTime.Now - time).TotalMilliseconds); //time = DateTime.Now; Thread.Sleep(50); } #endregion #endregion #region Operation private void btnWhiteBalance_Click(object sender, EventArgs e) { btnWhiteBalance.PressDownThenBack(); new Task(() => { _camera.WhiteBalanceMode = 1; CameraConfigs.Settings.WhiteBalance = 1; Thread.Sleep(1000); _camera.WhiteBalanceMode = 0; CameraConfigs.Settings.WhiteBalance = 0; }).Start(); } private void btnFit_Click(object sender, EventArgs e) { _document.ZoomToWindow(); } private void btnExposure_Click(object sender, EventArgs e) { btnExposure.PressDownThenBack(); new Task(() => { _camera.AutoExposure = 1; CameraConfigs.Settings.ATExposure = 1; Thread.Sleep(1000); _camera.AutoExposure = 0; CameraConfigs.Settings.ATExposure = 0; }).Start(); } #endregion #region Ruler /// /// 绑定标尺 /// 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; } } } private void Ruler_SelectedIndexChanged(object sender, EventArgs e) { var name = comboBox1.Text; if (string.IsNullOrEmpty(name)) return; //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(name)) { int rulid = rule.id; if (rulid != Startup.instance.configModel.RulerId) { //设置当前选中标尺 _app.SetActiveRulerIndex(((ComboBox)sender).SelectedIndex); _document.rules = Startup.instance.rules; _document.Refresh(); } break; } } getRulerMicronRatio(); _document.Refresh(); } } private double _micronRatio;//每像素多少微米 /// /// 获取当前标尺并换算为微米 /// void getRulerMicronRatio() { Startup.instance.rules.TryGetValue(MeasurementUnit.Micron, out this._micronRatio); _document.MicronRatio = this._micronRatio; } #endregion private void Preview2Dialog_Activated(object sender, EventArgs e) { BindingRule(); } /// /// 获取输入图片的清晰度 /// /// /// private static double getMeanValueOfBitmap(Bitmap bitmap) { Mat converted = PaintDotNet.Camera.Tools.ToMat(bitmap); Mat imageGrey = new Mat(); Mat imageSobel = new Mat(); try { if (converted.Channels() == 3) OpenCvSharp.Cv2.CvtColor(converted, imageGrey, OpenCvSharp.ColorConversionCodes.RGB2GRAY); else if (converted.Channels() == 1) imageGrey = converted; } catch (Exception) { imageGrey = converted; } OpenCvSharp.Mat meanValueImage = new OpenCvSharp.Mat(); OpenCvSharp.Mat meanStdValueImage = new OpenCvSharp.Mat(); //求灰度图像的标准差 值越大越好 OpenCvSharp.Cv2.MeanStdDev(imageGrey, meanValueImage, meanStdValueImage); return meanStdValueImage.At(0, 0); } #region 适配全局菜单按钮事件 internal void SetActiveTool(DrawToolType measurePointArcSize) { _document.ActiveTool = measurePointArcSize; } public void DrawObjClear() { _document.GraphicsList.Clear(); _document.Refresh(); } public void DrawObjSelectAll() { _document.GraphicsList.SelectAll(); _document.Refresh(); } #endregion private void Preview2Dialog_ResizeEnd(object sender, EventArgs e) { if (WindowState == FormWindowState.Normal) { if (Location.Y < 0) Location = _lb; } } System.Drawing.Point _lb; private Mat _lastDetp; private void Preview2Dialog_ResizeBegin(object sender, EventArgs e) { if (WindowState == FormWindowState.Normal) _lb = new System.Drawing.Point(Location.X, Math.Max(0, Location.Y)); } private void timer1_Tick(object sender, EventArgs e) { //panel1.Enabled = CameraManager.IsLive; } private void btnResize_Click(object sender, EventArgs e) { btnResize.Selected = !btnResize.Selected; } } }