Exemplo n.º 1
0
        /// <summary>
        ///A test for ToString
        ///</summary>
        public void ToStringTestHelper <T>()
        {
            MatrixBase <T> target = new MatrixBase <T>();
            string         actual = target.ToString();

            Assert.IsNotNull(actual);
        }
Exemplo n.º 2
0
        public static void Buy(Member user, PTCOfferWallPack pack, PurchaseBalances targetBalance, List <UserUrl> userUrls,
                               string title, string description, GeolocationUnit geoUnit, bool pcAllowed, bool mobileAllowed,
                               bool autosurfEnabled, int maxSingleUserDailyViews)
        {
            if (pack.Adverts != userUrls.Count)
            {
                throw new MsgException(string.Format(U6002.NUMBEROFURLSERROR, pack.Adverts));
            }

            if (userUrls.Any(u => u.Status != AdvertStatus.Active))
            {
                throw new MsgException("Fraud! Only active urls are permitted.");
            }

            PurchaseOption.ChargeBalance(user, pack.Price, PurchaseOption.Features.PtcOfferWall.ToString(), targetBalance, "PTC OfferWall");

            var offerWall = new PTCOfferWall(user.Id, pack, title, description, pcAllowed, mobileAllowed, autosurfEnabled, maxSingleUserDailyViews);

            if (geoUnit != null)
            {
                offerWall.AddGeolocation(geoUnit);
            }

            offerWall.Save();
            offerWall.MapWithUrls(userUrls);

            MatrixBase.TryAddMemberAndCredit(user, pack.Price, AdvertType.PTCOfferWall);
        }
