Beispiel #1
0
        public void Obraz_ShouldReturnColorBitmapAsBytesArray()
        {
            var obraz = new Obraz(fileName: @"Samples\Color\0_I.png");

            obraz.Etykieta.ShouldBe("I");
            var features = obraz.GetBitmapFeatures(color: true);

            features.Count().ShouldBe(96 * 96 * 3);
        }
Beispiel #2
0
        public void Obraz_ShouldReturnGrayBitmapAsBytesArray()
        {
            var obraz = new Obraz(fileName: @"Samples\Gray\0_I.png");

            obraz.Etykieta.ShouldBe("I");
            var features = obraz.GetBitmapFeatures();

            features.Count().ShouldBe(28 * 28);
        }
Beispiel #3
0
        private void Obraz_MouseUp(object sender, MouseEventArgs e)
        {
            if (!ChangeColorMode)
            {
                return;
            }

            unsafe
            {
                Bitmap     pic            = new Bitmap(Obraz.Image);
                BitmapData bmpDat         = pic.LockBits(new Rectangle(0, 0, pic.Width, pic.Height), ImageLockMode.ReadWrite, pic.PixelFormat);
                int        BytesPerPixel  = System.Drawing.Bitmap.GetPixelFormatSize(pic.PixelFormat) / 8;
                int        HeightInPixels = bmpDat.Height;
                int        WidthInBytes   = bmpDat.Width * BytesPerPixel;
                byte *     PtrFirstPixel  = (byte *)bmpDat.Scan0;

                //************************************
                //kursor.Text = "k: " + ((int)(e.X*xScale)).ToString() + "," + ((int)(e.Y*yScale)).ToString();
                byte *CurrentLine = PtrFirstPixel + (e.Y * bmpDat.Stride) + BytesPerPixel * e.X;

                byte PB = CurrentLine[0],
                     PG = CurrentLine[1],
                     PR = CurrentLine[2];

                for (int y = 0; y < HeightInPixels; ++y)
                {
                    CurrentLine = PtrFirstPixel + (y * bmpDat.Stride);
                    for (int x = 0; x < WidthInBytes; x = x + BytesPerPixel)
                    {
                        if (CurrentLine[x] == PB && CurrentLine[x + 1] == PG && CurrentLine[x + 2] == PR)
                        {
                            CurrentLine[x]     = choosedColor.B;
                            CurrentLine[x + 1] = choosedColor.G;
                            CurrentLine[x + 2] = choosedColor.R;
                        }
                    }
                }
                ;
                pic.UnlockBits(bmpDat);
                Obraz.Image.Dispose();
                images[indexChoosed].Image = pic;
                Obraz.Image = pic;
                images[indexChoosed].Invalidate();
                Obraz.Invalidate();
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Obraz img = new Obraz();

            /*
             * Sprawdzenie podania argumentów
             */
            if (args.Length == 0)
            {
                Console.WriteLine("Nie podano plikow wejsciowych w argumencie!!!!");
                Console.WriteLine("\n==>>Porada:");
                Console.WriteLine("==>>Prosze podawac pelna sciezke do pliku!!!");

                Console.ReadKey();
                return;
            }
            else
            {
                foreach (string file in args)
                {
                    /*
                     * Sprawdzenie poprawnosci wczytania pliku
                     */
                    if (img.wczytajObraz(file) == 0)
                    {
                        //img.rotation(30);
                        img.laplacian(0.2);

                        img.zapiszObraz();

                        img.unsharp(0);
                        img.zapiszObraz();
                    }
                }
            }
            //Console.ReadKey();
        }
Beispiel #5
0
        // Menu
        private void buttonRead_Click(object sender, EventArgs e)
        {
            OpenFileDialog oknoWyboruPliku = new OpenFileDialog();

            oknoWyboruPliku.InitialDirectory = @"C:\Users\diga.vo\Source\Repos\DPP\DPP\bin\Img+R"; //System.IO.Directory.GetCurrentDirectory();
            oknoWyboruPliku.Filter           = "Wszystkie obrazy|*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.tif;*.tiff|"
                                               + "PNG|*.png|BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|TIFF|*.tif;*.tiff";
            oknoWyboruPliku.Title            = "Wczytaj obraz";
            oknoWyboruPliku.RestoreDirectory = true;
            if (oknoWyboruPliku.ShowDialog() == DialogResult.OK)
            {
                nazwaPliku = oknoWyboruPliku.FileName;
                ObrazSat   = new Obraz(nazwaPliku);

                /*if (fileName.ToLower().Contains("tif") || fileName.ToLower().Contains("tiff"))
                 *  if (!ObrazSat.ReadTiff(fileName))
                 *  {
                 *      MessageBox.Show("Błąd wczytania pliku, spróbuj ponownie");
                 *      tabControl1.Enabled = false;
                 *      buttonSave.Enabled = buttonOrig.Enabled = button13.Enabled = button14.Enabled = button15.Enabled = button16.Enabled = false;
                 *      return;
                 *  }*/
                pictureBox0.Image   = ObrazSat.InImg;
                pictureBox1.Image   = null;
                tabControl1.Enabled = true;
                buttonSave.Enabled  = buttonOrig.Enabled = button13.Enabled = button14.Enabled = button15.Enabled = button16.Enabled = true;
                if (!ObrazSat.trueRoads())
                {
                    button17.Enabled = false;
                }
                else
                {
                    button17.Enabled = true;
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Получение вектора признаков
        /// </summary>
        /// <param name="CorrespondingObraz">Соответствующий образ</param>
        /// <param name="Y_fragment">Количество разбиений образа по вертикальной оси</param>
        /// <param name="X_fragment">Количество разбиений образа по горизонтальной оси</param>
        public Vector(Obraz CorrespondingObraz, uint Y_fragment, uint X_fragment)
        {
            obraz_matrix = CorrespondingObraz.obraz_matrix;

            Y_border = CorrespondingObraz.Y_border;
            X_border = CorrespondingObraz.X_border;

            Y_fragmentation = Y_fragment;
            X_fragmentation = X_fragment;

            //Задание компоненты вектора (разбиение на прямоугольники)
            RectangleFragmentation();

            //Задание компоненты вектора (разбиение горизонтальными линиями)
            HorLinesFragmentation();

            //Задание компоненты вектора (разбиение вертикальными линиями)
            VertLinesFragmentation();

            //Получение суммарного (полного) вектора
            SetCompleteVector();

            //WriteVectorLog(CorrespondingObraz.Obraz_File_Name);
        }
Beispiel #7
0
        private void DifferentFragmentationsRecognitionButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog FiguresToRecognizeFileDialog = new OpenFileDialog();

            MessageBox.Show("Все данные по будут помещены в лог " + DefaultDifferentFragmentationsRecognitionLog, "Форма", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            try
            {
                //Сброс матрицы весов
                WeightsMatrixCheckBox.Checked = false;

                FiguresToRecognizeFileDialog.Filter      = "Изображения " + DefaultImageExtension + "|*" + DefaultImageExtension; //"Файлы|*.bmp";
                FiguresToRecognizeFileDialog.Multiselect = true;

                if (FiguresToRecognizeFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Создание и предварительная запись образов для каждого изображения
                    {
                        foreach (String CurrentFigureFile in FiguresToRecognizeFileDialog.FileNames)
                        {
                            //Работа с образом
                            Obraz CurrentFigureObraz = new Obraz(CurrentFigureFile);

                            String FigureFileName = Path.GetFileNameWithoutExtension(CurrentFigureFile);

                            CurrentFigureObraz.WriteObrazLog(FigureFileName);
                        }
                    }

                    //Инициализация лога
                    String RecognitionLogFilePath = Directory.GetCurrentDirectory() + "\\" + DefaultDifferentFragmentationsRecognitionLog;

                    File.Delete(RecognitionLogFilePath);


                    foreach (String FilePath in FiguresToRecognizeFileDialog.FileNames)
                    {
                        String FileName = Path.GetFileName(FilePath);

                        File.AppendAllText(RecognitionLogFilePath, FileName + ";");
                    }

                    File.AppendAllText(RecognitionLogFilePath, Environment.NewLine + Environment.NewLine);

                    //Распознавание для различных разбиений
                    foreach (uint Y_fragment in Y_fragmentationsArray)
                    {
                        foreach (uint X_fragment in X_fragmentationsArray)
                        {
                            SetMainPerceptronVectorLength(Y_fragment, X_fragment);

                            //Обучение при текущих разбиениях
                            TeachOnAllTeachingSets(Y_fragment, X_fragment);

                            File.AppendAllText(RecognitionLogFilePath, Y_fragment.ToString() + " " + X_fragment.ToString() + ";");

                            foreach (String CurrentFigureFile in FiguresToRecognizeFileDialog.FileNames)
                            {
                                String ImageName = Path.GetFileNameWithoutExtension(CurrentFigureFile);

                                //Загрузка образов
                                Obraz CurrentFigureObraz = new Obraz();

                                String CurrentFigureObrazFilePath = Directory.GetCurrentDirectory()
                                                                    + DefaultRecognitionInformationCatalog
                                                                    + Obraz.GetDefaultObrazName(ImageName);

                                CurrentFigureObraz.LoadObrazFromFile(CurrentFigureObrazFilePath);

                                //Работа с вектором

                                Vector CurrentFigureVector = new Vector(CurrentFigureObraz, Y_fragment, X_fragment);

                                CurrentFigureVector.WriteVectorLog(ImageName);

                                //Получение ответа
                                String NeuralNetworkAnswer = MainPerceptron.GetAnswerFromVector(CurrentFigureVector.complete_vector);

                                //Запись в лог распознавания

                                File.AppendAllText(RecognitionLogFilePath, NeuralNetworkAnswer + ";");
                            }

                            File.AppendAllText(RecognitionLogFilePath, Environment.NewLine);   //Закрытие строки лога распознавания
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка при попытке распознавания вне функции распознавания", "Форма", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                if (FiguresToRecognizeFileDialog != null)
                {
                    FiguresToRecognizeFileDialog.Dispose();
                }
            }
        }
Beispiel #8
0
        private void RecognizeFiguresButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog FiguresToRecognizeFileDialog = new OpenFileDialog();

            try
            {
                FiguresToRecognizeFileDialog.Filter      = "Изображения " + DefaultImageExtension + "|*" + DefaultImageExtension; //"Файлы|*.bmp";
                FiguresToRecognizeFileDialog.Multiselect = true;

                RecognitionResultsTextBox.Text = ""; //Стирание предыдущих результатов

                InitializeFragmentations();

                SetMainPerceptronVectorLength(Y_fragmentation, X_fragmentation);

                //Если не получилось считать матрицу весов
                if (!MainPerceptron.TrySetWeightsMatrix())
                {
                    return;
                }

                String RecognitionLogFilePath = Directory.GetCurrentDirectory() + "\\" + DefaultRecognitionLogFileName;

                if (FiguresToRecognizeFileDialog.ShowDialog() == DialogResult.OK)
                {
                    File.AppendAllText(RecognitionLogFilePath, Y_fragmentation.ToString() + " " + X_fragmentation.ToString() + Environment.NewLine);   //Окрытие лога распознавания

                    foreach (String CurrentFigureFile in FiguresToRecognizeFileDialog.FileNames)
                    {
                        //Работа с образом
                        Obraz CurrentFigureObraz = new Obraz(CurrentFigureFile);

                        String FigureFileName = Path.GetFileNameWithoutExtension(CurrentFigureFile);

                        CurrentFigureObraz.WriteObrazLog(FigureFileName);

                        //Работа с вектором

                        Vector CurrentFigureVector = new Vector(CurrentFigureObraz, Y_fragmentation, X_fragmentation);

                        CurrentFigureVector.WriteVectorLog(FigureFileName);

                        //Получение ответа
                        String NeuralNetworkAnswer = MainPerceptron.GetAnswerFromVector(CurrentFigureVector.complete_vector); //Ответ сети

                        RecognitionResultsTextBox.Text += (NeuralNetworkAnswer + " ");                                        //Запись результата

                        //Запись в лог распознавания
                        File.AppendAllText(RecognitionLogFilePath, NeuralNetworkAnswer + " ");
                    }

                    File.AppendAllText(RecognitionLogFilePath, Environment.NewLine + "///////////////////////" + Environment.NewLine);   //Закрытие лога распознавания
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка при попытке распознавания вне функции распознавания", "Форма", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                if (FiguresToRecognizeFileDialog != null)
                {
                    FiguresToRecognizeFileDialog.Dispose();
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Обучение на всех обучающих наборах
        /// </summary>
        /// <param name="Y_frag">Разбиения вертикальной составляющей</param>
        /// <param name="X_frag">Разбиения горизонтальной составляющей</param>
        /// <returns>Количество итераций, за которое произошло полное обучение</returns>
        private uint TeachOnAllTeachingSets(uint Y_frag, uint X_frag)
        {
            try
            {
                SetMainPerceptronVectorLength(Y_frag, X_frag);

                //Если не создан каталог для хранения информации об обучающих наборах
                String TeachingSetsInformationCatalogPath = Directory.GetCurrentDirectory() + DefaultTeachingSetsInformationCatalog;

                if (!Directory.Exists(TeachingSetsInformationCatalogPath))
                {
                    Directory.CreateDirectory(TeachingSetsInformationCatalogPath);
                }


                uint TeachingSetsCount = Convert.ToUInt32(TeachingSetsCountTextBox.Text); //Количество заданных обучающих наборов

                bool EveryTeachingSuccessful = false;                                     //Прошло ли каждое обучение успешно

                uint IterationsAmount = 0;                                                //Количество итераций


                //Цикл обучения
                while (!EveryTeachingSuccessful)
                {
                    EveryTeachingSuccessful = true;

                    for (uint CurrentTeachingSet = 0; CurrentTeachingSet < TeachingSetsCount; ++CurrentTeachingSet)                 //Проход по всем обучающим наборам
                    {
                        for (uint CurrentFigureIndex = 0; CurrentFigureIndex < MainPerceptron.Figures_Amount; ++CurrentFigureIndex) //Проход по каждой фигуре в наборе
                        {
                            //Работа с образом

                            Obraz CurrentObraz = new Obraz(); //Образ текущего изображения

                            //Создание образов необходимо только на первом этапе для создания векторов
                            if (IterationsAmount == 0)
                            {
                                String ObrazName =
                                    Obraz.GetDefaultObrazName
                                    (
                                        Path.GetFileNameWithoutExtension
                                        (
                                            GetDefaultTeachingSetFileName(MainPerceptron.figures_array[CurrentFigureIndex], CurrentTeachingSet)
                                        )
                                    );                                                                              //Имя образа изображения

                                String CurrentFigureObrazFilePath = TeachingSetsInformationCatalogPath + ObrazName; //Путь к файлу текущего образа

                                if (File.Exists(CurrentFigureObrazFilePath))                                        //Попытка получения уже существующего образа
                                {
                                    CurrentObraz.LoadObrazFromFile(CurrentFigureObrazFilePath);
                                }
                                else  //Создание нового образа
                                {
                                    String CurrentFigureFilePath = TeachingSetsFilePaths.ElementAt(( int )(CurrentTeachingSet * MainPerceptron.Figures_Amount + CurrentFigureIndex));      //Путь к текущему файлу изображения

                                    CurrentObraz = new Obraz(CurrentFigureFilePath);

                                    CurrentObraz.WriteObrazLog(Path.GetFileNameWithoutExtension(CurrentFigureFilePath), DefaultTeachingSetsInformationCatalog);
                                }
                            }

                            //Работа с вектором

                            Vector CurrentVector = new Vector();

                            //Попытка получения уже существующего вектора
                            if (IterationsAmount != 0)
                            {
                                String VectorName =
                                    Vector.GetDefaultVectorName
                                    (
                                        Path.GetFileNameWithoutExtension
                                        (
                                            GetDefaultTeachingSetFileName(MainPerceptron.figures_array[CurrentFigureIndex], CurrentTeachingSet)
                                        )
                                    ); //Имя вектора изображения

                                String CurrentFigureVectorPath = TeachingSetsInformationCatalogPath + VectorName;

                                if (File.Exists(CurrentFigureVectorPath))
                                {
                                    CurrentVector.LoadVectorFromFile(CurrentFigureVectorPath, Y_frag, X_frag);
                                }
                            }
                            else //Создание нового вектора
                            {
                                String CurrentFigureFilePath = TeachingSetsFilePaths.ElementAt(( int )(CurrentTeachingSet * MainPerceptron.Figures_Amount + CurrentFigureIndex));      //Путь к текущему файлу изображения

                                CurrentVector = new Vector(CurrentObraz, Y_frag, X_frag);

                                CurrentVector.WriteVectorLog(Path.GetFileNameWithoutExtension(CurrentFigureFilePath), DefaultTeachingSetsInformationCatalog);
                            }

                            //Обучение

                            bool CurrentTeachingResult = MainPerceptron.TeachPerceptronOnFigure(CurrentVector.complete_vector, MainPerceptron.figures_array[CurrentFigureIndex]);     //Попытка обучения

                            if (CurrentTeachingResult == false)
                            {
                                EveryTeachingSuccessful = false;
                            }
                        }
                    }

                    ++IterationsAmount;
                }

                return(IterationsAmount);
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка при обучении на всех обучающих наборах во внутренней функции", "Форма", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(0);
            }
        }
Beispiel #10
0
        public void Obraz_ShouldHaveLabelWithoutUnderscore()
        {
            var obraz = new Obraz(fileName: @"c:\Obrazy\LabelWithoutUnderscore2.jpg");

            obraz.Etykieta.ShouldBe("LabelWithoutUnderscore2");
        }
Beispiel #11
0
        public void Obraz_ShouldHaveLabel()
        {
            var obraz = new Obraz(fileName: @"c:\Obrazy\Test_Label1.jpg");

            obraz.Etykieta.ShouldBe("Label1");
        }