예제 #1
0
        public void Run()
        {
            var gray = new Mat(FilePath.Image.Lenna, ImreadModes.GrayScale);
            var dst = new Mat(FilePath.Image.Lenna, ImreadModes.Color);

            BRISK brisk = BRISK.Create();
            KeyPoint[] keypoints = brisk.Detect(gray);

            if (keypoints != null)
            {
                var color = new Scalar(0, 255, 0);
                foreach (KeyPoint kpt in keypoints)
                {
                    float r = kpt.Size / 2;
                    Cv2.Circle(dst, kpt.Pt, (int)r, color);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y - r), 
                        color);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y - r), 
                        color);
                }
            }

            using (new Window("BRISK features", dst))
            {
                Cv2.WaitKey();
            }
        }
        public override ScalarValue GetValueToEncode(ScalarValue value, ScalarValue priorValue, Scalar field)
        {
            if (value == null)
                return ScalarValue.Null;

            return value;
        }
예제 #3
0
		public void setHsvColor (Scalar hsvColor)
		{
				double minH = (hsvColor.val [0] >= mColorRadius.val [0]) ? hsvColor.val [0] - mColorRadius.val [0] : 0;
				double maxH = (hsvColor.val [0] + mColorRadius.val [0] <= 255) ? hsvColor.val [0] + mColorRadius.val [0] : 255;
		
				mLowerBound.val [0] = minH;
				mUpperBound.val [0] = maxH;
		
				mLowerBound.val [1] = hsvColor.val [1] - mColorRadius.val [1];
				mUpperBound.val [1] = hsvColor.val [1] + mColorRadius.val [1];
		
				mLowerBound.val [2] = hsvColor.val [2] - mColorRadius.val [2];
				mUpperBound.val [2] = hsvColor.val [2] + mColorRadius.val [2];
		
				mLowerBound.val [3] = 0;
				mUpperBound.val [3] = 255;
		
				Mat spectrumHsv = new Mat (1, (int)(maxH - minH), CvType.CV_8UC3);
		
				for (int j = 0; j < maxH-minH; j++) {
						byte[] tmp = {(byte)(minH + j), (byte)255, (byte)255};
						spectrumHsv.put (0, j, tmp);
				}
		
				Imgproc.cvtColor (spectrumHsv, mSpectrum, Imgproc.COLOR_HSV2RGB_FULL, 4);
		}
예제 #4
0
 public override Field Parse(System.Xml.XmlElement fieldNode, bool optional, ParsingContext context)
 {
     Operator.Operator operator_Renamed = Operator.Operator.NONE;
     string defaultValue = null;
     string key = null;
     string ns = "";
     System.Xml.XmlElement operatorElement = GetOperatorElement(fieldNode);
     if (operatorElement != null)
     {
         if (operatorElement.HasAttribute("value"))
             defaultValue = operatorElement.GetAttribute("value");
         operator_Renamed = Operator.Operator.GetOperator(operatorElement.Name);
         if (operatorElement.HasAttribute("key"))
             key = operatorElement.GetAttribute("key");
         if (operatorElement.HasAttribute("ns"))
             ns = operatorElement.GetAttribute("ns");
         if (operatorElement.HasAttribute("dictionary"))
             context.Dictionary = operatorElement.GetAttribute("dictionary");
     }
     FASTType type = GetType(fieldNode, context);
     var scalar = new Scalar(GetName(fieldNode, context), type, operator_Renamed, type.GetValue(defaultValue), optional);
     if (fieldNode.HasAttribute("id"))
         scalar.Id = fieldNode.GetAttribute("id");
     if (key != null)
         scalar.Key = new QName(key, ns);
     scalar.Dictionary = context.Dictionary;
     ParseExternalAttributes(fieldNode, scalar);
     return scalar;
 }
        public override ScalarValue DecodeEmptyValue(ScalarValue priorValue, Scalar field)
        {
            if (!field.IsOptional)
                return field.DefaultValue;

            return null;
        }
        public override ScalarValue DecodeValue(ScalarValue newValue, ScalarValue priorValue, Scalar field)
        {
            if (priorValue == null && !field.IsOptional)
            {
                Global.ErrorHandler.OnError(null, DynError.MandatoryFieldNotPresent, "");
                return null;
            }

            var baseValue = (StringValue) (priorValue == null || priorValue.IsUndefined
                                               ? field.BaseValue
                                               : priorValue);

            if (newValue == null || newValue.IsNull)
            {
                if (!field.IsOptional)
                    throw new ArgumentException("");

                return null;
            }

            string delta = ((StringValue) newValue).Value;
            int length = Math.Max(baseValue.Value.Length - delta.Length, 0);
            string root = baseValue.Value.Substring(0, (length) - (0));

            return new StringValue(root + delta);
        }
 public override ScalarValue GetValueToEncode(ScalarValue value_Renamed, ScalarValue priorValue, Scalar field)
 {
     if (priorValue == null)
     {
         return value_Renamed;
     }
     if (value_Renamed == null)
     {
         if (field.Optional)
         {
             if (priorValue == ScalarValue.UNDEFINED && field.DefaultValue.Undefined)
             {
                 return null;
             }
             return ScalarValue.NULL;
         }
         throw new ArgumentException();
     }
     if (priorValue.Undefined)
     {
         if (value_Renamed.Equals(field.DefaultValue))
         {
             return null;
         }
         return value_Renamed;
     }
     if (!value_Renamed.Equals(((NumericValue) priorValue).Increment()))
     {
         return value_Renamed;
     }
     return null;
 }
