/// <summary> /// Tests the statistics calculation for consistency over a number of trial runs using the same shape. /// </summary> protected void TestRoiStatsCalculationConsistency() { const int samples = 100; const int gridSize = 4; foreach (ImageKey imageKey in Enum.GetValues(typeof(ImageKey))) { WriteLine("Testing on Image {0}", imageKey.ToString()); using (IPresentationImage image = GetImage(imageKey)) { IImageSopProvider provider = (IImageSopProvider)image; IOverlayGraphicsProvider overlayGraphicsProvider = (IOverlayGraphicsProvider)image; int rows = provider.Frame.Rows; int cols = provider.Frame.Columns; for (int r = rows / gridSize / 2; r < rows; r += rows / gridSize) { for (int c = cols / gridSize / 2; c < cols; c += cols / gridSize) { if (this.VerboseOutput) { WriteLine("Checking {0} core samples for consistent results at location {1}", samples, new PointF(c, r)); } T shapeData = CreateCoreSampleShape(new PointF(c, r), rows, cols); double expectedArea = 0, expectedMean = 0, expectedSigma = 0; for (int n = 0; n < samples; n++) { Roi userRoi = CreateRoiFromGraphic(overlayGraphicsProvider, shapeData); RoiStatistics stats = RoiStatistics.Calculate(userRoi); if (n == 0) { if (userRoi is IRoiAreaProvider) { expectedArea = ((IRoiAreaProvider)userRoi).Area; } expectedMean = stats.Mean; expectedSigma = stats.StandardDeviation; if (this.VerboseOutput) { WriteLine("First sample reported A={0:f0} \u03BC={1:f3} \u03C3={2:f3}", expectedArea, expectedMean, expectedSigma); } continue; } // very strict tolerance. performing the calculation the first time should yield the same result as the next hundred times. if (userRoi is IRoiAreaProvider) { Assert.AreEqual(expectedArea, ((IRoiAreaProvider)userRoi).Area, double.Epsilon, "Area calculation consistency fail."); } Assert.AreEqual(expectedMean, stats.Mean, double.Epsilon, "Mean calculation consistency fail."); Assert.AreEqual(expectedSigma, stats.StandardDeviation, double.Epsilon, "Stdev calculation consistency fail."); } } } } } }
public bool isTeamOnEchec(team team) { team otherTeam = (team == team.WHITE) ? team.BLACK : team.WHITE; Roi king = _kings[(int)team]; foreach (Piece ennemy in _teamPieces[(int)otherTeam]) { if (ennemy.alive == true) { int dX = (int)king.x - (int)ennemy.x; int dZ = (int)king.z - (int)ennemy.z; if (ennemy.team == team.WHITE) { dZ *= -1; } if (ennemy.canMoveOf(dX, dZ, false)) { king.GetComponent <Highlight>().on(new Color32(191, 10, 10, 255)); ennemy.GetComponent <Highlight>().on(new Color32(184, 87, 0, 255)); return(true); } } } return(false); }
private void ChangeColorBrightnessRoi(Point mousePoint) { int indexNearestRect = 0; DrawRois(); foreach (var roi in rois) { if (!roi.Rect.Contains(mousePoint)) { continue; } // マウスポイントと中心位置が一番近いROIを検索する double distance = CalculateDistanceSquared(roi.Center, mousePoint); double distanceNearest = CalculateDistanceSquared(this.nearestRect.Center, mousePoint); if (distance <= distanceNearest) { this.nearestRect = roi; indexNearestRect = rois.IndexOf(roi); } } bool hasNearestRoiRect = rois.Any(x => x.Rect.Contains(mousePoint)); if (hasNearestRoiRect) { var path = CreatePath(this.nearestRect.Rect, CreateColorBrush()); DisplayService.Replace(indexNearestRect, path); this.rois[indexNearestRect] = this.nearestRect; } }
/// <summary> /// Bitmap to roi converter. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="name">The name.</param> /// <returns> /// Roi dataset. /// </returns> public Roi BitmapToRoi(Bitmap bitmap, string name) { var color = default(Color); var roiColor = 0; var roidataset = new Roi( name, (uint)bitmap.Width, (uint)bitmap.Height, new List <RoiPixel>()); for (int xcoordinate = 0; xcoordinate < bitmap.Width; xcoordinate++) { for (int ycoordinate = 0; ycoordinate < bitmap.Height; ycoordinate++) { color = bitmap.GetPixel(xcoordinate, ycoordinate); if (color.B == roiColor) { roidataset.RoiPixels.Add(new RoiPixel(xcoordinate, ycoordinate)); } } } return(roidataset); }
private Roi FindTopRoi(Node map) { // Must be called node locked if (map == null) { return(null); } Roi roi = map as Roi; if (roi != null) { return(roi); } Group grp = map as Group; if (grp != null) { foreach (Node child in grp) { Roi sub = FindTopRoi(child); if (sub != null) { return(sub); } } } return(null); }
public static void ThrowIfNotSingleAnnulus(Roi roi) { if (roi.Count != 1 || roi[0].Type != ContourType.Annulus) { throw new VisionException(ErrorCode.RoiNotAnnulus); } }
private static void IVA_Mask_From_ROI(VisionImage image, Roi roi, bool invertMask, bool extractRegion) { using (VisionImage imageMask = new VisionImage(ImageType.U8, 7)) { PixelValue fillValue = new PixelValue(255); // Transforms the region of interest into a mask image. Algorithms.RoiToMask(imageMask, roi, fillValue, image); if (invertMask) { // Inverts the mask image. Algorithms.Xor(imageMask, fillValue, imageMask); } // Masks the input image using the mask image we just created. Algorithms.Mask(image, image, imageMask); if (extractRegion) { // Extracts the bounding box. Algorithms.Extract(image, image, roi.GetBoundingRectangle()); } } }
public Roi FindTopRoi(Node map) { if (map == null) { return(null); } Roi roi = map as Roi; if (roi != null) { return(roi); } Group grp = map as Group; if (grp != null) { foreach (Node child in grp) { Roi sub = FindTopRoi(child); if (sub != null) { return(sub); } } } return(null); }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) return null; IRoiLengthProvider lengthProvider = (IRoiLengthProvider) roi; Units oldUnits = lengthProvider.Units; lengthProvider.Units = lengthProvider.IsCalibrated ? _units : Units.Pixels; IRoiAnalyzerResult result; if (!lengthProvider.IsCalibrated || _units == Units.Pixels) { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthPixels, lengthProvider.Length, String.Format(SR.FormatLengthPixels, lengthProvider.Length)); } else if (_units == Units.Millimeters) { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthMm, lengthProvider.Length, String.Format(SR.FormatLengthMm, lengthProvider.Length)); } else { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthCm, lengthProvider.Length, String.Format(SR.FormatLengthCm, lengthProvider.Length)); } lengthProvider.Units = oldUnits; return result; }
private void btnFindTemp_Click(object sender, EventArgs e) { CPKTools tools = new CPKTools(); VisionImage align = this.image_Edit.Image; VisionImage image = Form_Main.Instance.imageSet.Image; Roi roi = Form_Main.Instance.imageSet.Roi; short Score = 600; double MinR = -10; double MaxR = 10; short rtn = 0; Variable.CamReturn camReturn = new Variable.CamReturn(); // 初步匹配 rtn = Form_Main.Instance.CamDetect_SearchGeometric(image, align, roi, Score, 1, MinR, MaxR, 100, 100, 0, 25, ref camReturn, 0, 0); if (rtn != 0) { MessageBox.Show("寻找模板失败,请检查参数!!!"); } // 记录ROI 的坐标 if (roi.Count > 0) { RectangleContour rect = (RectangleContour)roi[0].Shape; // save rect string strRoi = string.Format("{0},{1},{2},{3}", rect.Top, rect.Left, rect.Width, rect.Height); this.cpkIni.IniWriteValue("vision", "TemplateRoi", strRoi); } }
public static void LearnPattern(ImageViewer SourceImage, float fUpper = 0, float fLower = 0) { using (VisionImage plane = new VisionImage(ImageType.U8, 7)) { // Extract the green color plane and copy it to the main image. if (SourceImage.Image.Type == ImageType.Rgb32) { Algorithms.ExtractColorPlanes(SourceImage.Image, NationalInstruments.Vision.ColorMode.Rgb, null, plane, null); Algorithms.Copy(plane, SourceImage.Image); } } // Algorithms.LearnPattern2(SourceImage.Image); OvalContour vaRect2 = new OvalContour(0, 0, 0, 0); Roi roi = new Roi(); roi.Add(vaRect2); // Histogram Grayscale using (VisionImage imageMask = new VisionImage(ImageType.U8, 7)) { RotationAngleRange ra = new RotationAngleRange(fLower, fUpper); PixelValue fillValue = new PixelValue(255); Algorithms.RoiToMask(imageMask, roi, fillValue, SourceImage.Image); Algorithms.LearnPattern2(SourceImage.Image, imageMask, MatchingAlgorithm.MatchGrayValuePyramid, ra); } roi.Dispose(); }
private static void ThrowIfNotSingleRectangleOrNone(Roi roi) { if (roi.Count > 1 || (roi.Count > 0 && roi[0].Type != ContourType.Rectangle)) { throw new VisionException(ErrorCode.RoiNotRect); } }
//////////////////////////////////////////////////////////////////////////////// // // Function Name: IVA_Classification_Extract_Particles // // Description : Extracts the region of interests of the bounding rectangles of // all particles. // // Parameters : image - Input image // imageMask - Image mask // rois - Array of ROIs // // Return Value : success // //////////////////////////////////////////////////////////////////////////////// public static Collection <Roi> IVA_Classification_Extract_Particles(VisionImage image, VisionImage imageMask) { Collection <MeasurementType> measurements = new Collection <MeasurementType>(); measurements.Add(MeasurementType.BoundingRectLeft); measurements.Add(MeasurementType.BoundingRectTop); measurements.Add(MeasurementType.BoundingRectRight); measurements.Add(MeasurementType.BoundingRectBottom); // Compute the region of interests around each particle. ParticleMeasurementsReport particleReport = Algorithms.ParticleMeasurements(imageMask, measurements, Connectivity.Connectivity8, ParticleMeasurementsCalibrationMode.Pixel); Collection <Roi> rois = new Collection <Roi>(); for (int i = 0; i < particleReport.PixelMeasurements.GetLength(0); i++) { double top = particleReport.PixelMeasurements[i, 1] + imageMask.MaskOffset.Y - 5; top = (top < 0 ? 0 : top); double left = particleReport.PixelMeasurements[i, 0] + imageMask.MaskOffset.X - 5; left = (left < 0 ? 0 : left); double bottom = particleReport.PixelMeasurements[i, 3] + imageMask.MaskOffset.Y + 5; bottom = (bottom > (image.Height - 1) ? (image.Height - 1) : bottom); double right = particleReport.PixelMeasurements[i, 2] + imageMask.MaskOffset.X + 5; right = (right > (image.Width - 1) ? (image.Width - 1) : right); Roi particleROI = new Roi(); particleROI.Add(new RectangleContour(left, top, right - left + 1, bottom - top + 1)); rois.Add(particleROI); } return(rois); }
/// <summary> /// 找到一个圆 /// </summary> /// <param name="image">图片</param> /// <param name="rect">ROI</param> /// <param name="minr">最小圆半径</param> /// <param name="maxr">最大圆半径</param> /// <param name="center">圆心</param> /// <param name="radius">半径</param> /// <param name="gain">预处理参数</param> /// <param name="offset">预处理参数</param> /// <param name="cycle">预处理参数</param> /// <returns>找到/没找到</returns> public static bool FindCircle(VisionImage image, RectangleContour rect, short minr, short maxr, ref PointContour center, ref double radius, double gain, double offset, int cycle) { if (image == null) { return(false); } for (int i = 0; i < cycle; i++) { image = Form_Main.Instance.GainOffset(image, gain, offset); } Roi roi = rect.ConvertToRoi(); short rtn = 0; try { rtn = Form_Main.Instance.CamDetect_Circle(image, roi, minr, maxr, ref center, ref radius); if (rtn != 0) { return(false); } } catch { return(false); } return(true); }
/// <summary> /// 创建NCC模板 /// </summary> /// <param name="img">图像</param> /// <param name="Roi">ROI</param> /// <param name="ModeID">NCC模板</param> /// <returns></returns> public static bool CreatNCCTemplate(VisionImage img, Roi Roi, out HTuple ModeID) { img.Type = ImageType.U8; ModeID = null; HObject Himage = null, HRoi = null; HObject imgreduced = null; try { HOperatorSet.GenImage1(out Himage, "byte", img.Width, img.Height, img.StartPtr); HOperatorSet.GenRectangle1(out HRoi, ((RectangleContour)Roi[0].Shape).Top, ((RectangleContour)Roi[0].Shape).Left, ((RectangleContour)Roi[0].Shape).Top + ((RectangleContour)Roi[0].Shape).Height, ((RectangleContour)Roi[0].Shape).Left + ((RectangleContour)Roi[0].Shape).Width); HOperatorSet.ReduceDomain(Himage, HRoi, out imgreduced); HOperatorSet.CreateNccModel(imgreduced, "auto", 0, 0, "auto", "use_polarity", out ModeID); Himage.Dispose(); HRoi.Dispose(); imgreduced.Dispose(); return(true); } catch (Exception) { Himage?.Dispose(); imgreduced?.Dispose(); return(false); } }
internal void HighlightWordCandidate(IEnumerable <CandidateData> wordsCandidates) { // Clear prev candidate ROI var remove = m_imageViewerVM.ImageViewerViewModel.RecognitionRois.Where(x => x.LinkedObject == "WordCandidate").ToList(); foreach (var item in remove) { m_imageViewerVM.ImageViewerViewModel.Rois.Remove(item); } m_imageViewerVM.ImageViewerViewModel.SelectedRois.Clear(); // Add new candidate ROI foreach (var wordCandidate in wordsCandidates.SelectMany(x => x.Words)) { var originalWordRec = wordCandidate.OriginRectangle; var recFieldRoi = new Roi() { Rect = new System.Windows.Rect( originalWordRec.X, originalWordRec.Y, originalWordRec.Width, originalWordRec.Height), LinkedObject = "WordCandidate" }; m_imageViewerVM.ImageViewerViewModel.RecognitionRois.Add(recFieldRoi); m_imageViewerVM.ImageViewerViewModel.SelectedRois.Add(recFieldRoi); } }
public static void ThrowIfNotSingleLine(Roi roi) { if (roi.Count != 1 || roi[0].Type != ContourType.Line) { throw new VisionException(ErrorCode.RoiNotLine); } }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) { return(null); } IRoiLengthProvider lengthProvider = (IRoiLengthProvider)roi; Units oldUnits = lengthProvider.Units; lengthProvider.Units = lengthProvider.IsCalibrated ? _units : Units.Pixels; IRoiAnalyzerResult result; if (!lengthProvider.IsCalibrated || _units == Units.Pixels) { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthPixels, lengthProvider.Length, String.Format(SR.FormatLengthPixels, lengthProvider.Length)); } else if (_units == Units.Millimeters) { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthMm, lengthProvider.Length, String.Format(SR.FormatLengthMm, lengthProvider.Length)); } else { result = new SingleValueRoiAnalyzerResult("Length", SR.FormatLengthCm, lengthProvider.Length, String.Format(SR.FormatLengthCm, lengthProvider.Length)); } lengthProvider.Units = oldUnits; return(result); }
public Roi CreateRoi(Point point) { var lefttopX = Math.Max(Math.Min(point.X + 50, canvas.ActualWidth) - 100, 0); var lefttopY = Math.Max(Math.Min(point.Y + 50, canvas.ActualHeight) - 100, 0); var roi = new Roi(lefttopX, lefttopY, 100, 100); return(roi); }
public IActionResult Calculate(Roi roi) { roi.RoiValue = (roi.GainFromInvestment - roi.CostOfInvestment) / roi.CostOfInvestment; return(View("Index", roi)); }
private void Form1_Load(object sender, EventArgs e) { // Use FindLcdSegments to get the appropriate Roi. lcdRoi = Algorithms.FindLcdSegments(GetNextImage(), new RectangleContour(27, 55, 243, 92)); // Enable the timer. timer1.Enabled = true; timer1_Tick(timer1, EventArgs.Empty); }
public static PaletteType ProcessImage(VisionImage image) { // Initialize the IVA_Data structure to pass results and coordinate systems. IVA_Data ivaData = new IVA_Data(3, 0); // Extract Color Plane using (VisionImage plane = new VisionImage(ImageType.U8, 7)) { // Extract the green color plane and copy it to the main image. Algorithms.ExtractColorPlanes(image, ColorMode.Rgb, null, plane, null); Algorithms.Copy(plane, image); } // Creates a new, empty region of interest. Roi roi = new Roi(); // Creates a new RectangleContour using the given values. RectangleContour vaRect = new RectangleContour(20, 20, 2552, 1904); roi.Add(vaRect); // Geometric Matching string vaTemplateFile = $"{ @"./VisionModel/Polygon_20.5M/Mode.png"}"; CurveOptions vaCurveOptions = new CurveOptions(); vaCurveOptions.ColumnStepSize = 15; vaCurveOptions.ExtractionMode = ExtractionMode.NormalImage; vaCurveOptions.FilterSize = EdgeFilterSize.Normal; vaCurveOptions.MaximumEndPointGap = 10; vaCurveOptions.MinimumLength = 20; vaCurveOptions.RowStepSize = 15; vaCurveOptions.Threshold = 145; MatchGeometricPatternEdgeBasedOptions matchGPMOptions = new MatchGeometricPatternEdgeBasedOptions(); matchGPMOptions.Advanced.ContrastMode = ContrastMode.Original; matchGPMOptions.Advanced.MatchStrategy = GeometricMatchingSearchStrategy.Balanced; matchGPMOptions.MinimumMatchScore = 800; matchGPMOptions.Mode = GeometricMatchModes.RotationInvariant; matchGPMOptions.NumberOfMatchesRequested = 1; double[] vaRangesMin = { -20, 0, 50, 0 }; double[] vaRangesMax = { 20, 0, 200, 50 }; matchGPMOptions.OcclusionRange = new Range(vaRangesMin[3], vaRangesMax[3]); matchGPMOptions.RotationAngleRanges.Add(new Range(vaRangesMin[0], vaRangesMax[0])); matchGPMOptions.RotationAngleRanges.Add(new Range(vaRangesMin[1], vaRangesMax[1])); matchGPMOptions.ScaleRange = new Range(vaRangesMin[2], vaRangesMax[2]); matchGPMOptions.SubpixelAccuracy = true; gpm2Results = IVA_MatchGeometricPattern2(image, vaTemplateFile, vaCurveOptions, matchGPMOptions, ivaData, 2, roi); roi.Dispose(); // Dispose the IVA_Data structure. ivaData.Dispose(); // Return the palette type of the final image. return(PaletteType.Gray); }
private void MoveRoi(Point mousePoint, MouseButtonState leftButton) { if (CurrentButtonState == ButtonState.Select && this.hasSelectedRoi) { if (leftButton == MouseButtonState.Pressed) { if (!_inDraw && _inDrag) { Roi roi = CreateRoi(mousePoint); this.rois[selectedRoiIndex] = roi; DrawRois(); } // resize ROI //else if (_inDraw && !_inDrag) //{ // this.ResizeSelectedRoi(clickedPoint); //} //else //{ // // Not implemented //} //anchorPoint = clickedPoint; } else { // change mouse point when mouse is on the selected ROI //if (indexNearestRect == selectedRoiIndex) //{ // MouseHitType = SetHitType(clickedPoint); // SetMouseCursor(); // if (MouseHitType == HitType.Body) // { // _inDrag = true; // _inDraw = false; // } // else if (MouseHitType != HitType.None) // { // _inDrag = false; // _inDraw = true; // } // else // { // _inDrag = false; // _inDraw = false; // } //} //else //{ // MouseHitType = HitType.None; // Mouse.OverrideCursor = Cursors.Arrow; //} } } }
private static void ThrowIfNotAllPoints(Roi roi) { foreach (Contour c in roi) { if (c.Type != ContourType.Point) { throw new VisionException(ErrorCode.RoiNotPoints); } } }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> //public string Analyze(Roi roi, RoiAnalysisMode mode) //{ // if (!SupportsRoi(roi)) // return null; // // performance enhancement to restrict excessive computation of polygon area. // if (mode == RoiAnalysisMode.Responsive) // { // if (_units == Units.Pixels) // return String.Format(SR.FormatAreaPixels, SR.StringNoValue); // else if (_units == Units.Millimeters) // return String.Format(SR.FormatAreaSquareMm, SR.StringNoValue); // else // return String.Format(SR.FormatAreaSquareCm, SR.StringNoValue); // } // IRoiAreaProvider areaProvider = (IRoiAreaProvider) roi; // string text; // Units oldUnits = areaProvider.Units; // areaProvider.Units = areaProvider.IsCalibrated ? _units : Units.Pixels; // if (!areaProvider.IsCalibrated || _units == Units.Pixels) // text = String.Format(SR.FormatAreaPixels, areaProvider.Area); // else if (_units == Units.Millimeters) // text = String.Format(SR.FormatAreaSquareMm, areaProvider.Area); // else // text = String.Format(SR.FormatAreaSquareCm, areaProvider.Area); // areaProvider.Units = oldUnits; // return text; //} /// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) { return(null); } // performance enhancement to restrict excessive computation of polygon area. if (mode == RoiAnalysisMode.Responsive) { if (_units == Units.Pixels) { return(new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsPixels, SR.StringNoValue))); } if (_units == Units.Millimeters) { return(new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsMm2, SR.StringNoValue))); } return (new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsCm2, SR.StringNoValue))); } IRoiAreaProvider areaProvider = (IRoiAreaProvider)roi; IRoiAnalyzerResult result; Units oldUnits = areaProvider.Units; areaProvider.Units = areaProvider.IsCalibrated ? _units : Units.Pixels; if (!areaProvider.IsCalibrated || _units == Units.Pixels) { result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsPixels, areaProvider.Area, String.Format(SR.FormatAreaPixels, areaProvider.Area)); } else if (_units == Units.Millimeters) { result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsMm2, areaProvider.Area, String.Format(SR.FormatAreaSquareMm, areaProvider.Area)); } else { result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsCm2, areaProvider.Area, String.Format(SR.FormatAreaSquareCm, areaProvider.Area)); } areaProvider.Units = oldUnits; return(result); }
/// <summary> /// This method converts the Roi to a collection of points. /// Requires that the Roi is not null and not disposed. /// </summary> /// <param name="roi">The Roi to convert</param> /// <returns>The points in the Roi</returns> public static Collection <PointContour> ConvertRoiToPoints(Roi roi) { Utilities.ThrowIfNotAllPoints(roi); Collection <PointContour> points = new Collection <PointContour>(); foreach (Contour c in roi) { points.Add((PointContour)c.Shape); } return(points); }
/// <summary> /// Writes list of doubles into a png file. /// </summary> /// <param name="roidataset">The prototyp.</param> /// <param name="path">The path.</param> public void RoiWriterTool(Roi roidataset, string path) { var roiConverter = new RoiConverter(); using (var bitmap = roiConverter.RoiToBitmap(roidataset)) { var writepath = Path.GetFullPath(Path.Combine(path, roidataset.Name)); bitmap.Save(writepath + ".png", ImageFormat.Png); } }
/// <summary> /// This method converts the Roi to a RectangleContour or RectangleContour.None. /// Requires that the Roi is not disposed (checks if it's a rectangle or not) /// </summary> /// <param name="roi">The Roi to convert</param> /// <returns>The RectangleContour in the Roi</returns> public static RectangleContour ConvertRoiToRectangle(Roi roi) { if (roi != null) { Utilities.ThrowIfNotSingleRectangleOrNone(roi); if (roi.Count > 0) { return((RectangleContour)roi[0].Shape); } } return(RectangleContour.None); }
private void timer1_Tick(object sender, EventArgs e) { // Get the next image. VisionImage image = GetNextImage(); // Look for rotational shift in the image. PointContour imageCenter = new PointContour(image.Width / 2.0, image.Height / 2.0); double angle = Algorithms.DetectRotation(images[0], image, imageCenter, imageCenter, (int)(.475 * image.Width)); // Transform the regions of interest. CoordinateTransform transform = new CoordinateTransform(new CoordinateSystem(imageCenter), new CoordinateSystem(imageCenter, angle)); // Copy to a new Roi so we don't lose the information. Roi transformedRoi = new Roi(testLines); Algorithms.TransformRoi(transformedRoi, transform); // Find the actual number of edges along each line in the image. bool allTargetsPassed = true; for (int i = 0; i < transformedRoi.Count; ++i) { Collection <PointContour> linePoints = Algorithms.GetPointsOnLine((LineContour)transformedRoi[i].Shape); Collection <PointContour> edges = Algorithms.SimpleEdge(image, linePoints, simpleEdgeOptions); // Display the results. GetActualTextBox(i).Text = edges.Count.ToString(); foreach (PointContour pt in edges) { image.Overlays.Default.AddOval(new OvalContour(pt.X - 2, pt.Y - 2, 5, 5), Rgb32Value.YellowColor, DrawingMode.PaintValue); } if (Int32.Parse(GetExpectedTextBox(i).Text) == edges.Count) { // Part passes. GetPassFailLed(i).Value = true; image.Overlays.Default.AddLine((LineContour)transformedRoi[i].Shape, Rgb32Value.GreenColor); } else { // Part fails. GetPassFailLed(i).Value = false; image.Overlays.Default.AddLine((LineContour)transformedRoi[i].Shape, Rgb32Value.RedColor); } allTargetsPassed = allTargetsPassed && GetPassFailLed(i).Value; } globalPassFailLed.Value = allTargetsPassed; // Overlay the outside circle of the part. OvalContour outsideOval = new OvalContour(image.Width * .025, image.Height * .025, image.Width * .95, image.Height * .95); image.Overlays.Default.AddOval(outsideOval, allTargetsPassed ? Rgb32Value.GreenColor : Rgb32Value.RedColor); imageViewer1.Attach(image); }
public bool ComputeHistogram() { Roi roi = GetRoi(); if (roi != null) { return(ComputeHistogram(roi)); } this.Enabled = false; return(false); }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> //public string Analyze(Roi roi, RoiAnalysisMode mode) //{ // if (!SupportsRoi(roi)) // return null; // IRoiStatisticsProvider statisticsProvider = (IRoiStatisticsProvider) roi; // StringBuilder sb = new StringBuilder(); // bool isGrayscale = roi.PixelData is GrayscalePixelData; // var meanValue = SR.StringNotApplicable; // var stdDevValue = SR.StringNotApplicable; // if (isGrayscale && roi.ContainsPixelData) // { // if (mode == RoiAnalysisMode.Responsive) // { // meanValue = stdDevValue = SR.StringNoValue; // } // else // { // double mean = statisticsProvider.Mean; // double stdDev = statisticsProvider.StandardDeviation; // var units = roi.ModalityLutUnits.Label; // var displayFormat = @"{0:" + (roi.SubnormalModalityLut ? @"G3" : @"F1") + "}" + (!string.IsNullOrEmpty(units) ? ' ' + units : string.Empty); // meanValue = string.Format(displayFormat, mean); // stdDevValue = string.Format(displayFormat, stdDev); // } // } // sb.AppendFormat(SR.FormatMean, meanValue); // sb.AppendLine(); // sb.AppendFormat(SR.FormatStdDev, stdDevValue); // return sb.ToString(); //} public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) { return(null); } IRoiStatisticsProvider statisticsProvider = (IRoiStatisticsProvider)roi; MultiValueRoiAnalyzerResult result = new MultiValueRoiAnalyzerResult("Statistics") { ShowHeader = false }; bool isGrayscale = roi.PixelData is GrayscalePixelData; var meanValue = SR.StringNotApplicable; var stdDevValue = SR.StringNotApplicable; if (isGrayscale && roi.ContainsPixelData) { if (mode == RoiAnalysisMode.Responsive) { meanValue = stdDevValue = SR.StringNoValue; result.Add(new RoiAnalyzerResultNoValue("Mean", String.Format(SR.FormatMean, meanValue))); result.Add(new RoiAnalyzerResultNoValue("StdDev", String.Format(SR.FormatStdDev, stdDevValue))); } else { double mean = statisticsProvider.Mean; double stdDev = statisticsProvider.StandardDeviation; var units = roi.ModalityLutUnits.Label; var displayFormat = @"{0:" + (roi.SubnormalModalityLut ? @"G3" : @"F1") + "}" + (!string.IsNullOrEmpty(units) ? ' ' + units : string.Empty); meanValue = string.Format(displayFormat, mean); stdDevValue = string.Format(displayFormat, stdDev); result.Add(new SingleValueRoiAnalyzerResult("Mean", units, mean, String.Format(SR.FormatMean, meanValue))); result.Add(new SingleValueRoiAnalyzerResult("StdDev", units, stdDevValue, String.Format(SR.FormatStdDev, stdDevValue))); } } else { result.Add(new RoiAnalyzerResultNoValue("Mean", String.Format(SR.FormatMean, meanValue))); result.Add(new RoiAnalyzerResultNoValue("StdDev", String.Format(SR.FormatStdDev, stdDevValue))); } return(result); }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) return null; IRoiStatisticsProvider statisticsProvider = (IRoiStatisticsProvider) roi; MultiValueRoiAnalyzerResult result = new MultiValueRoiAnalyzerResult("Statistics") {ShowHeader = false}; bool isGrayscale = roi.PixelData is GrayscalePixelData; var meanValue = SR.StringNotApplicable; var stdDevValue = SR.StringNotApplicable; if (isGrayscale && roi.ContainsPixelData) { if (mode == RoiAnalysisMode.Responsive) { meanValue = stdDevValue = SR.StringNoValue; result.Add(new RoiAnalyzerResultNoValue("Mean", String.Format(SR.FormatMean, meanValue))); result.Add(new RoiAnalyzerResultNoValue("StdDev", String.Format(SR.FormatStdDev, stdDevValue))); } else { double mean = statisticsProvider.Mean; double stdDev = statisticsProvider.StandardDeviation; var units = roi.ModalityLutUnits.Label; var displayFormat = @"{0:" + (roi.SubnormalModalityLut ? @"G3" : @"F1") + "}" + (!string.IsNullOrEmpty(units) ? ' ' + units : string.Empty); meanValue = string.Format(displayFormat, mean); stdDevValue = string.Format(displayFormat, stdDev); result.Add(new SingleValueRoiAnalyzerResult("Mean", units, mean, String.Format(SR.FormatMean, meanValue))); result.Add(new SingleValueRoiAnalyzerResult("StdDev", units, stdDevValue, String.Format(SR.FormatStdDev, stdDevValue))); } } else { result.Add(new RoiAnalyzerResultNoValue("Mean", String.Format(SR.FormatMean, meanValue))); result.Add(new RoiAnalyzerResultNoValue("StdDev", String.Format(SR.FormatStdDev, stdDevValue))); } return result; }
/// <summary> /// Analyzes the given ROI. /// </summary> /// <param name="roi">The ROI being analyzed.</param> /// <param name="mode">The analysis mode.</param> /// <returns>A string containing the analysis results, which can be appended to the analysis /// callout of the associated <see cref="RoiGraphic"/>, if one exists.</returns> public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { if (!SupportsRoi(roi)) return null; // performance enhancement to restrict excessive computation of polygon area. if (mode == RoiAnalysisMode.Responsive) { if (_units == Units.Pixels) return new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsPixels, SR.StringNoValue)); if (_units == Units.Millimeters) return new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsMm2, SR.StringNoValue)); return new RoiAnalyzerResultNoValue("Area", String.Format(SR.LabelUnitsCm2, SR.StringNoValue)); } IRoiAreaProvider areaProvider = (IRoiAreaProvider) roi; IRoiAnalyzerResult result; Units oldUnits = areaProvider.Units; areaProvider.Units = areaProvider.IsCalibrated ? _units : Units.Pixels; if (!areaProvider.IsCalibrated || _units == Units.Pixels) result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsPixels, areaProvider.Area, String.Format(SR.FormatAreaPixels, areaProvider.Area)); else if (_units == Units.Millimeters) result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsMm2, areaProvider.Area, String.Format(SR.FormatAreaSquareMm, areaProvider.Area)); else result = new SingleValueRoiAnalyzerResult("Area", SR.LabelUnitsCm2, areaProvider.Area, String.Format(SR.FormatAreaSquareCm, areaProvider.Area)); areaProvider.Units = oldUnits; return result; }
public bool SupportsRoi(Roi roi) { return roi is ProtractorRoi; }
/// <summary> /// Checks if this analyzer class can analyze the given ROI. /// </summary> /// <param name="roi">The ROI to analyze.</param> /// <returns>True if this class can analyze the given ROI; False otherwise.</returns> public bool SupportsRoi(Roi roi) { return roi is IRoiAreaProvider; }
/// <summary> /// Checks if this analyzer class can analyze the given ROI. /// </summary> /// <param name="roi">The ROI to analyze.</param> /// <returns>True if this class can analyze the given ROI; False otherwise.</returns> public bool SupportsRoi(Roi roi) { return roi is IRoiLengthProvider; }
/// <summary> /// Checks if this analyzer class can analyze the given ROI. /// </summary> /// <remarks> /// Implementations should return a result based on the type of ROI, not on the particular current state of the ROI. /// </remarks> /// <param name="roi">The ROI to analyze.</param> /// <returns>True if this class can analyze the given ROI; False otherwise.</returns> public bool SupportsRoi(Roi roi) { return roi is IRoiStatisticsProvider; }
//TODO (cr Feb 2010): All the analysis should really be done in the ProtractorRoi. public IRoiAnalyzerResult Analyze(Roi roi, RoiAnalysisMode mode) { return Analyze((ProtractorRoi) roi, mode); }
/// <summary> /// Checks if this analyzer class can analyze the given ROI. /// </summary> /// <remarks> /// Implementations should return a result based on the type of ROI, not on the particular current state of the ROI. /// </remarks> /// <param name="roi">The ROI to analyze.</param> /// <returns>True if this class can analyze the given ROI; False otherwise.</returns> public bool SupportsRoi(Roi roi) { return roi is IRoiStatisticsProvider && roi.PixelData != null; }