Пример #1
0
        static void Main(string[] args)
        {
            List <Image> imagesArray = new System.Collections.Generic.List <Image>();

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"C:\CosaHelperLib");

            foreach (System.IO.FileInfo file in dir.GetFiles())
            {
                String ext = file.Extension;
                Console.WriteLine(file.FullName);
                if (ext.Equals(".ico"))
                {
                    Stream            iconStream = new FileStream(file.FullName, FileMode.Open);
                    IconBitmapDecoder decoder    = new IconBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

                    foreach (var item in decoder.Frames)
                    {
                        var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
                        src.BeginInit();
                        src.Source = item;
                        src.EndInit();

                        Console.WriteLine(file.FullName + '_' + src.PixelHeight + 'X' + src.PixelWidth);
                        //Console.WriteLine("Pixel Width: " + src.PixelWidth);
                        //Console.WriteLine("Pixel Height: " + src.PixelHeight);
                        //Console.WriteLine("Pixel Width: " + src.PixelWidth);
                        Console.WriteLine("Alpha Channel Threshold: " + src.AlphaThreshold);
                    }
                }
                Console.WriteLine();
            }
            Console.Read();
        }
Пример #2
0
        public static System.Drawing.Bitmap setPixelFormat2(BitmapSource bitmapsource, System.Drawing.Imaging.PixelFormat format)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
            src.BeginInit();
            src.Source = bitmapsource;
            if (format == System.Drawing.Imaging.PixelFormat.Format1bppIndexed)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.BlackWhite;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Gray8;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr24;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr32;
            }
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, format);
            var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, format);
            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return bitmap;
        }
Пример #3
0
        public static System.Drawing.Bitmap setPixelFormat2(BitmapSource bitmapsource, System.Drawing.Imaging.PixelFormat format)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();

            src.BeginInit();
            src.Source = bitmapsource;
            if (format == System.Drawing.Imaging.PixelFormat.Format1bppIndexed)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.BlackWhite;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Gray8;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr24;
            }
            if (format == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
            {
                src.DestinationFormat = System.Windows.Media.PixelFormats.Bgr32;
            }
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, format);
            var    data   = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, format);

            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return(bitmap);
        }
        public MemoryStream ReduceColorDepth(Bitmap bmp)
        {
            var ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Png);

            var bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();

            var newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();

            newFormatedBitmapSource.Source = bi;

            var myPalette = new BitmapPalette(bi, 256);

            newFormatedBitmapSource.DestinationPalette = myPalette;

            //Set PixelFormats
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Indexed8;
            newFormatedBitmapSource.EndInit();

            var pngBitmapEncoder = new PngBitmapEncoder();
            pngBitmapEncoder.Interlace = PngInterlaceOption.Off;
            pngBitmapEncoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));

            var memstream = new MemoryStream();
            pngBitmapEncoder.Save(memstream);
            memstream.Position = 0;
            return memstream;
        }
Пример #5
0
 public static BitmapImage ConvertToOtherPixelFormat(BitmapSource source, PixelFormat format)
 {
     var newFormatedBitmapSource = new FormatConvertedBitmap();
     newFormatedBitmapSource.BeginInit();
     newFormatedBitmapSource.Source = source;
     newFormatedBitmapSource.DestinationFormat = format;
     newFormatedBitmapSource.EndInit();
     return BitmapSourceToBitmapImage(newFormatedBitmapSource.Source);
 }
Пример #6
0
        public static FormatConvertedBitmap GetFormatConvertedBitmap(SWM.PixelFormat pf, BitmapSource bs)
        {
            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = bs;
            newFormatedBitmapSource.DestinationFormat = pf;
            newFormatedBitmapSource.EndInit();

            return newFormatedBitmapSource;
        }
Пример #7
0
        private static void SetGrayscale(System.Windows.Controls.Image img)
        {
            img.IsEnabled = false;

            FormatConvertedBitmap bitmap = new FormatConvertedBitmap();
            bitmap.BeginInit();
            bitmap.Source = (BitmapSource)img.Source;
            bitmap.DestinationFormat = PixelFormats.Gray32Float;
            bitmap.EndInit();

            img.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { img.Source = bitmap; }));
        }
Пример #8
0
        /// <summary>
        /// Convert bmpSource to format declared in pixFormat.
        /// </summary>
        /// <param name="bmpSource"></param>
        /// <param name="pixFormat"></param>
        /// <returns></returns>
        public static FormatConvertedBitmap BitmapToFormat(BitmapSource bmpSource,
                                           PixelFormat pixFormat)
        {
            if (bmpSource == null) { return null; }
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();

            fcb.BeginInit();
            fcb.Source = bmpSource;
            fcb.DestinationFormat = pixFormat;
            fcb.EndInit();
            return fcb;
        }
        public ShowMyFace()
        {
            Title = "Show My Face";

            ///******************************************************************
            //  3���� ShowMyFace ����
            //******************************************************************/
            Uri uri = new Uri("http://www.charlespetzold.com/PetzoldTattoo.jpg");
            //BitmapImage bitmap = new BitmapImage(uri);
            //Image img = new Image();
            //img.Source = bitmap;
            //Content = img;

            ///******************************************************************
            //  p1245 BitmapImage �ڵ�
            //******************************************************************/
            Image rotated90 = new Image();
            TransformedBitmap tb = new TransformedBitmap();
            FormatConvertedBitmap fb = new FormatConvertedBitmap();
            CroppedBitmap cb = new CroppedBitmap();

            // Create the source to use as the tb source.
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = uri;
            bi.EndInit();

            //cb.BeginInit();
            //cb.Source = bi;
            //Int32Rect rect = new Int32Rect();
            //rect.X = 220;
            //rect.Y = 200;
            //rect.Width = 120;
            //rect.Height = 80;
            //cb.SourceRect = rect;

            //cb.EndInit();

            fb.BeginInit();
            fb.Source = bi;
            fb.DestinationFormat = PixelFormats.Gray2;
            fb.EndInit();

            // Properties must be set between BeginInit and EndInit calls.
            tb.BeginInit();
            tb.Source = fb;
            // Set image rotation.
            tb.Transform = new RotateTransform(90);
            tb.EndInit();
            // Set the Image source.
            rotated90.Source = tb;
            Content = rotated90;
        }
