public void RoundTest( float x, float y, int expectedX, int expectedY ) { Point point = new Point( x, y ); IntPoint iPoint = new IntPoint( expectedX, expectedY ); Assert.AreEqual( iPoint, point.Round( ) ); }
/// <summary> /// Implements the observer pattern for the mouse down event, communicating the event to all listeners implementing the necessary interface. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> void surface_MouseDown(object sender, MouseEventArgs e) { #region Coordinates logic // Get a point adjusted by the current scroll position and zoom factor Point p = Point.Round(this.View.ViewToWorld(this.View.DeviceToView(e.Location))); MouseEventArgs ce = new MouseEventArgs(e.Button, e.Clicks, p.X, p.Y, e.Delta); #endregion if (eventsEnabled) { RaiseOnMouseDown(ce); } if (!controllerEnabled) { return; } this.parentControl.Focus(); //(parentControl as Win.DiagramControl).toolTip.Show("Yihaaa", parentControl as Win.DiagramControl, ce.Location); //this selection process will work independently of the tools because //some tools need the current selection or hit entity //On the other hand, when drawing a simple rectangle for example the selection //should be off, so there is an overhead. //Selection.CollectEntitiesAt(e.Location); //raise the event to give the host the opportunity to show the properties of the selected item(s) //Note that if the selection is empty the property grid will show 'nothing'. RaiseOnShowSelectionProperties(new SelectionEventArgs(Selection.SelectedItems.ToArray())); foreach (IMouseListener listener in mouseListeners) { if (listener.MouseDown(ce)) { break; } } }
/// <summary> /// Function to draw a spray on the screen. /// </summary> /// <param name="joystick">Joystick to use for the spray.</param> /// <param name="index">Index of the joystick.</param> private void DrawSpray(GorgonJoystick joystick, int index) { SprayCan state = _sprayStates[index]; // Update the origin of the spray. state.Origin = _stickPosition[index]; // Find out if we're spraying. if (joystick.Throttle > joystick.Capabilities.ThrottleAxisRange.Minimum) { if ((!state.IsActive) && (!state.NeedReset)) { // Convert the throttle value to a unit value. float throttleUnit = ((float)(joystick.Throttle - joystick.Capabilities.ThrottleAxisRange.Minimum) / joystick.Capabilities.ThrottleAxisRange.Range); // Set up the spray state. state.Position = state.Origin; state.Amount = joystick.Capabilities.ThrottleAxisRange.Range / 2.0f; state.Time = throttleUnit * 10.0f; state.VibrationAmount = joystick.Capabilities.VibrationMotorRanges[1].Maximum; state.SprayAlpha = (throttleUnit * 239.0f) + 16; state.IsActive = true; } } else { state.IsActive = false; } if (!state.IsActive) { return; } // Update the state spray effect. state.Update(); _surface.DrawPoint(Point.Round(state.Position), state.SprayColor, state.SprayPointSize); }
private void DetectIllegalServing(Mat image) { Mat final = image.Clone(); Mat contours = GetBallContours(image); Mat handContours = GetHandContours(image); Image <Bgr, byte> hand = GetPalm(handContours); CircleF[] circles = CvInvoke.HoughCircles(contours, HoughType.Gradient, dp, minDist, param1, param2); if (circles.Length > 0) { foreach (var circle in circles) { CvInvoke.Circle(final, Point.Round(circle.Center), (int)circle.Radius, new Bgr(Color.Red).MCvScalar, 3); } } label7.BeginInvoke(new MethodInvoker(delegate { label7.Text = $"Circle count: {circles.Length}"; })); pictureBox2.Image = contours.Bitmap; pictureBox3.Image = hand.Bitmap; pictureBox4.Image = final.Bitmap; }
private Bitmap DrawCircle(Image <Bgr, byte> raw, List <CircleF> mainCircle, List <CircleF> auxCircle = null) { Mat circleImage = raw.Mat; if (mainCircle != null) { for (int i = 0; i < mainCircle.Count; i++) { CvInvoke.Circle(circleImage, Point.Round(mainCircle[i].Center), (int)mainCircle[i].Radius, new Bgr(Color.Red).MCvScalar, 1); CvInvoke.PutText(circleImage, i.ToString("D3"), new Point((int)mainCircle[i].Center.X, (int)mainCircle[i].Center.Y), Emgu.CV.CvEnum.FontFace.HersheyScriptComplex, 1, new MCvScalar(255, 255, 0), 1); } } if (auxCircle != null) { for (int i = 0; i < auxCircle.Count; i++) { CvInvoke.Circle(circleImage, Point.Round(auxCircle[i].Center), (int)auxCircle[i].Radius, new Bgr(Color.Yellow).MCvScalar, 1); } } return(circleImage.Bitmap); }
public static void LinearSmoothMove(Point newPosition, int steps) { Point start = Cursor.Position; PointF iterPoint = start; // Find the slope of the line segment defined by start and newPosition PointF slope = new PointF(newPosition.X - start.X, newPosition.Y - start.Y); // Divide by the number of steps slope.X = slope.X / steps; slope.Y = slope.Y / steps; // Move the mouse to each iterative point. for (int i = 0; i < steps; i++) { iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y); SetCursorPos(Point.Round(iterPoint).X, Point.Round(iterPoint).Y); Thread.Sleep(2); } // Move the mouse to the final destination. SetCursorPos(Point.Round(newPosition).X, Point.Round(newPosition).Y); }
private IEnumerable <BlobPack> GetPacksFromImage(Image <Gray, byte> focus, IEnumerable <CvBlob> blobs, DebugState debugState) { var frame_center = new Point(focus.Width / 2, focus.Height / 2); var parts = new List <BlobPack>(); foreach (var b in blobs) { b.BoundingBox.Inflate(2, 2); var rotationAngle = Math2.GetPolarHeadingFromLine(new LineSegment2D(Point.Round(b.Centroid), frame_center)); var rotated_frame = focus.Rotate(-1 * rotationAngle, new Gray(0)); var rotated_letter_only = rotated_frame.Copy(new Rectangle(rotated_frame.Width / 2 - 30, 0, 60, 60)); // rotated_letter_only = Utils.RemoveBlobs(rotated_letter_only, 1, 3); debugState.Add(rotated_letter_only); parts.Add(new BlobPack { BlobImage = rotated_letter_only, BlobRationAngle = rotationAngle, BlobBox = b.BoundingBox }); } return(parts); }
private PointF GetNearestValidPoint(MouseEventArgs e)//返回PictureBox坐标下的PointF { //float x = (float)Math.Round((e.X - 20) / 40.0); //float y = (float)Math.Round((500 - e.Y) / 40.0); //PointF ptf1 = new PointF(40f * x + 20f, 500f - 40f * y); PointF ptf1 = ToPictureBoxPointF(Point.Round(ToGridPointF(e.Location))); PointF ptf2 = TS.GetNearestNode(ToGridPointF(e.Location));//ptf2此时是Grid坐标下的PointF if (ptf2.IsEmpty) { return(ptf1); } ptf2 = ToPictureBoxPointF(ptf2);//将ptf2转为PictureBox坐标下的PointF double d1 = Math.Pow(ptf1.X - e.X, 2) + Math.Pow(ptf1.Y - e.Y, 2); double d2 = Math.Pow(ptf2.X - e.X, 2) + Math.Pow(ptf2.Y - e.Y, 2); if (d1 < d2) { return(ptf1); } return(ptf2); }
public override GH_ObjectResponse RespondToMouseDown(GH_Canvas sender, GH_CanvasMouseEvent e) { if (e.Button == MouseButtons.Left && imgBitmap != null) { RectangleF recImg = GetImgBounds(this.Bounds, TopOffset, BtmOffset); RectangleF recNavLeft = GetNavBounds(recImg, BtmOffset, NavButtonSize, false); RectangleF recNavRight = GetNavBounds(recImg, BtmOffset, NavButtonSize, true); //Click inside the img if (recImg.Contains(e.CanvasLocation) && !ViewOwner.DisableClickable) { float img2ViewportRatio = (float)recImg.Width / (float)this.imgBitmap.Width; PointF clickedPt = PointF.Subtract(e.CanvasLocation, new SizeF(recImg.X, recImg.Y)); //convert current pt location on grasshopper view back to original image size system Point PixelPtOnOriginalBitmap = Point.Round(new PointF(clickedPt.X / img2ViewportRatio, clickedPt.Y / img2ViewportRatio)); this.MouseImgClickEvent(this, PixelPtOnOriginalBitmap); return(GH_ObjectResponse.Handled); } else if (recNavLeft.Contains(e.CanvasLocation)) { //Left Nav click this.MouseNavClickEvent(this, false); } else if (recNavRight.Contains(e.CanvasLocation)) { //Right Nav click this.MouseNavClickEvent(this, true); } else { //MessageBox.Show("ImgBounds:" + ImgBounds + "\nclicked at: " + e.CanvasLocation + "\n" + Pivot + "\n" + ImgBounds.Contains(e.CanvasLocation)); } } return(base.RespondToMouseDown(sender, e)); }
public Edge GetEdge(EdgeDirection dir) { var p1 = Point.Round(OriginalLocation); foreach (var e in Edges) { var p2 = Point.Round(e.GetOtherNode(this).OriginalLocation); switch (dir) { case EdgeDirection.North: if (p1.X == p2.X && p1.Y > p2.Y) { return(e); } break; case EdgeDirection.East: if (p1.Y == p2.Y && p1.X < p2.X) { return(e); } break; case EdgeDirection.South: if (p1.X == p2.X && p1.Y < p2.Y) { return(e); } break; case EdgeDirection.West: if (p1.Y == p2.Y && p1.X > p2.X) { return(e); } break; } } return(null); }
/// <summary> /// Get handle point by 1-based number /// </summary> /// <param name="handleNumber"></param> /// <returns></returns> public override Point GetHandle(ZWPictureBox pictureBox, int handleNumber) { float x = 0, y = 0, xCenter, yCenter; RectangleF rect = outterCircle.Rectangle; xCenter = rect.X + rect.Width / 2; yCenter = rect.Y + rect.Height / 2; switch (handleNumber) { case 1: x = rect.X; y = yCenter; break; case 2: x = xCenter; y = rect.Y; break; case 3: x = rect.Right; y = yCenter; break; case 4: x = xCenter; y = rect.Bottom; break; } PointF[] pts = new PointF[1]; pts[0] = new PointF(x, y); return(Point.Round(pts[0])); }
private GraphicsPath GenerateStem(double minD, double maxD, double minA, double maxA, [Optional] Point offset) { GraphicsPath path = new GraphicsPath(); double d = random.NextDouble() * (maxD - minD) + minD; double a = random.NextDouble() * (maxA - minA) + minA; if (offset.Equals(new Point(0, 0))) { offset = new Point(1920 / 2, 1080 / 6 * 5); } Point start = new Point(0, 0); start.Offset(offset); Point end = new Point(Convert.ToInt32(Math.Cos(a) * d), Convert.ToInt32(Math.Sin(a) * d)); end.Offset(offset); Point control = end; control.Offset(random.Next(-50, 50), random.Next(25, 100)); Point control1 = Point.Round(LerpPoint(start, control, 2 / 3)); Point control2 = Point.Round(LerpPoint(control, end, 1 / 3)); //g.DrawLine(penWhite, start, end); path.AddBezier(start, control1, control2, end); //Pen penDebug = new Pen(Color.FromArgb(0, 255, 0)); //Size s20 = new Size(20, 20); //Size s10 = new Size(10, 10); //Size s5 = new Size(5, 5); //g.DrawEllipse(penDebug, new Rectangle(start - s10, s20)); //g.DrawEllipse(penDebug, new Rectangle(control - s5, s10)); //g.DrawEllipse(penDebug, new Rectangle(end - s10, s20)); return(path); }
public static void TestBinarize() { string testName = System.Reflection.MethodBase.GetCurrentMethod().Name; StringBuilder msgBuilder = new StringBuilder("Performance: "); Stopwatch watch = Stopwatch.StartNew(); Image <Bgr, Byte> img = Load(testImage); UMat uimage = Grayed(img); Image <Gray, Byte> image = Binarize(30, ToImage(uimage)); CircleF[] circles = CvInvoke.HoughCircles(image, HoughType.Gradient, 2, 40, 180, 13, 18, 20); watch.Stop(); msgBuilder.Append(string.Format("{0} Hough circles - {1} ms; ", testName, watch.ElapsedMilliseconds)); Mat circleImage = img.Mat; for (int i = 0; i < circles.Length; i++) { CvInvoke.Circle(circleImage, Point.Round(circles[i].Center), (int)circles[i].Radius, new Bgr(Color.Red).MCvScalar, 2); CvInvoke.PutText(circleImage, i.ToString("D3"), new Point((int)circles[i].Center.X, (int)circles[i].Center.Y), Emgu.CV.CvEnum.FontFace.HersheyScriptComplex, 1, new MCvScalar(255, 255, 0), 1); } circleImage.Save(resultPath + testName + ".jpg"); (new Logger()).Debug(msgBuilder.ToString()); msgBuilder = new StringBuilder("Circles: " + Environment.NewLine); int[] lights = new int[circles.Length]; for (int i = 0; i < circles.Length; i++) { lights[i] = CountPixels(ToImage(uimage), circles[i]); msgBuilder.Append(string.Format("{0} {1}", i.ToString("D3"), lights[i]) + Environment.NewLine); } (new Logger()).Debug(msgBuilder.ToString()); }
public override void MouseUp(object sender, MouseButtons button, PointF location) { PointF pf = GetRevertScrollAndScalePointF(location); PointF revertDownPoint = GetRevertScrollAndScalePointF(_downPoint); if (_create.MouseUp(button, location, pf, revertDownPoint)) { return; } base.MouseUp(sender, button, pf); if (_isSelectFrame) { DrawFrame(PointF.Empty, PointF.Empty, FrameStyle.Dashed, true); _selectedObjs.Clear(); RectangleF rf = Tool.GetRect(Point.Round(_downPoint), Point.Round(location)); rf = GetRevertScrollAndScaleRect(rf); foreach (IDrawObj obj in Objs) { if (obj.CanSelect(rf)) { _selectedObjs.Add(obj); } } _controlPoint.ChangeSelectObj(_selectedObjs); _isSelectFrame = false; } _controlPoint.MouseUp(pf); RefreshProperty(); }
/// <summary> /// Invokes an interactive edit box on the name of the graphic, allowing the user to assign a name to the <see cref="IRoiGraphic"/>. /// </summary> public void Rename() { var parent = ParentGraphic; if (parent == null) return; this.CoordinateSystem = CoordinateSystem.Destination; try { EditBox editBox = new EditBox(parent.Name ?? string.Empty); editBox.Location = Point.Round(base.TextGraphic.Location); editBox.Size = Size.Round(base.TextGraphic.BoundingBox.Size); editBox.FontName = base.TextGraphic.Font; editBox.FontSize = base.TextGraphic.SizeInPoints; editBox.Multiline = false; editBox.ValueAccepted += OnEditBoxAccepted; editBox.ValueCancelled += OnEditBoxCancelled; base.ParentPresentationImage.Tile.EditBox = editBox; } finally { this.ResetCoordinateSystem(); } }
private Bitmap LoadFrame(bool transparent, bool useCornerBug) { var transparentFrame = $"{Directory.GetCurrentDirectory()}/DataSource/InsertFrameTrans.png"; var greenFrame = $"{Directory.GetCurrentDirectory()}/DataSource/InsertFrameGreen.png"; Bitmap image; if (transparent) { image = new Bitmap(transparentFrame); } else { image = new Bitmap(greenFrame); } if (useCornerBug && File.Exists($"{Environment.GetEnvironmentVariable("userprofile")}/InsertCreator/Logo.png")) { var drawingTool = Graphics.FromImage(image); var logoImage = new Bitmap($"{Environment.GetEnvironmentVariable("userprofile")}/InsertCreator/Logo.png"); drawingTool.DrawImage(logoImage, new Rectangle(Point.Round(_positionData.CornerbugPosition), new Size(_positionData.SizeCornerbug, _positionData.SizeCornerbug))); } return(image); }
public void SmoothMouse(Point newPosition, int steps) { System.Threading.Thread.Sleep(200 + Random(0, 100)); newPosition = new Point(newPosition.X + Random(0, 45), newPosition.Y + Random(-25, 0)); Point start = System.Windows.Forms.Cursor.Position; PointF iterPoint = start; PointF slope = new PointF(newPosition.X - start.X, newPosition.Y - start.Y); int closeness = 0; closeness = (start.X + start.Y) - (newPosition.X + newPosition.Y); if (closeness <= 55 && closeness >= -55) { steps -= 108 + Random(-3, 3); } slope.X = slope.X / steps; slope.Y = slope.Y / steps; for (int i = 0; i <= steps - 1; i++) { iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y); System.Windows.Forms.Cursor.Position = (Point.Round(iterPoint)); System.Threading.Thread.Sleep(1 + Random(0, 3)); } System.Windows.Forms.Cursor.Position = newPosition; }
private void picSwitch_Click(object sender, EventArgs e) { _BeginPeriod((uint)_speed); if (switch_flag == 0) { for (int i = 0; i < 90; i++) { picSwitch.Image = display[i]; picSwitch.Location = Point.Round(set[i]); picSwitch.Update(); switchPanel.Invalidate(); Thread.Sleep(_speed); } picSwitch.Location = new Point(0, 0); picSwitch.Image = secondBmp; switch_flag = 1; } else if (switch_flag == 1) { for (int i = 89; i >= 0; i--) { picSwitch.Image = display[i]; picSwitch.Location = Point.Round(set[i]); picSwitch.Update(); switchPanel.Invalidate(); Thread.Sleep(_speed); } picSwitch.Location = new Point(0, 0); picSwitch.Image = firstBmp; switch_flag = 0; } _EndPeriod((uint)_speed); }
void ProcessFrame(object sender, EventArgs e) { Mat frame = _cameraCapture.QueryFrame(); Image <Bgr, Byte> smoothedFrame = new Image <Bgr, byte>(frame.Size); CvInvoke.GaussianBlur(frame, smoothedFrame, new Size(3, 3), 1); //filter out noises //frame._SmoothGaussian(3); #region use the BG/FG detector to find the forground mask _detector.Update(smoothedFrame); Image <Gray, Byte> forgroundMask = _detector.ForegroundMask; #endregion _tracker.Process(smoothedFrame, forgroundMask); foreach (MCvBlob blob in _tracker) { CvInvoke.Rectangle(frame, (Rectangle)blob, new MCvScalar(255.0, 255.0, 255.0), 2); CvInvoke.PutText(frame, blob.ID.ToString(), Point.Round(blob.Center), FontFace.HersheyPlain, 1.0, new MCvScalar(255.0, 255.0, 255.0)); } imageBox1.Image = frame; imageBox2.Image = forgroundMask; }
public static void LinearSmoothMove(Point newPosition, int steps, int sleepTime, MouseButtons mouseButton) { Point start = new Point(Cursor.Position.X, Cursor.Position.Y); PointF iterPoint = start; // Find the slope of the line segment defined by start and newPosition PointF slope = new PointF(newPosition.X - start.X, newPosition.Y - start.Y); // Divide by the number of steps slope.X = slope.X / steps; slope.Y = slope.Y / steps; // Move the mouse to each iterative point. for (int i = 0; i < steps; i++) { iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y); Cursor.Position = Point.Round(iterPoint); Thread.Sleep(sleepTime); } // Move the mouse to the final destination. Cursor.Position = newPosition; ClickCurrentPositionEvent(mouseButton); }
private void DrawPoints(Map map, IEnumerable <DataRow> features, Bitmap dot, Bitmap image) { var size = new Size(dot.Width, dot.Height); foreach (FeatureDataRow row in features) { var heatValue = HeatValueComputer(row); if (heatValue <= 0) { continue; } if (heatValue >= 1f) { heatValue = 1; } var c = row.Geometry.PointOnSurface.Coordinate; if (CoordinateTransformation != null) { #if !DotSpatialProjection c = GeometryTransform.TransformCoordinate(c, CoordinateTransformation.MathTransform); #else c = GeometryTransform.TransformCoordinate(c, CoordinateTransformation.Source, CoordinateTransformation.Target); #endif } var posF = map.WorldToImage(c); var pos = Point.Round(posF); //var pos = Point.Round(PointF.Subtract(posF, halfSize)); using (var tmpDot = ApplyHeatValueToImage(dot, heatValue)) { ImageBlender.BlendImages(image, pos.X, pos.Y, size.Width, size.Height, tmpDot, 0, 0, BlendOperation.BlendMultiply); } } }
public void runLinearSim(Graphics g, PointF[] points) { PointF currDrawPoint = points[0]; PointF destination = points[1]; Brush pointBrush = new SolidBrush(Color.Red); Brush brush = new SolidBrush(Color.White); while ((int)Math.Round(currDrawPoint.X) != destination.X || (int)Math.Round(currDrawPoint.Y) != destination.Y) { Vector3 p1 = new Vector3(); p1.X = currDrawPoint.X; p1.Y = currDrawPoint.Y; Vector3 p2 = new Vector3(); p2.X = destination.X; p2.Y = destination.Y; if (curvebut.Checked) { Vector3 Delta = p2 - p1; Delta += new Vector3(Delta.Y / 50, Delta.X / 50, Delta.Z); destination.X = currDrawPoint.X + Delta.X; destination.Y = currDrawPoint.Y + Delta.Y; } Vector3 smoothedVector = Smooth(p1, p2, smoothbar.Value); PointF newDrawPoint = new PointF(smoothedVector.X, smoothedVector.Y); g.DrawLine(new Pen(brush, 1), currDrawPoint, newDrawPoint); currDrawPoint = newDrawPoint; Thread.Sleep(15); } g.FillRectangle(pointBrush, new Rectangle(Point.Round(points[0]), new Size(2, 2))); g.FillRectangle(pointBrush, new Rectangle(Point.Round(points[1]), new Size(2, 2))); }
public void PointToScreenShouldWorkOnSecondaryScreen() { bool wasClicked = false; Form childForm = null; try { ManualForm("The Form with the button should be above the text box exactly.\nClick the button to pass the test, close the window to fail.", form => { var screens = Screen.Screens.ToArray(); Assert.GreaterOrEqual(screens.Length, 2, "You must have a secondary monitor for this test"); form.Location = Point.Round(screens[1].Bounds.Location) + new Size(50, 50); form.ClientSize = new Size(200, 200); var textBox = new TextBox { Text = "You shouldn't see this" }; form.Shown += (sender, e) => { childForm = new Form { WindowStyle = WindowStyle.None, ShowInTaskbar = false, Maximizable = false, Resizable = false, BackgroundColor = Colors.Red, Topmost = true, Location = Point.Round(textBox.PointToScreen(PointF.Empty)), Size = textBox.Size }; var b = new Button { Text = "Click Me!" }; b.Click += (sender2, e2) => { wasClicked = true; childForm.Close(); childForm = null; form.Close(); }; childForm.Content = new TableLayout { Rows = { b } }; childForm.Show(); }; var layout = new DynamicLayout(); layout.AddCentered(textBox); return(layout); }, allowPass: false, allowFail: false); } finally { if (childForm != null) { Application.Instance.Invoke(() => childForm.Close()); } } Assert.IsTrue(wasClicked, "The test completed without clicking the button"); }
public void Recognize(Mat m) { int[] dim = new int[] { 1, m.Height, m.Width, 3 }; if (_imageTensor == null) { _imageTensor = new Tensor(Emgu.TF.DataType.Uint8, dim); } else { if (!(_imageTensor.Type == Emgu.TF.DataType.Uint8 && Enumerable.SequenceEqual(dim, _imageTensor.Dim))) { _imageTensor.Dispose(); _imageTensor = new Tensor(Emgu.TF.DataType.Uint8, dim); } } Emgu.TF.TensorConvert.ReadTensorFromMatBgr(m, _imageTensor); MaskRcnnInceptionV2Coco.RecognitionResult[] results; if (_coldSession) { //First run of the recognition graph, here we will compile the graph and initialize the session //This is expected to take much longer time than consecutive runs. results = _inceptionGraph.Recognize(_imageTensor)[0]; _coldSession = false; } //Here we are trying to time the execution of the graph after it is loaded Stopwatch sw = Stopwatch.StartNew(); results = _inceptionGraph.Recognize(_imageTensor)[0]; sw.Stop(); int goodResultCount = 0; foreach (var r in results) { if (r.Probability > 0.5) { float x1 = r.Region[0] * m.Height; float y1 = r.Region[1] * m.Width; float x2 = r.Region[2] * m.Height; float y2 = r.Region[3] * m.Width; RectangleF rectf = new RectangleF(y1, x1, y2 - y1, x2 - x1); Rectangle rect = Rectangle.Round(rectf); rect.Intersect(new Rectangle(Point.Empty, m.Size)); //only keep the region that is inside the image if (rect.IsEmpty) { continue; } //draw the rectangle around the region CvInvoke.Rectangle(m, rect, new Emgu.CV.Structure.MCvScalar(0, 0, 255), 2); #region draw the mask float[,] mask = r.Mask; GCHandle handle = GCHandle.Alloc(mask, GCHandleType.Pinned); using (Mat mk = new Mat(new Size(mask.GetLength(1), mask.GetLength(0)), Emgu.CV.CvEnum.DepthType.Cv32F, 1, handle.AddrOfPinnedObject(), mask.GetLength(1) * sizeof(float))) using (Mat subRegion = new Mat(m, rect)) using (Mat maskLarge = new Mat()) using (Mat maskLargeInv = new Mat()) using (Mat largeColor = new Mat(subRegion.Size, Emgu.CV.CvEnum.DepthType.Cv8U, 3)) { CvInvoke.Resize(mk, maskLarge, subRegion.Size); //give the mask at least 30% transparency using (ScalarArray sa = new ScalarArray(0.7)) CvInvoke.Min(sa, maskLarge, maskLarge); //Create the inverse mask for the original image using (ScalarArray sa = new ScalarArray(1.0)) CvInvoke.Subtract(sa, maskLarge, maskLargeInv); //The mask color largeColor.SetTo(new Emgu.CV.Structure.MCvScalar(255, 0, 0)); CvInvoke.BlendLinear(largeColor, subRegion, maskLarge, maskLargeInv, subRegion); } handle.Free(); #endregion //draw the label CvInvoke.PutText(m, r.Label, Point.Round(rect.Location), Emgu.CV.CvEnum.FontFace.HersheyComplex, 1.0, new Emgu.CV.Structure.MCvScalar(0, 255, 0), 1); goodResultCount++; } } String resStr = String.Format("{0} objects detected in {1} milliseconds.", goodResultCount, sw.ElapsedMilliseconds); if (_renderMat == null) { _renderMat = new Mat(); } m.CopyTo(_renderMat); //Bitmap bmp = _renderMat.ToBitmap(); if (InvokeRequired) { this.Invoke((MethodInvoker)(() => { messageLabel.Text = resStr; pictureBox.Image = _renderMat; })); } else { messageLabel.Text = resStr; pictureBox.Image = _renderMat; } }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); UpdateTabLocations(); Brush selBrush = new SolidBrush(owner.Navigator.PageBackColor); Pen pathPen = SystemPens.ControlDark; Rectangle pageExtendRect = new Rectangle(); switch (owner.Navigator.Location) { case NavigatorLocation.Bottom: pageExtendRect = new Rectangle(0, 0, ClientSize.Width, pageHeight); break; case NavigatorLocation.Top: pageExtendRect = new Rectangle(0, NavMinSize.Height - pageHeight, ClientSize.Width, pageHeight); break; } e.Graphics.FillRectangle(selBrush, pageExtendRect); // draw the tab outline GraphicsPath path = new GraphicsPath(); Point drawPoint = new Point(0, pageHeight); for (int i = 0; i < visiblePages.Count; i++) { TabRenderInfo info = tabs[i]; Rectangle rect = tabs[i].Bounds; NotebookPage page = visiblePages[i]; Font thisFont = this.Font; drawPoint = rect.Location; switch (owner.Navigator.Location) { case NavigatorLocation.Top: drawPoint.Y += tabMargin; break; } // fill background of the selected page if (owner.SelectedPage == page) { Rectangle fillRect = new Rectangle(); thisFont = mBoldFont; // add the right lines to the path to go around the tab switch (owner.Navigator.Location) { case NavigatorLocation.Top: path.AddLines(new Point[] { new Point(rect.Left, rect.Bottom), new Point(rect.Left, rect.Top + 2), new Point(rect.Left + 2, rect.Top), new Point(rect.Right - 2, rect.Top), new Point(rect.Right, rect.Top + 2), new Point(rect.Right, rect.Bottom) }); fillRect = new Rectangle( rect.Left + 1, rect.Top + 1, rect.Width - 1, rect.Height); break; case NavigatorLocation.Bottom: path.AddLines(new Point[] { rect.Location, new Point(rect.Left, rect.Bottom - 2), new Point(rect.Left + 2, rect.Bottom), new Point(rect.Right - 2, rect.Bottom), new Point(rect.Right, rect.Bottom - 2), new Point(rect.Right, rect.Top) }); fillRect = new Rectangle( rect.Left + 1, rect.Top, rect.Width - 1, rect.Height - 1); break; } e.Graphics.FillRectangle(selBrush, fillRect); } else { switch (owner.Navigator.Location) { case NavigatorLocation.Bottom: path.AddLine(rect.Location, new Point(rect.Right, rect.Top)); break; case NavigatorLocation.Top: path.AddLine(new Point(rect.X, rect.Bottom), new Point(rect.Right, rect.Bottom)); break; } if (i > 0) { e.Graphics.DrawLine(pathPen, new Point(rect.Left, rect.Top + 4), new Point(rect.Left, rect.Bottom - 4)); } } drawPoint.X += tabMargin; // draw page image if (page.Image != null) { drawPoint.X += imageMargin; Rectangle imageRect = new Rectangle(drawPoint, info.imageSize); imageRect.Y += (rect.Height - imageRect.Height) / 2; e.Graphics.DrawImage(page.Image, imageRect); drawPoint.X += info.imageSize.Width + imageMargin; } if (navProperties.AllowClose && info.ShowCloseBox) { Image image = Properties.Resources.Close; if (mOverCloseBox == i) { image = Properties.Resources.CloseMouseOver; } e.Graphics.DrawImage(image, info.CloseBox); } Rectangle textRect = Rectangle.FromLTRB( drawPoint.X, drawPoint.Y, rect.Right - tabMargin, rect.Bottom - tabMargin - 1); TextRenderer.DrawText(e.Graphics, page.Text, thisFont, textRect, ForeColor, TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix); } if (path.PointCount > 0) { switch (owner.Navigator.Location) { case NavigatorLocation.Bottom: path.AddLine(Point.Round(path.GetLastPoint()), new Point(ClientRectangle.Right, drawPoint.Y)); break; case NavigatorLocation.Top: path.AddLine(Point.Round(path.GetLastPoint()), new Point(ClientRectangle.Right, TabHeight)); break; } e.Graphics.DrawPath(pathPen, path); } }
public TabelaElemenataForm(TabelaElemenataFormRezimRada rezimRada, Sprava sprava) { InitializeComponent(); MinimumSize = SystemInformation.MinimizedWindowSize + new Size(0, panel1.Height + panelHeader.Height + 100); try { using (ISession session = NHibernateHelper.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); List <Element> sviElementi = new List <Element>(DAOFactoryFactory.DAOFactory.GetElementDAO().FindAll()); grupe = DAOFactoryFactory.DAOFactory.GetGrupaDAO().FindAll(); Graphics g = CreateGraphics(); float elementSizeMM = Math.Min(210 / 4, 297 / 6); SizeF elementSizePxl = (Size)Point.Round( Utils.mmToPixel(g, new PointF(elementSizeMM, elementSizeMM))); tabela = new TabelaElemenata(sviElementi, elementSizePxl); initUI(); float tezineHeaderHeightMM = 7; float grupaHeaderHeightMM = 5; tezineHeaderHeightPxl = Point.Round( Utils.mmToPixel(g, new PointF(0, tezineHeaderHeightMM))).Y; grupaHeaderHeightPxl = Point.Round( Utils.mmToPixel(g, new PointF(0, grupaHeaderHeightMM))).Y; g.Dispose(); panelHeader.Height = tezineHeaderHeightPxl + grupaHeaderHeightPxl + 1; this.rezimRada = rezimRada; if (rezimRada == TabelaElemenataFormRezimRada.Select) { setSpravaCombo(sprava); cmbSprava.Enabled = false; btnPrint.Enabled = false; btnPrint.Visible = false; btnClose.Enabled = false; btnClose.Visible = false; } else { btnOK.Enabled = false; btnOK.Visible = false; } cmbSprava.SelectedIndexChanged += cmbSprava_SelectedIndexChanged; cmbGrupa.SelectedIndexChanged += cmbGrupa_SelectedIndexChanged; disableTrackBar(); promeniGrupu(); zumiraj(120); panelTabela.MouseWheel += new MouseEventHandler(panelTabela_MouseWheel); } } finally { CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory); } }
public string ProcessAndRender(IInputArray imageIn, IInputOutputArray imageOut) { Stopwatch watch = Stopwatch.StartNew(); #region Pre-processing //Convert the image to grayscale and filter out the noise CvInvoke.CvtColor(imageIn, _gray, ColorConversion.Bgr2Gray); //Remove noise CvInvoke.GaussianBlur(_gray, _gray, new Size(3, 3), 1); double cannyThreshold = 180.0; double cannyThresholdLinking = 120.0; CvInvoke.Canny(_gray, _cannyEdges, cannyThreshold, cannyThresholdLinking); #endregion #region circle detection double circleAccumulatorThreshold = 120; CircleF[] circles = CvInvoke.HoughCircles(_gray, HoughModes.Gradient, 2.0, 20.0, cannyThreshold, circleAccumulatorThreshold, 5); #endregion #region Edge detection LineSegment2D[] lines = CvInvoke.HoughLinesP( _cannyEdges, 1, //Distance resolution in pixel-related units Math.PI / 45.0, //Angle resolution measured in radians. 20, //threshold 30, //min Line width 10); //gap between lines #endregion #region Find triangles and rectangles List <Triangle2DF> triangleList = new List <Triangle2DF>(); List <RotatedRect> boxList = new List <RotatedRect>(); //a box is a rotated rectangle using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint()) { CvInvoke.FindContours(_cannyEdges, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple); int count = contours.Size; for (int i = 0; i < count; i++) { using (VectorOfPoint contour = contours[i]) using (VectorOfPoint approxContour = new VectorOfPoint()) { CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true); if (CvInvoke.ContourArea(approxContour, false) > 250 ) //only consider contours with area greater than 250 { if (approxContour.Size == 3) //The contour has 3 vertices, it is a triangle { Point[] pts = approxContour.ToArray(); triangleList.Add(new Triangle2DF( pts[0], pts[1], pts[2] )); } else if (approxContour.Size == 4) //The contour has 4 vertices. { #region determine if all the angles in the contour are within [80, 100] degree bool isRectangle = true; Point[] pts = approxContour.ToArray(); LineSegment2D[] edges = PointCollection.PolyLine(pts, true); for (int j = 0; j < edges.Length; j++) { double angle = Math.Abs( edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j])); if (angle < 80 || angle > 100) { isRectangle = false; break; } } #endregion if (isRectangle) { boxList.Add(CvInvoke.MinAreaRect(approxContour)); } } } } } } #endregion watch.Stop(); using (Mat triangleRectangleImage = new Mat(_gray.Size, DepthType.Cv8U, 3)) //image to draw triangles and rectangles on using (Mat circleImage = new Mat(_gray.Size, DepthType.Cv8U, 3)) //image to draw circles on using (Mat lineImage = new Mat(_gray.Size, DepthType.Cv8U, 3)) //image to draw lines on { #region draw triangles and rectangles triangleRectangleImage.SetTo(new MCvScalar(0)); foreach (Triangle2DF triangle in triangleList) { CvInvoke.Polylines(triangleRectangleImage, Array.ConvertAll(triangle.GetVertices(), Point.Round), true, new Bgr(Color.DarkBlue).MCvScalar, 2); } foreach (RotatedRect box in boxList) { CvInvoke.Polylines(triangleRectangleImage, Array.ConvertAll(box.GetVertices(), Point.Round), true, new Bgr(Color.DarkOrange).MCvScalar, 2); } //Drawing a light gray frame around the image CvInvoke.Rectangle(triangleRectangleImage, new Rectangle(Point.Empty, new Size(triangleRectangleImage.Width - 1, triangleRectangleImage.Height - 1)), new MCvScalar(120, 120, 120)); //Draw the labels CvInvoke.PutText(triangleRectangleImage, "Triangles and Rectangles", new Point(20, 20), FontFace.HersheyDuplex, 0.5, new MCvScalar(120, 120, 120)); #endregion #region draw circles circleImage.SetTo(new MCvScalar(0)); foreach (CircleF circle in circles) { CvInvoke.Circle(circleImage, Point.Round(circle.Center), (int)circle.Radius, new Bgr(Color.Brown).MCvScalar, 2); } //Drawing a light gray frame around the image CvInvoke.Rectangle(circleImage, new Rectangle(Point.Empty, new Size(circleImage.Width - 1, circleImage.Height - 1)), new MCvScalar(120, 120, 120)); //Draw the labels CvInvoke.PutText(circleImage, "Circles", new Point(20, 20), FontFace.HersheyDuplex, 0.5, new MCvScalar(120, 120, 120)); #endregion #region draw lines lineImage.SetTo(new MCvScalar(0)); foreach (LineSegment2D line in lines) { CvInvoke.Line(lineImage, line.P1, line.P2, new Bgr(Color.Green).MCvScalar, 2); } //Drawing a light gray frame around the image CvInvoke.Rectangle(lineImage, new Rectangle(Point.Empty, new Size(lineImage.Width - 1, lineImage.Height - 1)), new MCvScalar(120, 120, 120)); //Draw the labels CvInvoke.PutText(lineImage, "Lines", new Point(20, 20), FontFace.HersheyDuplex, 0.5, new MCvScalar(120, 120, 120)); #endregion using (InputArray iaImageIn = imageIn.GetInputArray()) using (Mat imageInMat = iaImageIn.GetMat()) CvInvoke.VConcat(new Mat[] { imageInMat, triangleRectangleImage, circleImage, lineImage }, imageOut); } return(String.Format("Detected in {0} milliseconds.", watch.ElapsedMilliseconds)); }
private void DrawToGraphics(Graphics g) { ColorBgra colorSolid = ColorBgra.FromColor(this.ForeColor); ColorBgra colorGuide = ColorBgra.FromColor(this.ForeColor); ColorBgra colorGrid = ColorBgra.FromColor(this.ForeColor); colorGrid.A = 128; colorGuide.A = 96; Pen penSolid = new Pen(colorSolid.ToColor(), 1); Pen penGrid = new Pen(colorGrid.ToColor(), 1); Pen penGuide = new Pen(colorGuide.ToColor(), 1); penGrid.DashStyle = DashStyle.Dash; g.Clear(this.BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; ////绘制底图 //GrawActiveDrawing(g); Rectangle ourRect = ClientRectangle; ourRect.Inflate(-1, -1); //辅助线_格网线 for (float f = 0.25f; f <= 0.75f; f += 0.25f) { float x = Utility.Lerp(ourRect.Left, ourRect.Right, f); float y = Utility.Lerp(ourRect.Top, ourRect.Bottom, f); g.DrawLine(penGrid, Point.Round(new PointF(x, ourRect.Top)), Point.Round(new PointF(x, ourRect.Bottom))); g.DrawLine(penGrid, Point.Round(new PointF(ourRect.Left, y)), Point.Round(new PointF(ourRect.Right, y))); } //辅助线_对角线 g.DrawLine(penGrid, ourRect.Left, ourRect.Bottom, ourRect.Right, ourRect.Top); float width = this.ClientRectangle.Width; float height = this.ClientRectangle.Height; //绘制控制点 for (int c = 0; c < channels; ++c) { Point pt = _controlPoints[c]; Color color = GetVisualColor(c); //Color colorSelected = ColorBgra.Blend(ColorBgra.FromColor(color), ColorBgra.White, 128).ToColor(); const float penWidthNonSelected = 1; const float penWidthSelected = 2; float penWidth = mask[c] ? penWidthSelected : penWidthNonSelected; Pen penSelected = new Pen(color, penWidth); //color.A = 128; Pen pen = new Pen(color, penWidth); Brush brush = new SolidBrush(color); SolidBrush brushSelected = new SolidBrush(Color.White); int k = pt.X; float x = k * (width - 1) / (entries - 1); float y = (entries - 1 - pt.Y) * (height - 1) / (entries - 1); const float radiusSelected = 4; const float radiusNotSelected = 3; const float radiusUnMasked = 2; bool selected = mask[c];//当前控制点 float size = selected ? radiusSelected : (mask[c] ? radiusNotSelected : radiusUnMasked); RectangleF rect = Utility.RectangleFromCenter(new PointF(x, y), size); g.FillEllipse(selected ? brushSelected : brush, rect.X, rect.Y, rect.Width, rect.Height); g.DrawEllipse(selected ? penSelected : pen, rect.X, rect.Y, rect.Width, rect.Height); pen.Dispose(); } penSolid.Dispose(); penGrid.Dispose(); penGuide.Dispose(); }
private CircleImage FindRegularCircle(string path, Parameters param = null) { _log.Debug(param.ToString()); bool saveFile = param.SaveFile; bool useCanny = param.UseCanny; Path = path; RawImg = EmguIntfs.Load(path); Image <Gray, Byte> _grayedUmat = EmguIntfs.ToImage(EmguIntfs.Grayed(RawImg)); Image <Gray, Byte> _bin = EmguIntfs.Binarize(param.BinThreshold, _grayedUmat); _bin.Save(Utils.String.FilePostfix(Path, "-0-bin")); Image <Gray, byte> _edged = EmguIntfs.Canny(_bin, param.Canny1Threshold1, param.Canny1Threshold2, param.Canny1ApertureSize, param.Canny1I2Gradient); _edged.Save(Utils.String.FilePostfix(Path, "-1-edge")); Image <Gray, byte> tempc = new Image <Gray, byte>(_bin.Width, _bin.Height); Image <Gray, byte> d = new Image <Gray, byte>(_bin.Width, _bin.Height); VectorOfVectorOfPoint con = new VectorOfVectorOfPoint(); CvInvoke.FindContours(_edged, con, tempc, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple); for (int conId = 0; conId < con.Size; conId++) { CvInvoke.DrawContours(d, con, conId, new MCvScalar(255, 0, 255, 255), 2); } d.Save(Utils.String.FilePostfix(Path, "-1-contour")); List <RotatedRect> rects = new List <RotatedRect>(); for (int conId = 0; conId < con.Size; conId++) { if (con[conId].Size > 5) { rects.Add(CvInvoke.FitEllipse(con[conId])); } } foreach (var rect in rects) { CvInvoke.Ellipse(d, rect, new Bgr(Color.White).MCvScalar, 2); } d.Save(Utils.String.FilePostfix(Path, "-1-rects")); Circles = CvInvoke.HoughCircles(_edged, HoughType.Gradient, param.Hough1Dp, param.Hough1MinDist, param.Hough1Param1, param.Hough1Param2, param.Hough1MinRadius, param.Hough1MaxRadius); Circles = Calc.Sort(Circles); #region filter 86.3% FilteredCircles = new List <CircleF>(); FilteredLights = new List <int>(); FilteredCircles2nd = new List <CircleF>(); var raw = _grayedUmat; foreach (var circle in Circles) { int extra = param.FilterSquareExtra; int startX = (int)System.Math.Floor(circle.Center.X - circle.Radius - extra); int startY = (int)System.Math.Floor(circle.Center.Y - circle.Radius - extra); int len = (int)System.Math.Ceiling((double)circle.Radius * 2.0) + 2 * extra; if (startX < 0 || startY < 0) { _log.Warn("FilterSizeExtra may be too big, filter abandoned"); continue; } int strength = raw.Data[(int)circle.Center.Y, (int)circle.Center.X, 0]; if (strength >= 30)/* filter fake circles */ { FilteredCircles.Add(circle); FilteredCircles2nd.Add(circle); int threshold = (int)((double)strength * 0.863); raw.ROI = new Rectangle(startX, startY, len, len); Image <Gray, Byte> oneCircle = EmguIntfs.Binarize(threshold, raw); raw.ROI = Rectangle.Empty; for (int x = 0; x < len; x++) { for (int y = 0; y < len; y++) { raw.Data[startY + y, startX + x, 0] = oneCircle.Data[y, x, 0]; } } } } if (saveFile) { raw.Save(Utils.String.FilePostfix(Path, "-2-filter")); } #endregion if (useCanny) { _edged = EmguIntfs.Canny(raw, param.Canny2Threshold1, param.Canny2Threshold2, param.Canny2ApertureSize, param.Canny2I2Gradient); if (saveFile) { _edged.Save(Utils.String.FilePostfix(Path, "-3-edge")); } } else { _edged = raw; } Circles2nd = CvInvoke.HoughCircles(_edged, HoughType.Gradient, param.Hough2Dp, param.Hough2MinDist, param.Hough2Param1, param.Hough2Param2, param.Hough2MinRadius, param.Hough2MaxRadius); Circles2nd = Calc.Sort(Circles2nd); FilteredCircles2nd = new List <CircleF>(); List <int> brightness = new List <int>(); _log.Info($"Circles Information"); for (int i = 0; i < Circles2nd.Length; i++) { CircleF circle = Circles2nd[i]; int strength = raw.Data[(int)circle.Center.Y, (int)circle.Center.X, 0]; if (strength > 30) { int b = CountPixels(_grayedUmat, ref circle, ValidRatio); brightness.Add(b); _log.Info($"Circle{i:D3}: ({circle.Center.X},{circle.Center.Y}) {circle.Radius} {b}"); FilteredCircles2nd.Add(circle); } } #region draw Mat _result = RawImg.Mat; for (int c = 0; c < FilteredCircles2nd.Count; c++) { Point center = Point.Round(FilteredCircles2nd[c].Center); center.X *= 1; center.Y *= 1; int radius = (int)FilteredCircles2nd[c].Radius * 1; //if (2 * radius < _result.Size.Height && 2 * radius < _result.Size.Width) { CvInvoke.Circle(_result, center, radius, new Bgr(Color.Red).MCvScalar, 1); CvInvoke.PutText(_result, c.ToString("D3"), new Point((int)FilteredCircles2nd[c].Center.X, (int)FilteredCircles2nd[c].Center.Y), Emgu.CV.CvEnum.FontFace.HersheyScriptComplex, 1, new MCvScalar(255, 255, 0), 1); } } _result.Save(Utils.String.FilePostfix(Path, "-result")); #endregion CircleImage ret = new CircleImage(); ret.Circles = FilteredCircles2nd; ret.Brightness = brightness; ret.RetImg = _result.Bitmap; return(ret); }
/// <summary> /// this function perform "Tracking step" in Hand Tracking Algorithm /// </summary> /// <param name="elapsed_time">the interval time between frame i and frame i+1 used to calculate the feature speed</param> internal void StartTracking(double elapsed_time) { global_time += elapsed_time; GetImages(); OpticalFlow.PyrLK(previous_image, current_image, previous_features, window_size, levels, criteria, out current_features, out status, out point_error); previous_image = current_image; CalculateFeatureVelocity(current_features); old_cursor_location_pt = new_cursor_location_pt; new_center_pt = GetCentroid(good_features.ToArray()); ExtractHandRegion(new_center_pt); new_cursor_location_pt = contour_rect.Location; double movement_sensitivity = FindDistance(new_cursor_location_pt, old_cursor_location_pt); if (movement_sensitivity > 10)// to control the small movement of hand { LinearSmoothMove(Point.Round(new_center_pt), Convert.ToInt32(movement_sensitivity)); } best_tracked_feature_Array = FindSkinColoredFeatures(good_features.ToArray()); if (best_tracked_feature_Array.Length == 0) { Console.WriteLine("exception inside number of good_features {0} ", good_features.Count); Console.WriteLine("exception inside best_tracked_feature_Array.Length == 0 "); } AddNewFeatures(number_of_bad_features, best_tracked_feature_Array);// u can move these line above the //old_cursor_location_pt = new_cursor_location_pt; // and use good_features instead of best_tracked_feature_Array int diff = 30 - good_features.Count; if (diff > 0) { AddNewFeatures(diff, good_features.ToArray()); } foreach (PointF p in good_features) { colored_temp_image.Draw(new CircleF(p, 3f), new Bgr(Color.Cyan), -1); } colored_temp_image.Draw(new CircleF(new_center_pt, 10f), new Bgr(Color.Blue), -1); previous_features = good_features.ToArray(); current_features = null; status = null; good_features.Clear(); bad_features.Clear(); number_of_bad_features = 0; //colored_temp_image.Save("H:\\debug\\test" + Convert.ToInt32(global_time) + ".jpg"); Form1.NewImage = colored_temp_image; }
public Line(Point startPoint, Point endPoint, int decimals = 0) : this() { this.StartPoint = startPoint.Round(decimals); this.EndPoint = endPoint.Round(decimals); }
static Tuple <Rectangle, bool, string>[] retrieve_area_by_filename(string filename) { List <Tuple <Rectangle, bool, string> > area = new List <Tuple <Rectangle, bool, string> >(); try { XmlDocument doc = new XmlDocument(); doc.Load(filename); XmlNodeList reg_list = doc.DocumentElement.SelectNodes("//region"); foreach (XmlNode n in reg_list) { Rectangle r = Rectangle.Empty; Point p = Point.Empty; bool is_mask = true; string path = get_path_by_node(n); if (n["is_mask"] != null) { if (Int32.Parse(n["is_mask"].InnerText) == 0) { is_mask = false; } } //if (is_mask == 1) { if (n["center"] != null) { string s = n["center"].InnerText; string[] ss = s.Split(','); float x = float.Parse(ss[0]); float y = float.Parse(ss[1]); PointF pf = new PointF(x, y); p = Point.Round(pf); } if (n["radius"] != null) { float f = float.Parse(n["radius"].InnerText); int x = p.X - (int)f; int y = p.Y - (int)f; int w = (int)(2 * f); int h = (int)(2 * f); r = new Rectangle(x, y, w, h); } if (n["width"] != null && n["height"] != null) { int w = int.Parse(n["width"].InnerText); int h = int.Parse(n["height"].InnerText); int x = p.X - w / 2; int y = p.Y - h / 2; r = new Rectangle(x, y, w, h); } if (!r.IsEmpty) { //Program.logIt($"center={p}, rect={r}"); Tuple <Rectangle, bool, string> i = new Tuple <Rectangle, bool, string>(r, is_mask, path); area.Add(i); } } } } catch (Exception) { } return(area.ToArray()); }
/// <summary> /// Gets current window position taking into account animation effects. /// </summary> /// <returns>Current window position.</returns> private Point GetCurrentWindowPosition() { var transformGroup = contentRoot.RenderTransform as TransformGroup; var translateTransform = transformGroup.Children.OfType<TranslateTransform>().FirstOrDefault(); var position = new Point(translateTransform.X, translateTransform.Y); // Round coordinates to avoid blured window return position.Round(); }
public bool IsEqual(Point p, int round) { if (round >= 0) { Point p1 = this.Round(round); Point p2 = p.Round(round); return p1.X == p2.X && p1.Y == p2.Y; } return this.X == p.X && this.Y == p.Y; }