예제 #1
0
 private void load()
 {
     lock (lockObj)
     {
         if (loaded != 0)
         {
             return;
         }
         string extension = FileUtils.getExtension(filename);
         try
         {
             UI.printInfo(UI.Module.TEX, "Reading texture bitmap from: \"{0}\" ...", filename);
             BitmapReader reader = PluginRegistry.bitmapReaderPlugins.createObject(extension);
             if (reader != null)
             {
                 bitmap = reader.load(filename, isLinear);
                 if (bitmap.getWidth() == 0 || bitmap.getHeight() == 0)
                 {
                     bitmap = null;
                 }
             }
             if (bitmap == null)
             {
                 UI.printError(UI.Module.TEX, "Bitmap reading failed");
                 bitmap = new BitmapBlack();
             }
         }
         catch (Exception e)
         {
             UI.printError(UI.Module.TEX, "{0}", e);
         }
         loaded = 1;
     }
 }
예제 #2
0
        static void Experiment5Taskv2Performence()
        {
            int    level = 2;
            string name  = "lenna";

            Logger.Info(name);
            string inputName = $"../../../test_images/{name}.png";
            Bitmap input     = new Bitmap(inputName);
            Bitmap output    = new Bitmap(input.Width, input.Height, input.PixelFormat);

            var imageReader = new BitmapReader <int>(input);
            var mallat      = new MallatDecomposition <int, NineSevenBiortogonalInteger <int> >(imageReader).Build(input.Size, level);

            Logger.Info(mallat.ToString());
            var    calculator      = new MallatEntropyEvaluator <int>(input.Size, level, mallat);
            var    mallatCollector = new MallatMerger <int>(input.Size, level, mallat);
            var    imageWriter     = new BitmapWriter <int>(new Bitmap(input.Width, input.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb), "", mallatCollector);
            string outputName      = $"{inputName}_{mallat.ToString()}.png";

            imageWriter.SetImageName(outputName);
            calculator.DataLength = 3;

            var sw = System.Diagnostics.Stopwatch.StartNew();

            Logger.Info("Sync:");
            imageWriter.Process();
            Logger.Info($"Time:\t{sw.Elapsed}");
            sw.Restart();
            Logger.Info("Async v2:");
            imageWriter.ProcessAsync();
            Logger.Info($"Time:\t{sw.Elapsed}");
        }
예제 #3
0
 public void ExportAltitudes(string directory, int x, int y, IUltimaMapDataProvider manager)
 {
     using (var bitmap = BitmapReader.ExportAltitude(manager, x, y, EventExtractAltitudeProgress))
     {
         bitmap.Save(Path.Combine(directory, "Altitude.BMP"), ImageFormat.Bmp);
     }
     GC.Collect();
     EventEndExtractAltitudeEnd(this, EventArgs.Empty);
 }
