//-----------------------------------------------------------------------------------------------
        //Приведение значений матрицы к интервалу
        public static IntegerMatrix TransformMatrixValuesToFinishIntervalValues(
            IntegerMatrix matrix, Interval <double> finishInterval
            )
        {
            double minValue = matrix.GetMinValue();
            double maxValue = matrix.GetMaxValue();

            Interval <double>     startInterval     = new Interval <double>(minValue, maxValue);
            RealIntervalTransform intervalTransform =
                new RealIntervalTransform(startInterval, finishInterval);

            int           rowCount          = matrix.RowCount;
            int           columnCount       = matrix.ColumnCount;
            IntegerMatrix transformedMatrix = new IntegerMatrix(rowCount, columnCount);

            for (int row = 0; row < rowCount; row++)
            {
                for (int column = 0; column < columnCount; column++)
                {
                    double value            = matrix[row, column];
                    double transformedValue =
                        intervalTransform.TransformToFinishIntervalValue(value);
                    transformedMatrix[row, column] = Convert.ToInt32(transformedValue);
                }
            }
            return(transformedMatrix);
        }
Beispiel #2
0
        public static IntegerMatrix CreateIntegerMatrix(this REngine engine, Raster raster)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }
            if (!engine.IsRunning)
            {
                throw new InvalidOperationException();
            }
            if (raster == null)
            {
                throw new ArgumentNullException("raster");
            }

            var width  = raster.Width;
            var height = raster.Height;
            var matrix = new IntegerMatrix(engine, height, width);

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    matrix[x, y] = ToInteger(raster[x, y]);
                }
            }

            return(matrix);
        }
Beispiel #3
0
        public static IntegerMatrix CreateIntegerMatrix(this REngine engine, Raster raster)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }
            if (!engine.IsRunning)
            {
                throw new InvalidOperationException();
            }
            if (raster == null)
            {
                throw new ArgumentNullException("raster");
            }

            var width = raster.Width;
            var height = raster.Height;
            var matrix = new IntegerMatrix(engine, height, width);
            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    matrix[x, y] = ToInteger(raster[x, y]);
                }
            }

            return matrix;
        }
        //-------------------------------------------------------------------------------------------------
        //Ортогональный вектор
        public IntegerVector GetOrthogonalVector()
        {
            IntegerMatrix transformatingMatrix = this.CreateOrthogonalVectorTransformingMatrix(this.Size);
            IntegerVector orthogonalVector     = transformatingMatrix * this;

            return(orthogonalVector);
        }
        //-----------------------------------------------------------------------------------------------
        //Преобразование значений матрицы по шаблону
        public static IntegerMatrix TransformMatrixValues(
            IntegerMatrix matrix, BitMask2D stencilMatrix,
            RealIntervalTransform intervalTransform, int prickedValue
            )
        {
            int           rowCount          = matrix.RowCount;
            int           columnCount       = matrix.ColumnCount;
            IntegerMatrix transformedMatrix = new IntegerMatrix(rowCount, columnCount);

            for (int row = 0; row < rowCount; row++)
            {
                for (int column = 0; column < columnCount; column++)
                {
                    if (stencilMatrix[row, column] == true)
                    {
                        double value            = matrix[row, column];
                        double transformedValue =
                            intervalTransform.TransformToFinishIntervalValue(value);
                        transformedMatrix[row, column] = Convert.ToInt32(transformedValue);
                    }
                    else
                    {
                        transformedMatrix[row, column] = prickedValue;
                    }
                }
            }
            return(transformedMatrix);
        }
        //------------------------------------------------------------------------------------------------
        //Создание изображения из матриц R G B
        public static WriteableBitmap CreateWriteableBitmapFromMatricesRGB(
            IntegerMatrix redMatrix, IntegerMatrix greenMatrix, IntegerMatrix blueMatrix,
            int dpiX, int dpiY
            )
        {
            int             width       = redMatrix.ColumnCount;
            int             height      = redMatrix.RowCount;
            PixelFormat     pixelFormat = PixelFormats.Bgra32;
            WriteableBitmap newImage    = WriteableBitmapCreator.CreateWriteableBitmap
                                              (width, height, dpiX, dpiY, pixelFormat);
            WriteableBitmapWrapper wrapper = WriteableBitmapWrapper.Create(newImage);

            byte[] pixelBytes     = new byte[4 * width * height]; //BGRA
            int    pixelByteIndex = 0;

            for (int y = 0; y < newImage.PixelHeight; y++)
            {
                for (int x = 0; x < newImage.PixelWidth; x++)
                {
                    pixelBytes[pixelByteIndex++] = Convert.ToByte(blueMatrix[y, x]);
                    pixelBytes[pixelByteIndex++] = Convert.ToByte(greenMatrix[y, x]);
                    pixelBytes[pixelByteIndex++] = Convert.ToByte(redMatrix[y, x]);
                    pixelBytes[pixelByteIndex++] = byte.MaxValue;
                }
            }

            wrapper.WritePixels(pixelBytes);

            return(newImage);
        }
        public static void CreateFromFile(string expr, List <Exception> exceptionsList, SortedList <string, Graph> graphsList, RichTextBox output)
        {
            try
            {
                int    startIndex  = expr.IndexOf("\"") + 1;
                int    endIndex    = expr.IndexOf("\")");
                string path        = expr.Substring(startIndex, endIndex - startIndex);
                string name        = expr.Contains(":=") ? expr.Substring(0, expr.IndexOf(":=")) : "";
                var    graphMatrix = new IntegerSquareMatrix(IntegerMatrix.GetFromFile(path));


                if (graphMatrix.Columns == 0)
                {
                    exceptionsList.Add(new FormatException("Incorrect matrix size in file"));
                }

                var graph = new Graph(graphMatrix, name);
                graphsList.Add(name, graph);
                output.Text = graph.ToString();
            }
            catch (Exception e)
            {
                exceptionsList.Add(e);
                output.Text += e.Message;
            }
        }