Пример #10
0
        public static System.Drawing.Bitmap BmpSource2Img(BitmapSource bmpsource)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
            src.BeginInit();
            src.Source = bmpsource;
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.DontCare);
            var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.DontCare);
            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return bitmap;
        }
Пример #11
0
        /// <summary>
        /// Extension method
        /// </summary>
        /// <param name="bitmapsource"></param>
        /// <returns></returns>
        public static Bitmap BitmapSourceToBitmap(this BitmapSource bitmapsource) {
            //convert image format
            FormatConvertedBitmap src = new FormatConvertedBitmap();
            src.BeginInit();
            src.Source = bitmapsource;
            src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, PixelFormat.Format32bppArgb);
            BitmapData data = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            src.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height*data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return bitmap;
        }
Пример #12
0
        public static System.Drawing.Bitmap BmpSource2Img(BitmapSource bmpsource)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();

            src.BeginInit();
            src.Source = bmpsource;
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.DontCare);
            var    data   = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.DontCare);

            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return(bitmap);
        }
        public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();

            src.BeginInit();
            src.Source            = bitmapsource;
            src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var    data   = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return(bitmap);
        }
Пример #14
0
        private void BtnCon_Click(object sender, RoutedEventArgs e)
        {
            BitmapImage myBitmapImage = new BitmapImage();

            // BitmapSource objects like BitmapImage can only have their properties// changed within a BeginInit/EndInit block.
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri("pack://application:,,,/Images/xiaoxiong.jpg");
            //myBitmapImage.DecodePixelWidth = 200;
            myBitmapImage.EndInit();

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = myBitmapImage;

            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
            newFormatedBitmapSource.EndInit();

            img2.Source = newFormatedBitmapSource;
        }
Пример #15
0
        private static ImageSource Convert(BitmapSource input, PixelFormat format)
        {
            ////////// Convert the BitmapSource to a new format //////////// 
            // Use the BitmapImage created above as the source for a new BitmapSource object 
            // which is set to a gray scale format using the FormatConvertedBitmap BitmapSource.                                                
            // Note: New BitmapSource does not cache. It is always pulled when required.

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            // BitmapSource objects like FormatConvertedBitmap can only have their properties 
            // changed within a BeginInit/EndInit block.
            newFormatedBitmapSource.BeginInit();

            // Use the BitmapSource object defined above as the source for this new  
            // BitmapSource (chain the BitmapSource objects together).
            newFormatedBitmapSource.Source = input;

            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = format;
            newFormatedBitmapSource.EndInit();

            return newFormatedBitmapSource;
        }
Пример #16
0
        public static BitmapSource Dither(BitmapSource source, ColorFormat format)
        {
            if(source.Format == PixelFormats.Indexed8)
            {
                var rgb = new FormatConvertedBitmap();
                rgb.BeginInit();
                rgb.Source = source;
                rgb.DestinationFormat = PixelFormats.Rgb24;
                rgb.EndInit();
                source = rgb;
            }

            var dest = new FormatConvertedBitmap();
            dest.BeginInit();

            dest.Source = source;
            var numColors = (int)Math.Pow(2, (int) format);
            var colors = ColorList.Take(numColors).ToList();
            dest.DestinationPalette = new BitmapPalette(colors);
            dest.DestinationFormat = PixelFormats.Indexed8;
            dest.EndInit();

            return dest;
        }
Пример #17
0
        /// <summary>
        /// Converts BitmapSource to Bitmap.
        /// </summary>
        /// <param name="sourceWpf">BitmapSource</param>
        /// <returns>Bitmap</returns>
        private static Bitmap ConvertToBitmap(BitmapSource sourceWpf)
        {
            BitmapSource bmpWpf = sourceWpf;

            // PixelFormat settings/conversion
            System.Drawing.Imaging.PixelFormat formatBmp = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
            if (sourceWpf.Format == PixelFormats.Bgr24)
            {
                formatBmp = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
            }
            else if (sourceWpf.Format == System.Windows.Media.PixelFormats.Pbgra32)
            {
                formatBmp = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
            }
            else if (sourceWpf.Format != System.Windows.Media.PixelFormats.Bgra32)
            {
                // Convert BitmapSource
                FormatConvertedBitmap convertWpf = new FormatConvertedBitmap();
                convertWpf.BeginInit();
                convertWpf.Source = sourceWpf;
                convertWpf.DestinationFormat = PixelFormats.Bgra32;
                convertWpf.EndInit();
                bmpWpf = convertWpf;
            }

            // Copy/Convert to Bitmap
            Bitmap bmp = new Bitmap(bmpWpf.PixelWidth, bmpWpf.PixelHeight, formatBmp);
            Rectangle rect = new Rectangle(Point.Empty, bmp.Size);
            BitmapData data = bmp.LockBits(rect, ImageLockMode.WriteOnly, formatBmp);
            bmpWpf.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bmp.UnlockBits(data);

            return bmp;
        }