Exemplo n.º 3
0
        public void ToTensor <T>(MatrixBase matrix, uint count, T tensor)
            where T : Tensor
        {
            this.ThrowIfDisposed();

            if (matrix == null)
            {
                throw new ArgumentNullException(nameof(matrix));
            }

            matrix.ThrowIfDisposed();

            var type = matrix.MatrixElementType.ToNativeMatrixElementType();
            var ret  = Dlib.Native.input_rgb_image_pyramid_to_tensor(this.NativePtr,
                                                                     this._PyramidType,
                                                                     this._PyramidRate,
                                                                     type,
                                                                     matrix.NativePtr,
                                                                     matrix.TemplateRows,
                                                                     matrix.TemplateRows,
                                                                     count,
                                                                     tensor.NativePtr);

            switch (ret)
            {
            case Dlib.Native.ErrorType.MatrixElementTypeNotSupport:
                throw new ArgumentException($"{type} is not supported.");

            case Dlib.Native.ErrorType.PyramidNotSupportRate:
            case Dlib.Native.ErrorType.PyramidNotSupportType:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        ///A test for MatrixBase`1 Constructor
        ///</summary>
        public void MatrixBaseConstructorTest5Helper <T>()
        {
            int            rank   = 0; // TODO: Initialize to an appropriate value
            MatrixBase <T> target = new MatrixBase <T>(rank);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemplo n.º 5
0
        /// <summary>
        ///A test for MatrixBase`1 Constructor
        ///</summary>
        public void MatrixBaseConstructorTestHelper <T>()
        {
            MatrixBase <T> matrix = null; // TODO: Initialize to an appropriate value
            MatrixBase <T> target = new MatrixBase <T>(matrix);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemplo n.º 6
0
        public static MatrixBase Multiply(MatrixBase m1, MatrixBase m2)
        {
            int h            = m1.Height;
            int w            = m2.Width;
            int l            = m1.Width;
            var resultMatrix = new double[m1.Height, m2.Width];

            unsafe
            {
                fixed(double *pm = resultMatrix, pm1 = m1.Rows, pm2 = m2.Rows)
                {
                    int i1, i2;

                    for (int i = 0; i < h; i++)
                    {
                        i1 = i * l;
                        for (int j = 0; j < w; j++)
                        {
                            i2 = j;
                            double res = 0;
                            for (int k = 0; k < l; k++, i2 += w)
                            {
                                res += pm1[i1 + k] * pm2[i2];
                            }
                            pm[i * w + j] = res;
                        }
                    }
                }
            }

            return(new Matrix(resultMatrix));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns probabilities of gender of face image correspond to specified location in specified image.
        /// </summary>
        /// <param name="matrix">The matrix contains a face.</param>
        /// <param name="location">The location rectangle for a face.</param>
        /// <returns>Probabilities of gender of face image correspond to specified location in specified image.</returns>
        protected override IDictionary <Gender, float> RawPredictProbability(MatrixBase matrix, Location location)
        {
            if (!(matrix is Matrix <RgbPixel> mat))
            {
                throw new ArgumentException();
            }

            var rect   = new Rectangle(location.Left, location.Top, location.Right, location.Bottom);
            var dPoint = new[]
            {
                new DPoint(rect.Left, rect.Top),
                new DPoint(rect.Right, rect.Top),
                new DPoint(rect.Left, rect.Bottom),
                new DPoint(rect.Right, rect.Bottom),
            };

            using (var img = DlibDotNet.Dlib.ExtractImage4Points(mat, dPoint, 227, 227))
            {
                var results = this._Network.Probability(img, 1).ToArray();
                return(new Dictionary <Gender, float>
                {
                    { Gender.Male, results[0][0] },
                    { Gender.Female, results[0][1] }
                });
            }

            #endregion
        }
Exemplo n.º 8
0
        /// <summary>
        ///A test for DefaultView
        ///</summary>
        public void DefaultViewTestHelper <T>()
        {
            T[,] sampleData = new T[6, 3];
            for (int i = 0; i < sampleData.GetLength(0); i++)
            {
                for (int j = 0; j < sampleData.GetLength(1); j++)
                {
                    sampleData[i, j] = default(T);
                }
            }

            MatrixDataSource <T> target = new MatrixDataSource <T>(sampleData);
            MatrixBase <T>       actual;

            actual = target.DefaultView;
            Assert.AreEqual(sampleData.GetLength(1), actual.ColumnCount);
            Assert.AreEqual(sampleData.GetLength(0), actual.RowCount);

            T[,] sampleData2 = new T[, ]
            {
                { default(T), default(T) },
                { default(T), default(T) },
                { default(T), default(T) },
                { default(T), default(T) }
            };
            MatrixDataSource <T> target2 = new MatrixDataSource <T>(sampleData2);
            MatrixBase <T>       actual2 = target2.DefaultView;

            Assert.AreEqual(2, actual2.ColumnCount);
            Assert.AreEqual(4, actual2.RowCount);
        }
Exemplo n.º 9
0
    private static MatrixCrediterBase GetMatrixCrediter(MatrixBase matrix)
    {
        MatrixCrediterBase crediter = null;

        switch (AppSettings.Matrix.Crediter)
        {
        case MatrixCrediter.None:
            crediter = null;
            break;

        case MatrixCrediter.Commission:
            crediter = new CommissionMatrixCrediter();
            break;

        case MatrixCrediter.CommissionReferrals:
            crediter = new CommissionReferralMatrixCrediter();
            break;

        case MatrixCrediter.Cycles:
            crediter = new BinaryReferralMatrixCrediter();
            break;

        default:
            throw new MsgException("Unuknown Matrix Crediter Type: " + (AppSettings.Matrix.Crediter.ToString() ?? "NULL"));
        }

        return(crediter);
    }
Exemplo n.º 10
0
        public void ExtractFHogFeatures2()
        {
            var path = this.GetDataFile($"{LoadTarget}.bmp");

            var tests = new[]
            {
                new { Type = MatrixElementTypes.Float, ExpectResult = true },
                new { Type = MatrixElementTypes.Double, ExpectResult = true }
            };

            foreach (var output in tests)
            {
                Array2DBase       imageObj  = null;
                Array2DMatrixBase outputObj = null;

                try
                {
                    imageObj = DlibTest.LoadImageHelp(ImageTypes.RgbPixel, path);

                    switch (output.Type)
                    {
                    case MatrixElementTypes.Float:
                        outputObj = Dlib.ExtractFHogFeatures <float>(imageObj);
                        break;

                    case MatrixElementTypes.Double:
                        outputObj = Dlib.ExtractFHogFeatures <double>(imageObj);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    MatrixBase matrix = Dlib.DrawFHog(outputObj);

                    if (this.CanGuiDebug)
                    {
                        var window = new ImageWindow(matrix);
                        window.WaitUntilClosed();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                finally
                {
                    if (imageObj != null)
                    {
                        this.DisposeAndCheckDisposedState(imageObj);
                    }
                    if (outputObj != null)
                    {
                        this.DisposeAndCheckDisposedState(outputObj);
                    }
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        ///A test for CopyFrom
        ///</summary>
        public void CopyFromTestHelper <T>()
        {
            MatrixBase <T> target       = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            MatrixBase <T> sourceMatrix = null;                 // TODO: Initialize to an appropriate value

            target.CopyFrom(sourceMatrix);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Exemplo n.º 12
0
        /// <summary>
        ///A test for Columns
        ///</summary>
        public void ColumnsTestHelper <T>()
        {
            MatrixBase <T> target = new MatrixBase <T>(); // TODO: Initialize to an appropriate value

            MatrixBase <T> .ColumnAccessor <T> actual;
            actual = target.Columns;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 13
0
        /// <summary>
        ///A test for DataColumnRange
        ///</summary>
        public void DataColumnRangeTestHelper <T>()
        {
            MatrixBase <T> target = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            Int32Range     actual;

            actual = target.DataColumnRange;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 14
0
        /// <summary>
        ///A test for IsColumnVector
        ///</summary>
        public void IsColumnVectorTestHelper <T>()
        {
            MatrixBase <T> target = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            bool           actual;

            actual = target.IsColumnVector;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 15
0
        /// <summary>
        ///A test for RowCount
        ///</summary>
        public void RowCountTestHelper <T>()
        {
            MatrixBase <T> target = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            int            actual;

            actual = target.RowCount;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 16
0
        /// <summary>
        ///A test for ColumnAccessor`1 Constructor
        ///</summary>
        public void MatrixBase_ColumnAccessorConstructorTestHelper <T, T1>()
        {
            MatrixBase <T> dataView = null; // TODO: Initialize to an appropriate value

            MatrixBase <T> .ColumnAccessor <T> target = new MatrixBase <T> .ColumnAccessor <T>(dataView);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemplo n.º 17
0
 public ActionResult <string[][]> Get(int matrixSize = 10, MatrixBase matrixBase = MatrixBase.Decimal)
 {
     try {
         return(Ok(_multiplyer.GetMultiplicationTable(matrixSize, matrixBase)));
     } catch (ArgumentException e) {
         ModelState.AddModelError(nameof(matrixSize), e.Message);
         return(BadRequest(ModelState));
     }
 }
Exemplo n.º 18
0
            internal clCommVector(MatrixBase M, clVector v)
                : base(M, v)
            {
                this.owner = v;

                clfill = cl.CreateKernel(owner.device.vectorProgram, "fillSendBuffer");

                IDictionary <int, int[]> comLists = M._SpmvCommPattern.ComLists;
                //int[] procranks = new int[comLists.Count]; // put all proccessor ranks in one list to have a unique ordering

                int totLen = 0;

                foreach (int procRnk in comLists.Keys)
                {
                    int l = comLists[procRnk].Length;
                    base.SendBuffersLengths[procRnk] = l;
                    totLen += l;
                }

                size       = totLen;
                globalsize = size;
                int m = size % localsize;

                if (m > 0)
                {
                    globalsize += localsize - m;
                }

                if (size > 0)
                {
                    // alloc
                    h_IndicesToSend = new int[size];
                    d_IndicesToSend = cl.CreateBuffer(owner.device.env.context, cl_mem_flags.CL_MEM_READ_ONLY, (uint)size * sizeof(int));

                    h_SendBuffer = Marshal.AllocHGlobal(size * sizeof(double));
                    d_SendBuffer = cl.CreateBuffer(owner.device.env.context, cl_mem_flags.CL_MEM_WRITE_ONLY, (uint)size * sizeof(double));

                    // concat lists:
                    int i0 = 0;
                    unsafe
                    {
                        double *P0 = (double *)h_SendBuffer;

                        foreach (int procRnk in comLists.Keys)
                        {
                            base.SendBuffers[procRnk] = (IntPtr)P0;  // startaddres for sending to process 'procRnk'

                            int l = base.SendBuffersLengths[procRnk];
                            P0 += l;
                            Array.Copy(comLists[procRnk], 0, h_IndicesToSend, i0, l); // concat comm list
                            i0 += l;
                        }
                    }

                    cl.EnqueueWriteBuffer(owner.device.cq, d_IndicesToSend, true, 0, (uint)size * sizeof(int), h_IndicesToSend);
                }
            }
Exemplo n.º 19
0
        /// <summary>
        ///A test for op_Implicit
        ///</summary>
        public void op_ImplicitTestHelper <T>()
        {
            T[,] dataArray = null;          // TODO: Initialize to an appropriate value
            MatrixBase <T> expected = null; // TODO: Initialize to an appropriate value
            MatrixBase <T> actual;

            actual = dataArray;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 20
0
 public void MultiplyThis(MatrixBase <double> ret, MatrixBase <double> a, double b)
 {
     for (int x = 0; x < a.Width; x++)
     {
         for (int y = 0; y < a.Height; y++)
         {
             ret[x, y] = a[x, y] * b;
         }
     }
 }
Exemplo n.º 21
0
        /// <summary>
        ///A test for CopyInto
        ///</summary>
        public void CopyIntoTest1Helper <T>()
        {
            MatrixBase <T> target             = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            MatrixBase <T> targetMatrix       = null;                 // TODO: Initialize to an appropriate value
            int            targetColumnOffset = 0;                    // TODO: Initialize to an appropriate value
            int            targetRowOffset    = 0;                    // TODO: Initialize to an appropriate value

            target.CopyInto(targetMatrix, targetColumnOffset, targetRowOffset);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Exemplo n.º 22
0
        /// <summary>
        ///A test for GetHashCode
        ///</summary>
        public void GetHashCodeTestHelper <T>()
        {
            MatrixBase <T> target   = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            int            expected = 0;                    // TODO: Initialize to an appropriate value
            int            actual;

            actual = target.GetHashCode();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 23
0
            public FullMatrix(MatrixBase matrix)
            {
                int rowCount    = matrix.RowCount;
                int columncount = matrix.ColumnCount;

                _matrix = new double[rowCount][];
                for (int i = 0; i < rowCount; i++)
                {
                    _matrix[i] = matrix.RowArray(i);
                }
            }
Exemplo n.º 24
0
        public MatrixBase <int> Multiply(MatrixBase <int> a, int b)
        {
            MatrixBase <int> ret =
                a.Width == 1
                ? new Vector <int>(a.Dimension) as MatrixBase <int>
                : new Matrix <int>(a.Dimension) as MatrixBase <int>;

            MultiplyThis(ret, a, b);

            return(ret);
        }
Exemplo n.º 25
0
        /// <summary>
        ///A test for JoinHorizontal
        ///</summary>
        public void JoinHorizontalTestHelper <T>()
        {
            IEnumerable <MatrixBase <T> > matricies = null; // TODO: Initialize to an appropriate value
            MatrixBase <T> expected = null;                 // TODO: Initialize to an appropriate value
            MatrixBase <T> actual;

            actual = MatrixBase <T> .JoinHorizontal(matricies);

            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 26
0
        /// <summary>
        ///A test for ElementWiseCopy
        ///</summary>
        public void ElementWiseCopyTestHelper <T>()
        {
            MatrixBase <T> source             = null; // TODO: Initialize to an appropriate value
            MatrixBase <T> target             = null; // TODO: Initialize to an appropriate value
            int            targetColumnOffset = 0;    // TODO: Initialize to an appropriate value
            int            targetRowOffset    = 0;    // TODO: Initialize to an appropriate value

            MatrixBase <T> .ElementWiseCopy(source, target, targetColumnOffset, targetRowOffset);

            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Exemplo n.º 27
0
        /// <summary>
        ///A test for IsNull
        ///</summary>
        public void IsNullTestHelper <T>()
        {
            MatrixBase <T> matrix   = null;  // TODO: Initialize to an appropriate value
            bool           expected = false; // TODO: Initialize to an appropriate value
            bool           actual;

            actual = MatrixBase <T> .IsNull(matrix);

            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 28
0
        /// <summary>
        ///A test for Equals
        ///</summary>
        public void EqualsTestHelper <T>()
        {
            MatrixBase <T> target   = new MatrixBase <T>(); // TODO: Initialize to an appropriate value
            object         obj      = null;                 // TODO: Initialize to an appropriate value
            bool           expected = false;                // TODO: Initialize to an appropriate value
            bool           actual;

            actual = target.Equals(obj);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 29
0
        public MatrixBase <double> Multiply(MatrixBase <double> a, double b)
        {
            MatrixBase <double> ret =
                a.Width == 1
                ? new Vector <double>(a.Dimension) as MatrixBase <double>
                : new Matrix <double>(a.Dimension) as MatrixBase <double>;

            MultiplyThis(ret, a, b);

            return(ret);
        }
Exemplo n.º 30
0
        /// <summary>
        ///A test for System.Collections.IEnumerable.GetEnumerator
        ///</summary>
        public void GetEnumeratorTest1Helper <T, T1>()
        {
            MatrixBase <T> dataView = null;                                             // TODO: Initialize to an appropriate value
            IEnumerable    target   = new MatrixBase <T> .ColumnAccessor <T>(dataView); // TODO: Initialize to an appropriate value

            IEnumerator expected = null;                                                // TODO: Initialize to an appropriate value
            IEnumerator actual;

            actual = target.GetEnumerator();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 31
0
        public static MatrixBase<YCbCrColor> ToYCbCr(this MatrixBase<Color> matrix)
        {
            var ret = new MatrixBase<YCbCrColor>(matrix.RowCount, matrix.ColumnCount);

            for (int i = 0; i < matrix.RowCount; i++)
            {
                for (int j = 0; j < matrix.ColumnCount; j++)
                {
                    var color = matrix[i, j].ToYCrCb();
                    ret[i, j] = new YCbCrColor { Y = color[0], Cb = color[1], Cr = color[2] };
                }
            }
            return ret;
        }
Exemplo n.º 32
0
        public static MatrixBase<Color> ToRgb(this MatrixBase<YCbCrColor> matrix)
        {
            var ret = new MatrixBase<Color>(matrix.RowCount, matrix.ColumnCount);

            for (int i = 0; i < matrix.RowCount; i++)
            {
                for (int j = 0; j < matrix.ColumnCount; j++)
                {
                    var color = matrix[i, j].ToRgb();
                    ret[i, j] = color;
                }
            }
            return ret;
        }
Exemplo n.º 33
0
 public static bool GetWatermarkDctForBlock(MatrixBase<Color> block, int bitIndex, ZigZagAccessorFactory<double> zigzagAccessorFactory, Double[,] quantizationTable,
     ChannelType channelType, bool log = false)
 {
     var yCbCrColorBlock = block.ToYCbCr();
     var yChannel = yCbCrColorBlock.GetChannel(channelType);
     var shiftetBlock = yChannel - 128;
     var dctBlockTransform = (DiscreteCosineTransform.ForwardDct8Block(shiftetBlock).CrossDivide(quantizationTable)).Round();
     if (log)
     {
         _debugDecodeStringBuilder.AppendLine(dctBlockTransform.ToString());
     }
     var accessor = zigzagAccessorFactory.Access(dctBlockTransform);
     var coefficient = accessor[bitIndex];
     var curentElelement = (int) Math.Round(coefficient);
     bool isEven = curentElelement%2 == 0;
     return isEven;
 }
Exemplo n.º 34
0
        private static MatrixBase<Color> WatermarkDctBlock(MatrixBase<Color> block, ZigZagAccessorFactory<Double> accessorFactory, double[,] quantizationTable, bool canEncrypt,
            byte[] secretMessage,
            ref int embeddingSecretMessageBitIndex, int byteIndexForEncryption, ChannelType channelType)
        {
            if (!canEncrypt)
            {
                return block;
            }

            var byteIndex = embeddingSecretMessageBitIndex / 8;
            if (embeddingSecretMessageBitIndex % 8 == 0)
            {
                byteIndex = embeddingSecretMessageBitIndex / 8;
                _debugEncodeStringBuilder.AppendLine("Appending byte:" + (byteIndex + 1));
            }

            var correction = 1;
            bool embeddCorrectly;
            MatrixBase<Color> ret;

            //#region Convert block

            var yCbCrColorBlock = block.ToYCbCr();
            var channel = yCbCrColorBlock.GetChannel(channelType);
            channel = channel - 128;
            DoubleMatrix dctBlockTransform = null;

            //#endregion

            do
            {
                // For luminance channel yMax = 127, ymin = -128

                DoubleMatrix stegoBlock;
                bool redo = false;
                var nextSecretBit = MathUtilities.GetBit(secretMessage, embeddingSecretMessageBitIndex);
                bool changed = false;
                dctBlockTransform = DiscreteCosineTransform.ForwardDct8Block(channel);
                dctBlockTransform = (dctBlockTransform.CrossDivide(quantizationTable));
                dctBlockTransform = dctBlockTransform.Round();

                var accessor = accessorFactory.Access(dctBlockTransform);
                var curentElelement = accessor[byteIndexForEncryption];
                bool isEven = ((int) Math.Round(curentElelement))%2 == 0;
                double possibleValue = curentElelement;
                DoubleMatrix oldStegoBlock = null;

                do
                {
                    if ((isEven && nextSecretBit) || (!isEven && !nextSecretBit))
                    {
                        if (!redo)
                        {
                            possibleValue = isEven ? curentElelement - correction : curentElelement + correction;
                        }
                        else
                        {
                            possibleValue = isEven ? curentElelement + correction : curentElelement - correction;
                        }
                        changed = true;
                    }

                    accessor[byteIndexForEncryption] = possibleValue;
                    stegoBlock = dctBlockTransform.CrossProduct(quantizationTable);
                    stegoBlock = DiscreteCosineTransform.InverseDct8Block(stegoBlock);

                    if (!redo && changed)
                    {
                        for (var i = 0; i < 8; i++)
                        {
                            for (var j = 0; j < 8; j++)
                            {
                                var value = Math.Round(stegoBlock[i, j]);
                                if (value < -128 || value > 127)
                                {
                                    redo = true;
                                    oldStegoBlock = stegoBlock;
                                    break;
                                }
                            }
                            if (redo)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (changed)
                        {
                            var maximumValue = oldStegoBlock.MaximumValue;
                            var minimumValue = oldStegoBlock.MinimumValue;
                            var currentMaximumValue = stegoBlock.MaximumValue;
                            var currentMinimumValue = stegoBlock.MinimumValue;

                            if (currentMinimumValue < -128 || currentMaximumValue > 127)
                            {
                                if ((currentMinimumValue < -128 && minimumValue > currentMinimumValue) || (currentMaximumValue > 127 && maximumValue < currentMaximumValue))
                                {
                                    stegoBlock = oldStegoBlock;
                                }
                            }
                       }
                        redo = false;
                    }
                } while (redo);

                stegoBlock = stegoBlock + 128; //
                var tmpyCbCrColorBlock = yCbCrColorBlock.Copy;
                tmpyCbCrColorBlock.UpdateChannel(channelType, stegoBlock);

                ret = tmpyCbCrColorBlock.ToRgb();

                #region Verification (check if embeddding is correctly (rounding problems might occurs))

                if (changed)
                {
                    embeddCorrectly = !GetWatermarkDctForBlock(ret, byteIndexForEncryption, accessorFactory, quantizationTable, channelType) == nextSecretBit;
                    if (!embeddCorrectly)
                    {
                        correction = correction + 2;
                    }
                    else
                    {
                        correction = 1;
                    }
                }
                else
                {
                    embeddCorrectly = true;
                    correction = 1;
                }

                #endregion

            } while (!embeddCorrectly);

            _debugEncodeStringBuilder.AppendLine(dctBlockTransform.ToString());
            embeddingSecretMessageBitIndex++;

            return ret;
        }
Exemplo n.º 35
0
        /*
        RILASSAMENTO
        Da scrivere dopo aver completato Bisezione, PassoFisso e Grossolana
        */
        /*
        STEEPEST
        Da scrivere dopo aver completato Bisezione, PassoFisso e Grossolana
        */
        /*
        PASSOFISSO
        Analoga a Bisezione (stessi parametri o quasi...)
        Usa pero` il gradiente come condizione di uscita al posto della distanza (oltre alla f)
        */
        /// <summary>
        /// Incrementa contatori
        /// </summary>
        /// <param name="contatori">Colonna (n,1) con i contatori</param>
        /// <param name="passi">Colonna (n,1) con i passi massimi</param>
        /// <param name="indIncrementato">Indice incrementato, oppure -1 se variato piu` di uno</param>
        /// <returns>true se ha incrementato un indice, false se era gia` l'ultimo passo</returns>
        public static bool Incrementa(	ref MatrixBase<int> contatori,
									MatrixBase<int> passi,
									ref int indIncrementato)
        {
            bool fine = false;						// Flag finale
            int n;									// Dimensione dei vettori
            n = contatori.Row;
            if((passi.Row != n) || (passi.Col!=1) || (contatori.Col != 1) )
            {
            return fine;						// Verifica gli indici
            }

            int indice = 0;							// Inizia con il primo indice
            indIncrementato = 0;					// Indice da ricalcolare (-1 se tutti)
            while(indice < n)
            {
            int c;
            c = contatori.Get(indice,0) + 1;	// Calcola indice incrementato
            if(c < passi.Get(indice,0))			// Se entro i limiti...
                {
                contatori.Set(indice,0,c);		// Aggiorna indice
                if(indIncrementato != -1)		// Lo salva, per aggiornamento calcoli...
                    indIncrementato = indice;	// ... ma solo se non erano gia` cambiati piu` indici
                fine = true;					// Raggiunta uscita prima della fine
                break;							// Esce dal ciclo while
                }
            else
                {								// ...se superato i limiti
                contatori.Set(indice,0,0);		// Azzera contatore
                indice += 1;					// Passa all'indice successivo
                indIncrementato = -1;
                continue;						// Continua il ciclo while
                }
            }									// Se esce normalmente dal while, fine resta true
            if(indice >= n)
            fine = false;						// Se superato ultimo indice: ultimo passo, false
            return fine;
        }
Exemplo n.º 36
0
        /*

        NOTA GENERALE.

        I metodi precedenti, steepest descent, rilassamento (per la scelta delle direzioni) e
        passo fisso e bisezione (per la ricerca del minimo (o del massimo)
        non sono sufficienti da soli.

        E' ragionevole scrivere prima alcune funzioni che lavorino separatamente.
        Tutte sono incluse nella classe Fmin e hanno gia` implicito il delegate alla funzione
        Tutte devono prima verificare che il delegate non sia nullo.

        */
        /// <summary>
        /// Ricerca per punti
        /// </summary>
        /// <param name="xk">Punto centrale</param>
        /// <param name="range">Meta` ampiezza di ricerca (ammessi valori nulli)</param>
        /// <param name="passiU">Numero di passi unilaterali (almeno 1)</param>
        /// <param name="xmin">Punto con il valore minore</param>
        /// <param name="cicli">Numero di punti calcolati</param>
        /// <returns></returns>
        public bool Campionamento(	Matrix xk,
								Matrix range,
								MatrixBase<int> passiU,
								ref Matrix xmin,
								ref int cicli)
        {
            bool found = false;
            int n;														// Dimensioni dei vettori
            int i;														// Contatore
            n = xk.Row;
            if((range.Row != n) || (passiU.Row != n) || (xmin.Row != n) || (xk.Col != 1) || (range.Col != 1) || (passiU.Col != 1) || (xmin.Col != 1) )
            {
            return found;											// Verifica indici
            }
            for(i=0; i<n; i++)											// Verifica intervalli (ammessi valori nulli)
            {
            if(range.Get(i,0) < 0.0)
                {
                return found;
                }
            }
            for(i=0; i<n; i++)											// Verifica passi (almeno 1 per lato)
            {
            if(passiU.Get(i,0) < 1)
                {
                return found;
                }
            }
            MatrixBase<int> passi = new MatrixBase<int>(n,1);			// Matrice dei passi
            for(i=0; i<n; i++)											// Calcola i passi effettivi (segmenti, non punti)
            {
            passi.Set(i, 0, passiU.Get(i,0) * 2);
            }
            Matrix step = new Matrix(n,1);
            for(i=0; i<n; i++)											// Calcola i passi effettivi
            {
            step.Set(i, 0, range.Get(i,0)/passi.Get(i,0));
            }
            Matrix xo = new Matrix(n,1);
            for(i=0; i<n; i++)											// Calcola i punti di partenza
            {
            xo.Set(i, 0, xk.Get(i,0) - step.Get(i,0) * passiU.Get(i,0));
            }
            MatrixBase<int> contatori = new MatrixBase<int>(n,1,0);		// Vettore dei contatotri (tutti a 0)
            Matrix x = new Matrix(n,1);									// Vettore dei valori effettivi
            int iinc = -1;
            double minimo = double.MaxValue;
            double f;
            cicli = 0;
            bool fine = false;
            while(!fine)
            {
            if(iinc >= 0)											// ricalcola nuovo vettore x
                {
                x.Set(	iinc,0, xo.Get(iinc,0) + step.Get(iinc,0) * contatori.Get(iinc,0) );
                }
            else
                {
                for(i=0; i<n; i++)
                    x.Set(	i,0, xo.Get(i,0) + step.Get(i,0) * contatori.Get(i,0) );
                }
            f = Funzione(x);										// Calcola la f del punto x attuale
            if(f < minimo)											// Vede se e` minima (rispetto ai valori trovati finora)
                {
                minimo = f;
                xmin = x.Copy();
                found = true;
                }
            fine = !Incrementa(ref contatori, passi, ref iinc);
            cicli++;
            }
            return found;
        }
Exemplo n.º 37
0
 // Fattorizza la matrice A con il metodo di Gauss con pivoting parziale
 public bool Factor(Matrix A)
 {
     int n;													// Dimensione matrice
     if (A.Row != A.Col)										// Verifica che A sia quadrata
         return false;
     n = A.Row;												// Legge dimensione
     if (n < 1)												// Verifica dimensione
         return false;
     pivot = new MatrixBase<int>(n - 1, 1);					// Inizializza dimensioni matrici
     a = new Matrix(A, true);								// Crea nuova matrice idntica ad A
     if (n == 1)												// Se di ordine 1...
         {
         det = a[0,0];
         if( System.Math.Abs(det) <= LinearSys.Epsilon)		// Se det nullo, esce con errore
             return false;
         return true;										// Se det non nullo, esce regolarmente
         }
     int k, i, io, j;										// Ciclo di calcolo
     double amax;
     double tmp;
     for(io = 0, det = Matrix.One, k = 0; k < n-1; k++)		// Ciclo 1
         {
         for(amax=0.0, i=k; i<n; i++)						// Cerca la riga io con il massimo amax sulla colonna k
             if(System.Math.Abs(a[i,k]) >= amax )
                 {
                 io = i;
                 amax = System.Math.Abs(a[i,k]);
                 }
         pivot[k,0] = io;
         if (amax <= LinearSys.Epsilon)						// Se amax è nullo, esce con errore
             {
             det = 0.0;
             return false;
             }
         if(io != k)											// Se l'indice non è k...
             {
             for(j = k; j < n; j++)							// Scambia le righe k e io
                 {
                 tmp = a[k, j];
                 a[k,j] = a[io, j];
                 a[io, j] = tmp;
                 }
             det = -det;										// e cambia segno al determinante
             }
         for(i=k+1; i<n; i++)								// Ciclo 2
             {
             a[i, k] =  - a[i,k] / a[k,k];
             for(j = k+1; j < n; j++)
                 {
                 a[i, j] = a[i,j] + a[i,k]*a[k,j];
                 }
             }												// Fine ciclo 2
         det = det * a[k,k];
         }													// Fine ciclo 1
     if (System.Math.Abs(a[n - 1, n - 1]) <= LinearSys.Epsilon)
         {
         det = 0.0;
         return false;
         }
     det = det * a[n-1, n-1];
     return true;
 }