예제 #4
0
        static void TesterParameterDemo()
        {
            string inputName   = "../../../test_images/lenna.png";
            Bitmap input       = new Bitmap(inputName);
            var    imageReader = new BitmapReader <float>(input);
            var    mallat      = new MallatDecomposition <float, Haar <float> >(imageReader).Build(input.Size, 1);
            var    imageWriter = new BitmapWriter <float>(new Bitmap(input.Size.Width, input.Size.Height), "", mallat);
            var    tester      = new ParameterTester <float>(imageWriter)
                                 .SetNextParameters(new ParameterStorage().SetParameter("outputName", "../lenna_1.png"))
                                 .SetNextParameters(new ParameterStorage().SetParameter("outputName", "../lenna_2.png"))
                                 .SetNextParameters(new ParameterStorage().SetParameter("outputName", "../lenna_3.png"));

            tester.RunSync();
        }
        public void ReadTest()
        {
            using (var fileStream = new FileStream("Evic11.dec", FileMode.Open, FileAccess.Read))
            {
                var bitmapReader = new BitmapReader();
                var actualBitmap = bitmapReader.Read(fileStream, 0x2FC1);
                BitmapData actualBitmapData = null;
                byte[] actual;
                try
                {
                    actualBitmapData =
                        actualBitmap.LockBits(
                            new Rectangle(0, 0, actualBitmap.Width, actualBitmap.Height),
                            ImageLockMode.WriteOnly,
                            PixelFormat.Format1bppIndexed);
                    actual = new byte[actualBitmap.Height * actualBitmapData.Stride];
                    Marshal.Copy(actualBitmapData.Scan0, actual, 0, actual.Length);
                }
                finally
                {
                    if (actualBitmapData != null)
                    {
                        actualBitmap.UnlockBits(actualBitmapData);
                    }
                }

                var expectedBitmap = (Bitmap)Image.FromFile("Evic11_0x2FC1.bmp");
                BitmapData expectedBitmapData = null;
                byte[] expected;
                try
                {
                    expectedBitmapData =
                        expectedBitmap.LockBits(
                            new Rectangle(0, 0, expectedBitmap.Width, expectedBitmap.Height),
                            ImageLockMode.WriteOnly,
                            PixelFormat.Format1bppIndexed);
                    expected = new byte[expectedBitmap.Height * expectedBitmapData.Stride];
                    Marshal.Copy(expectedBitmapData.Scan0, expected, 0, expected.Length);
                }
                finally
                {
                    if (expectedBitmapData != null)
                    {
                        expectedBitmap.UnlockBits(expectedBitmapData);
                    }
                }

                CollectionAssert.AreEquivalent(expected, actual);
            }
        }
        private async void SaveHandler()
        {
            try
            {
                var             id   = Global.LoggedUser.ID;
                RepositoryModel item = null;
                await Task.Run(() =>
                {
                    using (CoreContext context = new CoreContext())
                    {
                        Repository repo = new DataLayer.Models.Repository()
                        {
                            SampleImage = Repository.SampleImage,
                            UserID      = Repository.UserID
                        };
                        var user = context.Users.FirstOrDefault(x => x.ID == id);
                        if (user != null)
                        {
                            user.Repositories.Add(repo);
                            context.SaveChanges();
                            BitmapImage image = BitmapReader.Read(Repository.SampleImage);
                            Bitmap bitmap     = BitmapConversion.BitmapImageToBitmap(image);
                            item = new RepositoryModel
                            {
                                ID          = repo.ID,
                                UserID      = repo.UserID,
                                SampleImage = repo.SampleImage,
                                Image       = BitmapConversion.BitmapToBitmapSource(bitmap),
                            };
                        }
                    }
                });

                if (item != null)
                {
                    Repositories.Add(item);
                    Repository = null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogException(new string[] { ex.ToString() });
            }
        }
예제 #7
0
        static void Experiment7()
        {
            string name      = "barbara";
            string folder    = "../../../test_images";
            string inputName = $"{folder}/{name}.png";

            Logger.Info(inputName);
            Bitmap input   = new Bitmap(inputName);
            Bitmap output1 = new Bitmap(input.Width / 2, input.Height, input.PixelFormat);
            Bitmap output2 = new Bitmap(input.Width / 2, input.Height, input.PixelFormat);

            var imageReader  = new BitmapReader <int>(input);
            var d4           = new DaubechiesWaveletD4Integer <int>(imageReader);
            var imageWriter1 = new BitmapWriter <int>(output1, $"{folder}/Experiment7_barbara_0.png", d4[0]);
            var imageWriter2 = new BitmapWriter <int>(output1, $"{folder}/Experiment7_barbara_1.png", d4[1]);

            imageWriter1.ProcessAsync();
            imageWriter2.ProcessAsync();
        }
예제 #8
0
        private static void RunCase(int no, char color, Position pos)
        {
            var input  = Fixture.Resource($"Case{no}-Input.txt");
            var output = Fixture.Resource($"Case{no}-Output.txt");

            var bitmap  = new BitmapReader().Read(input);
            var canvas  = new Canvas(bitmap);
            var surface = new Surface(canvas);

            surface.Fill(pos, color);

            var result = new StringBuilder();

            new BitmapWriter(bitmap).Write(result);

            var newLine  = Environment.NewLine;
            var expected = $"{newLine}{output}{newLine}";
            var actual   = $"{newLine}{result.ToString()}{newLine}";

            Fixture.AreEqual(expected, actual);
        }
예제 #9
0
        static void Main(string[] args)
        {
            KnnTrainResult <SURFFeature> TrainedFeatures  = new KnnTrainResult <SURFFeature>();
            SURFFeatureExtractor         FeatureExtractor = new SURFFeatureExtractor(threshold, octaves, initial)
            {
                ExtractNegativeOnly = true, MinimumScale = minimumScale
            };

            //Training
            foreach (var SamplePathTag_Pair in SamplePathTag_Pairs)
            {
                string Path = SamplePathTag_Pair.Key;
                string Tag  = SamplePathTag_Pair.Value;

                BitmapReader TestSampleBitmapReader = new BitmapReader(Path);
                var          Bitmaps = TestSampleBitmapReader.GetBitmaps();

                Console.WriteLine("Extract features from tag:{0}, path:{1}", Tag, Path);

                var features = FeatureExtractor.ExtractFeatures(Bitmaps, Tag);
                Console.WriteLine("Features extract ,Count:{0}", features.Count());

                var knnTrainer     = new KnnTrainer <SURFFeature>(features);
                var knnTrainResult = knnTrainer.Train();
                TrainedFeatures.AddRange(knnTrainResult);

                foreach (var b in Bitmaps)
                {
                    b.Dispose();
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            Application.EnableVisualStyles();
            Application.Run(new MainForm(FeatureExtractor, TrainedFeatures));
        }
        public async void LoadSamples()
        {
            try
            {
                var id = Global.LoggedUser.ID;
                List <RepositoryModel> list = new List <RepositoryModel>();
                await Task.Run(() =>
                {
                    using (CoreContext context = new CoreContext())
                    {
                        var result = context.Repositories.Where(x => x.UserID == id).ToList();
                        if (result != null && result.Count > 0)
                        {
                            foreach (var item in result)
                            {
                                RepositoryModel model = new RepositoryModel
                                {
                                    ID          = item.ID,
                                    UserID      = item.UserID,
                                    SampleImage = item.SampleImage
                                };

                                BitmapImage image = BitmapReader.Read(item.SampleImage);
                                Bitmap bitmap     = BitmapConversion.BitmapImageToBitmap(image);
                                model.Image       = BitmapConversion.BitmapToBitmapSource(bitmap);

                                list.Add(model);
                            }
                            Repositories = new ObservableCollection <RepositoryModel>(list);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogHelper.LogException(new string[] { ex.ToString() });
            }
        }
예제 #11
0
        private void LoadPath_btn_Click(object sender, EventArgs e)
        {
            string path = FolderPath_TextBox.Text;

            if (String.IsNullOrEmpty(path) == false && Directory.Exists(path))
            {
                string ResultPath = path + "\\Result\\";
                Directory.CreateDirectory(ResultPath);
                BitmapReader bitmapReader = new BitmapReader(path);
                var          bitmaps      = bitmapReader.GetBitmaps();
                foreach (var b in bitmaps)
                {
                    string Filename          = b.Tag as string;
                    var    RecognizedBitmaps = DoRecognize(b);
                    foreach (var RecognizedBitmap in RecognizedBitmaps)
                    {
                        RecognizedBitmap.Save(ResultPath + Filename + (RecognizedBitmap.Tag as string) + ".png", System.Drawing.Imaging.ImageFormat.Png);

                        RecognizedBitmap.Dispose();
                    }
                }
            }
        }
예제 #12
0
        static void ExperimentEntropy(string name, int level)
        {
            string folder    = "../../../test_images";
            string inputName = $"{folder}/{name}.png";

            Logger.Info(inputName);
            Bitmap input  = new Bitmap(inputName);
            Bitmap output = new Bitmap(input.Width, input.Height, input.PixelFormat);

            var tester = new MallatTester <int>((GetMallat) =>
            {
                var imageReader = new BitmapReader <int>(input);
                var mallat      = GetMallat(imageReader);
                Logger.Info(mallat.ToString());
                var calculator      = new MallatEntropyEvaluator <int>(input.Size, level, (Segment <int>)mallat);
                var mallatCollector = new MallatMerger <int>(input.Size, level, (Segment <int>)mallat);
                var imageWriter     = new BitmapWriter <int>(new Bitmap(input.Width, input.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb), "", mallatCollector);
                string outputName   = $"{folder}/{level}/{name}_{mallat.ToString()}.png";
                imageWriter.SetImageName(outputName);
                calculator.DataLength = 3;
                return(new Node <int>[] { imageWriter, calculator });
            });

            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, TwoTwoInterpolatingInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, FourTwoInterpolatingInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, TwoFourInterpolatingInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, FourFourInterpolatingInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, TwoPlusTwoTwoInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, DaubechiesWaveletD4Integer <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, NineSevenBiortogonalInteger <int> >(predecessor).Build(input.Size, level)); });
            tester.AddNewMallat((predecessor) => { return(new MallatDecomposition <int, BaseWavelet <int> >(predecessor).Build(input.Size, level)); });

            var sw = System.Diagnostics.Stopwatch.StartNew();

            tester.RunAsync();
            Logger.Info($"Time:\t{sw.Elapsed}");
        }
예제 #13
0
        /// <inheritdoc/>
        public async Task <ProcessResultModel> ProcessAsync(ProcessPathCommand command, CancellationToken ct)
        {
            Ensure.ArgumentNotNull(command, nameof(command));
            Ensure.ArgumentNotNull(ct, nameof(ct));

            ImageFormat imageFormat    = GetImageFormat(command.ImageFormat);
            string      imageExtension = imageFormat.FileExtensionFromEncoder();

            if (string.IsNullOrWhiteSpace(imageExtension))
            {
                throw new UnexpectedNullException("Image file extension could not be determined.");
            }

            var fs = fileSystemStrategy.Create(command.DestinationPath);

            if (fs == null)
            {
                throw new UnexpectedNullException("Filesystem could not be created based on the destination path.");
            }

            var reader = readerFactory.Create();

            if (reader == null)
            {
                throw new UnexpectedNullException("Image reader could not be created.");
            }

            await reader.InitAsync(command.SourcePath, ct);

            reader.Mapper = new AxisPositionMapper(command.AmountPerAxis, reader.Width, reader.Height, reader.Depth);

            PreProcess(reader, imageFormat, command.AmountPerAxis, command.OutputSize);

            var result = new ProcessResultModel
            {
                LabelCount = Convert.ToInt32(reader.GetLabelCount()),
                Size       = new int[] { reader.Width, reader.Height, reader.Depth }
            };

            ISet <AxisType> axisTypes = new HashSet <AxisType>(command.AxisTypes);

            if (axisTypes.Count == 0)
            {
                axisTypes = new HashSet <AxisType> {
                    AxisType.Z
                };
            }

            BitmapWrapper watermark = null;

            if (!string.IsNullOrWhiteSpace(command.WatermarkSourcePath))
            {
                BitmapReader bitmapReader    = new BitmapReader();
                var          watermarkBitmap = await bitmapReader.ReadAsync(command.WatermarkSourcePath, command.OutputSize, ct);

                if (watermarkBitmap == null)
                {
                    throw new UnexpectedNullException("Watermark could not be read.");
                }

                watermark = new BitmapWrapper(watermarkBitmap);
            }

            var images = new List <PositionAxisContainerModel <string> >();

            foreach (AxisType axisType in axisTypes)
            {
                for (int i = 0; i < reader.Mapper.GetLength(axisType); i++)
                {
                    ct.ThrowIfCancellationRequested();

                    string filename = $"{axisType}_{i}{imageExtension}";

                    var image = WriteImage(i, fs, command, reader, axisType, imageFormat, filename, watermark);
                    if (image != null)
                    {
                        images.Add(image);
                    }
                }
            }

            reader.Dispose();

            result.Images = images.OrderBy(e => e.Position).ToList();

            return(result);
        }
예제 #14
0
        public void MapMake(string directory, string bitmaplocation, string bitmapZLocation, int x, int y, int index)
        {
            CollectionColorArea.InitializeSeaches();
            CollectionAreaTexture.InitializeSeaches();
            var list_errors = new List <string>();

            foreach (var VARIABLE in CollectionColorArea.List)
            {
                Elements.Textures.TextureArea.AreaTextures area;
                CollectionAreaTexture._fast.TryGetValue(VARIABLE.TextureIndex, out area);
                if (VARIABLE.Max < VARIABLE.Min)
                {
                    var tmp = VARIABLE.Max;
                    VARIABLE.Max = VARIABLE.Min;
                    VARIABLE.Min = tmp;
                }

                if (area != null || VARIABLE.Type == TypeColor.Cliff)
                {
                    continue;
                }

                var error = VARIABLE.Name + @" refers to a non-existent texture '" + VARIABLE.TextureIndex + @"' not found";
                list_errors.Add(error);
            }

            if (list_errors.Count > 0)
            {
                string errors = "";
                foreach (var error_in in list_errors)
                {
                    errors += error_in + '\n';
                }

                throw new Exception(errors);
            }

            var task = new Task[2];



            var taskMapBitmap =
                Task <AreaColor[]> .Factory.StartNew(() => BitmapReader.ColorsFromBitmap(CollectionColorArea,
                                                                                         bitmaplocation, x, y));

            var taskMapZ = Task <sbyte[]> .Factory.StartNew(() => BitmapReader.AltitudeFromBitmapVersion2(bitmapZLocation, x, y));

            task[0] = taskMapBitmap;
            task[1] = taskMapZ;
            try
            {
                Task.WaitAll(task);
            }
            catch (Exception e)
            {
                throw e;
            }
            GC.Collect();

            var mulmaker = new MapMaking.MapMaker(taskMapZ.Result, taskMapBitmap.Result, x, y, index)
            {
                CollectionAreaColor = CollectionColorArea,
                TextureAreas        = CollectionAreaTexture,
                AutomaticZMode      = AutomaticMode,
                MulDirectory        = directory
            };

            mulmaker.ProgressText += EventProgress;

            try
            {
                mulmaker.Bmp2Map();
                OnMakingMap(EventArgs.Empty);
            }
            catch (Exception e)
            {
                throw e;
            }
            GC.Collect();
        }
        /// <summary>
        /// Processes the images asynchronous.
        /// </summary>
        /// <param name="command">The command information.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>
        /// The result of the image processing.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// command
        /// or
        /// ct
        /// </exception>
        /// <exception cref="UnexpectedNullException">
        /// Image file extension could not be determined.
        /// or
        /// Filesystem could not be created based on the destination path.
        /// or
        /// Image reader could not be created.
        /// or
        /// Watermark could not be read.
        /// or
        /// Bitmap could not be centered.
        /// </exception>
        public async Task <ProcessResultModel> ProcessAsync(ProcessPathCommand command, CancellationToken ct)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

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

            var result         = new ProcessResultModel();
            var imageFormat    = GetImageFormat(command.ImageFormat);
            var imageExtension = imageFormat.FileExtensionFromEncoder();

            if (string.IsNullOrWhiteSpace(imageExtension))
            {
                throw new UnexpectedNullException("Image file extension could not be determined.");
            }

            var fs = fileSystemStrategy.Create(command.DestinationPath);

            if (fs == null)
            {
                throw new UnexpectedNullException("Filesystem could not be created based on the destination path.");
            }

            var reader = readerFactory.Create();

            if (reader == null)
            {
                throw new UnexpectedNullException("Image reader could not be created.");
            }

            await reader.InitAsync(command.SourcePath, ct);

            reader.Mapper = new AxisPositionMapper(Convert.ToUInt32(command.AmountPerAxis), reader.Width, reader.Height, reader.Depth);

            PreProcess(reader, imageFormat, Convert.ToUInt32(command.AmountPerAxis), Convert.ToUInt32(command.DesiredSize));

            result.LabelCount = Convert.ToInt32(reader.GetLabelCount());

            ISet <AxisType> axisTypes = new HashSet <AxisType>(command.AxisTypes);

            if (axisTypes.Count == 0)
            {
                axisTypes = reader.GetRecommendedAxisTypes();
            }

            BitmapWrapper watermark = null;

            if (!string.IsNullOrWhiteSpace(command.WatermarkSourcePath))
            {
                BitmapReader bitmapReader    = new BitmapReader();
                var          watermarkBitmap = await bitmapReader.ReadAsync(command.WatermarkSourcePath, Convert.ToUInt32(command.DesiredSize), ct);

                if (watermarkBitmap == null)
                {
                    throw new UnexpectedNullException("Watermark could not be read.");
                }

                watermark = new BitmapWrapper(watermarkBitmap);
            }

            var images = new List <PositionAxisContainerModel <string> >();

            foreach (AxisType axisType in axisTypes)
            {
                for (int i = 0; i < command.AmountPerAxis; i++)
                {
                    ct.ThrowIfCancellationRequested();
                    string filename = $"{axisType}_{i}{imageExtension}";
                    var    bitmap   = reader.ExtractPosition(axisType, Convert.ToUInt32(i), Convert.ToUInt32(command.DesiredSize));
                    if (bitmap != null)
                    {
                        if (command.Grayscale)
                        {
                            bitmap = bitmap.To8bppIndexedGrayscale();
                        }

                        bitmap = bitmap.ToCenter(Convert.ToUInt32(command.DesiredSize), Color.Black);
                        if (bitmap == null)
                        {
                            throw new UnexpectedNullException("Bitmap could not be centered.");
                        }

                        if (watermark != null)
                        {
                            bitmap = bitmap.AppendWatermark(watermark);
                        }

                        fs.File.WriteAllBytes(fs.Path.Combine(command.DestinationPath, filename), bitmap.ToByteArray(imageFormat));
                        images.Add(new PositionAxisContainerModel <string>(Convert.ToUInt32(i), axisType, filename));
                    }
                }
            }

            result.Images = images.OrderBy(e => e.Position).ToList();

            return(result);
        }