Пример #18
0
        private void Tick(object sender, EventArgs eventArgs)
        {
            lock (GL)
            {
                _sw.Restart();
                GL.MakeCurrent();

                OnUpdate(GL);
                OnRender(GL);

                GL.Blit(IntPtr.Zero);

                var provider = GL.RenderContextProvider as FBORenderContextProvider;
                if (provider == null) return;
                var newFormatedBitmapSource = new FormatConvertedBitmap();
                newFormatedBitmapSource.BeginInit();

                newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
                newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                newFormatedBitmapSource.EndInit();

                image.Source = newFormatedBitmapSource;

                _sw.Stop();
                FPS = 1000.0 / _sw.Elapsed.TotalMilliseconds;
            }
        }
        /// <summary>
        /// Handles the Tick event of the timer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void timer_Tick(object sender, EventArgs e)
        {
            //  Lock on OpenGL.
            lock (gl)
            {
                //  Start the stopwatch so that we can time the rendering.
                stopwatch.Restart();

                //  Make GL current.
                gl.MakeCurrent();

                //	If there is a draw handler, then call it.
                var handler = OpenGLDraw;
                if (handler != null)
                    handler(this, eventArgsFast);
                else
                    gl.Clear(SharpGL.OpenGL.GL_COLOR_BUFFER_BIT);

                //  Draw the FPS.
                if (DrawFPS)
                {
                    gl.DrawText(5, 5, 1.0f, 0.0f, 0.0f, "Courier New", 12.0f, string.Format("Draw Time: {0:0.0000} ms ~ {1:0.0} FPS", frameTime, 1000.0 / frameTime));
                    gl.Flush();
                }

                //  Render.
                gl.Blit(IntPtr.Zero);

                switch (RenderContextType)
                {
                    case SharpGL.RenderContextType.DIBSection:
                        {
                            SharpGL.RenderContextProviders.DIBSectionRenderContextProvider provider = gl.RenderContextProvider as SharpGL.RenderContextProviders.DIBSectionRenderContextProvider;

                            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 
                            //  meaning the drawing comes out transparent.
                            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                            newFormatedBitmapSource.BeginInit();
                            newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap);
                            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                            newFormatedBitmapSource.EndInit();

                            //  Copy the pixels over.
                            image.Source = newFormatedBitmapSource;
                        }
                        break;
                    case SharpGL.RenderContextType.NativeWindow:
                        break;
                    case SharpGL.RenderContextType.HiddenWindow:
                        break;
                    case SharpGL.RenderContextType.FBO:
                        {
                            SharpGL.RenderContextProviders.FBORenderContextProvider provider = gl.RenderContextProvider as SharpGL.RenderContextProviders.FBORenderContextProvider;

                            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 
                            //  meaning the drawing comes out transparent.
                            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                            newFormatedBitmapSource.BeginInit();
                            newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
                            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                            newFormatedBitmapSource.EndInit();

                            //  Copy the pixels over.
                            image.Source = newFormatedBitmapSource;
                        }
                        break;
                    default:
                        break;
                }

                //  Stop the stopwatch.
                stopwatch.Stop();

                //  Store the frame time.
                frameTime = stopwatch.Elapsed.TotalMilliseconds;
            }
        }
Пример #20
0
        public void GetLongitudinalSectionProfile(string FileNameCurve, List<double> list, double hInOnePoint)
        {
            BitmapImage myBitmapImage = GetImage(FileNameCurve);
            if (myBitmapImage == null)
            {
                return;
            }

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = myBitmapImage;
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            int width = newFormatedBitmapSource.PixelWidth;
            int height = newFormatedBitmapSource.PixelHeight;
            int stride = width * 3;
            int size = newFormatedBitmapSource.PixelHeight * stride;
            byte[] pixels = new byte[size];
            Array.Clear(pixels, 0, size);
            newFormatedBitmapSource.CopyPixels(pixels, stride, 0);

            int x = 0;
            int y = 0;
            for (x = 0; x < width; x++)
            {
                for (y = 0; y < height; y++)
                {
                    int index = y * stride + 3 * x;
                    byte red = pixels[index];
                    byte green = pixels[index + 1];
                    byte blue = pixels[index + 2];

                    Color cur_col = Color.FromRgb(red, green, blue);
                    if (cur_col != Color.FromRgb(255, 255, 255))
                    {
                        list.Add(height - y);
                        break;
                    }
                }
            }
            //double base_point = 0;
            //if (list.Count > 0)
            //{
            //    base_point = list[0];
            //    if (MathHelper.IsZero(base_point))
            //    {
            //        base_point = MathHelper.Epsilon;
            //    }
            //}
            for (x = 0; x < list.Count; x++)
            {
                double cur_point = list[x];
                double factor = cur_point  * hInOnePoint;
                list[x] = factor;
            }
        }
Пример #21
0
        public void FromBitmapSource(BitmapSource bitmap)
        {
            if(bitmap.Format != PixelFormats.Rgba128Float)
            {
                FormatConvertedBitmap bitmapFormater = new FormatConvertedBitmap();
                bitmapFormater.BeginInit();
                bitmapFormater.Source = bitmap;
                bitmapFormater.DestinationFormat = PixelFormats.Rgba128Float;
                bitmapFormater.EndInit();

                bitmap = bitmapFormater;
            }

            DpiX = bitmap.DpiX;
            DpiY = bitmap.DpiY;

            int stride = bitmap.PixelWidth * 4 * sizeof(float);
            float[] data = new float[bitmap.PixelHeight * bitmap.PixelWidth * 4];
            bitmap.CopyPixels(data, stride, 0);

            ImageMatrix = new DenseMatrix(bitmap.PixelHeight, bitmap.PixelWidth);
            for(int imgy = 0; imgy < bitmap.PixelHeight; ++imgy)
            {
                for(int imgx = 0; imgx < bitmap.PixelWidth; ++imgx)
                {
                    // Bitmap stores data in row-major order and matrix in column major
                    // So store data to transposed matrix and transpose it so bitmap[y,x] == matrix[y,x]
                    ImageMatrix[imgy, imgx] = (data[4 * imgy * bitmap.PixelWidth + 4 * imgx]
                     + data[4 * imgy * bitmap.PixelWidth + 4 * imgx + 1]
                     + data[4 * imgy * bitmap.PixelWidth + 4 * imgx + 2]) / 3.0;
                }
            }
        }