예제 #8
0
	// Update is called once per frame
	void Update () {
		
		cap.Read (frame);


		if (!frame.Empty()){

			//assume this part of the frame contains only background
			smoothed_img = frame.Blur(new Size(5,5));

			frame_hsv = frame.CvtColor (ColorConversionCodes.BGR2HSV);
			Scalar lb = new Scalar (0, 0, 50);
			Scalar ub = new Scalar (180, 70, 180);

			Mat disc = Cv2.GetStructuringElement (MorphShapes.Ellipse, new Size (7, 7));

			Cv2.MorphologyEx (thresh, thresh, MorphTypes.Close, disc,null,3);


			contours = Cv2.FindContoursAsMat (thresh , RetrievalModes.List, ContourApproximationModes.ApproxSimple);


			mask = new Mat (thresh.Size (), thresh.Type (), Scalar.All (0));


			Cv2.Merge(new Mat[]{mask,mask,mask},mask);
			Cv2.BitwiseAnd (mask, frame, mask);

			//Cv2.Merge(new Mat[]{frame_backproj,frame_backproj,frame_backproj},frame_backproj);

			tex.LoadImage (smoothed_img.ToBytes (".png", new int[]{ 0 }));

		}

	}
예제 #9
0
        public RaiseArmTrigger(XmlNode node)
        {
            mHeightThreshold = Nui.magnitude(Nui.joint(Nui.Shoulder_Centre) - Nui.joint(Nui.Hip_Centre));
            mAngleThreshold = Scalar.Create(.48f);
            mDepthThreshold = Scalar.Create(GetFloat(node, 3.6f, "DepthThreshold"));
            mWidthThreshold = Scalar.Create(GetFloat(node, 1f, "WidthThreshold"));

            mBody = Nui.joint(Nui.Hip_Centre);

            Condition inWidth = Nui.abs(Nui.x(Nui.joint(Nui.Hip_Centre))) < mWidthThreshold;
            Condition inDepth = Nui.z(Nui.joint(Nui.Hip_Centre)) < mDepthThreshold;
            Condition inRange = C.And(inWidth, inDepth);

            Vector up = Vector.Create(0f, 1f, 0f);
            mArmR = Nui.joint(Nui.Hand_Right) - Nui.joint(Nui.Shoulder_Right);
            mArmL = Nui.joint(Nui.Hand_Left) - Nui.joint(Nui.Shoulder_Left);
            mAngleR = Nui.dot(up, mArmR);
            mAngleL = Nui.dot(up, mArmL);

            mTriggerR = C.And(Nui.y(mArmR) > mHeightThreshold, mAngleR > mAngleThreshold);
            mTriggerL = C.And(Nui.y(mArmL) > mHeightThreshold, mAngleL > mAngleThreshold);
            mTrigger = C.And(C.Or(mTriggerR, mTriggerL), inRange);

            mTrigger.OnChange += new ChangeDelegate(mTrigger_OnChange);
        }
        public override ScalarValue DecodeValue(ScalarValue val, ScalarValue priorVal, Scalar field)
        {
            if (priorVal == null)
            {
                Global.HandleError(Error.FastConstants.D6_MNDTRY_FIELD_NOT_PRESENT, "The field " + field + " must have a priorValue defined.");
                return null;
            }

            if (val == null)
            {
                return null;
            }

            DecimalValue priorValue;

            if (priorVal.Undefined)
            {
                if (field.DefaultValue.Undefined)
                {
                    priorValue = (DecimalValue) field.BaseValue;
                }
                else
                {
                    priorValue = (DecimalValue) field.DefaultValue;
                }
            }
            else
            {
                priorValue = (DecimalValue) priorVal;
            }

            var value_Renamed = (DecimalValue) val;

            return new DecimalValue(value_Renamed.mantissa + priorValue.mantissa, value_Renamed.exponent + priorValue.exponent);
        }
예제 #11
0
        public void Run()
        {
            var dst = new Mat(FilePath.Lenna, LoadMode.Color);
            var gray = new Mat(FilePath.Lenna, LoadMode.GrayScale);

            StarDetector detector = new StarDetector(45);
            KeyPoint[] keypoints = detector.Run(gray);

            if (keypoints != null)
            {
                var color = new Scalar(0, 255, 0);
                foreach (KeyPoint kpt in keypoints)
                {
                    float r = kpt.Size / 2;
                    Cv2.Circle(dst, kpt.Pt, (int)r, color, 1, LineType.Link8, 0);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y - r), 
                        color, 1, LineType.Link8, 0);
                    Cv2.Line(dst, 
                        new Point2f(kpt.Pt.X - r, kpt.Pt.Y + r), 
                        new Point2f(kpt.Pt.X + r, kpt.Pt.Y - r), 
                        color, 1, LineType.Link8, 0);
                }
            }

            using (new Window("StarDetector features", dst))
            {
                Cv.WaitKey();
            }
        }
 public override ScalarValue DecodeEmptyValue(ScalarValue previousValue, Scalar field)
 {
     if (!field.Optional)
     {
         return field.DefaultValue;
     }
     return null;
 }
