public override void Render(DrawingContext dc, CoordinateTransform transform) { var x = ViewportPanel.GetX(this); var y = ViewportPanel.GetY(this); dc.DrawEllipse(Brushes.Red, null, new Point(x, y).ViewportToScreen(transform), 3, 3); }
private static UncertainValue Integrate_Adaptive(MultiFunctor f, CoordinateTransform[] map, IntegrationRegion r, EvaluationSettings settings) { // Create an evaluation rule GenzMalik75Rule rule = new GenzMalik75Rule(r.Dimension); // Use it on the whole region and put the answer in a linked list rule.Evaluate(f, map, r); LinkedList<IntegrationRegion> regionList = new LinkedList<IntegrationRegion>(); regionList.AddFirst(r); // Iterate until convergence while (f.EvaluationCount < settings.EvaluationBudget) { // Add up value and errors in all regions. // While we are at it, take note of the region with the largest error. double value = 0.0; double error = 0.0; LinkedListNode<IntegrationRegion> regionNode = regionList.First; double maxError = 0.0; LinkedListNode<IntegrationRegion> maxErrorNode = null; while (regionNode != null) { IntegrationRegion region = regionNode.Value; value += region.Value; error += region.Error; //error += MoreMath.Sqr(region.Error); if (region.Error > maxError) { maxError = region.Error; maxErrorNode = regionNode; } regionNode = regionNode.Next; } // Check for convergence. if ((error <= settings.AbsolutePrecision) || (error <= settings.RelativePrecision * Math.Abs(value))) { return (new UncertainValue(value, error)); } // Split the region with the largest error, and evaluate each subregion. IntegrationRegion maxErrorRegion = maxErrorNode.Value; regionList.Remove(maxErrorNode); IList<IntegrationRegion> subRegions = maxErrorRegion.Split(maxErrorRegion.SplitIndex); /* Countdown cnt = new Countdown(2); ThreadPool.QueueUserWorkItem((object state) => { rule.Evaluate(f, subRegions[0]); cnt.Signal(); }); ThreadPool.QueueUserWorkItem((object state) => { rule.Evaluate(f, subRegions[1]); cnt.Signal(); }); cnt.Wait(); foreach (IntegrationRegion subRegion in subRegions) { regionList.AddLast(subRegion); } */ foreach (IntegrationRegion subRegion in subRegions) { rule.Evaluate(f, map, subRegion); regionList.AddLast(subRegion); } } throw new NonconvergenceException(); }
protected override Rect GetElementScreenBoundsCore(CoordinateTransform transform, UIElement child) { Rect bounds = base.GetElementScreenBoundsCore(transform, child); Size margin = GetScreenMargin(child); if (!margin.IsEmpty) { bounds.Inflate(margin); } return bounds; }
protected GameObject CreateCanvas(string name, int level, Vector2 position, GameObject parentCanvas = null) { GameObject createdCanvas = Object.Instantiate(Resources.Load <GameObject>("Canvas")); createdCanvas.name = name; createdCanvas.tag = "Canvas"; RectTransform rectTransform = createdCanvas.GetComponent <RectTransform>(); rectTransform.anchorMin = new Vector2(0, 1); rectTransform.anchorMax = new Vector2(0, 1); createdCanvas.GetComponent <CanvasMeta>().Level = level; rectTransform.anchoredPosition = CoordinateTransform.InverseYCoordinate(position); rectTransform.pivot = new Vector2(0, 1); if (parentCanvas != null) { createdCanvas.transform.SetParent(parentCanvas.transform, false); } return(createdCanvas); }
protected override IEnumerable GetDataCore(DataSourceEnvironment environment) { double time = watch.Elapsed.TotalSeconds; DataRect visible = environment.Visible; DataRect realVisible = environment.RealVisible; Rect output = environment.Output; CoordinateTransform transform = environment.Transform; double yMin = Double.PositiveInfinity; double yMax = Double.NegativeInfinity; double step = visible.Width / output.Width; for (double x = visible.XMin; x <= visible.XMax; x += step) { double dataX = x; double viewportY = func(dataX, time); if (realVisible.HorizontalRange.Contains(x)) { if (viewportY < yMin) { yMin = viewportY; } if (viewportY > yMax) { yMax = viewportY; } } yield return(new Point(dataX, viewportY)); } DataRect bounds = DataRect.Empty; bounds.UnionY(yMin); bounds.UnionY(yMax); environment.ContentBounds = bounds; }
public void ChangeItemModel(TilesetModel tilesetModel) { if (tilesetModel == null) { return; } if (!this.TilesetModels.Contains(tilesetModel)) { return; } this.IsSourceLoaded.Value = true; this.TilesetModel.Value = tilesetModel; this.TilesetModel.Value.IsTransparent = tilesetModel.IsTransparent; this.TilesetModel.Value.TransparentColor = tilesetModel.TransparentColor; this.Session.CurrentTileset.Value = this.TilesetModel.Value; this.ItemImage.Value = CvInvoke.Imread(this.TilesetModel.Value.SourcePath.Value, Emgu.CV.CvEnum.ImreadModes.Unchanged); this.itemTransform = new CoordinateTransform(); this.itemTransform.SetPixelToTile(this.TilesetModel.Value.TileWidth.Value, this.TilesetModel.Value.TileHeight.Value); this.itemTransform.SetSelectionToPixel(this.TilesetModel.Value.TileWidth.Value / 2, this.TilesetModel.Value.TileHeight.Value / 2); this.TilesetModel.Value.IsTransparent.PropertyChanged += IsTransparentChanged; Mat drawingMat = this.ItemImage.Value; if (this.TilesetModel.Value.IsTransparent.Value) { drawingMat = ImageUtils.ColorToTransparent(this.ItemImage.Value, this.TilesetModel.Value.TransparentColor.Value); } Application.Current.Dispatcher.BeginInvoke(new Action(() => { using (DrawingContext context = this.tilesetImage.Open()) { context.DrawDrawing(ImageUtils.MatToImageDrawing(drawingMat)); } }), DispatcherPriority.Render); RedrawBackground(); RedrawGrid(); }
protected override void UpdateLevel(CoordinateTransform transform) { var visible = Plotter.Viewport.Visible; var output = Plotter.Viewport.Output; prevLevel = TileProvider.Level; var num = output.Height / 512; double tileHeight = visible.Height / num; double level = -Math.Log(tileHeight, 2); level = RoundLevel(level); levels.Add(level); TileProvider.Level = level; if (level != prevLevel) { TileSystem.SourceServer.CancelRunningOperations(); } }
protected override void UpdateLevel(CoordinateTransform transform) { var visible = Plotter.Viewport.Visible; var output = Plotter.Viewport.Output; prevLevel = TileProvider.Level; var num = output.Height / 512; double tileHeight = visible.Height / num; double level = -Math.Log(tileHeight, 2); level = RoundLevel(level); levels.Add(level); TileProvider.Level = level; if (level != prevLevel) { TileSystem.SourceServer.CancelRunningOperations(); } }
public void TestSpain() { using (var c = new ProjContext()) { using (var wgs84 = CoordinateReferenceSystem.Create("EPSG:4326", c)) using (var google = CoordinateReferenceSystem.Create("EPSG:3857", c)) using (var q1 = CoordinateReferenceSystem.Create("EPSG:23030")) using (var q2 = CoordinateReferenceSystem.Create("EPSG:2062")) { Assert.AreEqual("Engineering survey, topographic mapping.", q1.Scope); Assert.AreEqual("Engineering survey, topographic mapping.", q2.Scope); using (var t = CoordinateTransform.Create(google, wgs84)) { var r = t.Apply(-333958.47, 4865942.28); Assert.AreEqual(0, t.GridUsageCount); Assert.AreEqual(40.0, Math.Round(r[0], 3)); Assert.AreEqual(-3, Math.Round(r[1], 3)); } using (var t = CoordinateTransform.Create(google, q1)) { var r = t.Apply(-333958.47, 4865942.28); Assert.AreEqual(0, t.GridUsageCount); Assert.AreEqual(500110.0, Math.Round(r[0], 0)); Assert.AreEqual(4427965.0, Math.Round(r[1], 0)); } using (var t = CoordinateTransform.Create(google, q2)) { var r = t.Apply(-333958.47, 4865942.28); Assert.AreEqual(0, t.GridUsageCount); Assert.AreEqual(658629.5, Math.Round(r[0], 1)); Assert.AreEqual(600226.1, Math.Round(r[1], 1)); } } } }
public SelectedBrushViewModel(IEventAggregator eventAggregator, IConstants constants, IScrollModel scrollModel) { this.eventAggregator = eventAggregator ?? throw new ArgumentNullException("eventAggregator is null"); this.ScrollModel = scrollModel ?? throw new ArgumentNullException("scrollModel is null"); this.Title.Value = "Selected Brush"; this.imageTransform = new CoordinateTransform(); this.drawingGroup = new DrawingGroup(); this.extendedBackground = new DrawingGroup(); this.selectedBrushImage = new DrawingGroup(); this.gridLines = new DrawingGroup(); this.drawingGroup.Children.Add(this.selectedBrushImage); this.drawingGroup.Children.Add(this.extendedBackground); this.drawingGroup.Children.Add(this.gridLines); this.BrushImage.Value = new DrawingImage(this.drawingGroup); RenderOptions.SetEdgeMode(this.selectedBrushImage, EdgeMode.Aliased); this.gridModel = new PaddedGridRenderable(); this.Scale.Value = ScaleType.Pixel; this.PositionText.Value = "0, 0"; this.maxGridThickness = constants.MaxGridThickness; this.updatePositionLabelMsDelay = constants.DefaultUpdatePositionLabelMsDelay; this.updatePositionLabelStopWatch = Stopwatch.StartNew(); this.ScrollModel.PropertyChanged += ScrollModelPropertyChanged; this.ShowGridCommand = new DelegateCommand(() => DrawGrid(this.IsGridOn.Value)); this.HandleMouseMoveCommand = new DelegateCommand <object>((point) => HandleMouseMove((Point)point)); this.ZoomInCommand = new DelegateCommand(() => this.ScrollModel.ZoomIn()); this.ZoomOutCommand = new DelegateCommand(() => this.ScrollModel.ZoomOut()); this.SetZoomCommand = new DelegateCommand <ZoomLevel>((zoomLevel) => this.ScrollModel.SetZoom(zoomLevel)); this.eventAggregator.GetEvent <NewPaddedBrushEvent>().Subscribe((brushEvent) => { UpdateBrushImage(brushEvent); }, ThreadOption.UIThread); }
public void TestAmersfoort() { using (var c = new ProjContext()) { using (var rd = CoordinateReferenceSystem.Create("EPSG:28992", c)) using (var wgs84 = CoordinateReferenceSystem.Create("EPSG:4326", c)) using (var google = CoordinateReferenceSystem.Create("EPSG:3857", c)) { var area = rd.UsageArea; Assert.IsNotNull(area); Assert.AreEqual("Netherlands - onshore, including Waddenzee, Dutch Wadden Islands and 12-mile offshore coastal zone.", area.Name); Assert.AreEqual(3.2, area.WestLongitude); Assert.AreEqual(7.22, area.EastLongitude); using (var t = CoordinateTransform.Create(rd, wgs84)) { var r = t.Apply(155000, 463000); Assert.AreEqual(52.155, Math.Round(r[0], 3)); Assert.AreEqual(5.387, Math.Round(r[1], 3)); Assert.AreEqual(1, t.Accuraracy); } using (var t = CoordinateTransform.Create(rd, google)) { var r = t.Apply(155000, 463000); Assert.AreEqual(599701.0, Math.Round(r[0], 0)); Assert.AreEqual(6828231.0, Math.Round(r[1], 0)); Assert.AreEqual(1, t.Accuraracy); } } } }
private void Parent_MouseMove(object sender, MouseEventArgs e) { circleGrid.Visibility = Visibility.Visible; if (Plotter2D != null && Plotter2D.IsHitTestVisible) { Point mousePos = Mouse.GetPosition(this); CoordinateTransform transform = Plotter2D.Viewport.Transform; DataRect visible = Plotter2D.Viewport.Visible; Rect output = Plotter2D.Viewport.Output; if (!output.Contains(mousePos)) { circleGrid.Visibility = Visibility.Hidden; return; } Vector screenDistance = new Vector(bigCircle.Width * 0.5, bigCircle.Height * 0.5); _nearestPointSearch.UpdatePositionInData(mousePos, screenDistance, transform); } else { circleGrid.Visibility = Visibility.Hidden; } }
protected void RenderIsolineCollection(DrawingContext dc, double strokeThickness, IsolineCollection collection, CoordinateTransform transform) { foreach (LevelLine line in collection) { StreamGeometry lineGeometry = new StreamGeometry(); using (var context = lineGeometry.Open()) { context.BeginFigure(line.StartPoint.ViewportToScreen(transform), false, false); if (!UseBezierCurves) { context.PolyLineTo(line.OtherPoints.ViewportToScreen(transform).ToArray(), true, true); } else { context.PolyBezierTo(BezierBuilder.GetBezierPoints(line.AllPoints.ViewportToScreen(transform).ToArray()).Skip(1).ToArray(), true, true); } } lineGeometry.Freeze(); Pen pen = new Pen(new SolidColorBrush(Palette.GetColor(line.Value01)), strokeThickness); dc.DrawGeometry(null, pen, lineGeometry); } }
private void InitTransform(Size newRenderSize) { Rect dataRect = CreateDataRect(); transform = transform.WithRects(dataRect, new Rect(newRenderSize)); }
public MultiFunctor(Func<IList<double>, double> function, CoordinateTransform[] map) { this.function = function; this.map = map; }
public MapEditorViewModel(IEventAggregator eventAggregator, IConstants constants, IAmeSession session, Map map, IScrollModel scrollModel) { this.eventAggregator = eventAggregator ?? throw new ArgumentNullException("eventAggregator is null"); this.session = session ?? throw new ArgumentNullException("session is null"); this.Map.Value = map ?? throw new ArgumentNullException("map is null"); this.ScrollModel = scrollModel ?? throw new ArgumentNullException("scrollModel is null"); this.Title.Value = map.Name.Value; this.orderer = new LayerOrderRenderer(this.session); this.imageTransform = new CoordinateTransform(); this.imageTransform.SetPixelToTile(map.TileWidth.Value, map.TileHeight.Value); this.imageTransform.SetSelectionToPixel(map.TileWidth.Value / 2, map.TileHeight.Value / 2); this.drawingGroup = new DrawingGroup(); this.mapBackground = new DrawingGroup(); this.layerItems = new DrawingGroup(); this.hoverSample = new DrawingGroup(); this.gridLines = new DrawingGroup(); this.layerBoundaries = new DrawingGroup(); RenderOptions.SetEdgeMode(this.hoverSample, EdgeMode.Aliased); this.drawingGroup.Children.Add(this.mapBackground); this.drawingGroup.Children.Add(this.layerItems); this.drawingGroup.Children.Add(this.hoverSample); this.drawingGroup.Children.Add(this.gridLines); this.drawingGroup.Children.Add(this.layerBoundaries); this.DrawingCanvas = new DrawingImage(this.drawingGroup); this.BackgroundBrush.Value = new SolidColorBrush(map.BackgroundColor.Value); this.BackgroundPen.Value = new Pen(Brushes.Transparent, 0); this.Scale.Value = ScaleType.Tile; this.PositionText.Value = "0, 0"; this.HoverSampleOpacity.Value = hoverSampleOpacity; this.hoverSample.Opacity = hoverSampleOpacity; this.maxGridThickness = constants.MaxGridThickness; this.updatePositionLabelMsDelay = constants.DefaultUpdatePositionLabelMsDelay; this.updatePositionLabelStopWatch = Stopwatch.StartNew(); SetMapLayers(map); ChangeCurrentLayer(this.Map.Value.CurrentLayer.Value); RedrawBackground(); UpdateMapRecentlySaved(); this.Map.Value.CurrentLayer.PropertyChanged += CurrentLayerChanged; this.Map.Value.Name.PropertyChanged += MapNameChanged; this.Map.Value.Layers.CollectionChanged += LayersChanged; this.Map.Value.IsRecentlySaved.PropertyChanged += MapRecentlySavedChanged; this.ScrollModel.PropertyChanged += ScrollModelPropertyChanged; this.BackgroundBrush.PropertyChanged += BackgroundChanged; this.BackgroundPen.PropertyChanged += BackgroundChanged; this.HoverSampleOpacity.PropertyChanged += HoverSampleOpacityChanged; this.HandleLeftClickDownCommand = new DelegateCommand <object>((point) => HandleLeftClickDown((Point)point)); this.HandleLeftClickUpCommand = new DelegateCommand <object>((point) => HandleLeftClickUp((Point)point)); this.ShowGridCommand = new DelegateCommand(() => DrawGrid(this.IsGridOn.Value)); this.HandleMouseMoveCommand = new DelegateCommand <object>((point) => HandleMouseMove((Point)point)); this.UndoCommand = new DelegateCommand(() => this.Undo()); this.RedoCommand = new DelegateCommand(() => this.Redo()); this.ZoomInCommand = new DelegateCommand(() => this.ScrollModel.ZoomIn()); this.ZoomOutCommand = new DelegateCommand(() => this.ScrollModel.ZoomOut()); this.SetZoomCommand = new DelegateCommand <ZoomLevel>((zoomLevel) => this.ScrollModel.SetZoom(zoomLevel)); this.eventAggregator.GetEvent <NewPaddedBrushEvent>().Subscribe((brushEvent) => { UpdateBrushImage(brushEvent); }, ThreadOption.PublisherThread); }
private void CreateUIRepresentation() { if (Plotter == null) { return; } if (DataSource == null) { return; } drawnPaths.Clear(); DataSourceEnvironment environment = CreateEnvironment(); var points = DataSource.GetPoints(environment); var indexedPoints = IndexWrapper.Generate(points); // do nothing if there is nothing to draw if (!points.Any()) { return; } transformWhileCreateUI = Plotter.Viewport.Transform; int globalMinIndex; int globalMaxIndex; CreateAndAddPath(indexedPoints, out globalMinIndex, out globalMaxIndex, transformWhileCreateUI); indexRange = new Range <int>(globalMinIndex, globalMaxIndex); ViewportPanel.SetViewportBounds(canvas, Plotter.Viewport.Visible); // switching off content bounds calculation for children of ViewportHostPanel. panel.BeginBatchAdd(); if (canvas.Parent == null) { panel.Children.Add(canvas); } if (panel.Plotter == null) { Plotter.Dispatcher.BeginInvoke(() => { if (panel.Plotter == null && Plotter != null) { Plotter.Children.Add(panel); } }); } DataRect bounds = DataRect.Empty; if (environment.ContentBounds != null) { bounds = environment.ContentBounds.Value; } else { // todo is this necessary? bounds = points.GetBounds(); } Viewport2D.SetContentBounds(this, bounds); }
//////////////////////////////////////////////////////////////////////////////// // // Function Name: IVA_Classification_Segmentation // // Description : Segments the classification image // // Parameters : image - Input Image // imageMask - Segmented image // roi - Region of Interest // preprocessingOptions - Preprocessing options // // Return Value : None // //////////////////////////////////////////////////////////////////////////////// public static void IVA_Classification_Segmentation(VisionImage image, VisionImage imageMask, Roi roi, ParticleClassifierPreprocessingOptions preprocessingOptions) { int useExpandedROI = 0; RectangleContour boundingBox = roi.GetBoundingRectangle(), expandedBox = roi.GetBoundingRectangle(), reducedBox = roi.GetBoundingRectangle(); // Local Threshold method uses a kernel size, and the ROI must be larger than the kernel size for the function to work // Take care of making the ROI to extract larger if needed for the local threshold case if (preprocessingOptions.ThresholdType == ThresholdType.Local) { // Get the image size int xRes, yRes; xRes = image.Width; yRes = image.Height; boundingBox = roi.GetBoundingRectangle(); // Take into account clipping of ROI. Just get ROI that's within bounds of image. if (Math.Min(xRes, (boundingBox.Left + boundingBox.Width)) - Math.Max(0, boundingBox.Left) < preprocessingOptions.LocalThresholdOptions.WindowWidth || Math.Min(yRes, (boundingBox.Top + boundingBox.Height)) - Math.Max(0, boundingBox.Top) < preprocessingOptions.LocalThresholdOptions.WindowHeight) { // The ROI is smaller than the kernel. Try to expand the kernel in the directions needed to meet the minimum size required by the kernel. int expandX = (int)(preprocessingOptions.LocalThresholdOptions.WindowWidth / 2); int expandY = (int)(preprocessingOptions.LocalThresholdOptions.WindowHeight / 2); int leftExpand = expandX; int rightExpand = expandX; int leftSlack = (int)boundingBox.Left; int rightSlack = (int)(xRes - (boundingBox.Left + boundingBox.Width)); if (leftExpand > leftSlack) { rightExpand += (leftExpand - leftSlack); } if (rightExpand > rightSlack) { leftExpand += (rightExpand - rightSlack); } int leftOut = (int)boundingBox.Left - leftExpand; if (leftOut < 0) { leftOut = 0; } int rightOut = (int)(boundingBox.Left + boundingBox.Width + rightExpand); if (rightOut > xRes) { rightOut = xRes; } int topExpand = expandY; int bottomExpand = expandY; int topSlack = (int)boundingBox.Top; int bottomSlack = (int)(yRes - (boundingBox.Top + boundingBox.Height)); if (topExpand > topSlack) { bottomExpand += (topExpand - topSlack); } if (bottomExpand > bottomSlack) { topExpand += (bottomExpand - bottomSlack); } int topOut = (int)(boundingBox.Top - topExpand); if (topOut < 0) { topOut = 0; } int bottomOut = (int)(boundingBox.Top + boundingBox.Height + bottomExpand); if (bottomOut > yRes) { bottomOut = yRes; } expandedBox.Initialize(leftOut, topOut, rightOut - leftOut, bottomOut - topOut); // Create the reduced Rect so after performing the local threshold, we can reduce the size back to the original ROI dimensions. reducedBox.Initialize(Math.Max(boundingBox.Left - leftOut, 0), Math.Max(boundingBox.Top - topOut, 0), boundingBox.Width + Math.Min(boundingBox.Left, 0), boundingBox.Height + Math.Min(boundingBox.Top, 0)); // Set this flag so the image can be reduced after performing the local threshold. useExpandedROI = 1; } } // if Expanded Box hasn't been updated, use the boundingBox passed in to extract. if (useExpandedROI == 0) { expandedBox = boundingBox; } // Extract the region of interest into the mask image. Algorithms.Extract(image, imageMask, expandedBox, 1, 1); // Create a temporary ROI that will be used to mask the extracted image, to get rid of // the pixels outside of the rotated rectangle. Roi tmpROI = new Roi(roi); // If the ROI is a rotated rectangle, then compute the new location of the search ROI. if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { CoordinateSystem baseSystem = new CoordinateSystem(); baseSystem.Origin.X = (roi.GetBoundingRectangle().Left < 0 ? 0 : roi.GetBoundingRectangle().Left); baseSystem.Origin.Y = (roi.GetBoundingRectangle().Top < 0 ? 0 : roi.GetBoundingRectangle().Top); baseSystem.Angle = 0; baseSystem.AxisOrientation = AxisOrientation.Direct; CoordinateSystem newSystem = new CoordinateSystem(new PointContour(0, 0), 0, AxisOrientation.Direct); CoordinateTransform transform = new CoordinateTransform(baseSystem, newSystem); Algorithms.TransformRoi(tmpROI, transform); } // Create a temporary image. using (VisionImage tmpImageMask = new VisionImage(ImageType.U8, 7)) { double thresholdMin; double thresholdMax; switch (preprocessingOptions.ThresholdType) { case ThresholdType.Manual: thresholdMin = preprocessingOptions.ManualThresholdRange.Minimum; thresholdMax = preprocessingOptions.ManualThresholdRange.Maximum; Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1); break; case ThresholdType.Auto: Collection <ThresholdData> thresholdData; thresholdData = Algorithms.AutoThreshold(image, tmpImageMask, 2, preprocessingOptions.AutoThresholdOptions.Method); if (preprocessingOptions.AutoThresholdOptions.ParticleType == ParticleType.Bright) { thresholdMin = (thresholdData[0].Range.Maximum > preprocessingOptions.AutoThresholdOptions.Limits.Minimum ? thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Minimum); thresholdMax = 255; } else { thresholdMin = 0; thresholdMax = (thresholdData[0].Range.Maximum < preprocessingOptions.AutoThresholdOptions.Limits.Maximum ? thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Maximum); } Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1); break; case ThresholdType.Local: LocalThresholdOptions Options = new LocalThresholdOptions(preprocessingOptions.LocalThresholdOptions.ParticleType, preprocessingOptions.LocalThresholdOptions.Method, 1.0, preprocessingOptions.LocalThresholdOptions.WindowWidth, preprocessingOptions.LocalThresholdOptions.WindowHeight); Options.DeviationWeight = preprocessingOptions.LocalThresholdOptions.DeviationWeight; Algorithms.LocalThreshold(imageMask, imageMask, Options); break; default: break; } /// If the expanded ROI was used, reduce it so no particles are found outside requested ROI. if (useExpandedROI == 1) { Algorithms.Extract(imageMask, imageMask, reducedBox, 1, 1); } // Cast the image to 8 bit. imageMask.Type = ImageType.U8; // Eliminates particles that touch the border of the image. if (preprocessingOptions.RejectBorder) { if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { // Special case for the rotated rectangle. Algorithms.Label(imageMask, imageMask, Connectivity.Connectivity8); Collection <short> lookupTable = new Collection <short>(); lookupTable.Add(0); for (int i = 1; i < 256; i++) { lookupTable.Add(1); } RoiProfileReport roiProfile = Algorithms.RoiProfile(imageMask, tmpROI); for (int i = 0; i < roiProfile.Report.ProfileData.Count; i++) { lookupTable[0] = (short)roiProfile.Report.ProfileData[i]; } Algorithms.UserLookup(imageMask, imageMask, lookupTable); } else { Algorithms.RejectBorder(imageMask, imageMask, Connectivity.Connectivity8); } } // Remove small particles. if (preprocessingOptions.NumberOfErosions > 0) { Algorithms.RemoveParticle(imageMask, imageMask, preprocessingOptions.NumberOfErosions, SizeToKeep.KeepLarge); } // If the rectangle is rotated, mask out the areas of the image that are not in the ROI. if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { // Perform the mask Algorithms.RoiToMask(tmpImageMask, tmpROI, new PixelValue(255)); Algorithms.And(imageMask, tmpImageMask, imageMask); } // Sets the mask offset. imageMask.MaskOffset.X = Math.Max(0, roi.GetBoundingRectangle().Left); imageMask.MaskOffset.Y = Math.Max(0, roi.GetBoundingRectangle().Top); } tmpROI.Dispose(); }
private void CreateAndAddPath(IEnumerable<IndexWrapper<Point>> indexedPoints, out int globalMinIndex, out int globalMaxIndex, CoordinateTransform transform) { var screenPoints = indexedPoints.DataToScreen(transform); var parts = screenPoints.Split(pathLength); var splittedParts = from part in parts select missingValueSplitter.SplitMissingValue(part); bool isSmoothJoin = UseSmoothJoin; Point? lastPoint = null; globalMinIndex = Int32.MaxValue; globalMaxIndex = Int32.MinValue; foreach (var shortSegment in splittedParts) { foreach (var part in shortSegment) { if (part.MinIndex < globalMinIndex) globalMinIndex = part.MinIndex; if (part.MaxIndex > globalMaxIndex) globalMaxIndex = part.MaxIndex; List<Point> list = part.GetPoints().ToList(); if (list.Count == 0) continue; if (part.Splitted) lastPoint = null; StreamGeometry geometry = new StreamGeometry(); using (var context = geometry.Open()) { var start = lastPoint ?? list[0]; context.BeginFigure(start, isFilled: false, isClosed: false); context.PolyLineTo(list, isStroked: true, isSmoothJoin: isSmoothJoin); } lastPoint = list.Last(); Path path = pathsPool.GetOrCreate(); drawnPaths.Add(path); PointChartBase.SetIndexRange(path, new Range<int>(part.MinIndex, part.MaxIndex)); LineChartBase.SetPointsCount(path, list.Count); DataRect localBounds = list.GetBounds(); PointChartBase.SetContentBounds(path, localBounds); //if (path.CacheMode == null) // path.CacheMode = new BitmapCache(); // todo for debug purpose //path.Stroke = ColorHelper.RandomBrush; path.SetBinding(Path.StrokeProperty, strokeBinding); path.SetBinding(Path.StrokeThicknessProperty, strokeThicknessBinding); path.SetBinding(Path.StrokeDashArrayProperty, strokeDashArrayBinding); path.SetBinding(Panel.ZIndexProperty, zIndexBinding); path.SetBinding(Path.IsHitTestVisibleProperty, isHitTestVisibleBinding); path.SetBinding(Path.VisibilityProperty, visibilityBinding); path.SetBinding(Path.ToolTipProperty, tooltipBinding); path.Data = geometry; canvas.Children.Add(path); } } }
private static UncertainValue Integrate_MonteCarlo(MultiFunctor f, CoordinateTransform[] map, IList<Interval> box, EvaluationSettings settings) { int d = box.Count; // Use a Sobol quasi-random sequence. This give us 1/N accuracy instead of 1/\sqrt{N} accuracy. //VectorGenerator g = new RandomVectorGenerator(d, new Random(314159265)); VectorGenerator g = new SobolVectorGenerator(d); // Start with a trivial Lepage grid. // We will increase the grid size every few cycles. // My tests indicate that trying to increase every cycle or even every other cycle is too often. // This makes sense, because we have no reason to believe our new grid will be better until we // have substantially more evaluations per grid cell than we did for the previous grid. LePageGrid grid = new LePageGrid(box, 1); int refineCount = 0; // Start with a reasonable number of evaluations per cycle that increases with the dimension. int cycleCount = 8 * d; //double lastValue = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); // Each cycle consists of three sets of evaluations. // At first I did this with just two set and used the difference between the two sets as an error estimate. // I found that it was pretty common for that difference to be low just by chance, causing error underestimatation. double value1 = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); double value2 = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); double value3 = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); while (f.EvaluationCount < settings.EvaluationBudget) { // Take the largest deviation as the error. double value = (value1 + value2 + value3) / 3.0; double error = Math.Max(Math.Abs(value1 - value3), Math.Max(Math.Abs(value1 - value2), Math.Abs(value2 - value3))); Debug.WriteLine("{0} {1} {2}", f.EvaluationCount, value, error); // Check for convergence. if ((error <= settings.AbsolutePrecision) || (error <= Math.Abs(value) * settings.RelativePrecision)) { return (new UncertainValue(value, error)); } // Do more cycles. In order for new sets to be equal-sized, one of those must be at the current count and the next at twice that. double smallValue = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); cycleCount *= 2; double bigValue = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); // Combine all the cycles into new ones with twice the number of evaluations each. value1 = (value1 + value2) / 2.0; value2 = (value3 + smallValue) / 2.0; value3 = bigValue; //double currentValue = Integrate_MonteCarlo_Cycle(f, map, g, grid, cycleCount); //double error = Math.Abs(currentValue - lastValue); //double value = (currentValue + lastValue) / 2.0; //lastValue = value; // Increase the number of evaluations for the next cycle. //cycleCount *= 2; // Refine the grid for the next cycle. refineCount++; if (refineCount == 2) { Debug.WriteLine("Replacing grid with {0} bins after {1} evaluations", grid.BinCount, grid.EvaluationCount); grid = grid.ComputeNewGrid(grid.BinCount * 2); refineCount = 0; } } throw new NonconvergenceException(); }
public void HeightConversionNLBE() { using (ProjContext pc = new ProjContext()) using (var nlNAP = CoordinateReferenceSystem.Create("EPSG:7415", pc)) using (var beOstend = CoordinateReferenceSystem.Create("EPSG:8370", pc)) { pc.AllowNetworkConnections = true; Assert.AreEqual(3, nlNAP.AxisCount); Assert.AreEqual(3, beOstend.AxisCount); Coordinate domNL, servaasNL; using (var wgs84 = CoordinateReferenceSystem.Create("EPSG:4326", pc)) using (var wgs84D3 = CoordinateReferenceSystem.Create("EPSG:4329", pc)) { Assert.AreEqual(2, wgs84.AxisCount); Assert.AreEqual(3, wgs84D3.AxisCount); using (var n = wgs84D3.WithAxisNormalized()) { Assert.IsFalse(wgs84D3.IsEquivalentTo(n)); Assert.IsTrue(wgs84D3.IsEquivalentToRelaxed(n)); } Coordinate domWGS84 = new Coordinate(DomUtrechtWGS84); Coordinate stServaasWGS84 = new Coordinate(StServaasMaastrichtWGS84); using (var t = CoordinateTransform.Create(wgs84, nlNAP)) { domNL = t.Apply(domWGS84); Assert.AreEqual(new CoordinateZ(136898.7, 455851.9, -43.4), domNL.RoundAll(1)); servaasNL = t.Apply(stServaasWGS84); Assert.AreEqual(new CoordinateZ(176164.5, 317770.5, -45.7), servaasNL.RoundAll(1)); } using (var t = CoordinateTransform.Create(nlNAP, beOstend)) { var servaasBE = t.Apply(servaasNL); Assert.AreEqual(new CoordinateZ(742877.4, 671835, -45.7), servaasBE.RoundAll(1)); servaasNL.Z = 15; servaasBE = t.Apply(servaasNL); Assert.IsTrue(new CoordinateZ(742877.4, 671835, 15).Equals3D(servaasBE.RoundAll(1)), $"Unexpected coordinate {servaasBE.RoundAll(1)}"); servaasNL.Z = 0; //revert to original value } using (var t = CoordinateTransform.Create(nlNAP, wgs84D3)) { var domGPS = t.Apply(domNL); Assert.AreEqual(new CoordinateZ(52.09063, 5.123078, 0), domGPS.RoundAll(7)); var servaasGPS = t.Apply(servaasNL); Assert.AreEqual(new CoordinateZ(50.84938, 5.687712, 45.7353891), servaasGPS.RoundAll(7)); servaasNL.Z = 15; servaasGPS = t.Apply(servaasNL); Assert.IsTrue(new CoordinateZ(50.84938, 5.68771, 60.73539).Equals3D(servaasGPS.RoundAll(5)), $"Unexpected coordinate {servaasGPS.RoundAll(5)}"); } } } }
/// <summary> /// Wraps <see cref="CoordinateTransform.ApplyReversed(PPoint)"/> for NTS /// </summary> /// <param name="op"></param> /// <param name="c"></param> /// <returns></returns> public static Coordinate ApplyReversed(this CoordinateTransform op, Coordinate c) { return(op.ApplyReversed(c.ToPPoint()).ToCoordinate()); }
protected void RenderIsolineCollection(DrawingContext dc, double strokeThickness, IsolineCollection collection, CoordinateTransform transform) { foreach (LevelLine line in collection) { StreamGeometry lineGeometry = new StreamGeometry(); using (var context = lineGeometry.Open()) { context.BeginFigure(line.StartPoint.ViewportToScreen(transform), false, false); if (!UseBezierCurves) { context.PolyLineTo(line.OtherPoints.ViewportToScreen(transform).ToArray(), true, true); } else { context.PolyBezierTo(BezierBuilder.GetBezierPoints(line.AllPoints.ViewportToScreen(transform).ToArray()).Skip(1).ToArray(), true, true); } } lineGeometry.Freeze(); Pen pen = new Pen(new SolidColorBrush(Palette.GetColor(line.Value01)), strokeThickness); dc.DrawGeometry(null, pen, lineGeometry); } }
private static Rect GetElementBounds(CoordinateTransform transform, UIElement child) { Point p1 = GetPoint1(child); Point p2 = GetPoint2(child); Point p1Screen = p1.DataToScreen(transform); Point p2Screen = p2.DataToScreen(transform); Rect bounds = new Rect(p1Screen, p2Screen); return bounds; }
public abstract void Render(DrawingContext dc, CoordinateTransform transform);
// Sample a pre-determined number of points using the given generator and grid and return the average function value. private static double Integrate_MonteCarlo_Cycle(MultiFunctor f, CoordinateTransform[] map, VectorGenerator g, LePageGrid grid, int n) { double sum = 0.0; for (int i = 0; i < n; i++) { double[] x = g.NextVector(); //sum += f.Evaluate(x); sum += grid.Evaluate(f, map, x); } return (sum / n); }
public double Evaluate(MultiFunctor f, CoordinateTransform[] map, double[] x) { Debug.Assert(x.Length == dimension); // Increase the evaluation count. count++; // We will need to record the bin number into which each coordinate falls // in order to acrue the result to the proper bin. int[] binIndexes = new int[dimension]; // Map incoming x into a grid cell and value based on grid. double v = v0; for (int i = 0; i < x.Length; i++) { Debug.Assert((0.0 <= x[i]) && (x[i] < 1.0)); double z = (grid[i].Length - 1) * x[i]; int j = (int) Math.Floor(z); z = z - j; double w = grid[i][j + 1] - grid[i][j]; x[i] = (1.0 - z) * grid[i][j] + z * grid[i][j + 1]; v *= w; binIndexes[i] = j; } // Use the map to further transform that value. if (map != null) { Debug.Assert(map.Length == dimension); for (int i = 0; i < x.Length; i++) { map[i].TransformInPlace(ref x[i], ref v); } } double y = f.Evaluate(x); // Record the value in the appropriate bins. for (int i = 0; i < binIndexes.Length; i++) { int j = binIndexes[i]; //binSum[i][j] += y * y * v / ((grid[i][j + 1] - grid[i][j]) * (grid[i].Length - 1)); //binSum[i][j] += Math.Abs(y) * (grid[i][j + 1] - grid[i][j]); //binSum[i][j] += Math.Abs(v * y) * (grid[i][j + 1] - grid[i][j]); binSum[i][j] += Math.Abs(v * y); } return (v * y); }
private void InitTransform(Size newDesiredSize) { Rect dataRect = CreateDataRect(); transform = transform.WithRects(dataRect, new Rect(new Point(0, 0), newDesiredSize)); }
private double MeasureMaximumDistance(VisionImage image, RectangleContour searchRectangle, RakeDirection rakeDirection, DrawOptions drawOptions, CoordinateTransform transform) { // Convert the search rectangle to an Roi. Roi roi = searchRectangle.ConvertToRoi(); // Transform the Roi. Algorithms.TransformRoi(roi, transform); // Perform a rake operation. RakeReport report = Algorithms.Rake(image, roi, rakeDirection, EdgeProcess.FirstAndLast); // Find the maximum edge positions and compute the distance. Collection <LineContour> perpendicularLines; PointContour closestFirstEdge, closestLastEdge; double distance = FindMinMaxPosition(report, out perpendicularLines, out closestFirstEdge, out closestLastEdge); // Draw the results. if (drawOptions.ShowSearchLines) { foreach (SearchLineInfo lineInfo in report.SearchLines) { image.Overlays.Default.AddLine(lineInfo.Line, Rgb32Value.BlueColor); } } if (drawOptions.ShowSearchArea) { image.Overlays.Default.AddRoi(roi); } if (drawOptions.ShowEdgesFound) { foreach (EdgeInfo edgeInfo in report.FirstEdges) { image.Overlays.Default.AddRectangle(new RectangleContour(edgeInfo.Position.X - 1, edgeInfo.Position.Y - 1, 3, 3), Rgb32Value.YellowColor, DrawingMode.PaintValue); } foreach (EdgeInfo edgeInfo in report.LastEdges) { image.Overlays.Default.AddRectangle(new RectangleContour(edgeInfo.Position.X - 1, edgeInfo.Position.Y - 1, 3, 3), Rgb32Value.YellowColor); } } if (drawOptions.ShowResult) { // Overlay the measurement edge points. image.Overlays.Default.AddOval(new OvalContour(closestFirstEdge.X - 2, closestFirstEdge.Y - 2, 5, 5), Rgb32Value.RedColor, DrawingMode.PaintValue); image.Overlays.Default.AddOval(new OvalContour(closestLastEdge.X - 2, closestLastEdge.Y - 2, 5, 5), Rgb32Value.RedColor, DrawingMode.PaintValue); // Overlay the two lines that point inward from the search area to the clamp position. LineContour line1 = new LineContour(FindMidpoint(report.SearchLines[0].Line.Start, report.SearchLines[report.SearchLines.Count - 1].Line.Start), FindMidpoint(perpendicularLines[0])); image.Overlays.Default.AddLine(line1, Rgb32Value.RedColor); DrawArrow(image.Overlays.Default, line1, Rgb32Value.RedColor); LineContour line2 = new LineContour(FindMidpoint(report.SearchLines[0].Line.End, report.SearchLines[report.SearchLines.Count - 1].Line.End), FindMidpoint(perpendicularLines[1])); image.Overlays.Default.AddLine(line2, Rgb32Value.RedColor); DrawArrow(image.Overlays.Default, line2, Rgb32Value.RedColor); // Overlay the two lines perpendicular to the search lines that correspond to the clamp position. image.Overlays.Default.AddLine(perpendicularLines[0], Rgb32Value.RedColor); image.Overlays.Default.AddLine(perpendicularLines[1], Rgb32Value.RedColor); } return(distance); }
private void CreateUIRepresentation() { if (Plotter == null) return; if (DataSource == null) return; drawnPaths.Clear(); DataSourceEnvironment environment = CreateEnvironment(); var points = DataSource.GetPoints(environment); var indexedPoints = IndexWrapper.Generate(points); // do nothing if there is nothing to draw if (!points.Any()) return; transformWhileCreateUI = Plotter.Viewport.Transform; int globalMinIndex; int globalMaxIndex; CreateAndAddPath(indexedPoints, out globalMinIndex, out globalMaxIndex, transformWhileCreateUI); indexRange = new Range<int>(globalMinIndex, globalMaxIndex); ViewportPanel.SetViewportBounds(canvas, Plotter.Viewport.Visible); // switching off content bounds calculation for children of ViewportHostPanel. panel.BeginBatchAdd(); if (canvas.Parent == null) panel.Children.Add(canvas); if (panel.Plotter == null) { Plotter.Dispatcher.BeginInvoke(() => { if (panel.Plotter == null && Plotter != null) Plotter.Children.Add(panel); }); } DataRect bounds = DataRect.Empty; if (environment.ContentBounds != null) { bounds = environment.ContentBounds.Value; } else { // todo is this necessary? bounds = points.GetBounds(); } Viewport2D.SetContentBounds(this, bounds); }
protected Rect GetElementScreenBounds(CoordinateTransform transform, UIElement child) { Rect screenBounds = GetElementScreenBoundsCore(transform, child); DataRect viewportBounds = screenBounds.ScreenToViewport(transform); DataRect prevViewportBounds = GetActualViewportBounds(child); SetPrevActualViewportBounds(child, prevViewportBounds); SetActualViewportBounds(child, viewportBounds); return screenBounds; }
/// <summary> /// Calculates the distance between the two coordinates (X,Y) in meters /// </summary> /// <param name="operation"></param> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns>The distance in meters or <see cref="double.NaN"/> if the value can't be calculated</returns> public static double GeoDistance(this CoordinateTransform operation, Coordinate c1, Coordinate c2) { return(operation.GeoDistance(c1.ToPPoint(), c2.ToPPoint())); }
private void CreateAndAddPath(IEnumerable <IndexWrapper <Point> > indexedPoints, out int globalMinIndex, out int globalMaxIndex, CoordinateTransform transform) { var screenPoints = indexedPoints.DataToScreen(transform); var parts = screenPoints.Split(pathLength); var splittedParts = from part in parts select missingValueSplitter.SplitMissingValue(part); bool isSmoothJoin = UseSmoothJoin; Point?lastPoint = null; globalMinIndex = Int32.MaxValue; globalMaxIndex = Int32.MinValue; foreach (var shortSegment in splittedParts) { foreach (var part in shortSegment) { if (part.MinIndex < globalMinIndex) { globalMinIndex = part.MinIndex; } if (part.MaxIndex > globalMaxIndex) { globalMaxIndex = part.MaxIndex; } List <Point> list = part.GetPoints().ToList(); if (list.Count == 0) { continue; } if (part.Splitted) { lastPoint = null; } StreamGeometry geometry = new StreamGeometry(); using (var context = geometry.Open()) { var start = lastPoint ?? list[0]; context.BeginFigure(start, isFilled: false, isClosed: false); context.PolyLineTo(list, isStroked: true, isSmoothJoin: isSmoothJoin); } lastPoint = list.Last(); Path path = pathsPool.GetOrCreate(); drawnPaths.Add(path); PointChartBase.SetIndexRange(path, new Range <int>(part.MinIndex, part.MaxIndex)); LineChartBase.SetPointsCount(path, list.Count); DataRect localBounds = list.GetBounds(); PointChartBase.SetContentBounds(path, localBounds); //if (path.CacheMode == null) // path.CacheMode = new BitmapCache(); // todo for debug purpose //path.Stroke = ColorHelper.RandomBrush; path.SetBinding(Path.StrokeProperty, strokeBinding); path.SetBinding(Path.StrokeThicknessProperty, strokeThicknessBinding); path.SetBinding(Path.StrokeDashArrayProperty, strokeDashArrayBinding); path.SetBinding(Panel.ZIndexProperty, zIndexBinding); path.SetBinding(Path.IsHitTestVisibleProperty, isHitTestVisibleBinding); path.SetBinding(Path.VisibilityProperty, visibilityBinding); path.SetBinding(Path.ToolTipProperty, tooltipBinding); path.Data = geometry; canvas.Children.Add(path); } } }
protected virtual Size GetElementSize(FrameworkElement child, Size availableSize, CoordinateTransform transform) { Size result = availableSize; DataRect ownViewportBounds = GetViewportBounds(child); if (!ownViewportBounds.IsEmpty) { result = ownViewportBounds.ViewportToScreen(transform).Size; } else { double viewportWidth = GetViewportWidth(child); double viewportHeight = GetViewportHeight(child); bool hasViewportWidth = viewportWidth.IsNotNaN(); bool hasViewportHeight = viewportHeight.IsNotNaN(); double minScreenWidth = GetMinScreenWidth(child); bool hasMinScreenWidth = minScreenWidth.IsNotNaN(); double selfWidth = child.Width.IsNotNaN() ? child.Width : availableSize.Width; double width = hasViewportWidth ? viewportWidth : selfWidth; double selfHeight = child.Height.IsNotNaN() ? child.Height : availableSize.Height; double height = hasViewportHeight ? viewportHeight : selfHeight; if (width < 0) width = 0; if (height < 0) height = 0; DataRect bounds = new DataRect(new Size(width, height)); Rect screenBounds = bounds.ViewportToScreen(transform); result = new Size(hasViewportWidth ? screenBounds.Width : selfWidth, hasViewportHeight ? screenBounds.Height : selfHeight); if (hasMinScreenWidth && result.Width < minScreenWidth) { result.Width = minScreenWidth; } } if (result.Width.IsNaN()) result.Width = 0; if (result.Height.IsNaN()) result.Height = 0; return result; }
public PositionAndCheckDistance(Point screenPosition, CoordinateTransform transform) : this(screenPosition, new Vector(), transform) { }
protected virtual Rect GetElementScreenBoundsCore(CoordinateTransform transform, UIElement child) { Rect bounds = new Rect(0, 0, 1, 1); DataRect ownViewportBounds = GetViewportBounds(child); if (!ownViewportBounds.IsEmpty) { bounds = ownViewportBounds.ViewportToScreen(transform); } else { double viewportX = GetX(child); double viewportY = GetY(child); if (viewportX.IsNaN() || viewportY.IsNaN()) { //Debug.WriteLine("ViewportRectPanel: Position is not set!"); return bounds; } double viewportWidth = GetViewportWidth(child); if (viewportWidth < 0) viewportWidth = 0; double viewportHeight = GetViewportHeight(child); if (viewportHeight < 0) viewportHeight = 0; bool hasViewportWidth = viewportWidth.IsNotNaN(); bool hasViewportHeight = viewportHeight.IsNotNaN(); DataRect r = new DataRect(new Size(hasViewportWidth ? viewportWidth : child.DesiredSize.Width, hasViewportHeight ? viewportHeight : child.DesiredSize.Height)); r = r.ViewportToScreen(transform); double screenWidth = hasViewportWidth ? r.Width : child.DesiredSize.Width; double screenHeight = hasViewportHeight ? r.Height : child.DesiredSize.Height; double minScreenWidth = GetMinScreenWidth(child); bool hasMinScreemWidth = minScreenWidth.IsNotNaN(); if (hasViewportWidth && screenWidth < minScreenWidth) screenWidth = minScreenWidth; Point location = new Point(viewportX, viewportY).ViewportToScreen(transform); double screenX = location.X; double screenY = location.Y; HorizontalAlignment horizAlignment = GetViewportHorizontalAlignment(child); switch (horizAlignment) { case HorizontalAlignment.Stretch: case HorizontalAlignment.Center: screenX -= screenWidth / 2; break; case HorizontalAlignment.Left: break; case HorizontalAlignment.Right: screenX -= screenWidth; break; } VerticalAlignment vertAlignment = GetViewportVerticalAlignment(child); switch (vertAlignment) { case VerticalAlignment.Bottom: screenY -= screenHeight; break; case VerticalAlignment.Center: case VerticalAlignment.Stretch: screenY -= screenHeight / 2; break; case VerticalAlignment.Top: break; default: break; } bounds = new Rect(screenX, screenY, screenWidth, screenHeight); } // applying screen offset double screenOffsetX = GetScreenOffsetX(child); if (screenOffsetX.IsNaN()) screenOffsetX = 0; double screenOffsetY = GetScreenOffsetY(child); if (screenOffsetY.IsNaN()) screenOffsetY = 0; Vector screenOffset = new Vector(screenOffsetX, screenOffsetY); bounds.Offset(screenOffset); return bounds; }
public abstract void Render(DrawingContext dc, CoordinateTransform transform);
public void Evaluate(MultiFunctor f, CoordinateTransform[] map, IntegrationRegion r) { if (map == null) { Evaluate(f, r); return; } // Evaluation at origin. Keep a vector of origin coordinates and jacobian values. double[] x0 = new double[d]; double[] x = new double[d]; double[] v0 = new double[d]; double[] v = new double[d]; for (int i = 0; i < x.Length; i++) { x0[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, 0.0), out v0[i]); x[i] = x0[i]; v[i] = v0[i]; } double f0 = Jacobian(v) * f.Evaluate(x); double I7 = w70 * f0; double I5 = w50 * f0; // near off-one-axis evaluations double f1 = 0.0; for (int i = 0; i < d; i++) { x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, a1), out v[i]); f1 += Jacobian(v) * f.Evaluate(x); x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, -a1), out v[i]); f1 += Jacobian(v) * f.Evaluate(x); x[i] = x0[i]; v[i] = v0[i]; } I7 += w71 * f1; I5 += w51 * f1; // far off-one-axis evaluations int sIndex = 0; double sMax = 0.0; double f2 = 0.0; for (int i = 0; i < d; i++) { x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, a2), out v[i]); double fp2 = Jacobian(v) * f.Evaluate(x); f2 += fp2; x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, -a2), out v[i]); double fm2 = Jacobian(v) * f.Evaluate(x); f2 += fm2; x[i] = x0[i]; v[i] = v0[i]; double s = Math.Abs(fm2 + fp2 - 2.0 * f0); if (s > sMax) { sMax = s; sIndex = i; } else if ((s == sMax) && (r.CoordinateWidth(i) > r.CoordinateWidth(sIndex))) { sIndex = i; } } I7 += w72 * f2; I5 += w52 * f2; // far off-two-axis evaluations double f3 = 0.0; for (int i = 0; i < d; i++) { for (int j = 0; j < i; j++) { // ++ x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, a3), out v[i]); x[j] = map[j].Transform(r.MapCoordinateFromSymmetricUnitInterval(j, a3), out v[j]); f3 += Jacobian(v) * f.Evaluate(x); // +- x[j] = map[j].Transform(r.MapCoordinateFromSymmetricUnitInterval(j, -a3), out v[j]); f3 += Jacobian(v) * f.Evaluate(x); // -- x[i] = map[i].Transform(r.MapCoordinateFromSymmetricUnitInterval(i, -a3), out v[i]); f3 += Jacobian(v) * f.Evaluate(x); // -+ x[j] = map[j].Transform(r.MapCoordinateFromSymmetricUnitInterval(j, a3), out v[j]); f3 += Jacobian(v) * f.Evaluate(x); x[i] = x0[i]; x[j] = x0[j]; v[i] = v0[i]; v[j] = v0[j]; } } I7 += w73 * f3; I5 += w53 * f3; // mid off-all-axis evaluations // We need all 2^d permutations of + and - in each position. // So that we only need to change one component each time, we proceed in Gray code order. // We use a bit-vector to keep track of which component is + (0) and which is - (1). int state = 0; for (int j = 0; j < d; j++) { x[j] = map[j].Transform(r.MapCoordinateFromSymmetricUnitInterval(j, a4), out v[j]); } double f4 = Jacobian(v) * f.Evaluate(x); for (int i = 0; i < (td - 1); i++) { int j = GrayFlipIndex(i); int mask = 1 << j; state = state ^ mask; x[j] = map[j].Transform(r.MapCoordinateFromSymmetricUnitInterval(j, ((state & mask) > 0) ? -a4 : a4), out v[j]); f4 += Jacobian(v) * f.Evaluate(x); } I7 += w74 * f4; double V = r.Volume(); r.Value = V * I7; r.Error = V * Math.Abs(I7 - I5); r.SplitIndex = sIndex; }
protected virtual Size GetElementSize(FrameworkElement child, Size availableSize, CoordinateTransform transform) { Size result = availableSize; DataRect ownViewportBounds = GetViewportBounds(child); if (!ownViewportBounds.IsEmpty) { result = ownViewportBounds.ViewportToScreen(transform).Size; } else { double viewportWidth = GetViewportWidth(child); double viewportHeight = GetViewportHeight(child); bool hasViewportWidth = viewportWidth.IsNotNaN(); bool hasViewportHeight = viewportHeight.IsNotNaN(); double minScreenWidth = GetMinScreenWidth(child); bool hasMinScreenWidth = minScreenWidth.IsNotNaN(); double selfWidth = child.Width.IsNotNaN() ? child.Width : availableSize.Width; double width = hasViewportWidth ? viewportWidth : selfWidth; double selfHeight = child.Height.IsNotNaN() ? child.Height : availableSize.Height; double height = hasViewportHeight ? viewportHeight : selfHeight; if (width < 0) { width = 0; } if (height < 0) { height = 0; } DataRect bounds = new DataRect(new Size(width, height)); Rect screenBounds = bounds.ViewportToScreen(transform); result = new Size(hasViewportWidth ? screenBounds.Width : selfWidth, hasViewportHeight ? screenBounds.Height : selfHeight); if (hasMinScreenWidth && result.Width < minScreenWidth) { result.Width = minScreenWidth; } } if (result.Width.IsNaN()) { result.Width = 0; } if (result.Height.IsNaN()) { result.Height = 0; } return(result); }
private FitCircleReport FindCircularEdge(VisionImage image, AnnulusContour searchAnnulus, SpokeDirection spokeDirection, DrawOptions drawOptions, CoordinateTransform transform) { // Add the search rectangle to an Roi. Roi roi = new Roi(new Shape[] { searchAnnulus }); // Transform the Roi. Algorithms.TransformRoi(roi, transform); // Perform a spoke operation. SpokeReport report = Algorithms.Spoke(image, roi, spokeDirection, EdgeProcess.FirstAndLast, 8); Collection <PointContour> circlePoints = new Collection <PointContour>(); foreach (EdgeInfo edgeInfo in report.FirstEdges) { circlePoints.Add(edgeInfo.Position); } // Fit a circle to the points found. FitCircleReport circleReport = Algorithms.FitCircle(circlePoints); // Draw the results. if (drawOptions.ShowSearchLines) { foreach (SearchLineInfo lineInfo in report.SearchLines) { image.Overlays.Default.AddLine(lineInfo.Line, Rgb32Value.BlueColor); DrawArrow(image.Overlays.Default, lineInfo.Line, Rgb32Value.BlueColor); } } if (drawOptions.ShowSearchArea) { image.Overlays.Default.AddRoi(roi); } if (drawOptions.ShowEdgesFound) { foreach (EdgeInfo edgeInfo in report.FirstEdges) { image.Overlays.Default.AddRectangle(new RectangleContour(edgeInfo.Position.X - 1, edgeInfo.Position.Y - 1, 3, 3), Rgb32Value.YellowColor, DrawingMode.PaintValue); } } if (drawOptions.ShowResult) { // Overlay the center point. image.Overlays.Default.AddOval(new OvalContour(circleReport.Center.X - 2, circleReport.Center.Y - 2, 5, 5), Rgb32Value.RedColor, DrawingMode.PaintValue); // Overlay the circle. image.Overlays.Default.AddOval(new OvalContour(circleReport.Center.X - circleReport.Radius, circleReport.Center.Y - circleReport.Radius, 2 * circleReport.Radius, 2 * circleReport.Radius), Rgb32Value.RedColor, DrawingMode.DrawValue); } return(circleReport); }
private void FillVertexBuffer() { if (DxHost == null) { return; } if (DataSource == null) { return; } if (Palette == null) { return; } if (Device == null) { return; } var dataSource = DataSource; var palette = Palette; var minMax = dataSource.GetMinMax(); transform = Plotter.Transform; vertexCount = DataSource.Width * DataSource.Height; verticesArray = new VertexPosition4Color[vertexCount]; for (int i = 0; i < verticesArray.Length; i++) { int ix = i % DataSource.Width; int iy = i / DataSource.Width; Point point = dataSource.Grid[ix, iy]; double data = dataSource.Data[ix, iy]; double interpolatedData = (data - minMax.Min) / minMax.GetLength(); var color = palette.GetColor(interpolatedData); var pointInScreen = point; //.DataToScreen(transform); var position = new Vector4((float)pointInScreen.X, (float)pointInScreen.Y, 0.5f, 1); verticesArray[i] = new VertexPosition4Color { Position = position, Color = //System.Windows.Media.Colors.Blue.ToArgb() color.ToArgb() }; } vertexBuffer = new VertexBuffer(Device, vertexCount * VertexPosition4Color.SizeInBytes, Usage.WriteOnly, VertexFormat.Position | VertexFormat.Diffuse, Pool.Default); using (var stream = vertexBuffer.Lock(0, vertexCount * VertexPosition4Color.SizeInBytes, LockFlags.None)) { stream.WriteRange <VertexPosition4Color>(verticesArray); } vertexBuffer.Unlock(); indicesCount = (dataSource.Width - 1) * (dataSource.Height - 1) * 2 * 3; indicesArray = new int[indicesCount]; int index = 0; int width = dataSource.Width; for (int iy = 0; iy < dataSource.Height - 1; iy++) { for (int ix = 0; ix < dataSource.Width - 1; ix++) { indicesArray[index + 0] = ix + 0 + iy * width; indicesArray[index + 1] = ix + 1 + iy * width; indicesArray[index + 2] = ix + (iy + 1) * width; indicesArray[index + 3] = ix + 1 + iy * width; indicesArray[index + 4] = ix + (iy + 1) * width; indicesArray[index + 5] = ix + 1 + (iy + 1) * width; index += 6; } } indexBuffer = new IndexBuffer(Device, indicesCount * sizeof(int), Usage.WriteOnly, Pool.Default, false); using (var stream = indexBuffer.Lock(0, indicesCount * sizeof(int), LockFlags.None)) { stream.WriteRange <int>(indicesArray); } indexBuffer.Unlock(); }
/// <summary> /// Calculates the distance between the two coordinates (X,Y) in meters, and then applies Z (assumed to be meters) via Pythagoras /// </summary> /// <param name="operation"></param> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns>The distance in meters or <see cref="double.NaN"/> if the value can't be calculated</returns> public static double GeoDistanceZ(this CoordinateTransform operation, Coordinate c1, Coordinate c2) { return(operation.GeoDistanceZ(ToPPoint(c1), ToPPoint(c2))); }
private void FindTransformWithPattern(VisionImage image, VisionImage template, FindTransformMode mode, MatchPatternOptions matchOptions, DrawOptions drawOptions, CoordinateTransform transform) { // Find the pattern in the image. Collection <PatternMatch> matches = Algorithms.MatchPattern(image, template, matchOptions); // If the pattern was found: if (matches.Count > 0) { // The points in the Corners collection are returned like this: // // 0 — 1 // | | // 3 — 2 // // Our main axis will be along the line from point 3 to point 2 and // our secondary axis will be from point 3 to point 0. The origin will // be at point 3. LineContour mainAxis = new LineContour(matches[0].Corners[3], matches[0].Corners[2]); LineContour secondaryAxis = new LineContour(matches[0].Corners[3], matches[0].Corners[0]); // Fill in the coordinate transform with the data obtained by the pattern matching. transform.MeasurementSystem.Origin = matches[0].Corners[3]; transform.MeasurementSystem.Angle = matches[0].Rotation; transform.MeasurementSystem.AxisOrientation = AxisOrientation.Direct; // If this is the first run, fill in the reference system too. if (mode == FindTransformMode.FindReference) { transform.ReferenceSystem.Origin = matches[0].Corners[3]; transform.ReferenceSystem.Angle = matches[0].Rotation; transform.ReferenceSystem.AxisOrientation = AxisOrientation.Direct; } // Draw the results on the image. if (drawOptions.ShowResult) { // Draw the origin. image.Overlays.Default.AddRectangle(new RectangleContour(mainAxis.Start.X - 2, mainAxis.Start.Y - 2, 5, 5), Rgb32Value.RedColor, DrawingMode.DrawValue); // Draw each axis. image.Overlays.Default.AddLine(mainAxis, Rgb32Value.RedColor); DrawArrow(image.Overlays.Default, mainAxis, Rgb32Value.RedColor); image.Overlays.Default.AddLine(secondaryAxis, Rgb32Value.RedColor); DrawArrow(image.Overlays.Default, secondaryAxis, Rgb32Value.RedColor); } } }
protected virtual Rect GetElementScreenBoundsCore(CoordinateTransform transform, UIElement child) { Rect bounds = new Rect(0, 0, 1, 1); DataRect ownViewportBounds = GetViewportBounds(child); if (!ownViewportBounds.IsEmpty) { bounds = ownViewportBounds.ViewportToScreen(transform); } else { double viewportX = GetX(child); double viewportY = GetY(child); if (viewportX.IsNaN() || viewportY.IsNaN()) { //Debug.WriteLine("ViewportRectPanel: Position is not set!"); return(bounds); } double viewportWidth = GetViewportWidth(child); if (viewportWidth < 0) { viewportWidth = 0; } double viewportHeight = GetViewportHeight(child); if (viewportHeight < 0) { viewportHeight = 0; } bool hasViewportWidth = viewportWidth.IsNotNaN(); bool hasViewportHeight = viewportHeight.IsNotNaN(); DataRect r = new DataRect(new Size(hasViewportWidth ? viewportWidth : child.DesiredSize.Width, hasViewportHeight ? viewportHeight : child.DesiredSize.Height)); r = r.ViewportToScreen(transform); double screenWidth = hasViewportWidth ? r.Width : child.DesiredSize.Width; double screenHeight = hasViewportHeight ? r.Height : child.DesiredSize.Height; double minScreenWidth = GetMinScreenWidth(child); bool hasMinScreemWidth = minScreenWidth.IsNotNaN(); if (hasViewportWidth && screenWidth < minScreenWidth) { screenWidth = minScreenWidth; } Point location = new Point(viewportX, viewportY).ViewportToScreen(transform); double screenX = location.X; double screenY = location.Y; HorizontalAlignment horizAlignment = GetViewportHorizontalAlignment(child); switch (horizAlignment) { case HorizontalAlignment.Stretch: case HorizontalAlignment.Center: screenX -= screenWidth / 2; break; case HorizontalAlignment.Left: break; case HorizontalAlignment.Right: screenX -= screenWidth; break; } VerticalAlignment vertAlignment = GetViewportVerticalAlignment(child); switch (vertAlignment) { case VerticalAlignment.Bottom: screenY -= screenHeight; break; case VerticalAlignment.Center: case VerticalAlignment.Stretch: screenY -= screenHeight / 2; break; case VerticalAlignment.Top: break; default: break; } bounds = new Rect(screenX, screenY, screenWidth, screenHeight); } // applying screen offset double screenOffsetX = GetScreenOffsetX(child); if (screenOffsetX.IsNaN()) { screenOffsetX = 0; } double screenOffsetY = GetScreenOffsetY(child); if (screenOffsetY.IsNaN()) { screenOffsetY = 0; } Vector screenOffset = new Vector(screenOffsetX, screenOffsetY); bounds.Offset(screenOffset); return(bounds); }
/// <summary> /// Calculates the area in square meters occupied by the polygon described in coordinates /// </summary> /// <param name="operation"></param> /// <param name="coordinates"></param> /// <returns></returns> public static double GeoArea(this CoordinateTransform operation, IEnumerable <Coordinate> coordinates) { return(operation.GeoArea(coordinates.Select(x => x.ToPPoint()))); }
/// <summary> /// Calculates the distance between the coordinates (X,Y) in meters /// </summary> /// <param name="operation"></param> /// <param name="coordinates"></param> /// <returns>The distance in meters or <see cref="double.NaN"/> if the value can't be calculated</returns> public static double GeoDistance(this CoordinateTransform operation, IEnumerable <Coordinate> coordinates) { return(operation.GeoDistance(coordinates.ToPPoints())); }
protected virtual void UpdateUIRepresentation(Point mousePos, CoordinateTransform transform) { Point mousePosInData = mousePos.ScreenToData(transform); UpdateUIRepresentation(mousePosInData, mousePosInData); }