Пример #22
0
        /// <summary>
        /// This method converts the output from the OpenGL render context provider to a 
        /// FormatConvertedBitmap in order to show it in the image.
        /// </summary>
        /// <param name="hBitmap">The handle of the bitmap from the OpenGL render context.</param>
        /// <returns>Returns the new format converted bitmap.</returns>
        private static FormatConvertedBitmap GetFormatedBitmapSource(IntPtr hBitmap)
        {
            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 
            //  meaning the drawing comes out transparent.

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(hBitmap);
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            return newFormatedBitmapSource;
        }
Пример #23
0
        private static void LoadImages(SQLiteConnection connection)
        {
            SQLiteCommand command;
            SQLiteDataReader reader;
            DataTable table;

            // Load Ball Caught Images
            command = new SQLiteCommand("SELECT * FROM BallImages", connection);
            reader = command.ExecuteReader();
            table = new DataTable("BallImages");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                byte id = (byte)(long)row["ID"];
                BitmapImage image = LoadImage((byte[])row["Image"]);
                ballCaughtImages.Add(id, image);
            }

            // Load Pokemon Images
            command = new SQLiteCommand("SELECT * FROM PokemonImages", connection);
            reader = command.ExecuteReader();
            table = new DataTable("PokemonImages");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                ushort id = (ushort)(long)row["DexID"];
                Gen3PokemonImageTypes pokemonImageTypes = new Gen3PokemonImageTypes();
                pokemonImageTypes.Image = LoadImage(row["Image"] as byte[]);
                pokemonImageTypes.ShinyImage = LoadImage(row["ShinyImage"] as byte[]);
                pokemonImageTypes.FRLGImage = LoadImage(row["FRLGImage"] as byte[]);
                pokemonImageTypes.FRLGShinyImage = LoadImage(row["FRLGShinyImage"] as byte[]);
                pokemonImageTypes.BoxImage = LoadImage(row["BoxImage"] as byte[]);
                pokemonImageTypes.NewBoxImage = LoadImage(row["NewBoxImage"] as byte[]);
                pokemonImageTypes.NewBoxShinyImage = LoadImage(row["NewBoxShinyImage"] as byte[]);
                gen3PokemonImages.Add(id, pokemonImageTypes);

                if (id == 327) {
                    writeableSpindaNormal = new FormatConvertedBitmap();
                    writeableSpindaNormal.BeginInit();
                    writeableSpindaNormal.Source = pokemonImageTypes.Image;
                    writeableSpindaNormal.DestinationFormat = PixelFormats.Bgra32;
                    writeableSpindaNormal.EndInit();

                    writeableSpindaShiny = new FormatConvertedBitmap();
                    writeableSpindaShiny.BeginInit();
                    writeableSpindaShiny.Source = pokemonImageTypes.ShinyImage;
                    writeableSpindaShiny.DestinationFormat = PixelFormats.Bgra32;
                    writeableSpindaShiny.EndInit();
                }
            }

            // Load Unown Form Images
            command = new SQLiteCommand("SELECT * FROM UnownFormImages", connection);
            reader = command.ExecuteReader();
            table = new DataTable("UnownFormImages");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                byte id = (byte)(long)row["ID"];
                DexFormID dexFormID = new DexFormID { DexID = 201, FormID = id };
                Gen3PokemonImageTypes pokemonImageTypes = new Gen3PokemonImageTypes();
                pokemonImageTypes.Image = LoadImage(row["Image"] as byte[]);
                pokemonImageTypes.ShinyImage = LoadImage(row["ShinyImage"] as byte[]);
                pokemonImageTypes.BoxImage = LoadImage(row["BoxImage"] as byte[]);
                pokemonImageTypes.NewBoxImage = LoadImage(row["NewBoxImage"] as byte[]);
                pokemonImageTypes.NewBoxShinyImage = LoadImage(row["NewBoxShinyImage"] as byte[]);
                gen3PokemonFormImages.Add(dexFormID, pokemonImageTypes);
            }

            // Load Deoxys Form Images
            command = new SQLiteCommand("SELECT * FROM DeoxysFormImages", connection);
            reader = command.ExecuteReader();
            table = new DataTable("DeoxysFormImages");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                byte id = (byte)(long)row["ID"];
                DexFormID dexFormID = new DexFormID { DexID = 386, FormID = id };
                Gen3PokemonImageTypes pokemonImageTypes = new Gen3PokemonImageTypes();
                pokemonImageTypes.Image = LoadImage(row["Image"] as byte[]);
                pokemonImageTypes.ShinyImage = LoadImage(row["ShinyImage"] as byte[]);
                pokemonImageTypes.BoxImage = LoadImage(row["BoxImage"] as byte[]);
                pokemonImageTypes.NewBoxImage = LoadImage(row["NewBoxImage"] as byte[]);
                pokemonImageTypes.NewBoxShinyImage = LoadImage(row["NewBoxShinyImage"] as byte[]);
                gen3PokemonFormImages.Add(dexFormID, pokemonImageTypes);
            }

            // Load Ribbon Images
            command = new SQLiteCommand("SELECT * FROM RibbonImages", connection);
            reader = command.ExecuteReader();
            table = new DataTable("RibbonImages");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                string id = row["ID"] as string;
                BitmapImage image = LoadImage((byte[])row["Image"]);
                ribbonImages.Add(id, image);
            }

            // Load Met Locations
            command = new SQLiteCommand("SELECT * FROM MetLocations", connection);
            reader = command.ExecuteReader();
            table = new DataTable("MetLocations");
            table.Load(reader);
            foreach (DataRow row in table.Rows) {
                ushort id = (ushort)(long)row["ID"];
                string name = row["Name"] as string;
                metLocationMap.Add(id, name);
                metLocationList.Add(name);
            }
        }