예제 #13
0
 //LEDの位置検出
 public Microsoft.Kinect.CameraSpacePoint GetLEDPositinon(int imgW, int imgH, byte[] colors, Scalar color, ushort[] depthBuffer)
 {
     //二値化 → 輪郭抽出・中心位置取得 → depth位置に変換 → 座標取得
     //Mat ColorImage = this.CreatMat(colors, imgW, imgH);
     //Mat GrayScaleImage = this.Converter(ColorImage);
     Mat GrayScaleImage = this.Converter(colors, imgW, imgH, 4);
     Point pt = this.GetCenterPointofLED(GrayScaleImage);
     return this.GetCenterPosition(pt, depthBuffer, imgW, imgH);
 }
        public override ScalarValue GetValueToEncode(ScalarValue value_Renamed, ScalarValue priorValue, Scalar field)
        {
            if (value_Renamed == null)
            {
                return field.DefaultValue.Undefined ? null : ScalarValue.NULL;
            }

            return value_Renamed.Equals(field.DefaultValue)?null:value_Renamed;
        }
        public override ScalarValue GetValueToEncode(ScalarValue value_Renamed, ScalarValue priorValue, Scalar field)
        {
            if (value_Renamed == null)
            {
                return ScalarValue.NULL;
            }

            return value_Renamed;
        }
예제 #16
0
        public KinectScaledAxis(string name, AxisBinding binding)
            : base(name, new ScalarUpdater(sAnchor * MakeDZ()), new ScalarUpdater(sAnchor * MakeScale()), binding)
        {
            mDeadzoneScale = sTmpDZScale;
            mScaleScale = sTmpSScale;

            mDeadzoneScale.Value = G.Cfg.GetDeadzone(name);
            mScaleScale.Value = G.Cfg.GetScale(name);

            Scale.ManuallyChanged += new Action<float>(Scale_ManuallyChanged);
            Deadzone.ManuallyChanged += new Action<float>(Deadzone_ManuallyChanged);
        }
        protected override ScalarValue GetInitialValue(Scalar field)
        {
            if (!field.DefaultValue.IsUndefined)
                return field.DefaultValue;

            if (field.IsOptional)
                return null;

            Global.ErrorHandler.OnError(null, DynError.NoDefaultValue, "No default value for {0}", field);

            return null;
        }
 public override ScalarValue DecodeEmptyValue(ScalarValue priorValue, Scalar field)
 {
     ScalarValue value = priorValue;
     if (value != null && value.IsUndefined)
         value = (field.DefaultValue.IsUndefined) ? null : field.DefaultValue;
     if (value == null && !field.IsOptional)
     {
         Global.ErrorHandler.OnError(null, DynError.MandatoryFieldNotPresent, "The field {0} was not present.",
                                     field);
     }
     return value;
 }
예제 #19
0
        public void TestScalar()
        {
            var a = new Scalar(2);
            var b = a.Pow(new Scalar(3));

            Assert.True(b.Value == 8);

            var c = new Scalar(1);
            var d = c.Log();

            Assert.True(d.Value == 0);
        }
예제 #20
0
 /// <summary>
 /// Forms a border around the image
 /// </summary>
 /// <param name="src">The source image</param>
 /// <param name="dst">The destination image; will have the same type as src and 
 /// the size Size(src.cols+left+right, src.rows+top+bottom)</param>
 /// <param name="top">Specify how much pixels in each direction from the source image rectangle one needs to extrapolate</param>
 /// <param name="bottom">Specify how much pixels in each direction from the source image rectangle one needs to extrapolate</param>
 /// <param name="left">Specify how much pixels in each direction from the source image rectangle one needs to extrapolate</param>
 /// <param name="right">Specify how much pixels in each direction from the source image rectangle one needs to extrapolate</param>
 /// <param name="borderType">The border type</param>
 /// <param name="value">The border value if borderType == Constant</param>
 public static void CopyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, BorderType borderType, Scalar? value = null)
 {
     if (src == null)
         throw new ArgumentNullException("src");
     if (dst == null)
         throw new ArgumentNullException("dst");
     src.ThrowIfDisposed();
     dst.ThrowIfNotReady();
     Scalar value0 = value.GetValueOrDefault(new Scalar());
     NativeMethods.imgproc_copyMakeBorder(src.CvPtr, dst.CvPtr, top, bottom, left, right, (int)borderType, value0);
     dst.Fix();
 }
예제 #21
0
        public CrouchAxis(AxisBinding binding)
            : base("Crouch", binding)
        {
            Scalar hip = Nui.y(Nui.joint(Nui.Hip_Centre));
            Scalar feet = Nui.y((Nui.joint(Nui.Ankle_Left) + Nui.joint(Nui.Ankle_Right))) / 2f;

            //How far pushing forward
            Scalar raw = feet - hip;
            Scalar anchor = Nui.smooth(Nui.magnitude(Nui.joint(Nui.Shoulder_Centre) - Nui.joint(Nui.Hip_Centre)), 50);

            mRaw = (anchor * 3) + raw;
            mRaw *= -1f;
        }
