/// <summary> /// 图片均衡操作,将传入图片自动转换,imgWidth:设定图片宽度,imgHeight图片设定高度 /// 图片(forexample:a.bmp)另存为同文件夹下面的_a.bmp /// </summary> /// <param name="ImagePath"></param> public void QualizerImage(string ImagePath, int imgWidth, int imgHeight) { try { if ((ImagePath.Length == 0) || (!File.Exists(ImagePath))) { return; } EImageBW8 EBW8ImageOrig = new EImageBW8(); // EImageBW8 instance EImageBW8 EBW8ImageDest = new EImageBW8(); // EImageBW8 instance EBW8ImageOrig.SetSize(imgWidth, imgHeight); // Make image black EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), EBW8ImageOrig); EBW8ImageOrig.Load(ImagePath); EBW8ImageDest.SetSize(imgWidth, imgHeight); // Make image black EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), EBW8ImageDest); EBW8ImageDest.SetSize(EBW8ImageOrig); EasyImage.Equalize(EBW8ImageOrig, EBW8ImageDest); EBW8ImageOrig.Dispose(); //EBW8ImageDest.Save(ImagePath); EBW8ImageDest.Save(ImageSaveAsPath(ImagePath)); } catch { throw; } }
public void SaveEMatcher_Blank( PatternMatcherParameters param, string pattern1_FilePath, string pattern2_FilePath, string pattern1_ImageFilePath, string pattern2_ImageFilePath) { EImageBW8 blackImage = new EImageBW8(512, 512); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), blackImage); // make it black EROIBW8 blackEROI = new EROIBW8(); blackEROI.OrgX = 0; blackEROI.OrgY = 0; blackEROI.Width = 512; blackEROI.Height = 512; blackEROI.Attach(blackImage); TeachAndSaveEMatcher( param, blackEROI, blackEROI, pattern1_FilePath, pattern2_FilePath, pattern1_ImageFilePath, pattern2_ImageFilePath); }
private void backgroundToolStripMenuItem_Click(object sender, EventArgs e) { float PictureBoxSizeRatio, ImageSizeRatio; if (openFileDialog1.ShowDialog() == DialogResult.OK) { Background.Load(openFileDialog1.FileName); PictureBoxSizeRatio = (float)pbImg3.Width / pbImg3.Height; ImageSizeRatio = (float)Background.Width / Background.Height; if (ImageSizeRatio > PictureBoxSizeRatio) { ScalingRatio = (float)pbImg3.Width / Background.Width; } else { ScalingRatio = (float)pbImg3.Height / Background.Height; } //顯示影像於Picturebox pbImg3.Refresh(); //先清除目前圖像 Background.Draw(pbImg3.CreateGraphics(), ScalingRatio); //再繪製上去 BackgroundGray.SetSize(Background); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), BackgroundGray); EasyImage.Convert(Background, BackgroundGray); //轉灰階 } }
public override EImageBW8 Run(EImageBW8 img) { if (!Enable) { return(img); } EImageBW8 imgBw8 = new EImageBW8(); imgBw8.SetSize(img); switch (Type) { case MorphologyType.Square: EasyImage.DilateBox(img, imgBw8, Width); break; case MorphologyType.Rectangle: EasyImage.DilateBox(img, imgBw8, Width, Height); break; case MorphologyType.Circle: EasyImage.DilateDisk(img, imgBw8, Width); break; default: EasyImage.DilateBox(img, imgBw8, Width); break; } img.Dispose(); img = new EImageBW8(); return(imgBw8); }
/// <summary> /// Average Pixel Value /// 0 if fully black /// 255 if fully white /// </summary> /// <param name="roi"></param> /// <param name="recipe"></param> /// <returns></returns> private static VisionMapCategory CalculateMapCategory( EROIBW8 roi, MapVisionParameters recipe) { float DiePresentThreshold = recipe.DiePresentThreshold; float averagePixelValue; EasyImage.PixelAverage(roi, out averagePixelValue); VisionMapCategory visionMapCategory = VisionMapCategory.Undefined; //if (averagePixelValue > TakenDieThreshold && averagePixelValue <= 256) visionMapCategory = VisionMapCategory.Taken; //else if (averagePixelValue > GoodDieThreshold && averagePixelValue <= TakenDieThreshold) visionMapCategory = VisionMapCategory.GoodDie; //else if (averagePixelValue > BadDieThreshold && averagePixelValue <= GoodDieThreshold) visionMapCategory = VisionMapCategory.BadDie; if (averagePixelValue > DiePresentThreshold) { visionMapCategory = VisionMapCategory.DieTaken; } else if (averagePixelValue <= DiePresentThreshold) { visionMapCategory = VisionMapCategory.DieRemain; } else { throw new Exception("Invalid vision Map Category"); } return(visionMapCategory); }
private void yIQToolStripMenuItem_Click(object sender, EventArgs e) { for (int i = 0; i < FileListBox.Items.Count; i++) { FileListBox.SelectedItem = i; FileListBox.Refresh(); OriginalImg1.Load(files[i]); OriginalImg2.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EC24(0, 0, 0), OriginalImg2); OriginalImg1.ColorSystem = EColorSystem.Rgb; EColorLookup1.ConvertFromRgb(EColorSystem.Yiq); EColorLookup1.Transform(OriginalImg1, OriginalImg2); //EC24Image2.Draw(pbImg2.CreateGraphics(), ScalingRatio); string path = settings.set_path() + "\\" + Path.GetFileName(files[i]); if (!Directory.Exists(settings.set_path())) { Directory.CreateDirectory(settings.set_path()); } OriginalImg2.SaveJpeg(path); } MessageBox.Show("YIQ轉換完成", "通知"); }
public override EImageBW8 Run(EImageBW8 img) { if (!Enable) { return(img); } EImageBW8 imgBw8 = new EImageBW8(); imgBw8.SetSize(img); switch (Mode) { case MyThresholdMode.Auto: EBW8 value1 = EasyImage.AutoThreshold(img, EThresholdMode.MinResidue); AbsoluteValue = value1.Value; break; case MyThresholdMode.Absolute: break; case MyThresholdMode.Relative: EBW8 value2 = EasyImage.AutoThreshold(img, EThresholdMode.Relative, RelativeValue); AbsoluteValue = value2.Value; break; default: break; } EasyImage.Threshold(img, imgBw8, AbsoluteValue); img.Dispose(); img = new EImageBW8(); return(imgBw8); }
/// <summary> /// 灰度&对比度处理,图片另存为imagePath\_*.* /// 图片(forexample:a.bmp)另存为同文件夹下面的_a.bmp /// </summary> /// <param name="ImagePath"></param> /// <param name="Val_gain"></param> /// <param name="Val_offSet"></param> public EImageBW8 EImageBW8GainOff(EImageBW8 ImageSource, float Val_gain, float Val_offSet) { EImageBW8 EBW8ImageDest = new EImageBW8(ImageSource.Width, ImageSource.Height); // EImageBW8 instance try { EasyImage.GainOffset(ImageSource, EBW8ImageDest, Val_gain, Val_offSet); } catch { } return(EBW8ImageDest); }
public override EImageBW8 Run(EImageBW8 img) { if (!Enable) { return(img); } EImageBW8 imgBw8 = new EImageBW8(); imgBw8.SetSize(img); EasyImage.Median(img, imgBw8); img.Dispose(); img = new EImageBW8(); return(imgBw8); }
public override EImageBW8 Run(EImageBW8 img) { if (!Enable) { return(img); } EImageBW8 imgBw8 = new EImageBW8(); imgBw8.SetSize(img); EasyImage.GainOffset(img, imgBw8, Gain, Offset); img.Dispose(); img = new EImageBW8(); return(imgBw8); }
private void btn_loadImg_Click(object sender, EventArgs e) { if (mPicBox1.LoadImg()) { roi.Attach(mPicBox1.Image); btn_action.Visible = true; btn_learn.Visible = true; btn_loadMoudle.Visible = true; btn_save.Visible = true; btn_process.Visible = true; ckbox_inRoi.Visible = true; copyImg = new EImageBW8(); copyImg.SetSize(mPicBox1.Image); EasyImage.Copy(mPicBox1.Image, copyImg); } }
public override EImageBW8 Run(EImageBW8 img) { if (!Enable) { return(img); } EImageBW8 imgBw8 = new EImageBW8(); float a = 0f, x = 0f, y = 0f; if (Value % 180 < 90) { //当前角度 a = (float)Math.Atan2((float)img.Height / 2, (float)img.Width / 2); //旋转后角度 float b = a + Value % 90 * ((float)Math.PI / 180); float c = a - Value % 90 * ((float)Math.PI / 180); //斜边 float z = (float)Math.Sqrt(img.Width * img.Width + img.Height * img.Height) / 2; //xy增量 x = (float)(Math.Cos(c) - Math.Cos(a)) * z; y = (float)(Math.Sin(b) - Math.Sin(a)) * z; //设置新图片大小 imgBw8.SetSize((int)(img.Width + 2 * x), (int)(img.Height + 2 * y)); } else if (Value % 180 >= 90) { //当前角度 a = (float)Math.Atan2((float)img.Height / 2, (float)img.Width / 2); //旋转后角度 float b = a + Value % 90 * ((float)Math.PI / 180); float c = a - Value % 90 * ((float)Math.PI / 180); //斜边 float z = (float)Math.Sqrt(img.Width * img.Width + img.Height * img.Height) / 2; //xy增量 y = (float)(Math.Cos(c) - Math.Cos(a)) * z; x = (float)(Math.Sin(b) - Math.Sin(a)) * z; //设置新图片大小 imgBw8.SetSize((int)(img.Height + 2 * x), (int)(img.Width + 2 * y)); } EasyImage.ScaleRotate(img, (float)img.Width / 2, (float)img.Height / 2, (float)imgBw8.Width / 2, (float)imgBw8.Height / 2, 1, 1, Value, imgBw8, 0); img.Dispose(); img = new EImageBW8(); return(imgBw8); }
private void FileListBox_SelectedIndexChanged(object sender, EventArgs e) { if (selecting) { OriginalImg1.Load(files[0]); //============================計算scaling ratio============================ float PictureBoxSizeRatio = (float)pbImg1.Width / pbImg1.Height; float ImageSizeRatio = (float)OriginalImg1.Width / OriginalImg1.Height; if (ImageSizeRatio > PictureBoxSizeRatio) { ScalingRatio = (float)pbImg1.Width / OriginalImg1.Width; } else { ScalingRatio = (float)pbImg1.Height / OriginalImg1.Height; } //========================================================================= OriginalImg1.Load(files[FileListBox.SelectedIndex]); OriginalImg1.Draw(pbImg1.CreateGraphics(), ScalingRatio); GrayImg1.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 EasyImage.Median(BackgroundGray, BackgroundGray); EasyImage.Median(GrayImg1, GrayImg1); EasyImage.Oper(EArithmeticLogicOperation.Subtract, GrayImg1, BackgroundGray, GrayImg1); EasyImage.Threshold(GrayImg1, GrayImg1, unchecked ((uint)EThresholdMode.MinResidue)); EasyImage.ErodeBox(GrayImg1, GrayImg1, 1); //侵蝕 EasyImage.CloseBox(GrayImg1, GrayImg1, 10); //閉合 GrayImg1.Draw(pbImg2.CreateGraphics(), ScalingRatio); Console.WriteLine(files[FileListBox.SelectedIndex]); } }
public override bool Run(bool isTaskRun = false) { int index = config.SelectImgIndex - 1; if (index < 0 || index >= ParentTask.Imgs.Count) { OutputImg = InputImg = null; ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Events.IndexOf(this))); return(false); } InputImg = ParentTask.Imgs[index].Img; if (InputImg == null || InputImg.IsVoid) { OutputImg = null; ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Events.IndexOf(this))); return(false); } OutputImg = new EImageBW8(); OutputImg.SetSize(InputImg); EasyImage.Copy(InputImg, OutputImg); foreach (var item in config.CfgGroup) { OutputImg = item.Run(OutputImg); } if (isTaskRun) { ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Events.IndexOf(this))); } else { ImgDictionary imgdic = ParentTask.Imgs.Find(s => { return(s.Config == Config); }); if (imgdic != null) { imgdic.Img = OutputImg; } } return(true); }
private void grayToolStripMenuItem_Click(object sender, EventArgs e) { for (int i = 0; i < FileListBox.Items.Count; i++) { FileListBox.SelectedItem = i; FileListBox.Refresh(); OriginalImg1.Load(files[i]); GrayImg1.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Convert(OriginalImg1, GrayImg1); string path = settings.set_path() + "\\" + Path.GetFileName(files[i]); if (!Directory.Exists(settings.set_path())) { Directory.CreateDirectory(settings.set_path()); } GrayImg1.SaveJpeg(path); } MessageBox.Show("灰階化轉換完成", "通知"); }
static void Main(string[] args) { int roiWidth1 = 58; int roiHeight1 = 39; int roiWidth2 = 22; int roiHeight2 = 130; imageSource = new EImageC24(); imageSource.SetSize(768, 576);//測試其他圖之前先修改圖這邊的影像尺寸,影像尺寸須與原圖相同 //EPatternFinder1.MaxInstances = 40; //EPatternFinder1.MinScore = 0.8f; imageSourceGray = new EImageBW8(imageSource.Width, imageSource.Height); EImageBW8 imgBrushed = new EImageBW8(imageSourceGray); //載入樣板 //EPatternFinder1.Load(Path.Combine(di.FullName, "EasyFindTemplate1.FND")); EMatcher1.Load(Path.Combine(di.FullName, "EMatcherTemplate1.MCH")); EMatcher2.Load(Path.Combine(di.FullName, "EMatcherTemplate2.MCH")); FileInfo[] files = di.GetFiles("*.jpg"); foreach (var file in files) { imageSource.Load(Path.Combine(di.FullName, file.Name)); EasyColor.C24ToBayer(imageSource, imageSourceGray); EasyImage.Copy(imageSourceGray, imgBrushed); //Find //EFoundPattern[] founds = EPatternFinder1.Find(imageSourceGray); EMatcher1.Match(imageSourceGray); EMatcher2.Match(imageSourceGray); IntPtr gintptr = Easy.OpenImageGraphicContext(imgBrushed); Graphics g = Graphics.FromHdc(gintptr); //foreach (var item in founds) //{ // EPoint center = item.Center; // //g.FillRectangle(new SolidBrush(Color.White) // // , (int)center.X - ((int)roiWidth / 2), (int)center.Y - ((int)roiHeight / 2) // // , roiWidth, roiHeight); // item.Draw(g, new ERGBColor(255, 255, 255), 1.0f, 1.0f, 0, 0); //} foreach (var item in EMatcher1.Positions) { EPoint center = new EPoint(item.CenterX, item.CenterY); g.FillRectangle(new SolidBrush(Color.White) , (int)center.X - ((int)roiWidth1 / 2), (int)center.Y - ((int)roiHeight1 / 2) , roiWidth1, roiHeight1); } foreach (var item in EMatcher2.Positions) { EPoint center = new EPoint(item.CenterX, item.CenterY); g.FillRectangle(new SolidBrush(Color.White) , (int)center.X - ((int)roiWidth2 / 2), (int)center.Y - ((int)roiHeight2 / 2) , roiWidth2, roiHeight2); } Easy.CloseImageGraphicContext(imgBrushed, gintptr); imgBrushed.SaveJpeg(@"D:\" + file.Name); } }
public override bool Run(bool isTaskRun = false) { OutputImg = new EImageBW8(); switch (config.SelectMode) { case 0: if (ParentTask.SourceImg != null) { OutputImg.SetSize(ParentTask.SourceImg); EasyImage.Copy(ParentTask.SourceImg, OutputImg); } else { OutputImg = null; } if (isTaskRun) { ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Imgs.Count)); } break; case 1: if (!File.Exists(config.ImgPath)) { return(false); } OutputImg.Load(config.ImgPath); if (isTaskRun) { ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Imgs.Count)); } break; case 2: if (!Directory.Exists(config.FolderPath)) { return(false); } DirectoryInfo dir = new DirectoryInfo(config.FolderPath); FileInfo[] fil = dir.GetFiles("*.bmp", SearchOption.TopDirectoryOnly); if (fil.Length == 0) { return(false); } if (selectImg >= fil.Length) { selectImg = 0; } OutputImg.Load(fil[selectImg++].FullName); if (isTaskRun) { ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Imgs.Count)); } break; case 3: if (config.SelectCCD > 0) { int select = config.SelectCCD - 1; if (ParentTask.Cameras[select].IsConnect) { ImgAtt att = ParentTask.Cameras[select].Grab(); OutputImg = new EImageBW8(); OutputImg.SetImagePtr(att.ImgWidth, att.ImgHeight, att.ImgPointer); if (isTaskRun) { ParentTask.Imgs.Add(new ImgDictionary(Config, OutputImg, ParentTask.Imgs.Count)); } } else { OutputImg = null; return(false); } } else { OutputImg = null; return(false); } break; default: return(false); } return(true); }
private void excelToolStripMenuItem_Click(object sender, EventArgs e) { Excel_APP1 = new Excel.Application(); Excel_WB1 = Excel_APP1.Workbooks.Add(); Excel_WS1 = new Excel.Worksheet(); saveFileDialog1.Filter = "Excel|*.xlsx"; saveFileDialog1.Title = "Save a Excel"; Excel_WS1 = Excel_WB1.Worksheets[1]; Excel_WS1.Name = "Data"; Excel_APP1.Cells[1, 1] = "圖片(.jpg)"; Excel_APP1.Cells[1, 2] = "Profile下"; Excel_APP1.Cells[1, 3] = "Profile上"; OriginalImg1.Load(files[0]); /*============================計算scaling ratio============================*/ float PictureBoxSizeRatio = (float)pbImg1.Width / pbImg1.Height; float ImageSizeRatio = (float)OriginalImg1.Width / OriginalImg1.Height; if (ImageSizeRatio > PictureBoxSizeRatio) { ScalingRatio = (float)pbImg1.Width / OriginalImg1.Width; } else { ScalingRatio = (float)pbImg1.Height / OriginalImg1.Height; } /*=========================================================================*/ for (int i = 0; i < FileListBox.Items.Count; i++) { FileListBox.SelectedIndex = i; FileListBox.Refresh(); OriginalImg1.Load(files[i]); OriginalImg1.Draw(pbImg1.CreateGraphics(), ScalingRatio); //EC24Image2.SetSize(EC24Image1); //EasyImage.Oper(EArithmeticLogicOperation.Copy, new EC24(0, 0, 0), EC24Image2); //EC24Image1.ColorSystem = EColorSystem.Rgb; //EColorLookup1.ConvertFromRgb(EColorSystem.Yiq); //EColorLookup1.Transform(EC24Image1, EC24Image2); //EC24Image2.Draw(pbImg2.CreateGraphics(), ScalingRatio); GrayImg1.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 //EasyImage.Oper(EArithmeticLogicOperation.Subtract, GrayImg1, BackgroundGray, GrayImg1); //EasyImage.Threshold(GrayImg1, GrayImg1, 56); //EasyImage.OpenBox(GrayImg1, GrayImg1, settings.set_value_3()); GrayImg1.Draw(pbImg2.CreateGraphics(), ScalingRatio); EasyImage.ImageToLineSegment(GrayImg1, In, 1485, 700, 1683, 700); //設定車子進入的偵測線,判斷車子是否準備進來 EasyImage.ImageToLineSegment(GrayImg1, Out, 1485, 400, 1683, 400); //設定車子出去的偵測線,判斷車子是否準備出去 Excel_APP1.Cells[2 + i, 1] = Path.GetFileNameWithoutExtension(files[i]); Excel_APP1.Cells[2 + i, 2] = getProfileValueSum(In); Excel_APP1.Cells[2 + i, 3] = getProfileValueSum(Out); //Console.WriteLine(files[i]); } if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "") { Excel_WB1.SaveAs(saveFileDialog1.FileName); } Excel_WS1 = null; Excel_WB1.Close(); Excel_WB1 = null; Excel_APP1.Quit(); Excel_APP1 = null; }
private async void excelToolStripMenuItem2_Click(object sender, EventArgs e) { Excel_APP1 = new Excel.Application(); Excel_WB1 = Excel_APP1.Workbooks.Add(); Excel_WS1 = new Excel.Worksheet(); saveFileDialog1.Filter = "Excel|*.xlsx"; saveFileDialog1.Title = "Save a Excel"; Excel_WS1 = Excel_WB1.Worksheets[1]; Excel_WS1.Name = "Data"; Excel_APP1.Cells[1, 1] = "圖片(.jpg)"; Excel_APP1.Cells[1, 2] = "Profile下"; Excel_APP1.Cells[1, 3] = "Profile上"; Excel_APP1.Cells[1, 4] = "時間"; try { while (framecount != totalframe) { Mat frame = new Mat(); frame = video.QueryFrame(); //擷取影片frame if (frame == null) { break; } pbImg1.Image = frame.Bitmap; //顯示frame fps = video.GetCaptureProperty(CapProp.Fps); //抓影片的fps videotime = video.GetCaptureProperty(CapProp.PosMsec) / 1000; //抓影片時間 framecount = video.GetCaptureProperty(CapProp.PosFrames); Bitmap bitmap_source = (Bitmap)frame.Bitmap; if (bitmap == null) { bitmap = (Bitmap)bitmap_source.Clone(); } bitmap = bitmap_source; if (bitmap == null) { return; } OriginalImg1 = BitmapToEImageC24(ref bitmap); GrayImg1.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 EasyImage.ImageToLineSegment(GrayImg1, In, 413, 104, 797, 104); //設定車子進入的偵測線,判斷車子是否準備進來 EasyImage.ImageToLineSegment(GrayImg1, Out, 325, 891, 776, 891); //設定車子出去的偵測線,判斷車子是否準備出去 ShowImage(GrayImg1, pbImg2); //Console.WriteLine("In:" + getProfileValueSum(In) + " / " + "Out:" + getProfileValueSum(Out) + " / " + "Time:" + videotime); Excel_APP1.Cells[framecount + 1, 1] = framecount.ToString(); Excel_APP1.Cells[framecount + 1, 2] = getProfileValueSum(In); Excel_APP1.Cells[framecount + 1, 3] = getProfileValueSum(Out); Excel_APP1.Cells[framecount + 1, 4] = videotime; bitmap.Dispose(); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); videoInfo.setValue(totalframe, framecount, videotime, fps); await Task.Delay(1000 / Convert.ToInt32(fps)); //延遲 } } catch (Exception ex) { MessageBox.Show(ex.Message); } if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "") { Excel_WB1.SaveAs(saveFileDialog1.FileName); } Excel_WS1 = null; Excel_WB1.Close(); Excel_WB1 = null; Excel_APP1.Quit(); Excel_APP1 = null; }
private async void videoPlayToolStripMenuItem_Click(object sender, EventArgs e) { if (video == null) { return; } if (!play) { play = true; videoPlayToolStripMenuItem.Text = "VideoPause"; } else { play = false; videoPlayToolStripMenuItem.Text = "VideoPlay"; } try { while (play) { Mat frame = new Mat(); if (frame == null) { break; } pbImg1.Image = frame.Bitmap; //顯示frame fps = video.GetCaptureProperty(CapProp.Fps); //抓影片的fps videotime = Math.Round(video.GetCaptureProperty(CapProp.PosMsec) / 1000, 3, MidpointRounding.AwayFromZero); //抓影片時間 framecount = video.GetCaptureProperty(CapProp.PosFrames); refBitmap(frame); OriginalImg1 = BitmapToEImageC24(ref bitmap); if (!firstSet) { GrayImg1.SetSize(OriginalImg1); GrayImg3.SetSize(OriginalImg1); BackgroundGray.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg3); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), BackgroundGray); EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 EasyImage.Convert(OriginalImg1, BackgroundGray); //轉灰階 firstSet = true; } else { EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 //EasyImage.Oper(EArithmeticLogicOperation.Subtract, GrayImg1, BackgroundGray, GrayImg3); //double profilevalue_in = getProfileValueSum(In); //double profilevalue_out = getProfileValueSum(Out); //if (profilevalue_in < 2500 && profilevalue_out < 2500) //{ // Console.WriteLine("Background:" + profilevalue_in); // EasyImage.Convert(OriginalImg1, BackgroundGray); //轉灰階 //} //else //{ // Console.WriteLine("有車進入:" + profilevalue_in); // EasyImage.Convert(OriginalImg1, BackgroundGray); //轉灰階 //} } EasyImage.ImageToLineSegment(GrayImg1, In, 968, 585, 1747, 585); //設定車子進入的偵測線,判斷車子是否準備進來 EasyImage.ImageToLineSegment(GrayImg1, Out, 968, 209, 1747, 209); //設定車子出去的偵測線,判斷車子是否準備出去 Console.WriteLine(getProfileValueSum(In)); ShowImage(GrayImg1, pbImg2); //ShowImage(BackgroundGray, pbImg3); bitmap.Dispose(); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); videoInfo.setValue(totalframe, framecount, videotime, fps); await Task.Delay(1000 / Convert.ToInt32(fps)); //延遲 } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 从EImageBW8中获得DecodeString /// </summary> /// <param name="EImageBW8"></param> /// <param name="Redecode">是否需要重复解析</param> /// <returns></returns> public string GetDecodeStrbyEImageBW8(EImageBW8 EBW8Image1) { EImageBW8 image_bak = new EImageBW8(EBW8Image1); try { //return "1234567890"; //fortest float center_x = image_bak.Width / 2; float center_y = image_bak.Height / 2; for (int i = 0; i <= GlobalVar.gl_decode_times; i++) { if (GlobalVar.gl_inEmergence) { return(""); } EMatrixCodeReader EMatrixCodeReader1 = new EMatrixCodeReader(); // EMatrixCodeReader instance EMatrixCode EMatrixCodeReader1Result = null; // EMatrixCode instance try { EMatrixCodeReader1.TimeOut = GlobalVar.gl_decode_timeout; #region 对图片进行其他处理 ----没有经过验证,无用 //定义数组保存位图 //int bytes = Math.Abs(bmpdata_src.Stride) * bmp.Height; //byte[] rgbvalues = new byte[bytes]; ////复制RGB值到数组 //System.Runtime.InteropServices.Marshal.Copy(pScan0, rgbvalues, 0, bytes); //将每个像素的第三个值设为255. A 24bpp的位图将变红 //for (int counter = 2; counter < rgbvalues.Length; counter += 3) //{ // rgbvalues[counter] = 255; //} //把RGB值拷回位图 //System.Runtime.InteropServices.Marshal.Copy(rgbvalues, 0, ptr, bytes); //解锁 //bmp.UnlockBits(bmpdata_src); //绘制更新了的位图 //DrawImage(bmp, 0, 150); #endregion EMatrixCodeReader1Result = EMatrixCodeReader1.Read(image_bak); return(EMatrixCodeReader1Result.DecodedString); } catch { switch (i) { case 0: //EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 20f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.643"), float.Parse("-69.0")); break; case 1: EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 90f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.643"), float.Parse("-29.0")); break; case 2: //EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 40f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("1.243"), float.Parse("-89.0")); break; case 3: //EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 50f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("1.243"), float.Parse("0.0")); break; case 4: //EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 180f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("1.30"), float.Parse("0.0")); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.0"), float.Parse("48.0")); break; case 5: EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 70f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.643"), float.Parse("0.0")); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.0"), float.Parse("118.0")); break; case 6: EasyImage.ScaleRotate(image_bak, center_x, center_y, center_x, center_y, 1.23f, 1.23f, 80f, image_bak); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.443"), float.Parse("0.0")); image_bak = EImageBW8GainOff(EBW8Image1, float.Parse("0.0"), float.Parse("129.0")); break; } } } return(""); } catch { return(""); } finally { EBW8Image1 = null; image_bak = null; GC.Collect(); } }
private void btnDetect_Click(object sender, EventArgs e) { double t1 = 0, t2 = 0, timeDiff = 0, fov = 5.0, speed = 0; bool hascar = false; valuein = double.Parse(Value_In.Text); valueout = double.Parse(Value_Out.Text); last_In = 0; last_Out = 0; EC24Image1.Load(files[0]); /*============================計算scaling ratio============================*/ float PictureBoxSizeRatio = (float)pbimg.Width / pbimg.Height; float ImageSizeRatio = (float)EC24Image1.Width / EC24Image1.Height; if (ImageSizeRatio > PictureBoxSizeRatio) { ScalingRatio = (float)pbimg.Width / EC24Image1.Width; } else { ScalingRatio = (float)pbimg.Height / EC24Image1.Height; } /*=========================================================================*/ for (int i = 0; i < listBox1.Items.Count; i++) { listBox1.SelectedIndex = i; listBox1.Refresh(); EC24Image1.Load(files[i]); EC24Image1.Draw(pbimg.CreateGraphics(), ScalingRatio); EBW8Image1.SetSize(EC24Image1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), EBW8Image1); EasyImage.Convert(EC24Image1, EBW8Image1); //轉灰階 EasyImage.ImageToLineSegment(EBW8Image1, In, 1000, 1079, 1750, 1079); //設定偵測線在最底部,判斷車子是否準備進來 EasyImage.ImageToLineSegment(EBW8Image1, Out, 1000, 0, 1750, 0); //設定偵測線在最頂部,判斷車子是否準備出去 if (CarIn(In) && !hascar) //假如沒有車子,且CarIn有偵測到車子情況下,視同進入 { previous = i; //記錄車子進來的圖片張數 //t1 = DateTime.Now.TimeOfDay.Seconds + DateTime.Now.TimeOfDay.Milliseconds / 1000.0; //記錄進來的時間 speed = 0; hascar = true; } else if (CarOut(Out) && hascar && speed == 0) //假如有車子,且CarOut有偵測到車子並尚未計算速度的情況下,視同出去 { current = i; //記錄車子出去的圖片張數 if (current - previous <= 10 || current - previous >= 100) //防呆機制,假如10張內或超過100張視同有問題 { //last_Out = 0; hascar = false; } else { Console.WriteLine("車子進來的第一張圖片:" + files[previous]); Console.WriteLine("車子出去的最後一張圖片:" + files[current]); t1 = Double.Parse(Path.GetFileNameWithoutExtension(files[previous])); //擷取進來的圖檔名當作進來的時間 t2 = Double.Parse(Path.GetFileNameWithoutExtension(files[current])); //擷取出去的圖檔名當作出去的時間 //t2 = DateTime.Now.TimeOfDay.Seconds + DateTime.Now.TimeOfDay.Milliseconds / 1000.0; //記錄出去的時間 Console.WriteLine("T1=" + t1.ToString()); Console.WriteLine("T2=" + t2.ToString()); //秒數做溢位處理 /* * if (t1 > t2) * timeDiff = (t2 + 60) - t1; * else */ timeDiff = t2 - t1; //出去的時間減去進來的時間 Console.WriteLine("timeDiff = " + timeDiff); speed = fov / (timeDiff / 4) * 3.6; //計算車子的速度,因為採用4倍慢速錄影所以時間要除以4,速度單位為km/hr speed = Math.Round(speed, 2, MidpointRounding.AwayFromZero); //將速度四捨五入 labelSpeed.Text = "Speed: " + speed.ToString(); Console.WriteLine("Speed: " + speed); labelSpeed.Update(); last_In = 0; hascar = false; } } } }
private void vehicleToolStripMenuItem_Click(object sender, EventArgs e) { float PictureBoxSizeRatio, ImageSizeRatio; codedImage1ObjectSelection.FeretAngle = 0.00f; codedImage1Encoder.GrayscaleSingleThresholdSegmenter.WhiteLayerEncoded = true; codedImage1Encoder.GrayscaleSingleThresholdSegmenter.BlackLayerEncoded = false; codedImage1Encoder.SegmentationMethod = ESegmentationMethod.GrayscaleSingleThreshold; codedImage1Encoder.GrayscaleSingleThresholdSegmenter.Mode = EGrayscaleSingleThreshold.MinResidue; OriginalImg1.Load(files[0]); /*============================計算scaling ratio============================*/ PictureBoxSizeRatio = (float)pbImg1.Width / pbImg1.Height; ImageSizeRatio = (float)OriginalImg1.Width / OriginalImg1.Height; if (ImageSizeRatio > PictureBoxSizeRatio) { ScalingRatio = (float)pbImg1.Width / OriginalImg1.Width; } else { ScalingRatio = (float)pbImg1.Height / OriginalImg1.Height; } /*=========================================================================*/ for (int i = 0; i < FileListBox.Items.Count; i++) { FileListBox.SelectedIndex = i; FileListBox.Refresh(); OriginalImg1.Load(files[i]); OriginalImg1.Draw(pbImg1.CreateGraphics(), ScalingRatio); GrayImg1.SetSize(OriginalImg1); EasyImage.Oper(EArithmeticLogicOperation.Copy, new EBW8(0), GrayImg1); EasyImage.Convert(OriginalImg1, GrayImg1); //轉灰階 EasyImage.Median(BackgroundGray, BackgroundGray); EasyImage.Median(GrayImg1, GrayImg1); EasyImage.Oper(EArithmeticLogicOperation.Subtract, GrayImg1, BackgroundGray, GrayImg1); EasyImage.Threshold(GrayImg1, GrayImg1, unchecked ((uint)EThresholdMode.MinResidue)); EasyImage.ErodeBox(GrayImg1, GrayImg1, 1); //侵蝕 EasyImage.CloseBox(GrayImg1, GrayImg1, 10); //閉合 codedImage1ObjectSelection.FeretAngle = 0.00f; codedImage1Encoder.Encode(GrayImg1, codedImage1); codedImage1ObjectSelection.Clear(); codedImage1ObjectSelection.AddObjects(codedImage1); codedImage1ObjectSelection.AttachedImage = GrayImg1; codedImage1ObjectSelection.RemoveUsingUnsignedIntegerFeature(EFeature.RunCount, 1000, ESingleThresholdMode.Less); //移除RunCount小於1000的物件 if (codedImage1ObjectSelection.ElementCount > 0) { Console.WriteLine("(" + codedImage1ObjectSelection.GetElement(0).BoundingBoxCenterX + ", " + codedImage1ObjectSelection.GetElement(0).BoundingBoxCenterY + ")"); } codedImage1.DrawFeature(pbImg1.CreateGraphics(), EDrawableFeature.BoundingBox, codedImage1ObjectSelection, ScalingRatio); // 把車的框框畫出來 GrayImg1.Draw(pbImg2.CreateGraphics(), ScalingRatio); Console.WriteLine(files[i]); } }