Example #1
0
        public static void teste()
        {
            Console.WriteLine("\n\nA imagem deve estar na pasta debug, com o nome 'char.bmp' (já deve ter uma lá)");
            var net2 = SerializationExtensions.FromJSON(File.ReadAllText("best"));

            byte[] imgbytes = null;
            var    newImage = MnistReader.ScaleImage(new Bitmap(@"char.bmp"), 24, 24);

            var x = new Volume(newImage.Width, newImage.Height, 1, 0.0);

            for (var i = 0; i < newImage.Width; i++)
            {
                for (var j = 0; j < newImage.Width; j++)
                {
                    x.Weights[j + i * newImage.Width] = (newImage.GetPixel(j, i).B + newImage.GetPixel(j, i).R + newImage.GetPixel(j, i).G) / 3;
                }
            }

            if (File.Exists("oi.txt"))
            {
                File.Delete("oi.txt");
            }
            for (int i = 0; i < x.Weights.Length; i++)
            {
                using (StreamWriter file = new StreamWriter(@"oi.txt", true))
                    file.WriteLine(x.Weights[i].ToString());
            }

            net2.Forward(x);

            var yhat = net2.GetPrediction();

            Console.WriteLine("label prevista = {0}", yhat);
        }
Example #2
0
        public static void segment_n_rec()
        {
            var image = new Bitmap(@"a.bmp");

            image = image.Clone(new Rectangle(0, 0, image.Width, image.Height), PixelFormat.Format8bppIndexed);
            byte[] imgbytes = new byte[image.Height * image.Width];
            #region parallel grey image conv
            var tasks = new Task[Environment.ProcessorCount];
            int oi    = -1;
            for (var ai = 0; ai < image.Width; ai++)
            {
                for (int taskNumber = 0; taskNumber < Environment.ProcessorCount; taskNumber++)
                {
                    tasks[taskNumber] = Task.Factory.StartNew(() =>
                    {
                        int j = Interlocked.Increment(ref oi);
                        while (j < image.Width)
                        {
                            imgbytes[j + ai * image.Width] = (byte)(((int)image.GetPixel(j, ai).B + (int)image.GetPixel(j, ai).R + (int)image.GetPixel(j, ai).G) / 3);
                            j = Interlocked.Increment(ref oi);
                        }
                    });
                }
                Task.WaitAll(tasks);
            }
            #endregion
            new OtsuThreshold().ApplyInPlace(image);
            // check threshold value


            var net2     = SerializationExtensions.FromJSON(File.ReadAllText("best"));
            var newImage = MnistReader.ScaleImage(new Bitmap(@"C:\Users\leoni.win7-PC\Desktop\Nova pasta\a.bmp"), 24, 24);

            var x = new Volume(newImage.Width, newImage.Height, 1, 0.0);
            for (var i = 0; i < newImage.Width; i++)
            {
                for (var j = 0; j < newImage.Width; j++)
                {
                    x.Weights[j + i * newImage.Width] = (newImage.GetPixel(j, i).B + newImage.GetPixel(j, i).R + newImage.GetPixel(j, i).G) / 3;
                }
            }

            if (File.Exists("oi.txt"))
            {
                File.Delete("oi.txt");
            }
            for (int i = 0; i < x.Weights.Length; i++)
            {
                using (StreamWriter file = new StreamWriter(@"oi.txt", true))
                    file.WriteLine(x.Weights[i].ToString());
            }

            net2.Forward(x);

            var yhat = net2.GetPrediction();
        }
        public static List <byte[]> LoadImages(string folder, bool train)
        {
            var           result = new List <byte[]>();
            int           train_count = 750, test_count = 250;
            DirectoryInfo root = new DirectoryInfo(folder);

            foreach (DirectoryInfo dr in root.GetDirectories())
            {
                var files = dr.GetFiles();
                for (int i = (train ? 0 : train_count); i < (train ? train_count : test_count + train_count); i++)
                {
                    byte[] imgbytes = new byte[24 * 24];
                    var    newImage = MnistReader.ScaleImage(new Bitmap(files[i].FullName), 24, 24);

                    for (var ai = 0; ai < newImage.Width; ai++)
                    {
                        for (var j = 0; j < newImage.Width; j++)
                        {
                            imgbytes[j + ai * newImage.Width] = (byte)(((int)newImage.GetPixel(j, ai).B + (int)newImage.GetPixel(j, ai).R + (int)newImage.GetPixel(j, ai).G) / 3);
                        }
                    }


                    //var tasks = new Task[Environment.ProcessorCount];
                    //int oi = -1;
                    //for (var ai = 0; ai < newImage.Width; ai++)
                    //{
                    //    for (int taskNumber = 0; taskNumber < Environment.ProcessorCount; taskNumber++)
                    //    tasks[taskNumber] = Task.Factory.StartNew(() =>
                    //    {
                    //        int j = Interlocked.Increment(ref oi);
                    //        while (j < newImage.Width)
                    //        {
                    //            imgbytes[j + ai * newImage.Width]= (byte)(((int)newImage.GetPixel(j, ai).B + (int)newImage.GetPixel(j, ai).R + (int)newImage.GetPixel(j, ai).G)/ 3);
                    //            j = Interlocked.Increment(ref oi);
                    //        }
                    //    });
                    //    Task.WaitAll(tasks);
                    //}



                    //if (File.Exists("oi.txt")) { File.Delete("oi.txt"); }
                    //for (int asd = 0; asd < imgbytes.Length; asd++)
                    //    using (StreamWriter file = new StreamWriter(@"oi.txt", true))
                    //        file.WriteLine(imgbytes[asd].ToString());

                    result.Add(imgbytes);
                }
            }

            return(result);
        }
        private const string folder = @"..\..\..\char\"; // para que saia da pasta 'debug' encontre os dados de treino
        private void MnistTrain()
        {
            // carrega os chars
            Console.WriteLine("carregando datasets...");
            if (File.Exists("dataset_training.dat") || File.Exists("dataset_testing.dat"))
            {   // se já tiver os datasets tratados, carrega eles
                training = useful.ReadObject <List <MnistEntry> >(File.ReadAllBytes("dataset_training.dat"));
                testing  = useful.ReadObject <List <MnistEntry> >(File.ReadAllBytes("dataset_testing.dat"));
            }
            else
            {   // caso contrário, carrega a partir das imagens
                training = MnistReader.Load(folder, true);
                testing  = MnistReader.Load(folder, false);
                File.WriteAllBytes("dataset_training.dat", useful.WriteObject <List <MnistEntry> >(training));
                File.WriteAllBytes("dataset_testing.dat", useful.WriteObject <List <MnistEntry> >(testing));
            }
            Random rnd = new Random();

            training = training.OrderBy(x => rnd.Next()).ToList();
            testing  = testing.OrderBy(x => rnd.Next()).ToList();

            if (training.Count == 0 || testing.Count == 0)
            {
                Console.WriteLine("ajuste o diretório dos arquivos de treino/teste.");
                Console.ReadKey();
                return;
            }
            // cria uma CNN simples
            net = new Net();
            net.AddLayer(new InputLayer(24, 24, 1)); //tamanho que eu escalei as imagens
            net.AddLayer(new ConvLayer(5, 5, 20)
            {
                Stride = 1, Pad = 2, Activation = Activation.Relu
            });
            net.AddLayer(new PoolLayer(2, 2)
            {
                Stride = 2
            });
            net.AddLayer(new ConvLayer(5, 5, 35)
            {
                Stride = 1, Pad = 2, Activation = Activation.Relu
            });
            net.AddLayer(new PoolLayer(3, 3)
            {
                Stride = 3
            });
            net.AddLayer(new FullyConnLayer(50));
            net.AddLayer(new SoftmaxLayer(33));

            // este é o meu otimizador
            // ver depois http://int8.io/comparison-of-optimization-techniques-stochastic-gradient-descent-momentum-adagrad-and-adadelta/#AdaDelta
            trainer = new AdadeltaTrainer(net)
            {
                BatchSize = 20,
                L2Decay   = 0.001,
            };
            Console.WriteLine("CNN treinando... aperte uma tecla para parar");
            // o passo
            do
            {
                var sample = SampleTrainingInstance();

                // // só pra ver no matlab a imagem (no matlab eu uso o script imag.m)
                //if (File.Exists("oi.txt")) { File.Delete("oi.txt"); }
                //for (int i = 0; i < sample.Volume.Weights.Length; i++)
                //    using (StreamWriter file = new StreamWriter(@"oi.txt", true))
                //        file.WriteLine(((sample.Volume.Weights[i] * 255.0)).ToString());
                Step(sample);
            } while (!Console.KeyAvailable);
        }