예제 #22
0
 public void draw(Mat im, Scalar  pts_color, Scalar con_color)
 {
     foreach (var point in points) {
                     int n = point.Length;
                     if (n == 0)
                             return;
                     for (int i = 0; i < smodel.C.rows(); i++) {
                             int j = (int)smodel.C.get (i, 0) [0], k = (int)smodel.C.get (i, 1) [0];
                             Core.line (im, point [j], point [k], con_color, 1);
                     }
                     for (int i = 0; i < n; i++) {
                             Core.circle (im, point [i], 1, pts_color, 2, Core.LINE_AA, 0);
                     }
             }
 }
예제 #23
0
        private Scalar ParseSequenceLengthField(QName name, System.Xml.XmlElement sequence, bool optional, ParsingContext parent)
        {
            System.Xml.XmlNodeList lengthElements = sequence.GetElementsByTagName("length");

            if (lengthElements.Count == 0)
            {
                var implicitLength = new Scalar(Global.CreateImplicitName(name), FASTType.U32, Operator.Operator.NONE, ScalarValue.UNDEFINED, optional)
                                         {Dictionary = parent.Dictionary};
                return implicitLength;
            }

            var length = (System.Xml.XmlElement) lengthElements.Item(0);
            var context = new ParsingContext(length, parent);
            return (Scalar) sequenceLengthParser.Parse(length, optional, context);
        }
예제 #24
0
 public TestForm(Vector topLeft, Vector normal, Vector top, Vector side, Vector pointStart, Vector pointDir, Vector intersection, Scalar w, Scalar h, Scalar x, Scalar y)
     : this()
 {
     topLeftPanel.Vector = new VectorUpdater(topLeft);
     normalPanel.Vector = new VectorUpdater(normal);
     topPanel.Vector = new VectorUpdater(top);
     sidePanel.Vector = new VectorUpdater(side);
     pointStartPanel.Vector = new VectorUpdater(pointStart);
     pointDirPanel.Vector = new VectorUpdater(pointDir);
     intersectionPanel.Vector = new VectorUpdater(intersection);
     wPanel.Scalar = new ScalarUpdater(w);
     hPanel.Scalar = new ScalarUpdater(h);
     xPanel.Scalar = new ScalarUpdater(x);
     yPanel.Scalar = new ScalarUpdater(y);
 }
        public override ScalarValue DecodeEmptyValue(ScalarValue priorValue, Scalar field)
        {
            if (field.DefaultValue.IsUndefined)
            {
                if (field.IsOptional)
                    return ScalarValue.Null;

                if (priorValue.IsUndefined)
                    throw new ArgumentException(
                        "Mandatory fields without a previous value or default value must be present.",
                        "priorValue");

                return priorValue;
            }
            return field.DefaultValue;
        }
 public override ScalarValue DecodeEmptyValue(ScalarValue previousValue, Scalar field)
 {
     if (field.DefaultValue.Undefined)
     {
         if (field.Optional)
         {
             return ScalarValue.NULL;
         }
         if (previousValue.Undefined)
         {
             throw new SystemException("Mandatory fields without a previous value or default value must be present.");
         }
         return previousValue;
     }
     return field.DefaultValue;
 }
        public override ScalarValue DecodeValue(ScalarValue newValue, ScalarValue previousValue, Scalar field)
        {
            if ((newValue == null) || newValue.Null)
            {
                return null;
            }

            var diffValue = (TwinValue) newValue;
            ScalarValue base_Renamed = (previousValue.Undefined)?field.BaseValue:previousValue;

            if (diffValue.first.ToInt() > base_Renamed.ToString().Length)
            {
                Global.HandleError(Error.FastConstants.D7_SUBTRCTN_LEN_LONG, "The string diff <" + diffValue + "> cannot be applied to the base value \"" + base_Renamed + "\" because the subtraction length is too long.");
            }
            return Util.ApplyDifference((StringValue) base_Renamed, diffValue);
        }
        protected internal override ScalarValue GetInitialValue(Scalar field)
        {
            if (!field.DefaultValue.Undefined)
            {
                return field.DefaultValue;
            }

            if (field.Optional)
            {
                return null;
            }

            Global.HandleError(Error.FastConstants.D5_NO_DEFAULT_VALUE, "No default value for " + field);

            return null;
        }
        public override ScalarValue GetValueToEncode(ScalarValue value_Renamed, ScalarValue priorValue, Scalar field)
        {
            if (value_Renamed == null)
            {
                return ScalarValue.NULL;
            }

            if (priorValue == null)
            {
                Global.HandleError(Error.FastConstants.D6_MNDTRY_FIELD_NOT_PRESENT, "The field " + field + " must have a priorValue defined.");
                return null;
            }

            ScalarValue base_Renamed = (priorValue.Undefined)?field.BaseValue:priorValue;

            return Util.GetDifference((StringValue) value_Renamed, (StringValue) base_Renamed);
        }
        public override ScalarValue DecodeValue(ScalarValue newValue, ScalarValue priorValue, Scalar field)
        {
            if (newValue == null || newValue.IsNull)
                return null;

            var diffValue = (TwinValue) newValue;
            ScalarValue v = (priorValue.IsUndefined) ? field.BaseValue : priorValue;
            if (diffValue.First.ToInt() > v.ToString().Length)
            {
                Global.ErrorHandler.OnError(null, DynError.SubtrctnLenLong,
                                            "The string diff <{0}> cannot be applied to the base value '{1}' because the subtraction length is too long.",
                                            diffValue, v);
            }
            byte[] bytes = Util.ApplyDifference(v, diffValue);
            return field.FastType.GetValue(bytes);
            //return Util.ApplyDifference((StringValue) v, diffValue);
        }