Пример #24
0
        private BitmapSource ConvertFullToGray(BitmapSource full)
        {
            FormatConvertedBitmap gray = new FormatConvertedBitmap();

            gray.BeginInit();
            gray.Source = full;
            gray.DestinationFormat = PixelFormats.Gray32Float;
            gray.EndInit();

            return gray;
        }
Пример #25
0
        public void GetCrossSectionProfile(List<Point> list, string fileName, int TotalPoints, double fPointWidth)
        {
            BitmapImage myBitmapImage = GetImage(fileName);
            if (myBitmapImage == null)
            {
                return;
            }

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = myBitmapImage;
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            int width = newFormatedBitmapSource.PixelWidth;

            int stride = width * 3;
            int size = newFormatedBitmapSource.PixelHeight * stride;
            byte[] pixels = new byte[size];
            Array.Clear(pixels, 0, size);
            newFormatedBitmapSource.CopyPixels(pixels, stride, 0);

            int x = 0;
            int y = 0;
            Point ptCenter = new Point();
            ptCenter.X = newFormatedBitmapSource.PixelWidth / 2;
            ptCenter.Y = newFormatedBitmapSource.PixelHeight / 2;
            int r_begin_min = (int)Math.Min(ptCenter.X, ptCenter.Y);

            ScaleTransform scaleTransform = new ScaleTransform(fPointWidth, fPointWidth);

            double delta = TotalPoints / 360;
            for (double angle = 0; angle < 360; angle += delta)
            {
                double rad_angle = Math.PI * angle / 180.0;
                int r_begin = (int)Math.Sqrt(2 * r_begin_min * r_begin_min);

                for (double r = r_begin; r > 0; r-=1)
                {
                    x = (int)(r * Math.Cos(rad_angle)) + (int)ptCenter.X;
                    y = (int)(r * Math.Sin(rad_angle)) + (int)ptCenter.Y;
                    if (x >= newFormatedBitmapSource.PixelWidth ||
                        y >= newFormatedBitmapSource.PixelHeight ||
                        x < 0 || y < 0)
                    {
                        continue;
                    }

                    int index = y * stride + 3 * x;
                    byte red = pixels[index];
                    byte green = pixels[index + 1];
                    byte blue = pixels[index + 2];

                    Color cur_col = Color.FromRgb(red, green, blue);
                    if (cur_col != Color.FromRgb(255, 255, 255))
                    {
                        int x_add = x - (int)ptCenter.X;
                        int y_add = y - (int)ptCenter.Y;
                        Point ptToAdd = new Point(x_add, y_add);

                        if (list.Count == 0 || list.Last() != ptToAdd)
                        {
                            list.Add(ptToAdd);
                            if (list.Count == 215)
                            {
                                int h = 0 + 4;
                            }
                        }

                        break;
                    }
                }
            }
            if (scaleTransform != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i] = scaleTransform.Transform(list[i]);
                }

            }
        }
Пример #26
0
        /// <summary>
        /// Handles the Tick event of the timer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void timer_Tick(object sender, EventArgs e)
        {
            //  If we don't have a scene, we're done.
            if (Scene == null)
                return;

            //  Lock on the Scene.
            lock (Scene)
            {
                //  Start the stopwatch so that we can time the rendering.
                stopwatch.Restart();

                //  Draw the scene.
                Scene.Draw(Camera);
                
                //  Draw the FPS.
                if (DrawFPS)
                {
                    Scene.OpenGL.DrawText(5, 5, 1.0f, 0.0f, 0.0f, "Courier New", 12.0f, string.Format("Draw Time: {0:0.0000} ms ~ {1:0.0} FPS", frameTime, 1000.0 / frameTime));
                    Scene.OpenGL.Flush();
                }

                if (Scene.OpenGL.RenderContextProvider is RenderContextProviders.DIBSectionRenderContextProvider)
                {
                    RenderContextProviders.DIBSectionRenderContextProvider provider = Scene.OpenGL.RenderContextProvider as RenderContextProviders.DIBSectionRenderContextProvider;

                    //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 
                    //  meaning the drawing comes out transparent.
                    FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                    newFormatedBitmapSource.BeginInit();
                    newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap);
                    newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                    newFormatedBitmapSource.EndInit();

                    //  Copy the pixels over.
                    image.Source = newFormatedBitmapSource;
                }
                else if (Scene.OpenGL.RenderContextProvider is RenderContextProviders.FBORenderContextProvider)
                {
                    RenderContextProviders.FBORenderContextProvider provider = Scene.OpenGL.RenderContextProvider as RenderContextProviders.FBORenderContextProvider;

                    //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0 
                    //  meaning the drawing comes out transparent.
                    FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                    newFormatedBitmapSource.BeginInit();
                    newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
                    newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                    newFormatedBitmapSource.EndInit();

                    //  Copy the pixels over.
                    image.Source = newFormatedBitmapSource;
                }

                //  Stop the stopwatch.
                stopwatch.Stop();

                //  Store the frame time.
                frameTime = stopwatch.Elapsed.TotalMilliseconds;
            }
        }
        void FillFrameList(BitmapDecoder decoder)
        {
            //continue if loaded
            Progress = 1;
            var list = new List<FrameData>(decoder.Frames.Count);
            var delaySpread = new Spread<int>(0);
            var positionSpread = new Spread<Vector2D>(0);
            var sizeSpread = new Spread<Vector2D>(0);
            var disposalSpread = new Spread<GifDisposal>(0);

            Format = decoder.Frames[0].Format;

            //convert and copy frames
            foreach (var frame in decoder.Frames)
            {

                //read meta data
                if(!frame.IsFrozen)
                    frame.Freeze();

                var meta = frame.Metadata as BitmapMetadata;
                if(meta != null)
                {
                    if(meta.ContainsQuery("/grctlext/Delay"))
                        delaySpread.Add((ushort)meta.GetQuery("/grctlext/Delay"));
                    else
                        delaySpread.Add(0);

                    if(meta.ContainsQuery("/grctlext/Disposal"))
                        disposalSpread.Add((GifDisposal)((byte)meta.GetQuery("/grctlext/Disposal")));
                    else
                        disposalSpread.Add(GifDisposal.None);

                    var left = (ushort)0;
                    var top = (ushort)0;

                     if(meta.ContainsQuery("/imgdesc/Left"))
                         left = (ushort)meta.GetQuery("/imgdesc/Left");

                     if(meta.ContainsQuery("/imgdesc/Top"))
                         top = (ushort)meta.GetQuery("/imgdesc/Top");

                    positionSpread.Add(new Vector2D(left, top));
                }

                sizeSpread.Add(new Vector2D(frame.PixelWidth, frame.PixelHeight));

                var convertedBitmap = new FormatConvertedBitmap();

                convertedBitmap.BeginInit();
                convertedBitmap.Source = frame;
                convertedBitmap.DestinationFormat = PixelFormats.Bgra32;
                convertedBitmap.EndInit();

                list.Add(CopyBitmapFrameToFrameData(convertedBitmap));
            }

            FFrameDataList = list;

            //recreate texture resources
            FTextureSpread.ResizeAndDispose(FFrameDataList.Count, i => CreateTextureResource(i));
            DelaySpread = delaySpread;
            PositionSpread = positionSpread;
            SizeSpread = sizeSpread;
            DisposalSpread = disposalSpread;
            IsLoading = false;
            HasNewData = true;
        }
