public override object MeasureRoot(RootInfo root, RootInfo parent = null) { List <object> distances = new List <object>(); List <object> angles = new List <object>(); // Obtain the curvature profile at the specified resolution double rootLength = root.Spline.Length; for (int i = K; i < rootLength - K; i += PixelResolution) { // Obtain points i - k, i, i + k Point p0 = root.Spline.GetPoint(root.Spline.GetPositionReference(i - K)); Point p1 = root.Spline.GetPoint(root.Spline.GetPositionReference(i + K)); double angle = 90 - Vector.AngleBetween(new Vector(1, 0), p1 - p0); angle = Math.Round(angle > 180 ? angle - 360 : angle, 2); distances.Add(i); angles.Add(angle); } List <List <object> > data = new List <List <object> >() { distances, angles }; data[0].Insert(0, "Distance"); data[1].Insert(0, ""); return(data); }
public bool UpdatesAvailableSince(int revision) { root = RootInfo.GetRoot(rootUri, connection); user = UserInfo.GetUser(root.User.ApiRef, connection); return(user.LatestSyncRevision.HasValue && user.LatestSyncRevision.Value > revision); }
// ------------------------------------------------------------------------ /// Add a root directory and query the status of the contining files /// by a QueryRootStatus call. // ------------------------------------------------------------------------ public bool AddRootDirectory(string directory) { if (directory == string.Empty) { return(false); } string root = HG.FindRootDirectory(directory); if (root != string.Empty && !_rootDirMap.ContainsKey(root)) { _rootDirMap[root] = new RootInfo() { _Branch = HG.GetCurrentBranchName(root) }; if (!_directoryWatcherMap.ContainsDirectory(root)) { _directoryWatcherMap.WatchDirectory(root); } Dictionary <string, char> fileStatusDictionary; if (HG.QueryRootStatus(root, out fileStatusDictionary)) { _fileStatusDictionary.Add(fileStatusDictionary); } } return(true); }
protected virtual void AddSession(PuttySessionInfo sessionInfo) { if (string.IsNullOrEmpty(sessionInfo?.Name) || Sessions.Any(child => child.Name == sessionInfo.Name)) { return; } RootInfo.AddChild(sessionInfo); RaisePuttySessionCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, sessionInfo)); }
protected virtual void RemoveSession(PuttySessionInfo sessionInfo) { if (!Sessions.Contains(sessionInfo)) { return; } RootInfo.RemoveChild(sessionInfo); RaisePuttySessionCollectionChangedEvent(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, sessionInfo)); }
public RootInfo CreateRootInfoIfNeed(TableKey tkey) { var cur = Value?.RootInfo; if (null == cur) { cur = new RootInfo(this, tkey); } return(cur); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { // If parent == null, then this is a primary root and there is no emergence angle if (parent == null) { double angleMax = 30.0; Point start, end; if (angleMax > root.Spline.Length) { double newMinDistanceOffset = angleMax - root.Spline.Length; start = root.Spline.Start; end = root.Spline.GetPoint(root.Spline.GetPositionReference(root.Spline.Length)); } else { start = root.Spline.Start; end = root.Spline.GetPoint(root.Spline.GetPositionReference(angleMax)); } // Angle between horizontal and emergence vectors double angle = 90 - Vector.AngleBetween(new Vector(1, 0), end - start); return(Math.Round(angle > 180 ? angle - 360 : angle, 2)); } else { double angleMax = 30.0, angleMin = 10.0, parentAngleRadius = 20.0; Point start, end; if (angleMax > root.Spline.Length) { double newMinDistanceOffset = angleMax - root.Spline.Length; start = root.Spline.GetPoint(root.Spline.GetPositionReference(Math.Max(0.0, angleMin - newMinDistanceOffset))); end = root.Spline.GetPoint(root.Spline.GetPositionReference(root.Spline.Length)); } else { start = root.Spline.GetPoint(root.Spline.GetPositionReference(Math.Min(root.Spline.Length, angleMin))); end = root.Spline.GetPoint(root.Spline.GetPositionReference(angleMax)); } Vector rootVector = end - start; SampledSpline parentSpline = parent.Spline; double parentIntersectionDistance = parentSpline.GetLength(root.StartReference); Point parentStart = parentSpline.GetPoint(parentSpline.GetPositionReference(Math.Max(0.0, parentIntersectionDistance - parentAngleRadius))); Point parentEnd = parentSpline.GetPoint(parentSpline.GetPositionReference(Math.Min(parent.Spline.Length, parentIntersectionDistance + parentAngleRadius))); Vector parentVector = parentEnd - parentStart; return(Math.Round(Vector.AngleBetween(rootVector, parentVector), 2)); } }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { if (root.Children != null) { return(root.Children.Count); } else { return(0); } }
private XmlNode CreateGeometry(XmlDocument document, RootInfo root) { XmlNode geometryNode = document.CreateElement("geometry"); // Polyline if (root.Polyline == null || root.Polyline.Points.Count <= 0) { // No polyline exists, create point list from spline if (root.Polyline == null) { root.Polyline = new Polyline() { Points = new List <Point3D>() }; } foreach (var p in root.Spline.SampledPoints) { root.Polyline.Points.Add(new Point3D(p.X, p.Y)); } root.Polyline.Points = Optimise2DPoints(root.Polyline.Points, 3); } XmlNode polylineNode = geometryNode.AppendChild(document.CreateElement("polyline")); root.Polyline.Points = Optimise2DPoints(root.Polyline.Points, 3); foreach (Point3D point in root.Polyline.Points) { polylineNode.AppendChild(CreatePoint(document, point)); } // Spline Geometry if (root.Spline != null) { XmlNode splineNode = geometryNode.AppendChild(document.CreateElement("rootnavspline")); splineNode.Attributes.Append(document.CreateAttribute("controlpointseparation")).InnerText = root.Spline.ControlPointSeparation.ToString(); splineNode.Attributes.Append(document.CreateAttribute("tension")).InnerText = string.Format(nullInfo, "{0}", root.Spline.Tension); List <System.Windows.Point> controlPoints = root.Spline.ControlPoints; foreach (var p in controlPoints) { splineNode.AppendChild(CreatePoint(document, new Point3D(p.X, p.Y))); } } return(geometryNode); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { // If parent == null, then this is a primary root and there is no emergence angle if (parent == null) { return(""); } else { SampledSpline parentSpline = parent.Spline; double parentIntersectionDistance = parentSpline.GetLength(root.StartReference); return(Math.Round(parentIntersectionDistance, 2)); } }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { double tipAngleDistance = 40.0; double tipDistance = root.Spline.SampledPointsLengths.Last(); double innerDistance = Math.Max(0, tipDistance - tipAngleDistance); Point innerPoint = root.Spline.GetPoint(root.Spline.GetPositionReference(innerDistance)); Point tipPoint = root.Spline.GetPoint(root.Spline.GetPositionReference(tipDistance)); // Tip Angle is angle between horizontal vector and the tip vector double angle = 90 - Vector.AngleBetween(new Vector(1, 0), tipPoint - innerPoint); return(Math.Round(angle > 180 ? angle - 360 : angle, 2)); }
/// <summary> /// Adds a directory to the model. /// </summary> /// <param name="sourcePath">Source path of the directory</param> /// <param name="rootInfo">Contains information about directory, *only* if the directory being added is the root</param> protected void AddDirectory(string sourcePath, RootInfo rootInfo) { WikiDirectory parent = null; if (rootInfo == null) { string parentPath = Path.GetDirectoryName(sourcePath); // recursively add any directories between us and the closest ancestor // in the map if (!UnderlyingModel.ContainsAssetBySourcePath(parentPath)) { AddDirectory(parentPath, null); } parent = UnderlyingModel.UnsafeGetAsset(parentPath) as WikiDirectory; } WikiDirectory newDirectory = new WikiDirectory { SourcePath = sourcePath, LastUpdated = DateTime.UtcNow, Depth = sourcePath.Count(c => c.Equals(Path.DirectorySeparatorChar)), Parent = parent, Children = new List <WikiEntry>() }; if (rootInfo == null) { newDirectory.WikiUrl = PathHelper.GetWikiUrl(UnderlyingModel.RootSourcePath, newDirectory.SourcePath); newDirectory.WikiPath = Path.Combine(UnderlyingModel.RootWikiPath, newDirectory.WikiUrl); // add child to the parent parent.Children.Add(newDirectory); } else { newDirectory.WikiUrl = ""; newDirectory.WikiPath = rootInfo.RootWikiPath; UnderlyingModel.SetRootDirectory(newDirectory); } UnderlyingModel.AddAsset(newDirectory.SourcePath, newDirectory); // fire event HandleDirectoryAdded(newDirectory); }
public virtual IEnumerable <PuttySessionInfo> GetSessions() { var sessionNamesFromProvider = GetSessionNames(true); foreach (var sessionName in GetSessionNamesToAdd(sessionNamesFromProvider)) { var sessionInfo = GetSession(sessionName); AddSession(sessionInfo); } foreach (var session in GetSessionToRemove(sessionNamesFromProvider)) { RemoveSession(session); } RootInfo.SortRecursive(); return(Sessions); }
private XmlNode CreateRoot(XmlDocument document, RootInfo root) { XmlNode rootNode = document.CreateElement("root"); // Attributes string id = root.RsmlID != "" ? root.RsmlID : root.RelativeID; rootNode.Attributes.Append(document.CreateAttribute("ID")).InnerText = id; if (root.Label != "") { rootNode.Attributes.Append(document.CreateAttribute("label")).InnerText = root.Label; } // Properties if (root.Properties != null && root.Properties.Count > 0) { rootNode.AppendChild(CreateProperties(document, root.Properties)); } // Geometry rootNode.AppendChild(CreateGeometry(document, root)); // Functions if (root.Functions != null && root.Functions.Count > 0) { rootNode.AppendChild(CreateFunctions(document, root.Functions)); } // Child Roots if (root.Children != null) { foreach (RootInfo childRoot in root.Children) { rootNode.AppendChild(CreateRoot(document, childRoot)); } } // Annotations if (root.Annotations != null && root.Annotations.Count > 0) { rootNode.AppendChild(CreateAnnotations(document, root.Annotations)); } return(rootNode); }
// Returns a list of paths. Each path is a sequence of objects, starting // on an object of type 'type' and ending on a root. public PathTree GetRoots(IProgressListener listener, int type) { RootInfo rootInfo = new RootInfo(); PathTree pathTree = new PathTree(this); foreach (int obj in GetObjectsByType(type)) { rootInfo.BaseObjects [obj] = obj; } int nc = 0; foreach (int obj in GetObjectsByType(type)) { if (listener.Cancelled) { return(null); } rootInfo.nc = 0; FindRoot(rootInfo, pathTree, obj); // Register partial paths to the root, to avoid having to // recalculate them again // if (nc % 100 == 0) // Console.WriteLine ("NC: " + nc + " " + rootInfo.Roots.Count); pathTree.AddBaseObject(obj); foreach (KeyValuePair <int, int[]> e in rootInfo.Roots) { pathTree.AddPath(e.Value); } rootInfo.Visited.Clear(); rootInfo.Roots.Clear(); nc++; double newp = (double)nc / (double)rootInfo.BaseObjects.Count; listener.ReportProgress("Looking for roots", newp); } pathTree.Flush(); return(pathTree); }
public void AddToPlayField(IntVector2 boardPosition, Vector3 worldPosition) { if (_gameState.rootPositionsForEachPiece.ContainsKey(boardPosition)) { return; } var newRoot = new RootInfo { worldPosition = worldPosition, boardPosition = boardPosition, connectedBoardPositions = new List <IntVector2> { boardPosition } }; _gameState.rootsByBoardPosition.Add(boardPosition, newRoot); _gameState.rootPositionsForEachPiece.Add(boardPosition, boardPosition); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { // If parent == null, then this is a primary root and there is no emergence angle if (parent == null) { Point start, end; start = root.Spline.Start; end = root.Spline.End; // Angle between horizontal and emergence vectors double angle = 90 - Vector.AngleBetween(new Vector(1, 0), end - start); return(Math.Round(angle > 180 ? angle - 360 : angle, 2)); } else { // Do not calculate for lateral roots return(null); } }
public bool BeginSyncTransaction() { // TODO: Check connection and auth (is getting root/user resources a sufficient check?) root = RootInfo.GetRoot(rootUri, connection); user = UserInfo.GetUser(root.User.ApiRef, connection); if (user.LatestSyncRevision.HasValue) { LatestRevision = user.LatestSyncRevision.Value; } else { VerifyLatestSyncRevision(user.LatestSyncRevision); } if (string.IsNullOrEmpty(user.CurrentSyncGuid)) { throw new TomboySyncException("No sync GUID for user provided in server response"); } pendingCommits = new List <NoteInfo> (); return(true); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { // If parent == null, then this is a primary root and there is no emergence angle if (parent == null) { return(""); } else { double parentAngleRadius = 10.0; SampledSpline parentSpline = parent.Spline; double parentIntersectionDistance = parentSpline.GetLength(root.StartReference); Point parentStart = parentSpline.GetPoint(parentSpline.GetPositionReference(Math.Max(0.0, parentIntersectionDistance - parentAngleRadius))); Point parentEnd = parentSpline.GetPoint(parentSpline.GetPositionReference(Math.Min(parent.Spline.Length, parentIntersectionDistance + parentAngleRadius))); Vector parentVector = parentEnd - parentStart; double angle = 90 - Vector.AngleBetween(new Vector(1, 0), parentEnd - parentStart); return(Math.Round(angle > 180 ? angle - 360 : angle, 2)); } }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { return(root.Label == null ? "" : root.Label); }
private void OnAuthButtonClicked(object sender, EventArgs args) { if (listener != null && listener.IsListening) { listener.Stop(); listener.Close(); } // TODO: Move this if (Auth == null) { Auth = new Api.OAuth(); } string rootUri = Server + "/api/1.0"; try { RootInfo root = RootInfo.GetRoot(rootUri, new Api.AnonymousConnection()); Auth.AuthorizeLocation = root.AuthorizeUrl; Auth.AccessTokenBaseUrl = root.AccessTokenUrl; Auth.RequestTokenBaseUrl = root.RequestTokenUrl; Auth.ConsumerKey = "anyone"; Auth.ConsumerSecret = "anyone"; Auth.Realm = "Snowy"; } catch (Exception e) { Logger.Error("Failed to get Root resource " + rootUri + ". Exception was: " + e.ToString()); authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } if (!Auth.IsAccessToken) { listener = new HL.HttpListener(); int portToTry = 8000; string callbackUrl = string.Empty; while (!listener.IsListening && portToTry < 9000) { callbackUrl = String.Format("http://localhost:{0}/tomboy-web-sync/", portToTry); try { listener.Prefixes.Add(callbackUrl); } catch (Exception e) { Logger.Error("Exception while trying to add {0} as an HttpListener Prefix", callbackUrl); Logger.Error(e.ToString()); break; } try { listener.Start(); Auth.CallbackUrl = callbackUrl; } catch { listener.Prefixes.Clear(); portToTry++; } } if (!listener.IsListening) { Logger.Error("Unable to start HttpListener on any port between 8000-8999"); authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } Logger.Debug("Listening on {0} for OAuth callback", callbackUrl); string authUrl = string.Empty; try { authUrl = Auth.GetAuthorizationUrl(); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Failed to get auth URL from " + Server + ". Exception was: " + e.ToString()); // Translators: The web service supporting Tomboy WebSync is not responding as expected authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } IAsyncResult result = listener.BeginGetContext(delegate(IAsyncResult localResult) { HL.HttpListenerContext context; try { context = listener.EndGetContext(localResult); } catch (Exception e) { // TODO: Figure out why this error occurs Logger.Error("Error processing OAuth callback. Could be a sign that you pressed the button to reset the connection. Exception details:"); Logger.Error(e.ToString()); return; } // Assuming if we got here user clicked Allow Logger.Debug("Context request uri query section: " + context.Request.Url.Query); // oauth_verifier is required in OAuth 1.0a, not 1.0 var qs = HttpUtility.ParseQueryString(context.Request.Url.Query); if (!String.IsNullOrEmpty(qs ["oauth_verifier"])) { Auth.Verifier = qs ["oauth_verifier"]; } try { if (!Auth.GetAccessAfterAuthorization()) { throw new ApplicationException("Unknown error getting access token"); } Logger.Debug("Successfully authorized web sync"); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Failed to authorize web sync, with exception:"); Logger.Error(e.ToString()); Gtk.Application.Invoke(delegate { authButton.Label = Catalog.GetString("Authorization Failed, Try Again"); authButton.Sensitive = true; }); oauth = null; return; } string htmlResponse = String.Format(callbackHtmlTemplate, // Translators: Title of web page presented to user after they authorized Tomboy for sync Catalog.GetString("Tomboy Web Authorization Successful"), // Translators: Body of web page presented to user after they authorized Tomboy for sync Catalog.GetString("Please return to the Tomboy Preferences window and press Save to start synchronizing.")); using (var writer = new System.IO.StreamWriter(context.Response.OutputStream)) writer.Write(htmlResponse); listener.Stop(); listener.Close(); if (Auth.IsAccessToken) { Gtk.Application.Invoke(delegate { authButton.Sensitive = false; authButton.Label = Catalog.GetString("Connected. Press Save to start synchronizing"); }); } }, null); Logger.Debug("Launching browser to authorize web sync: " + authUrl); authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)"); try { Services.NativeApplication.OpenUrl(authUrl, Screen); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Exception opening URL: " + e.Message); // Translators: Sometimes a user's default browser is not set, so we recommend setting it and trying again authButton.Label = Catalog.GetString("Set the default browser and try again"); return; } // Translators: The user must take action in their web browser to continue the authorization process authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)"); } }
// It returns -2 of obj is a dead end // Returns n >= 0, if all paths starting at 'obj' end in objects already // visited. 'n' is the index of a node in rootInfo.Path, which is the closest // visited node found // Returns -1 otherwise. // This return value is used to detect dead ends. int FindRoot(RootInfo rootInfo, PathTree pathTree, int obj) { if (rootInfo.DeadEnds.ContainsKey(obj)) { return(-2); } int curval; if (rootInfo.Visited.TryGetValue(obj, out curval)) { // The object has already been visited if (rootInfo.Path.Count >= curval) { return(rootInfo.Path.IndexOf(obj)); } } rootInfo.Visited [obj] = rootInfo.Path.Count; int treePos = pathTree.GetObjectNode(obj); if (treePos != -1) { // If this object already has partial paths to roots, // reuse them. FindTreeRoot(rootInfo.Path, rootInfo.Roots, pathTree, treePos); return(-1); } rootInfo.Path.Add(obj); bool hasrefs = false; int findresult = int.MaxValue; foreach (int oref in GetReferencers(obj)) { hasrefs = true; if (!rootInfo.BaseObjects.ContainsKey(oref)) { int fr = FindRoot(rootInfo, pathTree, oref); if (fr != -2 && fr < findresult) { findresult = fr; } } } if (!hasrefs) { // A root rootInfo.Visited.Remove(obj); RegisterPath(rootInfo.Roots, rootInfo.Path, obj); findresult = -1; } rootInfo.Path.RemoveAt(rootInfo.Path.Count - 1); // If all children paths end in nodes already visited, it means that it is a dead end. if (findresult >= rootInfo.Path.Count) { rootInfo.DeadEnds [obj] = obj; // Console.WriteLine ("de: " + findresult); } return(findresult); }
private List <ImageSource> CreateSeparatePlantImages(List <PlantInfo> plants, out List <Point> sourcePositions) { sourcePositions = new List <Point>(); var outputImages = new List <ImageSource>(); Pen p = new Pen(Brushes.Black, 6.0); p.StartLineCap = PenLineCap.Round; p.EndLineCap = PenLineCap.Round; List <Dictionary <String, RootInfo> > plantComponents = new List <Dictionary <string, RootInfo> >(); int index = 0; foreach (PlantInfo plant in plants) { plantComponents.Insert(index, new Dictionary <string, RootInfo>()); foreach (RootInfo root in plant) { // Start of first primary is the plant source if (root.RelativeID == plant.RelativeID + ".1") { sourcePositions.Add(new Point(root.Spline.Start.X, root.Spline.Start.Y)); } plantComponents[index].Add(root.RelativeID, root); } index++; } // For each plant, create a new image for (int i = 0; i < plantComponents.Count; i++) { var plantComponentDictionary = plantComponents[i]; // Find global plant bounding box double left = double.MaxValue, right = double.MinValue, top = double.MaxValue, bottom = double.MinValue; foreach (var components in plantComponentDictionary.Values) { SampledSpline spline = components.Spline as SampledSpline; if (spline == null) { continue; } Rect r = spline.BoundingBox; if (r.Left < left) { left = r.Left; } if (r.Right > right) { right = r.Right; } if (r.Top < top) { top = r.Top; } if (r.Bottom > bottom) { bottom = r.Bottom; } } int width = (int)right - (int)left + 8; int height = (int)bottom - (int)top + 8; RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, width, height)); // Draw splines StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext sgc = geometry.Open()) { foreach (var kvp in plantComponentDictionary) { SampledSpline spline = kvp.Value.Spline as SampledSpline; if (spline != null) { Point[] points = spline.SampledPoints; // Optional line from start position on parent RootInfo parent = plantComponentDictionary.ContainsKey(kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))) ? plantComponentDictionary[kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))] : null; if (parent != null) { Point start = parent.Spline.GetPoint(kvp.Value.StartReference); sgc.BeginFigure(new Point(start.X - left + 4, start.Y - top + 4), false, false); sgc.LineTo(new Point(points[0].X - left + 4, points[0].Y - top + 4), true, true); } else { sgc.BeginFigure(new Point(points[0].X - left + 4, points[0].Y - top + 4), false, false); } for (int i2 = 1; i2 < points.Length; i2++) { sgc.LineTo(new Point(points[i2].X - left + 4, points[i2].Y - top + 4), true, true); } } } } if (geometry.CanFreeze) { geometry.Freeze(); } drawingContext.DrawGeometry(null, p, geometry); sourcePositions[i] = new Point(sourcePositions[i].X - left + 4, sourcePositions[i].Y - top + 4); drawingContext.Close(); rtb.Render(drawingVisual); if (rtb.CanFreeze) { rtb.Freeze(); } outputImages.Add(rtb); } return(outputImages); }
unsafe private void segmentedImagesMenuItem_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog() { SelectedPath = "G:\\Training Sets\\new" }; var result = fbd.ShowDialog(); if (result != System.Windows.Forms.DialogResult.OK) { return; } foreach (double penWidth in new double[] { 8 }) { bool useCrop = true; bool tipsOnly = false; bool primaryOnly = false; bool lateralOnly = false; bool conflictOnly = false; bool sourceOnly = false; bool outputOriginalImages = false; //double penWidth = 10; this.SnapsToDevicePixels = true; RenderOptions.SetEdgeMode(this, EdgeMode.Aliased); string[] supportedDatasets = new string[] { "RSDH00", "RSDH01", "RSDH02", "RSDH03", "RSDH04", "RSDH06", "RSDH07", "RSDH08", "RSDH09", "RSDH10" }; List <string> tags = rootReader.FilterTags(supportedDatasets, true); Random rand = new Random(); string path = fbd.SelectedPath; string segPath = path + "\\segmentation" + penWidth; string imagePath = path + "\\images"; int runningTotal = 0; int count = 0; if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } if (!Directory.Exists(segPath)) { Directory.CreateDirectory(segPath); } foreach (string tag in tags) { var data = rootReader.Read(tag, true); // If no image, skip if (data.Item3 == null) { continue; } SceneMetadata metadata = data.Item1; SceneInfo scene = data.Item2; byte[] imageData = data.Item3; BitmapSource currentImage; using (MemoryStream ms = new MemoryStream(imageData)) { JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); // Due to what appears to be a bug in .NET, wrapping in a WBMP causes a cache refresh and fixes some image corruption currentImage = new WriteableBitmap(decoder.Frames[0]); } SolidColorBrush scb = new SolidColorBrush(Colors.White); Pen p = new Pen(Brushes.White, penWidth); p.StartLineCap = PenLineCap.Round; p.EndLineCap = PenLineCap.Round; // Obtain all root information Dictionary <String, RootInfo> plantComponents = new Dictionary <string, RootInfo>(); foreach (PlantInfo plant in scene.Plants) { foreach (RootInfo root in plant) { plantComponents.Add(root.RelativeID, root); } } // Initialise conflict data int conflictScale = 30; int conflictWidth = currentImage.PixelWidth / conflictScale; int conflictHeight = currentImage.PixelHeight / conflictScale; int[] rootCount = new int[conflictWidth * conflictHeight]; bool[] rootCounted = new bool[conflictWidth * conflictHeight]; // Crop // Find global plant bounding box double left = double.MaxValue, right = double.MinValue, top = double.MaxValue, bottom = double.MinValue; foreach (var kvp in plantComponents) { SampledSpline spline = kvp.Value.Spline as SampledSpline; if (spline == null) { continue; } Rect r = spline.BoundingBox; if (r.Left < left) { left = r.Left; } if (r.Right > right) { right = r.Right; } if (r.Top < top) { top = r.Top; } if (r.Bottom > bottom) { bottom = r.Bottom; } // If detecting conflict if (conflictOnly) { RootInfo parent = plantComponents.ContainsKey(kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))) ? plantComponents[kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))] : null; if (parent == null) { Array.Clear(rootCounted, 0, rootCounted.Length); foreach (Point splinePoint in spline.SampledPoints) { int conflictX = (int)(splinePoint.X / conflictScale); int conflictY = (int)(splinePoint.Y / conflictScale); int conflictIndex = conflictY * conflictWidth + conflictX; if (!rootCounted[conflictIndex]) { rootCount[conflictIndex]++; rootCounted[conflictIndex] = true; } } } } } // Render to drawingVisual, then image int width = currentImage.PixelWidth; int height = currentImage.PixelHeight; // Optional Crop Int32Rect?cropRectangle = null; if (useCrop) { int cropPadding = 64; int l = Math.Max(0, (int)(left - cropPadding)); int r = Math.Min(width, (int)(right + cropPadding)); int t = Math.Max(0, (int)(top - cropPadding)); int b = Math.Min(height, (int)(bottom + cropPadding)); cropRectangle = new Int32Rect(l, t, r - l, b - t); } RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); SolidColorBrush background = new SolidColorBrush(Colors.Black); drawingContext.DrawRectangle(Brushes.Black, null, new Rect(0, 0, width, height)); // Draw splines StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext sgc = geometry.Open()) { foreach (var kvp in plantComponents) { SampledSpline spline = kvp.Value.Spline as SampledSpline; if (spline != null) { Point[] points = spline.SampledPoints; // Optional line from start position on parent if (sourceOnly) { // First primary source if (kvp.Value.RelativeID == "1.1") { sgc.BeginFigure(points[0], false, false); sgc.LineTo(points[0], true, true); break; } } if (tipsOnly) { if (primaryOnly) { RootInfo parent = plantComponents.ContainsKey(kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))) ? plantComponents[kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))] : null; if (parent == null) { sgc.BeginFigure(points[points.Length - 2], false, false); sgc.LineTo(points[points.Length - 1], true, true); } } else if (lateralOnly) { RootInfo parent = plantComponents.ContainsKey(kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))) ? plantComponents[kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))] : null; if (parent != null) { sgc.BeginFigure(points[points.Length - 2], false, false); sgc.LineTo(points[points.Length - 1], true, true); } } else { sgc.BeginFigure(points[points.Length - 2], false, false); sgc.LineTo(points[points.Length - 1], true, true); } } else { RootInfo parent = plantComponents.ContainsKey(kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))) ? plantComponents[kvp.Key.Substring(0, kvp.Key.LastIndexOf("."))] : null; if (parent != null) { Point start = parent.Spline.GetPoint(kvp.Value.StartReference); sgc.BeginFigure(new Point(start.X, start.Y), false, false); sgc.LineTo(new Point(points[0].X, points[0].Y), true, true); } else { sgc.BeginFigure(new Point(points[0].X, points[0].Y), false, false); } for (int i = 1; i < points.Length; i++) { sgc.LineTo(new Point(points[i].X, points[i].Y), true, true); } } } } } if (geometry.CanFreeze) { geometry.Freeze(); } drawingContext.DrawGeometry(p.Brush, p, geometry); drawingContext.Close(); rtb.Render(drawingVisual); if (rtb.CanFreeze) { rtb.Freeze(); } // Save original file BitmapEncoder Encoder; if (outputOriginalImages) { Encoder = new PngBitmapEncoder(); using (FileStream FS = File.Open(imagePath + "\\" + count + ".png", FileMode.OpenOrCreate)) { Encoder.Frames.Add(BitmapFrame.Create(useCrop ? new CroppedBitmap(currentImage, cropRectangle.Value) : currentImage)); Encoder.Save(FS); FS.Close(); } } // Create mask from RTB int renderStride = rtb.PixelWidth * 4; byte[] renderArr = new byte[rtb.PixelWidth * rtb.PixelHeight * 4]; rtb.CopyPixels(renderArr, rtb.PixelWidth * 4, 0); WriteableBitmap mask = new WriteableBitmap(rtb.PixelWidth, rtb.PixelHeight, 96.0, 96.0, PixelFormats.Gray8, null); mask.Lock(); byte *ptr = (byte *)mask.BackBuffer.ToPointer(); int stride = mask.BackBufferStride; for (int x = 0; x < mask.PixelWidth; x++) { for (int y = 0; y < mask.PixelHeight; y++) { // Obtain red pixel as representative of gray value byte current = renderArr[y * renderStride + (x * 4) + 1]; if (current > 127) { if (conflictOnly) { int index = (y / conflictScale) * conflictWidth + (x / conflictScale); if (rootCount[index] > 1) { *(ptr + y * stride + x) = 255; } } else { *(ptr + y * stride + x) = 255; } } } } mask.AddDirtyRect(new Int32Rect(0, 0, width, height)); mask.Unlock(); BitmapSource outputMask = mask; Encoder = new PngBitmapEncoder(); using (FileStream FS = File.Open(segPath + "\\" + count.ToString("D4") + ".png", FileMode.OpenOrCreate)) { Encoder.Frames.Add(BitmapFrame.Create(useCrop ? new CroppedBitmap(outputMask, cropRectangle.Value) : outputMask)); Encoder.Save(FS); FS.Close(); } count++; runningTotal++; if (runningTotal > 20) { runningTotal -= 20; GC.Collect(); GC.WaitForPendingFinalizers(); } } } }
private RootInfo ReadRoot(XmlNode rootNode, string RelativeID, RootInfo parent) { RootInfo root = new RootInfo() { Children = new List <RootInfo>() }; // Attributes XmlAttribute id = rootNode.Attributes["ID"] == null ? rootNode.Attributes["id"] : rootNode.Attributes["ID"]; if (id != null) { root.RsmlID = id.InnerText; } XmlAttribute label = rootNode.Attributes["label"]; if (label != null) { root.Label = label.InnerText; } // RelativeID root.RelativeID = RelativeID; // If no id was supplied in the rsml file, use the relative ID. if (root.RsmlID == null) { root.RsmlID = RelativeID; } // Root Properties XmlNode propertiesNode = rootNode.SelectSingleNode("properties"); if (propertiesNode != null) { root.Properties = ReadProperties(propertiesNode); } // Geometry - not currently preserved XmlNode geometry = rootNode.SelectSingleNode("geometry"); if (geometry != null) { Polyline polyline; SampledSpline spline; ReadGeometry(geometry, out polyline, out spline); root.Polyline = polyline; root.Spline = spline; } // Start position if (parent != null) { var start = root.Spline.Start; root.StartReference = parent.Spline.GetPositionReference(start); } // Functions XmlNode functionsNode = rootNode.SelectSingleNode("functions"); if (functionsNode != null) { root.Functions = ReadFunctions(functionsNode); } // Child Roots int rootID = 1; foreach (XmlNode childRootNode in rootNode.SelectNodes("root")) { root.Children.Add(ReadRoot(childRootNode, root.RelativeID + "." + rootID++.ToString(), root)); } // Annotations XmlNode annotationsNode = rootNode.SelectSingleNode("annotations"); if (annotationsNode != null) { root.Annotations = ReadAnnotations(annotationsNode); } return(root); }
public static SceneInfo RootCollectionToRSMLScene(RootCollection collection) { SceneInfo scene = new SceneInfo() { Plants = new List <PlantInfo>() }; foreach (RootBase rootBase in collection.RootTree) { // Each rootbase tree represents a plant in this image. if (rootBase is RootGroup) { PlantInfo plant = new PlantInfo() { Roots = new List <RootInfo>(), RelativeID = rootBase.RelativeID }; if (rootBase.Label != "") { plant.Label = rootBase.Label; } RootGroup group = rootBase as RootGroup; // For each primary root foreach (PrimaryRoot primary in group.Children) { RootInfo primaryRootInfo = new RootInfo() { Children = new List <RootInfo>(), RelativeID = primary.RelativeID, RsmlID = primary.RelativeID, Polyline = null, Spline = primary.Spline }; if (primary.Label != "") { primaryRootInfo.Label = primary.Label; } foreach (LateralRoot lateral in primary.Children) { RootInfo lateralRootInfo = new RootInfo() { Children = new List <RootInfo>(), RelativeID = lateral.RelativeID, RsmlID = lateral.RelativeID, Polyline = null, Spline = lateral.Spline }; if (lateral.Label != "") { lateralRootInfo.Label = lateral.Label; } primaryRootInfo.Children.Add(lateralRootInfo); } plant.Roots.Add(primaryRootInfo); } scene.Plants.Add(plant); } } return(scene); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { double chordLength = (root.Spline.End - root.Spline.Start).Length; return(Math.Round(root.Spline == null ? 0.0 : root.Spline.Length / chordLength, 2)); }
public override object MeasureRoot(RootInfo root, RootInfo parent = null) { return(Math.Round(root.Spline == null ? 0.0 : root.Spline.Length, 2)); }
public virtual object MeasureRoot(RootInfo root, RootInfo parent = null) { throw new NotImplementedException(); }