Beispiel #8
0
        public void Integer_Matrix_Construction_Size_Test()
        {
            //Arrange
            int           row = rand.Next(1, 10);
            int           col = rand.Next(1, 10);
            IntegerMatrix m1  = new IntegerMatrix(row, col);

            //Act

            //Assert
            Assert.AreEqual(m1.RowSize, row);
            Assert.AreEqual(m1.ColumnSize, col);
        }
Beispiel #9
0
        public void Integer_Matrix_Value_Change_Test()
        {
            //Arrange
            int           row      = rand.Next(1, 10);
            int           col      = rand.Next(1, 10);
            int           rowIndex = rand.Next(1, row - 1);
            int           colIndex = rand.Next(1, col - 1);
            IntegerMatrix m1       = new IntegerMatrix(row, col);

            //Act
            m1.Replace(rowIndex, colIndex, 5); //value doesnt matter just cant be zero
            //Assert
            Assert.AreEqual(m1.Get(rowIndex, colIndex), 5);
        }
        //---------------------------------------------------------------------------------------
        //Преобразвание значений матрицы
        public static IntegerMatrix TransformMatrixValues(IntegerMatrix matrix, LogTransform logTransform)
        {
            IntegerMatrix newMatrix = new IntegerMatrix(matrix.RowCount, matrix.ColumnCount);

            for (int row = 0; row < matrix.RowCount; row++)
            {
                for (int column = 0; column < matrix.ColumnCount; column++)
                {
                    double newValue = logTransform.GetLogTransform(matrix[row, column]);
                    newMatrix[row, column] = Convert.ToInt32(newValue);
                }
            }
            return(newMatrix);
        }
Beispiel #11
0
        public void Matrix_Transpose_Test()
        {
            //Arrange
            IntegerMatrix m1 = GenerateRandomIntegerMatrix();
            IntegerMatrix m2 = (IntegerMatrix)m1.GetTranspose();

            for (int i = 0; i < m1.RowSize; i++)
            {
                for (int j = 0; j < m1.ColumnSize; j++)
                {
                    Assert.AreEqual(m1.Get(i, j), m2.Get(j, i));
                }
            }
        }