Пример #28
0
        System.Drawing.Bitmap GetBitmap() 
        {
            BitmapSource contentImage = GetImage(); 
            int imageWidth = (int)contentImage.Width;
            int imageHeight = (int)contentImage.Height;

            System.Drawing.Bitmap bitmapFinal = new System.Drawing.Bitmap( 
                                        imageWidth,
                                        imageHeight, 
                                        System.Drawing.Imaging.PixelFormat.Format32bppRgb); 

            System.Drawing.Imaging.BitmapData bmData = 
                                bitmapFinal.LockBits(
                                    new System.Drawing.Rectangle(0, 0, imageWidth, imageHeight),
                                    System.Drawing.Imaging.ImageLockMode.WriteOnly,
                                    System.Drawing.Imaging.PixelFormat.Format32bppRgb); 

            FormatConvertedBitmap formatConverter = new FormatConvertedBitmap(); 
            formatConverter.BeginInit(); 
            formatConverter.Source = contentImage;
            formatConverter.DestinationFormat = PixelFormats.Bgr32; 
            formatConverter.EndInit();

            CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null);
 
            if (mediaAccessPermission != null)
            { 
                mediaAccessPermission.Assert(); //BlessedAssert 
            }
            try 
            {
                formatConverter.CopyPixels(
                            new Int32Rect(0, 0, imageWidth, imageHeight),
                            bmData.Scan0, 
                            bmData.Stride * (bmData.Height - 1) + (bmData.Width * 4),
                            bmData.Stride); 
            } 
            finally
            { 
                if (mediaAccessPermission != null)
                {
                    CodeAccessPermission.RevertAssert();
                } 
            }
 
            bitmapFinal.UnlockBits(bmData); 

            return bitmapFinal; 
        }
Пример #29
0
        /// <summary>
        /// WriteableBitmap (Format = Bgr32) -> IplImage
        /// </summary>
        private void TestWriteableBitmapBgr32()
        {
            // loads color image
            PngBitmapDecoder decoder = new PngBitmapDecoder(
                new Uri(FilePath.Image.Lenna, UriKind.Relative),
                BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default
            );
            BitmapSource bs = decoder.Frames[0];

            // converts pixelformat from Bgr24 to Bgr32 (for this test)
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source = bs;
            fcb.DestinationFormat = PixelFormats.Gray8;
            fcb.EndInit();

            // creates WriteableBitmap
            WriteableBitmap wb = new WriteableBitmap(fcb);

            // shows wb 
            /*
            var image = new System.Windows.Controls.Image { Source = wb };
            var window = new System.Windows.Window
            {
                Title = string.Format("wb (Format:{0})", wb.Format),
                Width = wb.PixelWidth,
                Height = wb.PixelHeight,
                Content = image
            };
            var app = new System.Windows.Application();
            app.Run(window);
            //*/

            // convert wb into IplImage
            IplImage ipl = wb.ToIplImage();
            //IplImage ipl32 = new IplImage(wb.PixelWidth, wb.PixelHeight, BitDepth.U16, 1);
            //WriteableBitmapConverter.ToIplImage(wb, ipl32);

            using (new CvWindow("from WriteableBitmap(Bgr32) to IplImage", ipl))
            {
                Cv.WaitKey();
            }
        }
        public ImageSource GetFrame()
        {
            if (!BlitImage)
                return ImgSource;

            lock (Gl)
            {
                Gl.Blit(IntPtr.Zero);
                IntPtr hBitmap = IntPtr.Zero;

                switch (RenderContextType)
                {
                    case RenderContextType.DIBSection:
                        {
                            DIBSectionRenderContextProvider provider = Gl.RenderContextProvider as DIBSectionRenderContextProvider;

                            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
                            //  meaning the drawing comes out transparent.
                            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                            newFormatedBitmapSource.BeginInit();
                            newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap);
                            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                            newFormatedBitmapSource.EndInit();

                            //  Copy the pixels over.

                            return newFormatedBitmapSource;
                        }
                    case RenderContextType.NativeWindow:
                        break;
                    case RenderContextType.HiddenWindow:
                        break;
                    case RenderContextType.FBO:
                        {
                            FBORenderContextProvider provider = Gl.RenderContextProvider as FBORenderContextProvider;

                            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
                            //  meaning the drawing comes out transparent.
                            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                            newFormatedBitmapSource.BeginInit();
                            newFormatedBitmapSource.Source = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
                            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                            newFormatedBitmapSource.EndInit();

                            //  Copy the pixels over.
                            return newFormatedBitmapSource;
                        }
                    case RenderContextType.PBO:
                        {
                            PBORenderContextProvider provider = Gl.RenderContextProvider as PBORenderContextProvider;
                            var width = provider.Width;
                            var height = provider.Height;
                            var pixelsPtr = provider.PixelPtr;
                            if (pixelsPtr == IntPtr.Zero)
                                return null;
                            var size = provider.Size;
                            var stride = provider.Stride;
                            var rect = new Int32Rect(0, 0, width, height);
                            WriteableBitmap.WritePixels(rect, pixelsPtr, size, stride, 0, 0);

                            return WriteableBitmap;
                        }
                    default:
                        break;
                }

            }
            return null;
        }