예제 #31
0
 public static CubicBezierFunction2 Create(SnVector2 controlPoint0, SnVector2 controlPoint1, SnVector2 controlPoint2, SnVector2 controlPoint3, Scalar t)
 {
     return(new CubicBezierFunction2(controlPoint0, controlPoint1, controlPoint2, controlPoint3, t));
 }
예제 #32
0
        /**
         * Set preprocessing parameters for frame.
         * param size New input size.
         * param mean Scalar with mean values which are subtracted from channels.
         * param scale Multiplier for frame values.
         * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) )
         */
        public void setInputParams(double scale, Size size, Scalar mean)
        {
            ThrowIfDisposed();

            dnn_Model_setInputParams_12(nativeObj, scale, size.width, size.height, mean.val[0], mean.val[1], mean.val[2], mean.val[3]);
        }
예제 #33
0
 public static Key <uint, string> Hash <T>(this Scalar <T> me, int invertHashTokens)
 => _rec.Key <uint, string>(me);
예제 #34
0
        public bool TrySignBIP340(ReadOnlySpan <byte> msg32, ECPubKey?pubkey, INonceFunctionHardened?nonceFunction, [System.Diagnostics.CodeAnalysis.MaybeNullWhen(false)] out SecpSchnorrSignature signature)
        {
            signature = null;
            if (msg32.Length != 32)
            {
                return(false);
            }
            using var sha = new Secp256k1.SHA256();
            Span <byte> buf     = stackalloc byte[32];
            Span <byte> sig64   = stackalloc byte[64];
            Span <byte> pk_buf  = stackalloc byte[32];
            Span <byte> sec_key = stackalloc byte[32];

            if (nonceFunction == null)
            {
                nonceFunction = new BIP340NonceFunction(true);
            }

            var pk = (pubkey ?? CreatePubKey()).Q;
            var sk = this.sec;

            /* Because we are signing for a x-only pubkey, the secret key is negated
             * before signing if the point corresponding to the secret key does not
             * have an even Y. */
            if (pk.y.IsOdd)
            {
                sk = sk.Negate();
            }
            sk.WriteToSpan(sec_key);
            pk.x.WriteToSpan(pk_buf);
            var ret = nonceFunction.TryGetNonce(buf, msg32, sec_key, pk_buf, BIP340NonceFunction.ALGO_BIP340);
            var k   = new Scalar(buf, out _);

            ret &= !k.IsZero;
            Scalar.CMov(ref k, Scalar.One, ret ? 0 : 1);
            var rj = ctx.EcMultGenContext.MultGen(k);
            var r  = rj.ToGroupElement();
            var ry = r.y.NormalizeVariable();

            if (ry.IsOdd)
            {
                k = k.Negate();
            }
            var rx = r.x.NormalizeVariable();

            rx.WriteToSpan(sig64);
            /* tagged hash(r.x, pk.x, msg32) */
            sha.InitializeTagged(ECXOnlyPubKey.TAG_BIP0340Challenge);
            sha.Write(sig64.Slice(0, 32));
            sha.Write(pk_buf);
            sha.Write(msg32);
            sha.GetHash(buf);

            /* Set scalar e to the challenge hash modulo the curve order as per
             * BIP340. */
            var e = new Scalar(buf, out _);

            e = e * sk;
            e = e + k;
            e.WriteToSpan(sig64.Slice(32));

            ret &= SecpSchnorrSignature.TryCreate(sig64, out signature);

            k  = default;
            sk = default;
            sec_key.Fill(0);
            sig64.Fill(0);
            if (!ret)
            {
                signature = null;
            }
            return(signature is SecpSchnorrSignature);
        }