Beispiel #12
0
        private Random rand = new Random(); //TODO: Figure out whether to keep the same seed every time or not.

        public IntegerMatrix GenerateRandomIntegerMatrix()
        {
            int           row = rand.Next(1, 10);
            int           col = rand.Next(1, 10);
            IntegerMatrix ret = new IntegerMatrix(row, col);

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    ret.Replace(i, j, rand.Next(9, 255));
                }
            }
            return(ret);
        }
        public static IntegerMatrix GetRedMatrix(IntegerMatrix scanDataMatrix)
        {
            IntegerMatrix resMatrix = new IntegerMatrix(scanDataMatrix.RowCount, scanDataMatrix.ColumnCount);

            for (int row = 0; row < scanDataMatrix.RowCount; row++)
            {
                for (int column = 0; column < scanDataMatrix.ColumnCount; column++)
                {
                    ComponentEnum component = BayerMatrixHelper.GetComponent(row, column);
                    if (component == ComponentEnum.Red)
                    {
                        resMatrix[row, column] = scanDataMatrix[row, column];
                    }
                    if (component == ComponentEnum.Green1)
                    {
                        ComponentLocationEnum[] locations = new ComponentLocationEnum[]
                        {
                            ComponentLocationEnum.West,
                            ComponentLocationEnum.East
                        };
                        resMatrix[row, column] = InterpolateValue(scanDataMatrix, row, column, locations);
                    }
                    if (component == ComponentEnum.Green2)
                    {
                        ComponentLocationEnum[] locations = new ComponentLocationEnum[]
                        {
                            ComponentLocationEnum.Nord,
                            ComponentLocationEnum.South
                        };
                        resMatrix[row, column] = InterpolateValue(scanDataMatrix, row, column, locations);
                    }
                    if (component == ComponentEnum.Blue)
                    {
                        ComponentLocationEnum[] locations = new ComponentLocationEnum[]
                        {
                            ComponentLocationEnum.NordWest,
                            ComponentLocationEnum.NordEast,
                            ComponentLocationEnum.SouthWest,
                            ComponentLocationEnum.SouthEast
                        };
                        resMatrix[row, column] = InterpolateValue(scanDataMatrix, row, column, locations);
                    }
                }
            }

            return(resMatrix);
        }
Beispiel #14
0
        public void Row_Append_Test()
        {
            //Arrange
            IntegerMatrix m1  = GenerateRandomIntegerMatrix();
            int           col = rand.Next(1, 10);
            IntegerMatrix m2  = new IntegerMatrix(m1.RowSize, col);
            //Act
            IntegerMatrix m3 = (IntegerMatrix)m1.AppendByRow(m2);

            //Assert
            for (int i = 0; i < m1.RowSize; i++)
            {
                for (int j = m1.ColumnSize; j < m3.ColumnSize; j++)
                {
                    Assert.AreEqual(m3.Get(i, j), 0);
                }
            }
        }
Beispiel #15
0
        public void Column_Append_Test()
        {
            //Arrange
            IntegerMatrix m1  = GenerateRandomIntegerMatrix();
            int           row = rand.Next(1, 10);
            IntegerMatrix m2  = new IntegerMatrix(row, m1.ColumnSize);
            //Act
            IntegerMatrix m3 = (IntegerMatrix)m1.AppendByColumn(m2);

            //Assert
            for (int i = m1.RowSize; i < m3.RowSize; i++)
            {
                for (int j = 0; j < m1.ColumnSize; j++)
                {
                    Assert.AreEqual(m3.Get(i, j), 0);
                }
            }
        }
Beispiel #16
0
        public IntegerMatrix Power(IntegerMatrix value, int n)
        {
            if (n == 0)
            {
                return(value);
            }

            if (n % 2 == 0)
            {
                var halfValue = Power(value, n / 2);
                return(halfValue * halfValue);
            }
            else
            {
                var halfValue = Power(value, n / 2);
                return(halfValue * halfValue * value);
            }
        }
        private static int InterpolateValue(IntegerMatrix matrix, int row, int column, ComponentLocationEnum[] locationsArray)
        {
            int    count    = 0;
            int    resValue = 0;
            double sum      = 0;

            for (int k = 0; k < locationsArray.Length; k++)
            {
                int?value = BayerMatrixHelper.GetComponentValue(matrix, row, column, locationsArray[k]);
                if (value.HasValue)
                {
                    sum += value.Value;
                    count++;
                }
            }
            resValue = Convert.ToInt32(sum / count);
            return(resValue);
        }
        //-------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------
        //Матрица преобразования для вычисления ортогонального вектора
        private IntegerMatrix CreateOrthogonalVectorTransformingMatrix(int size)
        {
            IntegerMatrix transformingMatrix = new IntegerMatrix(size, size);

            for (int column = 1, row = 0; column < size; column++, row++)
            {
                transformingMatrix[row, column] = 1;
            }

            for (int row = 1, column = 0; row < size; row++, column++)
            {
                transformingMatrix[row, column] = -1;
            }

            transformingMatrix[size - 1, 0] = 1;
            transformingMatrix[0, size - 1] = -1;

            return(transformingMatrix);
        }