Пример #31
0
        public void FromBitmapSource(BitmapSource bitmap, Int32Rect area)
        {
            if(bitmap.Format != PixelFormats.Rgba128Float)
            {
                FormatConvertedBitmap bitmapFormater = new FormatConvertedBitmap();
                // BitmapSource objects like FormatConvertedBitmap can only have their properties
                // changed within a BeginInit/EndInit block.
                bitmapFormater.BeginInit();
                // Use the BitmapSource object defined above as the source for this new 
                // BitmapSource (chain the BitmapSource objects together).
                bitmapFormater.Source = bitmap;
                // Set the new format to Rgba128Float
                bitmapFormater.DestinationFormat = PixelFormats.Rgba128Float;
                bitmapFormater.EndInit();

                bitmap = bitmapFormater;
            }

            DpiX = bitmap.DpiX;
            DpiY = bitmap.DpiY;

            int stride = area.Width * 4 * sizeof(float);
            float[] data = new float[area.Height * area.Width * 4];
            bitmap.CopyPixels(area, data, stride, 0);
            
            ImageMatrix[0] = new DenseMatrix(area.Height, area.Width);
            ImageMatrix[1] = new DenseMatrix(area.Height, area.Width);
            ImageMatrix[2] = new DenseMatrix(area.Height, area.Width);

            for(int imgy = 0; imgy < area.Height; ++imgy)
            {
                for(int imgx = 0; imgx < area.Width; ++imgx)
                {
                    // Bitmap stores data in row-major order and matrix in column major
                    // So store data to transposed matrix and transpose it so bitmap[y,x] == matrix[y,x]
                    // Format is Rgba32, so first float is r, then g and b
                    ImageMatrix[0][imgy, imgx] = data[imgy * area.Width + imgx];
                    ImageMatrix[1][imgy, imgx] = data[imgy * area.Width + imgx + 1];
                    ImageMatrix[2][imgy, imgx] = data[imgy * area.Width + imgx + 2];
                }
            }
        }
Пример #32
0
        private byte[] GetPNGWithoutAlpha(byte[] bytes)
        {
            using (var pngStream = new MemoryStream(bytes))
            {
                var decoder = new PngBitmapDecoder(pngStream,BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.Default);
                if (!AlphaPalette(decoder.Frames[0].Palette))
                {
                    return bytes;
                }
                var encoder = new PngBitmapEncoder();

                var newFormatedBitmapSource = new FormatConvertedBitmap();

                newFormatedBitmapSource.BeginInit();
                newFormatedBitmapSource.Source = decoder.Frames[0];
                newFormatedBitmapSource.DestinationFormat = PixelFormats.Pbgra32;
                newFormatedBitmapSource.EndInit();

                encoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));
                encoder.Interlace = PngInterlaceOption.Off;
                using (var outStream = new MemoryStream())
                {
                    encoder.Save(outStream);
                    return outStream.ToArray();
                }
            }
        }