예제 #35
0
        public override object ConvertFrom(ref ObjectContext context, Scalar scalar)
        {
            var primitiveType = (PrimitiveDescriptor)context.Descriptor;
            var type          = primitiveType.Type;
            var text          = scalar.Value;

            // Return null if expected type is an object and scalar is null
            if (text == null)
            {
                switch (Type.GetTypeCode(type))
                {
                case TypeCode.Object:
                case TypeCode.Empty:
                case TypeCode.String:
                    return(null);

                default:
                    // TODO check this
                    throw new YamlException(scalar.Start, scalar.End, "Unexpected null scalar value");
                }
            }

            // If type is an enum, try to parse it
            if (type.IsEnum)
            {
                return(Enum.Parse(type, text, false));
            }

            // Parse default types
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Boolean:
                object value;
                context.SerializerContext.Schema.TryParse(scalar, type, out value);
                return(value);

            case TypeCode.DateTime:
                return(DateTime.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.String:
                return(text);
            }

            if (type == typeof(TimeSpan))
            {
                return(TimeSpan.Parse(text, CultureInfo.InvariantCulture));
            }

            // Remove _ character from numeric values
            text = text.Replace("_", string.Empty);

            // Parse default types
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Char:
                if (text.Length != 1)
                {
                    throw new YamlException(scalar.Start, scalar.End, "Unable to decode char from [{0}]. Expecting a string of length == 1".DoFormat(text));
                }
                return(text.ToCharArray()[0]);

                break;

            case TypeCode.Byte:
                return(byte.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.SByte:
                return(sbyte.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Int16:
                return(short.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.UInt16:
                return(ushort.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Int32:
                return(int.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.UInt32:
                return(uint.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Int64:
                return(long.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.UInt64:
                return(ulong.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Single:
                return(float.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Double:
                return(double.Parse(text, CultureInfo.InvariantCulture));

            case TypeCode.Decimal:
                return(decimal.Parse(text, CultureInfo.InvariantCulture));
            }

            // If we are expecting a type object, return directly the string
            if (type == typeof(object))
            {
                // Try to parse the scalar directly
                string defaultTag;
                object scalarValue;
                if (context.SerializerContext.Schema.TryParse(scalar, true, out defaultTag, out scalarValue))
                {
                    return(scalarValue);
                }

                return(text);
            }

            throw new YamlException(scalar.Start, scalar.End, "Unable to decode scalar [{0}] not supported by current schema".DoFormat(scalar));
        }
예제 #36
0
 internal IssuanceValidationData(Money amount, Scalar r, GroupElement ma)
 {
     Amount     = amount;
     Randomness = r;
     Ma         = ma;
 }
예제 #37
0
 public ScalarUpdater(Scalar scalar)
 {
     Scalar = scalar;
 }
예제 #38
0
 public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar)
 {
     return(realScalarSerializer.ConvertFrom(ref context, fromScalar));
 }
예제 #39
0
        public void Run()
        {
            Mat img = Cv2.ImRead(FilePath.Lenna, LoadMode.GrayScale);

            // expand input image to optimal size
            Mat padded = new Mat();
            int m      = Cv2.GetOptimalDFTSize(img.Rows);
            int n      = Cv2.GetOptimalDFTSize(img.Cols); // on the border add zero values

            Cv2.CopyMakeBorder(img, padded, 0, m - img.Rows, 0, n - img.Cols, BorderType.Constant, Scalar.All(0));

            // Add to the expanded another plane with zeros
            Mat paddedF32 = new Mat();

            padded.ConvertTo(paddedF32, MatType.CV_32F);
            Mat[] planes  = { paddedF32, Mat.Zeros(padded.Size(), MatType.CV_32F) };
            Mat   complex = new Mat();

            Cv2.Merge(planes, complex);

            // this way the result may fit in the source matrix
            Mat dft = new Mat();

            Cv2.Dft(complex, dft);

            // compute the magnitude and switch to logarithmic scale
            // => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
            Mat[] dftPlanes;
            Cv2.Split(dft, out dftPlanes);  // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))

            // planes[0] = magnitude
            Mat magnitude = new Mat();

            Cv2.Magnitude(dftPlanes[0], dftPlanes[1], magnitude);

            magnitude += Scalar.All(1);  // switch to logarithmic scale
            Cv2.Log(magnitude, magnitude);

            // crop the spectrum, if it has an odd number of rows or columns
            Mat spectrum = magnitude[
                new Rect(0, 0, magnitude.Cols & -2, magnitude.Rows & -2)];

            // rearrange the quadrants of Fourier image  so that the origin is at the image center
            int cx = spectrum.Cols / 2;
            int cy = spectrum.Rows / 2;

            Mat q0 = new Mat(spectrum, new Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant
            Mat q1 = new Mat(spectrum, new Rect(cx, 0, cx, cy));  // Top-Right
            Mat q2 = new Mat(spectrum, new Rect(0, cy, cx, cy));  // Bottom-Left
            Mat q3 = new Mat(spectrum, new Rect(cx, cy, cx, cy)); // Bottom-Right

            // swap quadrants (Top-Left with Bottom-Right)
            Mat tmp = new Mat();

            q0.CopyTo(tmp);
            q3.CopyTo(q0);
            tmp.CopyTo(q3);

            // swap quadrant (Top-Right with Bottom-Left)
            q1.CopyTo(tmp);
            q2.CopyTo(q1);
            tmp.CopyTo(q2);

            // Transform the matrix with float values into a
            Cv2.Normalize(spectrum, spectrum, 0, 1, NormType.MinMax);

            // Show the result
            Cv2.ImShow("Input Image", img);
            Cv2.ImShow("Spectrum Magnitude", spectrum);

            // calculating the idft
            Mat inverseTransform = new Mat();

            Cv2.Dft(dft, inverseTransform, DftFlag2.Inverse | DftFlag2.RealOutput);
            Cv2.Normalize(inverseTransform, inverseTransform, 0, 1, NormType.MinMax);
            Cv2.ImShow("Reconstructed by Inverse DFT", inverseTransform);
            Cv2.WaitKey();
        }
예제 #40
0
 public abstract object ConvertFrom(ref ObjectContext context, Scalar fromScalar);
예제 #41
0
        public override void Show(object value)
        {
            Point point;

            if (value is Point)
            {
                point = (Point)value;
            }
            else if (value is Point2f)
            {
                var point2f = (Point2f)value;
                point.X = float.IsNaN(point2f.X) ? -1 : (int)point2f.X;
                point.Y = float.IsNaN(point2f.Y) ? -1 : (int)point2f.Y;
            }
            else
            {
                var point2d = (Point2d)value;
                point.X = double.IsNaN(point2d.X) ? -1 : (int)point2d.X;
                point.Y = double.IsNaN(point2d.Y) ? -1 : (int)point2d.Y;
            }

            var image = visualizer.VisualizerImage;

            if (point.X < 0 || point.Y < 0 ||
                point.X >= image.Width || point.Y >= image.Height)
            {
                points = null;
            }
            else if (tracking != TrackingMode.None)
            {
                if (points == null)
                {
                    points = new Queue <Point>(1);
                    polylines.Enqueue(points);
                }

                points.Enqueue(point);
                if (tracking == TrackingMode.Fixed)
                {
                    var head = polylines.Peek();
                    head.Dequeue();
                    if (head.Count == 0)
                    {
                        polylines.Dequeue();
                    }
                }
            }

            if (polylines.Count > 0)
            {
                CV.PolyLine(image, polylines.Select(ps => ps.ToArray()).ToArray(), false, Scalar.Rgb(255, 0, 0), 2);
            }

            CV.Circle(image, point, 3, Scalar.Rgb(0, 255, 0), 3);
            if (tracking == TrackingMode.None)
            {
                polylines.Clear();
                points = null;
            }
        }
예제 #42
0
 public static Key <uint, T> Dictionarize <T>(this Scalar <T> me)
 => _rec.Key <uint, T>(me);
예제 #43
0
 public static VarVector <T> ConcatWith <T>(this Scalar <T> me, params ScalarOrVectorOrVarVector <T>[] i)
 => _rec.VarVector <T>(Helper(me, i));
예제 #44
0
파일: Tracer.cs 프로젝트: kijun/art
    /// <summary>
    /// Raises the webcam texture initialized event.
    /// </summary>
    private void OnInited()
    {
        prevPos = new Vector2(webCamTexture.width / 2, webCamTexture.height);
        if (colors == null || colors.Length != webCamTexture.width * webCamTexture.height)
        {
            colors = new Color32[webCamTexture.width * webCamTexture.height];
        }
        if (texture == null || texture.width != webCamTexture.width || texture.height != webCamTexture.height)
        {
            //texture = new Texture2D (webCamTexture.width, webCamTexture.height, TextureFormat.RGBA32, false);
            texture = new Texture2D(webCamTexture.width, webCamTexture.height, TextureFormat.RGBA32, false);
        }

        rgbaMat = new Mat(webCamTexture.height, webCamTexture.width, CvType.CV_8UC4);

        /*
         * rgbaMat2 = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4);
         * rgbaMat3 = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4);
         * rgbaMatFinal = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4);
         */
        rgbaMat2     = new Mat(requestedHeight, requestedWidth, CvType.CV_8UC4);
        rgbaMat3     = new Mat(requestedHeight, requestedWidth, CvType.CV_8UC4);
        rgbaMatFinal = new Mat(requestedHeight, requestedWidth, CvType.CV_8UC4);

        gameObject.GetComponent <Renderer> ().material.mainTexture = texture;

        gameObject.transform.localScale = new Vector3(webCamTexture.width, webCamTexture.height, 1);
        Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);

        if (fpsMonitor != null)
        {
            fpsMonitor.Add("width", rgbaMat.width().ToString());
            fpsMonitor.Add("height", rgbaMat.height().ToString());
            fpsMonitor.Add("orientation", Screen.orientation.ToString());
        }


        float width  = rgbaMat.width();
        float height = rgbaMat.height();

        float widthScale  = (float)Screen.width / width;
        float heightScale = (float)Screen.height / height;

        if (widthScale < heightScale)
        {
            Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
        }
        else
        {
            Camera.main.orthographicSize = height / 2;
        }
        KF = new KalmanFilter(4, 2, 0, CvType.CV_32FC1);

        // intialization of KF...
        Mat transitionMat = new Mat(4, 4, CvType.CV_32F);

        transitionMat.put(0, 0, new float[] { 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 });
        KF.set_transitionMatrix(transitionMat);

        measurement = new Mat(2, 1, CvType.CV_32FC1); measurement.setTo(Scalar.all(0));

        cursorPos = new Point();
        GetCursorPos(cursorPos);

        // Set initial state estimate.
        Mat statePreMat = KF.get_statePre();

        statePreMat.put(0, 0, new float[] { (float)cursorPos.x, (float)cursorPos.y, 0, 0 });
        Mat statePostMat = KF.get_statePost();

        statePostMat.put(0, 0, new float[] { (float)cursorPos.x, (float)cursorPos.y, 0, 0 });

        Mat measurementMat = new Mat(2, 4, CvType.CV_32FC1);

        Core.setIdentity(measurementMat);
        KF.set_measurementMatrix(measurementMat);

        Mat processNoiseCovMat = new Mat(4, 4, CvType.CV_32FC1);

        Core.setIdentity(processNoiseCovMat, Scalar.all(1e-4));
        KF.set_processNoiseCov(processNoiseCovMat);

        Mat measurementNoiseCovMat = new Mat(2, 2, CvType.CV_32FC1);

        Core.setIdentity(measurementNoiseCovMat, Scalar.all(10));
        KF.set_measurementNoiseCov(measurementNoiseCovMat);

        Mat errorCovPostMat = new Mat(4, 4, CvType.CV_32FC1);

        Core.setIdentity(errorCovPostMat, Scalar.all(.1));
        KF.set_errorCovPost(errorCovPostMat);

        /*Imgproc.rectangle (
         *  rgbaMatFinal,
         *  new Point (0, 0),
         *  new Point (rgbaMatFinal.width (), rgbaMatFinal.height ()),
         *  new Scalar (0, 0, 0, 255), -1);
         */
    }
예제 #45
0
        public void PutText_NullText_ThrowsArgumentNullException()
        {
            var image = new IplImage(new Size(10, 10), IplDepth.U8, 1);

            CV.PutText(image, null, Point.Zero, new Font(1), Scalar.All(0));
        }
 public static Proof Prove(Statement statement, Scalar witness, WasabiRandom random)
 {
     return(Prove(statement, new ScalarVector(witness), random));
 }
예제 #47
0
 internal ScalarMultiply(Scalar left, Vector2 right)
 {
     Left  = left;
     Right = right;
 }
예제 #48
0
 public static Key <uint> Hash <T>(this Scalar <T> me)
 => _rec.Key <uint>(me);
예제 #49
0
 public HsvThreshold()
 {
     Upper = new Scalar(179, 255, 255, 255);
 }
예제 #50
0
        public static IScalarValidationErrors Validate(IScalarValidationErrors result, Scalar <INamedTypeSymbol> resourceType, Scalar <IPropertySymbol> resourceProperty,
                                                       Scalar <string> message)
        {
            result = Validate(result, resourceType, resourceProperty);

            if (resourceType.Value == null && string.IsNullOrWhiteSpace(message.Value))
            {
                result = result.Add(new ScalarValidationError(UserMessages.MessageView_ValueIsRequired, message));
            }
            return(result);
        }
예제 #51
0
 protected _RegistrationPresenter()
 {
     _userName             = NewScalar(string.Empty).AddValidator(ValidateUserNameRequired);
     _passwordConfirmation = NewScalar(string.Empty).AddValidator(ValidatePasswordConfirmationLength);
     _interests            = NewScalar(Interests.None).AddValidator(ValidateInterests);
 }
예제 #52
0
 public static VarVector <string> Tokenize(this Scalar <string> me)
 => _rec.VarVector <string>(me);
예제 #53
0
 internal Constructed(Scalar x, Scalar y)
 {
     X = x;
     Y = y;
 }
예제 #54
0
 CubicBezierFunction2(SnVector2 controlPoint0, SnVector2 controlPoint1, SnVector2 controlPoint2, SnVector2 controlPoint3, Scalar t)
 {
     _p0 = controlPoint0;
     _p1 = controlPoint1;
     _p2 = controlPoint2;
     _p3 = controlPoint3;
     _t  = t;
 }
예제 #55
0
        public void AddBinding <T>(TemplateBuilder <T> builder, Scalar <INamedTypeSymbol> resourceType, Scalar <IPropertySymbol> resourceProperty, Scalar <string> message)
            where T : TemplateBuilder <T>
        {
            var resourceTypeValue = resourceType.Value;

            builder.AddBinding(_comboBoxResourceType, resourceType.BindToComboBox(GetResourceTypeSelection(resourceTypeValue)).ApplyRefresh((v, p) =>
            {
                Refresh(resourceType.Value != null);
            }));
            if (resourceTypeValue != null)
            {
                builder.AddBinding(_comboBoxResourceProperty, resourceProperty.BindToComboBox(GetResourcePropertySelection(resourceTypeValue)));
            }
            else
            {
                _comboBoxResourceType.IsEnabled = false;
            }
            builder.AddBinding(_textBoxMessage, message.BindToTextBox());
        }
예제 #56
0
 /// <summary>
 /// Performs text featurization on the input text. This will tokenize, do n-gram featurization,
 /// dictionary based term mapping, and finally produce a word-bag vector for the output.
 /// </summary>
 /// <param name="me">The text to featurize</param>
 /// <returns></returns>
 public static Vector <float> TextFeaturizer(this Scalar <string> me, bool keepDiacritics = true)
 => _rec.Vector <float>(me);
예제 #57
0
        public static IScalarValidationErrors Validate(IScalarValidationErrors result, Scalar <INamedTypeSymbol> resourceType, Scalar <IPropertySymbol> resourceProperty)
        {
            if (resourceType.Value != null && resourceProperty.Value == null)
            {
                result = result.Add(new ScalarValidationError(UserMessages.MessageView_ValueIsRequired, resourceProperty));
            }

            return(result);
        }
예제 #58
0
 /// <summary>
 /// Trains a linear predictor using logistic regression.
 /// </summary>
 /// <param name="label">The target label for this binary classification task</param>
 /// <param name="features">The features to train on. Should be normalized.</param>
 /// <returns>A tuple of columns representing the score, the calibrated score as a probability, and the boolean predicted label</returns>
 public static (Scalar <float> score, Scalar <float> probability, Scalar <bool> predictedLabel) TrainLinearClassification(this Scalar <bool> label, Vector <float> features)
 => (_rec.Scalar <float>(label, features), _rec.Scalar <float>(label, features), _rec.Scalar <bool>(label, features));
예제 #59
0
파일: info.cs 프로젝트: zjmit/go2cs
 // Count creates a new metric based on the Scalar information that counts
 // the number of times the supplied int64 measure is set.
 // Metrics of this type will use Int64Data.
 public static void Count(this Scalar info, ptr <Config> _addr_e, label.Key key)
 {
     ref Config e = ref _addr_e.val;
예제 #60
0
 private void GotoTargetPoint(Scalar targetPoint)
 {
     var startime    = DateTime.Now;
     var isNarrowing = false;
 }