Beispiel #19
0
        public static void Main(string[] args)
        {
            Random        rand = new Random();
            IntegerMatrix m1   = new IntegerMatrix(2, 3);

            m1.Replace(1, 1, 5);
            Console.WriteLine(m1.ToString());
            IntegerMatrix m2 = new IntegerMatrix(2, 3);

            m2.Replace(0, 2, 15);
            IntegerMatrix m3 = (IntegerMatrix)m1.AppendByRow(m2);
            IntegerMatrix m4 = (IntegerMatrix)m1.AppendByColumn(m2);

            Console.WriteLine(m3.ToString());
            Console.WriteLine(m4.ToString());
            SquareIntegerMatrix sq1 = new SquareIntegerMatrix(3);
            SquareIntegerMatrix sq2 = new SquareIntegerMatrix(3);

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    sq1.Replace(i, j, rand.Next(0, 10));
                    sq2.Replace(i, j, rand.Next(0, 10));
                }
            }
            Console.WriteLine(sq1.ToString());
            Console.WriteLine(sq2.ToString());
            SquareIntegerMatrix prod1 = sq1.Multiply(sq2);

            Console.WriteLine(prod1.ToString());
            IntegerMatrix minor1 = prod1.GetMinor(0);
            IntegerMatrix minor2 = prod1.GetMinor(1);
            IntegerMatrix minor3 = prod1.GetMinor(2);

            Console.WriteLine(minor1);
            Console.WriteLine(minor2);
            Console.WriteLine(minor3);
            TestAlgebra();
            Console.Read();
        }
Beispiel #20
0
        private void button1_Click(object sender, EventArgs e)
        {
            REngine.SetEnvironmentVariables();

            REngine cluster = REngine.GetInstance();

            cluster.Initialize();
            //try
            //{
            cluster.Evaluate("cluster = read.table(file.choose())");
            cluster.Evaluate("cluster <- as.matrix(cluster)");
            IntegerMatrix clusterinfo = cluster.GetSymbol("cluster").AsIntegerMatrix();


            app.cluster = new int[clusterinfo.AsNumericMatrix().ToArray().GetLength(1)];
            for (int i = 0; i < app.cluster.Length; i++)
            {
                app.cluster[i] = clusterinfo[0, i];
            }

            //foreach (var item in Enumerable.Range(0, clusterinfo.AsNumericMatrix().ToArray().GetLength(0) * clusterinfo.AsNumericMatrix().ToArray().GetLength(1)).Select(i => new { x = i / clusterinfo.AsNumericMatrix().ToArray().GetLength(1), y = i % clusterinfo.AsNumericMatrix().ToArray().GetLength(1) }))
            //{
            //    app.cluster[item.x, item.y] = (int)clusterinfo.AsNumericMatrix().ToArray()[item.x, item.y];
            //}
            //}

            //try
            //{
            //    StatConnector factor = new STATCONNECTORSRVLib.StatConnectorClass();
            //    factor.Init("R");
            //    factor.EvaluateNoReturn("cluster = read.table(file.choose())");
            //    factor.Evaluate("cluster <- as.matrix(cluster)");
            //    object temp = factor.GetSymbol("cluster");
            //    app.cluster = (int[,])temp;
            //}
            //catch { }
        }
        //------------------------------------------------------------------------------------------------
        //Создание изображения из матрицы интенсивностей серого
        public static WriteableBitmap CreateGrayScaleWriteableBitmapFromMatrix(
            IntegerMatrix grayScaleMatrix,
            int dpiX, int dpiY
            )
        {
            int             pixelWidth      = grayScaleMatrix.ColumnCount;
            int             pixelHeight     = grayScaleMatrix.RowCount;
            WriteableBitmap writeableBitmap = WriteableBitmapCreator.CreateWriteableBitmap
                                                  (pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Bgra32);
            WriteableBitmapWrapper bitmapWrapper = WriteableBitmapWrapper.Create(writeableBitmap);

            for (int x = 0; x < pixelWidth; x++)
            {
                for (int y = 0; y < pixelHeight; y++)
                {
                    int  grayIntensity = grayScaleMatrix[y, x];
                    byte red, green, blue;
                    red = green = blue = Convert.ToByte(grayIntensity);
                    Color color = Color.FromRgb(red, green, blue);
                    bitmapWrapper.SetPixelColor(x, y, color);
                }
            }
            return(writeableBitmap);
        }
Beispiel #22
0
 /// <summary>
 /// Аналог GetFromFile в <see cref="IntegerMatrix"/>
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static Graph GetFromFile(string path)
 {
     Arithmetics.Matrix.IntegerSquareMatrix graphMatrix = (IntegerSquareMatrix)IntegerMatrix.GetFromFile(path);
     if (graphMatrix.Columns == 0)
     {
         return(null);
     }
     return(new Graph(graphMatrix));
 }