Пример #33
0
        private static void Main( string[] args )
        {
            bool success = false;
             string fileName = "";
             if ( args.Length >= 1 )
             {
            directory = Path.GetDirectoryName( args[0] );
            fileName = Path.GetFileNameWithoutExtension( args[0] );

            success = !string.IsNullOrEmpty( fileName );
             }

             if ( !success )
             {
            Console.WriteLine( "Could not parse arguments: FoodClassifier.exe <filepath>" );
            Console.ReadKey();
            return;
             }
             if ( string.IsNullOrEmpty( directory ) )
             {
            directory = "";
             }

             var bitmap = new BitmapImage( new Uri( args[0], string.IsNullOrEmpty( directory ) ? UriKind.Relative : UriKind.Absolute ) );

            // give this directory to the bitmap operations class
             BitmapOperations.saveDirectory = directory;

             // Scale the image up if it is too small or down if it is too big
             double scale = 1.0;
             if ( bitmap.PixelHeight < 400 && bitmap.PixelWidth < 400 )
             {
            scale = Math.Min( 400.0 / bitmap.PixelWidth, 400.0 / bitmap.PixelHeight );
             }
             else if ( bitmap.PixelHeight > 1000 && bitmap.PixelWidth > 1000 )
             {
            scale = Math.Min( 1000.0 / bitmap.PixelWidth, 1000.0 / bitmap.PixelHeight );
             }
             var resizedBitmap = new BitmapImage();
             resizedBitmap.BeginInit();
             resizedBitmap.UriSource = bitmap.UriSource;
             resizedBitmap.DecodePixelHeight = (int)( scale * bitmap.PixelHeight );
             resizedBitmap.DecodePixelWidth = (int)( scale * bitmap.PixelWidth );
             resizedBitmap.EndInit();

             // Reformat to BGR
             var properFormatBitmap = new FormatConvertedBitmap();
             properFormatBitmap.BeginInit();
             properFormatBitmap.Source = resizedBitmap;
             properFormatBitmap.DestinationFormat = PixelFormats.Bgr32;
             properFormatBitmap.EndInit();

             var writeableBitmap = new WriteableBitmap( properFormatBitmap ); // The ready to go bitmap
             var cvImage = new Image<Gray, byte>( new Bitmap( args[0] ) );
             cvImage = cvImage.Resize( scale, INTER.CV_INTER_CUBIC );

             // var classifications = ClassifyBitmap( writeableBitmap, cvImage );

             BitmapOperations.analyzeBitmapGradient(bitmap);
        }
Пример #34
0
        static void Main(string[] args)
        {
            //DirectoryInfo rootDir = new DirectoryInfo("oracles");
            //List<int> train_labels = new List<int>(),
            //          test_labels = new List<int>();
            //List<Mat<byte>> train_images = new List<Mat<byte>>(),
            //                test_images = new List<Mat<byte>>();

            //int index = 1;
            //foreach (var dir in rootDir.GetDirectories())
            //{
            //    int counter = 0;
            //    foreach (var file in dir.GetFiles())
            //    {
            //        BitmapSource bmp = new PngBitmapDecoder(new Uri(file.FullName),
            //            BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];

            //        FormatConvertedBitmap formatedBmp = new FormatConvertedBitmap();
            //        formatedBmp.BeginInit();
            //        formatedBmp.Source = bmp;
            //        formatedBmp.DestinationFormat = PixelFormats.Gray8;
            //        formatedBmp.EndInit();

            //        if (counter % 3 < 2)
            //        {
            //            train_images.Add(BitmapSourceToMat(formatedBmp));
            //            train_labels.Add(index);
            //        }
            //        else
            //        {
            //            test_images.Add(BitmapSourceToMat(formatedBmp));
            //            test_labels.Add(index);
            //        }

            //        counter++;
            //    }

            //    index++;
            //}

            //List<GlobalFeatureVec> train_features = new List<GlobalFeatureVec>(),
            //                       test_features = new List<GlobalFeatureVec>();

            //for (int i = 0; i < train_images.Count; i++)
            //    train_features.Add(new GlobalFeatureVec());
            //for (int i = 0; i < test_images.Count; i++)
            //    test_features.Add(new GlobalFeatureVec());

            //Parallel.For(0, train_images.Count, (i) =>
            //{
            //    train_features[i] = GHOG.GetFeatureWithoutPreprocess(train_images[i]);
            //});
            //Parallel.For(0, test_images.Count, (i) =>
            //{
            //    test_features[i] = GHOG.GetFeatureWithoutPreprocess(test_images[i]);
            //});

            //Console.WriteLine(KNN(train_features, train_labels, test_features, test_labels));

            Uri uri = new Uri("00006.png", UriKind.Relative);
            BitmapSource bmp = new PngBitmapDecoder(uri, BitmapCreateOptions.None,
                BitmapCacheOption.Default).Frames[0];

            FormatConvertedBitmap formatedBmp = new FormatConvertedBitmap();
            formatedBmp.BeginInit();
            formatedBmp.Source = bmp;
            formatedBmp.DestinationFormat = PixelFormats.Gray8;
            formatedBmp.EndInit();

            Mat<byte> preprocessed = Feature.Preprocess(BitmapSourceToMat(formatedBmp), new Size(256, 256));
            var channels = BinaryImgProc.SplitViaOrientation(preprocessed, 8);
            foreach (var channel in channels)
            {
                ImageBox box = new ImageBox(MatToBitmapSource(channel));
                box.ShowDialog();
            }

            //int sigma = 9, lambda = 24, ksize = sigma * 6 + 1;
            //Mat<double> filter = Filter.GetGaborKernel(new Size(ksize, ksize), sigma,
            //        0, lambda, 1, 0);
            //Mat<double> filter = new Mat<double>(5, 5);
            //for (int i = 0; i < filter.Rows; i++)
            //    for (int i = 0; i < filter.Cols; i++)
            //        filter[i, i] = 1.0 / (filter.Rows * filter.Cols);

            //Mat<double> tmp = ImgProc.Filter2D(preprocessed, filter);
            //Mat<byte> result = new Mat<byte>(tmp.Size);
            //double max = double.MinValue, min = double.MaxValue;
            //for (int i = 0; i < tmp.Rows; i++)
            //    for (int k = 0; k < tmp.Cols; k++)
            //    {
            //        if (tmp[i, k] > max)
            //            max = tmp[i, k];
            //        if (tmp[i, k] < min)
            //            min = tmp[i, k];
            //    }

            //for (int i = 0; i < tmp.Rows; i++)
            //    for (int k = 0; k < tmp.Cols; k++)
            //        result[i, k] = (byte)((tmp[i, k] - min) / (max - min) * 256);

            //ImageBox box = new ImageBox(MatToBitmapSource(result));
            //box.ShowDialog();
        }