Beispiel #23
0
        private void CreateClick()
        {
            OpenFileDialog dialog = new OpenFileDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.FileName;


                Arithmetics.Matrix.IntegerSquareMatrix graphMatrix = (IntegerSquareMatrix)IntegerMatrix.GetFromFile(path);
                if (graphMatrix.Columns == 0)
                {
                    return;
                }
                string name = Interaction.InputBox("Введите имя графа", "", "");
                if (graphs.ContainsKey(name) == false)
                {
                    Graph NewGraph = new Graph(graphMatrix);
                    graphs.Add(name, NewGraph);
                    activeGraph       = name;
                    richTextBox1.Text = "";
                    richTextBox1.Text = graphs[activeGraph].ToString();
                    graphsToolStripMenuItem.DropDownItems.Add(name);

                    DialogResult result = MessageBox.Show("Граф " + name + " успешно добавлен");
                }
                else
                {
                    DialogResult result = MessageBox.Show("Граф c таким именем уже существует");
                }
            }
        }
Beispiel #24
0
        public static int?GetComponentValue(

            IntegerMatrix matrix,
            int rowIndex, int columnIndex,
            ComponentLocationEnum componentLocation
            )
        {
            int targetRow    = 0;
            int targetColumn = 0;

            int? resValue  = null;
            bool isCorrect = true;

            switch (componentLocation)
            {
            case ComponentLocationEnum.Nord:
            {
                targetRow    = rowIndex - 1;
                targetColumn = columnIndex;
                isCorrect    = targetRow >= 0;
                break;
            }

            case ComponentLocationEnum.East:
            {
                targetRow    = rowIndex;
                targetColumn = columnIndex + 1;
                isCorrect    = targetColumn < matrix.ColumnCount;
                break;
            }

            case ComponentLocationEnum.South:
            {
                targetRow    = rowIndex + 1;
                targetColumn = columnIndex;
                isCorrect    = targetRow < matrix.RowCount;
                break;
            }

            case ComponentLocationEnum.West:
            {
                targetRow    = rowIndex;
                targetColumn = columnIndex - 1;
                isCorrect    = targetColumn >= 0;
                break;
            }

            case ComponentLocationEnum.NordWest:
            {
                targetRow    = rowIndex - 1;
                targetColumn = columnIndex - 1;
                isCorrect    = targetRow >= 0 && targetColumn >= 0;
                break;
            }

            case ComponentLocationEnum.NordEast:
            {
                targetRow    = rowIndex - 1;
                targetColumn = columnIndex + 1;
                isCorrect    = targetRow >= 0 && targetColumn < matrix.ColumnCount;
                break;
            }

            case ComponentLocationEnum.SouthEast:
            {
                targetRow    = rowIndex + 1;
                targetColumn = columnIndex + 1;
                isCorrect    = targetRow < matrix.RowCount && targetColumn < matrix.ColumnCount;
                break;
            }

            case ComponentLocationEnum.SouthWest:
            {
                targetRow    = rowIndex + 1;
                targetColumn = columnIndex - 1;
                isCorrect    = targetRow < matrix.RowCount && targetColumn >= 0;
                break;
            }
            }

            if (isCorrect)
            {
                resValue = matrix[targetRow, targetColumn];
            }
            else
            {
                resValue = null;
            }

            return(resValue);
        }
        //------------------------------------------------------------------------------------------------
        //------------------------------------------------------------------------------------------------

        /*
         * //Создание изображения из файла
         * public static WriteableBitmap CreateWriteableBitmapFromFile( string fileName, double dpiX, double dpiY ) {
         *  System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( fileName );
         *
         *  //System.Windows.Media.PixelFormat targetPixelFormat = PixelFormats.Rgba64;
         *  System.Windows.Media.PixelFormat targetPixelFormat = PixelFormats.Pbgra32;
         *
         *  WriteableBitmap writeableBitmap =
         *      new WriteableBitmap( bitmap.Width, bitmap.Height, dpiX, dpiY, targetPixelFormat, null );
         *
         *  //WriteableBitmap writeableBitmap =
         *  //    new WriteableBitmap( bitmap.Width, bitmap.Height, dpiX, dpiY, PixelFormats.Rgba64, null );
         *
         *  System.Drawing.Rectangle rect = new System.Drawing.Rectangle( 0, 0, bitmap.Width, bitmap.Height );
         *  System.Drawing.Imaging.ImageLockMode lockMode = System.Drawing.Imaging.ImageLockMode.ReadOnly;
         *
         *  System.Drawing.Imaging.PixelFormat pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
         *  //System.Drawing.Imaging.PixelFormat pixelFormat = System.Drawing.Imaging.PixelFormat.Format64bppArgb;
         *  //System.Drawing.Imaging.PixelFormat pixelFormat = System.Drawing.Imaging.PixelFormat.Format16bppGrayScale;
         *
         *  System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits( rect, lockMode, pixelFormat );
         *  Int32Rect int32Rect = new System.Windows.Int32Rect( 0, 0, bitmapData.Width, bitmapData.Height );
         *
         *  writeableBitmap.WritePixels
         *      ( int32Rect, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride );
         *  bitmap.UnlockBits( bitmapData );
         *  bitmap.Dispose();
         *
         *  return writeableBitmap;
         * }
         */
        //------------------------------------------------------------------------------------------------
        public static ExtraImageInfo CreateWriteableBitmapFromFile(string fileName, double dpiX, double dpiY)
        {
            //public static WriteableBitmap CreateWriteableBitmapFromFile( string fileName, double dpiX, double dpiY ) {

            /*
             * if ( fileName.ToUpper().EndsWith( "CR2" ) ) {
             *
             *  MagickImage magicImage = new MagickImage( fileName );
             *
             *  int width = magicImage.Width;
             *  int height = magicImage.Height;
             *  PixelFormat pixelFormat = PixelFormats.Bgra32;
             *
             *  WriteableBitmap resultWriteableBitmap =
             *      WriteableBitmapCreator.CreateWriteableBitmap( width, height, (int)dpiX, (int)dpiY, pixelFormat );
             *  WriteableBitmapWrapper imageWrapper = WriteableBitmapWrapper.Create( resultWriteableBitmap );
             *
             *  PixelCollection pixelCollection = magicImage.GetPixels();
             *
             *  Interval<double> interval1 = new Interval<double>( 0, ushort.MaxValue );
             *  Interval<double> interval2 = new Interval<double>( 0, byte.MaxValue );
             *  RealIntervalTransform intervalTransform = new RealIntervalTransform( interval1, interval2 );
             *
             *  RealMatrix redMatrix = new RealMatrix( height, width );
             *
             *  for ( int x = 0; x < width; x++ ) {
             *      for ( int y = 0; y < height; y++ ) {
             *          Pixel pixel = pixelCollection.GetPixel(x, y);
             *          MagickColor magicColor = pixel.ToColor();
             *
             *          redMatrix[ y, x ] = intervalTransform.TransformToFinishIntervalValue(magicColor.R);
             *
             *          byte a = Convert.ToByte( intervalTransform.TransformToFinishIntervalValue( magicColor.A ) );
             *          byte r = Convert.ToByte( intervalTransform.TransformToFinishIntervalValue( magicColor.R ) );
             *          byte g = Convert.ToByte( intervalTransform.TransformToFinishIntervalValue( magicColor.G ) );
             *          byte b = Convert.ToByte( intervalTransform.TransformToFinishIntervalValue( magicColor.B ) );
             *
             *          Color color = Color.FromArgb( a, r, g, b );
             *
             *          imageWrapper.SetPixelColor( x, y, color );
             *      }
             *  }
             *
             *  ExtraImageInfo extraImageInfo = new ExtraImageInfo();
             *  extraImageInfo.RedMatrix = redMatrix;
             *  extraImageInfo.Image = resultWriteableBitmap;
             *
             *  //return resultWriteableBitmap;
             *  return extraImageInfo;
             *
             * }
             */

            /*
             * if ( fileName.ToUpper().EndsWith( "CR2" ) ) {
             *
             *
             *  //System.GC.Collect();
             *
             *  //BitmapDecoder bitmapDecoder =
             *  //    BitmapDecoder.Create( new Uri( fileName ),
             *  //    BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None );
             *
             *  //BitmapFrame frame = bitmapDecoder.Frames[ 0 ];
             *
             *  //WriteableBitmap bitmap = new WriteableBitmap( frame );
             *  //WriteableBitmapWrapper wrapper = WriteableBitmapWrapper.Create( bitmap );
             *
             *  //Color c = wrapper.GetPixelColor( 300, 300 );
             *
             *
             *  System.GC.Collect();
             *
             *  uint error;
             *
             *  IntPtr imgRef;
             *  //Open image
             *  IntPtr inStream;
             *  error = EDSDK.EdsCreateFileStream(fileName, EDSDK.EdsFileCreateDisposition.OpenExisting, EDSDK.EdsAccess.Read, out inStream);
             *  EDSDK.EdsCreateImageRef(inStream, out imgRef);
             *  EDSDK.EdsRelease(inStream);
             *
             *  string convertedFileName = Path.ChangeExtension(fileName, "TIFF");
             *
             *  //Save image
             *  IntPtr outStream;
             *  var settings = new EDSDK.EdsSaveImageSetting();
             *  error = EDSDK.EdsCreateFileStream(convertedFileName, EDSDK.EdsFileCreateDisposition.CreateAlways, EDSDK.EdsAccess.Write, out outStream);
             *  error = EDSDK.EdsSaveImage(imgRef, EDSDK.EdsTargetImageType.TIFF16, settings, outStream);
             *  EDSDK.EdsRelease(outStream);
             *
             *  ExtraImageInfo extraImageInfo = new ExtraImageInfo();
             *  return extraImageInfo;
             *
             * }
             */
            if (fileName.ToUpper().EndsWith("CR2"))
            {
                Interval <double> finishInterval = new Interval <double>(0, 255);

                IntegerMatrix matrix = RawReader.ReadImageFromFile(fileName);
                //matrix = matrix.GetSubMatrix(0, 2640 - 1, matrix.RowCount - 1, matrix.ColumnCount - 1);


                int min = matrix.GetMinValue();
                int max = matrix.GetMaxValue();

                IntegerMatrix redMatrix = InterpolationHelper.GetRedMatrix(matrix);
                int           minRed    = redMatrix.GetMinValue();
                int           maxRed    = redMatrix.GetMaxValue();

                IntegerMatrix greenMatrix = InterpolationHelper.GetGreenMatrix(matrix);
                int           minGreen    = greenMatrix.GetMinValue();
                int           maxGreen    = greenMatrix.GetMaxValue();

                IntegerMatrix blueMatrix = InterpolationHelper.GetBlueMatrix(matrix);
                int           minBlue    = blueMatrix.GetMinValue();
                int           maxBlue    = blueMatrix.GetMaxValue();

                int minValue = (new int[] { minRed, minGreen, minBlue }).Min();
                int maxValue = (new int[] { maxRed, maxGreen, maxBlue }).Max();

                RealIntervalTransform redIntervalTransform =
                    new RealIntervalTransform(new Interval <double>(minValue, maxValue), finishInterval);
                IntegerMatrix resRedMatrix =
                    IntegerMatrixValuesTransform.TransformMatrixValues(redMatrix, redIntervalTransform);

                RealIntervalTransform greenIntervalTransform =
                    new RealIntervalTransform(new Interval <double>(minValue, maxValue), finishInterval);
                IntegerMatrix resGreenMatrix =
                    IntegerMatrixValuesTransform.TransformMatrixValues(greenMatrix, greenIntervalTransform);

                RealIntervalTransform blueIntervalTransform =
                    new RealIntervalTransform(new Interval <double>(minValue, maxValue), finishInterval);
                IntegerMatrix resBlueMatrix =
                    IntegerMatrixValuesTransform.TransformMatrixValues(blueMatrix, blueIntervalTransform);

                WriteableBitmap resImage =
                    WriteableBitmapCreator.CreateWriteableBitmapFromMatricesRGB
                        (resRedMatrix, resGreenMatrix, resBlueMatrix, OS.OS.IntegerSystemDpiX, OS.OS.IntegerSystemDpiY);

                /*
                 * IntegerMatrix resMatrix =
                 *  IntegerMatrixValuesTransform.TransformMatrixValuesToFinishIntervalValues(matrix, finishInterval);
                 *
                 * WriteableBitmap resImage =
                 *  WriteableBitmapCreator.CreateGrayScaleWriteableBitmapFromMatrix
                 *  (resMatrix, OS.OS.IntegerSystemDpiX, OS.OS.IntegerSystemDpiY);
                 */

                ExtraImageInfo extraImageInfo = new ExtraImageInfo();
                extraImageInfo.Image = resImage;

                return(extraImageInfo);
            }

            else
            {
                Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

                BitmapDecoder decoder      = BitmapDecoder.Create(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource  bitmapSource = decoder.Frames[0];

                WriteableBitmap resultWriteableBitmap = new WriteableBitmap(bitmapSource);

                ExtraImageInfo extraImageInfo = new ExtraImageInfo();
                extraImageInfo.Image = resultWriteableBitmap;

                return(extraImageInfo);
            }
        }
        public static IntegerMatrix ReadScanData(byte[] scanDataBytes, DhtHeader dhtHeader, Sof3Header sof3Header, SosHeader sosHeader, UInt16[] slices)
        {
            int           columnsCount = GetImageWidth(slices);
            int           rowsCount = sof3Header.LinesNumber;
            int           rowIndex = 0, columnIndex = 0;
            IntegerMatrix resMatrix = new IntegerMatrix(rowsCount, columnsCount);

            ushort normalSliceWidth = slices[1];

            List <int> decompressionValueList = new List <int>();

            Dictionary <string, byte>[] huffmanCodeValueMapsArray = RawReader.GetHuffmanCodeValueMapsArray(dhtHeader);

            BitArray scanDataBitArray = RawReader.GetScanDataBitArray(scanDataBytes);

            int      index = 0, huffmanCodeIndex = 0;
            BitArray huffmanCodeBitArray = new BitArray(1);
            string   huffmanCodeString   = null;
            byte     huffmanValue        = 0;

            int componentIndex = 0;
            int componentValueIndex = 0, componentValue = 0;

            int[] previousComponentValues = RawReader.GetInitialComponentValues(sof3Header);

            int lastIndex = GetLastDecompressionValueIndex(sof3Header, slices);
            int lastSliceFirstDecompressionValueIndex = GetLastSliceFirstDecompressionValueIndex(sof3Header, slices);
            int sliceSize = slices[1] * sof3Header.LinesNumber;

            Dictionary <string, byte> huffmanCodeValueMap = huffmanCodeValueMapsArray[GetHuffmanTableIndex(rowIndex, columnIndex, sosHeader)];

            while (componentValueIndex <= lastIndex && index < scanDataBitArray.Length)
            {
                huffmanCodeBitArray[huffmanCodeIndex] = scanDataBitArray[index];
                huffmanCodeString = huffmanCodeBitArray.ToBitString();

                if (huffmanCodeValueMap.TryGetValue(huffmanCodeString, out huffmanValue))
                {
                    int differenceCodeValue = 0;

                    index++;
                    if (huffmanValue > 0)
                    {
                        //Read difference code
                        int finalIndex = index + huffmanValue - 1;
                        differenceCodeValue = GetDifferenceCodeValue(scanDataBitArray, index, finalIndex, huffmanValue);
                        index = finalIndex + 1;
                    }
                    else
                    {
                        differenceCodeValue = 0;
                    }

                    componentValue = previousComponentValues[componentIndex] + differenceCodeValue;
                    previousComponentValues[componentIndex] = componentValue;

                    decompressionValueList.Add(componentValue);
                    resMatrix[rowIndex, columnIndex] = componentValue;
                    componentValueIndex++;

                    huffmanCodeBitArray = new BitArray(1);
                    huffmanCodeIndex    = 0;

                    rowIndex    = GetNextRowIndex(componentValueIndex, lastSliceFirstDecompressionValueIndex, sliceSize, slices);
                    columnIndex = GetNextColumnIndex(componentValueIndex, lastSliceFirstDecompressionValueIndex, sliceSize, slices);

                    huffmanCodeValueMap = huffmanCodeValueMapsArray[GetHuffmanTableIndex(rowIndex, columnIndex, sosHeader)];

                    bool initComponentValuesRequired =
                        (columnIndex == 0) ||
                        ((columnIndex > 0) && (columnIndex % normalSliceWidth == 0));

                    if (initComponentValuesRequired)
                    {
                        previousComponentValues = GetInitialComponentValues(sof3Header);
                    }

                    componentIndex = GetComponentIndex(rowIndex, columnIndex);
                }
                else
                {
                    //Read huffman code
                    index++;
                    huffmanCodeIndex++;
                    huffmanCodeBitArray.Length++;
                }
            }

            return(resMatrix);
        }
        /// <summary>
        /// Converts the specified expression to an IntegerMatrix.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>The IntegerMatrix. Returns <c>null</c> if the specified expression is not vector.</returns>
        public static IntegerMatrix AsIntegerMatrix(this SymbolicExpression expression)
        {
            if (!expression.IsVector())
            {
                return null;
            }

            int rowCount = 0;
            int columnCount = 0;

            if (expression.IsMatrix())
            {
                if (expression.Type == SymbolicExpressionType.IntegerVector)
                {
                    return new IntegerMatrix(expression.Engine, expression.DangerousGetHandle());
                }
                else
                {
                    rowCount = expression.GetFunction<Rf_nrows>()(expression.DangerousGetHandle());
                    columnCount = expression.GetFunction<Rf_ncols>()(expression.DangerousGetHandle());
                }
            }

            if (columnCount == 0)
            {
                rowCount = expression.GetFunction<Rf_length>()(expression.DangerousGetHandle());
                columnCount = 1;
            }

            IntPtr coerced = expression.GetFunction<Rf_coerceVector>()(expression.DangerousGetHandle(), SymbolicExpressionType.IntegerVector);
            var dim = new IntegerVector(expression.Engine, new[] { rowCount, columnCount });
            SymbolicExpression dimSymbol = expression.Engine.GetPredefinedSymbol("R_DimSymbol");
            var matrix = new IntegerMatrix(expression.Engine, coerced);
            matrix.SetAttribute(dimSymbol, dim);
            return matrix;
        }