Beispiel #1
0
        public override void OnCreate()
        {
            base.OnCreate();

            entity.AddTag("Map");

            cells = new Array2D <int>(128, 128);

            mapCollider = entity.AddComponent <MapCollider>();
            mapCollider.cell2CollisionValue              = new int[Cell.COUNT];
            mapCollider.cell2CollisionValue[Cell.VOID]   = 1;
            mapCollider.cell2CollisionValue[Cell.GROUND] = 0;
            mapCollider.cell2CollisionValue[Cell.WALL]   = 1;
            mapCollider.cell2CollisionValue[Cell.TRUNK]  = 1;

            mapRenderer = entity.AddComponent <MapRenderer>();
            mapRenderer
            .SetTexture("terrain", RenderMode.BASE)
            .SetTexture("terrain_light_filter", RenderMode.LIGHT_FILTER)
            .SetTexture("black", RenderMode.LIGHT_MAP)
            .SetLayer(ViewLayers.TERRAIN);

            Tiler tiler = mapRenderer.tiler;

            tiler.AddPattern(new TilerPattern(Cell.GROUND, 0));
            tiler.AddPattern(new TilerPattern(Cell.WALL, 1));
            tiler.AddPattern(new TilerPattern(Cell.TRUNK, 2));
        }
Beispiel #2
0
        public void EnsureSameTileNotRenderedTwice_ForWeirdlyOrderedResultsReversed()
        {
            ISuperTile[] testCases =
            {
                new TimeOffsetSingleLayerSuperTile(TimeSpan.Zero, SpectrogramType.Index, 0.16.Seconds(), Image.Load <Rgba32>(PathHelper.ResolveAssetPath("[email protected]_0.png")), TimeSpan.FromMinutes(0)),
                new TimeOffsetSingleLayerSuperTile(TimeSpan.Zero, SpectrogramType.Index, 0.16.Seconds(), Image.Load <Rgba32>(PathHelper.ResolveAssetPath("[email protected]_1.png")), TimeSpan.FromMinutes(1)),
            };

            // scale size results in two images drawn
            var singleScaleTiler = new Tiler(
                this.outputDirectory,
                this.tilingProfile,
                new SortedSet <double>()
            {
                0.16
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1
            },
                1.0,
                300);

            // test
            // super tile 2 -> image b , c
            // super tile 1 -> image a , b
            // second super tile call fails because duplicate b
            singleScaleTiler.Tile(testCases[1]);
            TestHelper.ExceptionMatches <DuplicateTileException>(
                () => { singleScaleTiler.Tile(testCases[0]); },
                "Tile 'panojstile_00000_00001_00000' has already been created.");
        }
        public void Setup()
        {
            this.tilingProfile = new AbsoluteDateTilingProfile(
                "Filename",
                "Tile",
                new DateTimeOffset(2015, 04, 10, 0, 0, 0, TimeSpan.FromHours(10)),
                256,
                60);
            this.tilingProfileNotRoundStart = new AbsoluteDateTilingProfile(
                "Filename",
                "Tile",
                this.dateTimeOffset,
                256,
                60);

            this.outputDirectory = PathHelper.GetTempDir();

            this.tiler = new Tiler(
                this.outputDirectory.ToDirectoryEntry(),
                this.tilingProfile,
                new SortedSet <double>()
            {
                60.0
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1
            },
                1.0,
                256);
        }
 public void SetUp()
 {
     tiler = new FlatTiler();
     tiler.MaxZoomLevel = 15;
     tiler.NumberOfTiles = 4;
     tiler.ImageFetchFunction = Tiler_Test.FetchFunction;
 }
Beispiel #5
0
        public void TestGetImagePartsNonInstersectingRectangle()
        {
            var baseRectangle  = new Rectangle(100, 100, 100, 100);
            var otherRectangle = new Rectangle(0, 0, 50, 50);

            Tiler.GetImageParts(baseRectangle, otherRectangle);
        }
    protected void Awake()
    {
        if (renderer == null)
        {
            renderer = GetComponent <SpriteRenderer>();
        }
        if (camera == null)
        {
            Debug.LogError("A camera must be specified");
        }
        else
        {
            if (!camera.orthographic)
            {
                camera.orthographic = true;
                Debug.LogWarning("The Camera has been set to orthographic mode");
            }
        }

        if (renderer.sprite == null)
        {
            Debug.LogError("The Sprite Renderer must have a sprite");
        }
        else
        {
            spriteWidth = renderer.sprite.bounds.size.x;
        }

        left = right = null;

        start  = transform.position;
        offset = start - camera.transform.position;
    }
Beispiel #7
0
        private async void btnFetch_Click_1(object sender, EventArgs e)
        {
            // fetch an existing tile
            ITiler tiler = new Tiler();
            var    tile  = await tiler.FetchTile(txtDir.Text, Int32.Parse(txtX.Text), Int32.Parse(txtX.Text), Int32.Parse(txtX.Text));

            listBox1.Items.Add($"Tile returned. Size:{tile.Length}");
        }
Beispiel #8
0
        public static byte[] EncodeJPEG(Image jpgImage)
        {
            Tiler                 imgtiler;
            ForwCompTransf        fctransf;
            ImgDataConverter      converter;
            EncoderSpecs          encSpec;
            ForwardWT             dwt;
            Quantizer             quant;
            ROIScaler             rois;
            EntropyCoder          ecoder;
            PostCompRateAllocator ralloc;
            HeaderEncoder         headenc;
            CodestreamWriter      bwriter;

            float rate = Single.MaxValue;

            ImgReaderGDI imgsrc = new ImgReaderGDI(jpgImage);

            imgtiler = new Tiler(imgsrc, 0, 0, 0, 0, jpgImage.Width, jpgImage.Height);
            int ntiles = imgtiler.getNumTiles();

            encSpec = new EncoderSpecs(ntiles, 3, imgsrc, pl);

            fctransf  = new ForwCompTransf(imgtiler, encSpec);
            converter = new ImgDataConverter(fctransf);
            dwt       = ForwardWT.createInstance(converter, pl, encSpec);
            quant     = Quantizer.createInstance(dwt, encSpec);
            rois      = ROIScaler.createInstance(quant, pl, encSpec);
            ecoder    = EntropyCoder.createInstance(rois, pl, encSpec.cblks,
                                                    encSpec.pss, encSpec.bms,
                                                    encSpec.mqrs, encSpec.rts,
                                                    encSpec.css, encSpec.sss,
                                                    encSpec.lcs, encSpec.tts);

            using (MemoryStream stream = new MemoryStream())
            {
                bwriter = new FileCodestreamWriter(stream, Int32.MaxValue);
                ralloc  = PostCompRateAllocator.createInstance(ecoder, pl, rate, bwriter, encSpec);

                headenc = new HeaderEncoder(imgsrc, new bool[3], dwt, imgtiler, encSpec, rois, ralloc, pl);
                ralloc.HeaderEncoder = headenc;
                headenc.encodeMainHeader();
                ralloc.initialize();
                headenc.reset();
                headenc.encodeMainHeader();
                bwriter.commitBitstreamHeader(headenc);

                ralloc.runAndWrite();
                bwriter.close();

                return(stream.ToArray());
            }
        }
Beispiel #9
0
        public void EnsureSameThreeTilesWrittenForTwoOddlySizedSuperTiles()
        {
            ISuperTile[] testCases =
            {
                new TimeOffsetSingleLayerSuperTile(TimeSpan.Zero, SpectrogramType.Index, 0.16.Seconds(), Image.Load <Rgba32>(PathHelper.ResolveAssetPath("[email protected]_0.png")), TimeSpan.FromMinutes(0)),
                new TimeOffsetSingleLayerSuperTile(TimeSpan.Zero, SpectrogramType.Index, 0.16.Seconds(), Image.Load <Rgba32>(PathHelper.ResolveAssetPath("[email protected]_1.png")), TimeSpan.FromMinutes(1)),
            };

            var singleScaleTiler = new Tiler(
                this.outputDirectory.ToDirectoryEntry(),
                this.tilingProfile,
                new SortedSet <double>()
            {
                0.16
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1
            },
                1.0,
                300);

            // test
            // super tile 1 -> image a , b
            // super tile 2 -> image c
            singleScaleTiler.Tile(null, testCases[0], testCases[1]);
            singleScaleTiler.Tile(testCases[0], testCases[1], null);

            var producedFiles = this.outputDirectory.GetFiles().OrderBy(x => x.Name).ToArray();

            Assert.AreEqual(3, producedFiles.Length);

            var expectedImages =
                new[]
            {
                "panojstile_00000_00000_00000.png", "panojstile_00000_00001_00000.png", "panojstile_00000_00002_00000.png",
            }
            .OrderBy(x => x)
            .Select(x => PathHelper.ResolveAssetPath(x))
            .ToArray();

            var loadedImages = expectedImages.Select(Image.Load <Rgba32>).ToArray();

            for (int i = 0; i < loadedImages.Length; i++)
            {
                var producedImage = Image.Load <Rgba32>(producedFiles[i].FullName);
                var areEqual      = BitmapEquals(loadedImages[i], (producedImage));
                Assert.IsTrue(areEqual, "Bitmaps were not equal {0}, {1}", expectedImages[i], producedFiles[i].Name);
            }
        }
Beispiel #10
0
        private static void TileOutput(DirectoryInfo outputDirectory, string fileStem, string analysisTag, FileSegment fileSegment, Image <Rgb24> image)
        {
            const int TileHeight = 256;
            const int TileWidth  = 60;

            // seconds per pixel
            const double Scale = 60.0;
            TimeSpan     scale = Scale.Seconds();

            if (image.Height != TileHeight)
            {
                throw new InvalidOperationException("Expecting images exactly the same height as the defined tile height");
            }

            // if recording does not start on an absolutely aligned hour of the day
            // align it, then adjust where the tiling starts from, and calculate the offset for the super tile (the gap)
            var recordingStartDate = fileSegment.TargetFileStartDate.Value;

            // TODO: begin remove duplicate code
            var timeOfDay            = recordingStartDate.TimeOfDay;
            var previousAbsoluteHour = TimeSpan.FromSeconds(Math.Floor(timeOfDay.TotalSeconds / (Scale * TileWidth)) * (Scale * TileWidth));
            var gap              = timeOfDay - previousAbsoluteHour;
            var tilingStartDate  = recordingStartDate - gap;
            var tilingStartDate2 = ZoomTiledSpectrograms.GetPreviousTileBoundary(TileWidth, Scale, recordingStartDate);
            var padding          = recordingStartDate - tilingStartDate2;

            Debug.Assert(tilingStartDate == tilingStartDate2, "tilingStartDate != tilingStartDate2: these methods should be equivalent");

            // TODO: end remove duplicate code

            var tilingProfile = new AbsoluteDateTilingProfile(fileStem, analysisTag, tilingStartDate, TileHeight, TileWidth);

            // pad out image so it produces a whole number of tiles
            // this solves the asymmetric right padding of short audio files
            var width = (int)(Math.Ceiling(image.Width / Scale) * Scale);
            var tiler = new Tiler(outputDirectory, tilingProfile, Scale, width, 1.0, image.Height);

            // prepare super tile
            var tile = new TimeOffsetSingleLayerSuperTile(
                padding,
                SpectrogramType.Index,
                scale,
                image.CloneAs <Rgba32>(),
                fileSegment.SegmentStartOffset ?? TimeSpan.Zero);

            tiler.Tile(tile);
        }
    void CheckEdges(bool pool)
    {
        if (left == null || right == null)
        {
            float camWidth = camera.orthographicSize * camera.aspect;

            float edgeRight = transform.position.x + (spriteWidth / 2f);
            float edgeLeft  = transform.position.x - (spriteWidth / 2f);

            if (camera.transform.position.x + camWidth >= edgeRight + padding && right == null)
            {
                right = CreateTile(1, pool);
                right.CheckEdges(pool);
            }
            if (camera.transform.position.x - camWidth <= edgeLeft - padding && left == null)
            {
                left = CreateTile(-1, pool);
                left.CheckEdges(pool);
            }
        }
    }
Beispiel #12
0
        private async void button9_Click(object sender, EventArgs e)
        {
            // Make Bitmap Tile
            listBox1.Items.Add("Fetching DEM...");
            // class to get digital elevation models(DEM)
            BitmapDEMSource demSrc = new BitmapDEMSource();

            demSrc.Initalize(new MapHeader()
            {
                GridSize = Int32.Parse(txtTileSize.Text)
            });

            var elevData = await demSrc.GetDemXYZ(501, 190, 8); //) mp.GetTerrainTileAsync(x,y,z);

            listBox1.Items.Add($"DEM length {elevData.Elev.Length}");

            listBox1.Items.Add("Making Mesh...");
            // This class constructs a cesium quantized mesh from the dem
            var vertices = new Mesh().MakeFakeMesh(ref elevData);

            listBox1.Items.Add("Making Tile...");
            // This class constructs a quantized mesh tile mesh from the original mesh
            var tile = new Tiler().MakeTile(vertices,
                                            new TerrainTileHeader()
            {
                MinimumHeight = elevData.MinimumHeight, MaximumHeight = elevData.MaximumHeight
            },
                                            MapUtil.GridSizeToTriangleCount(elevData.GridSize), elevData.GridSize);

            listBox1.Items.Add($"Tile Ready. Size:{tile.Length} . Saving to {txtPath.Text}");

            var ms = new MemoryStream(tile);

            using (FileStream fs = new FileStream(txtPath.Text, FileMode.Create))
                using (GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress, false))
                {
                    zipStream.Write(ms.ToArray(), 0, ms.ToArray().Length); // .Write(bytes, 0, bytes.Length);
                }
        }
Beispiel #13
0
        public void Setup()
        {
            this.tilingProfile = new PanoJsTilingProfile();

            this.outputDirectory = PathHelper.GetTempDir();

            this.tiler = new Tiler(
                this.outputDirectory,
                this.tilingProfile,
                new SortedSet <double>()
            {
                60.0, 24, 12, 6, 2, 1
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1, 1, 1, 1, 1, 1
            },
                1.0,
                300);
        }
Beispiel #14
0
        public override bool Apply()
        {
            bool changed = false;

            for (int x = Area.X; x < Area.X + Area.Width; x++)
            {
                for (int y = Area.Y; y < Area.Y + Area.Height; y++)
                {
                    if (Grid[x, y] != Tileset)
                    {
                        changed = true;
                    }
                    Grid[x, y] = Tileset;
                }
            }

            Tiler.Update(DrawableRoom, Layer == ToolLayer.Foreground, Area);
            if (changed)
            {
                DrawableRoom.Dirty = true;
            }
            return(changed);
        }
Beispiel #15
0
        public void TestGetImageParts()
        {
            var baseRectangle = new Rectangle(100, 100, 100, 100);

            this.InitializeAnswers();

            for (int i = 0; i < this.testCases.Length; i++)
            {
                var testCase  = this.testCases[i];
                var fragments = Tiler.GetImageParts(baseRectangle, testCase);
                Assert.AreEqual(this.answers[i].Length, fragments.Length);

                for (int j = 0; j < fragments.Length; j++)
                {
                    var fragment = fragments[j];
                    var answer   = this.answers[i][j];

                    Assert.AreEqual(answer.XBias, fragment.XBias);
                    Assert.AreEqual(answer.YBias, fragment.YBias);
                    Assert.AreEqual(answer.Fragment, fragment.Fragment);
                }
            }
        }
        private static void GenerateStandardSpectrogramTiles(
            Dictionary <string, double[, ]> spectra,
            IndexGenerationData indexGeneration,
            LdSpectrogramConfig ldsConfig,
            Dictionary <string, IndexProperties> filteredIndexProperties,
            SpectrogramZoomingConfig zoomConfig,
            double[] standardScales,
            string fileStem,
            TilingProfile namingPattern,
            Tiler tiler,
            TimeSpan alignmentPadding)
        {
            Log.Info("START DRAWING ZOOMED-IN FRAME SPECTROGRAMS");

            TimeSpan dataDuration =
                TimeSpan.FromTicks(spectra["PMN"].GetLength(1) * indexGeneration.IndexCalculationDuration.Ticks);
            TimeSpan duration = indexGeneration.RecordingDuration;

            Contract.Requires(
                (dataDuration - duration).Absolute() < indexGeneration.IndexCalculationDuration,
                "The expected amount of data was not supplied");

            var minuteCount = (int)Math.Ceiling(dataDuration.TotalMinutes);

            // window the standard spectrogram generation so that we can provide adjacent supertiles to the
            // tiler, so that bordering / overlapping tiles (for cases where tile size != multiple of supertile size)
            // don't render partial tiles (i.e. bad/partial rendering of image)

            // this is the function generator
            // use of Lazy means results will only be evaluated once
            // and only when needed. This is useful for sliding window.
            Lazy <TimeOffsetSingleLayerSuperTile[]> GenerateStandardSpectrogramGenerator(int minuteToLoad)
            {
                return(new Lazy <TimeOffsetSingleLayerSuperTile[]>(
                           () =>
                {
                    Log.Info("Starting generation for minute: " + minuteToLoad);

                    var superTilingResults = DrawSuperTilesFromSingleFrameSpectrogram(
                        null /*inputDirectory*/,         //TODO:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        ldsConfig,
                        filteredIndexProperties,
                        zoomConfig,
                        minuteToLoad,
                        standardScales,
                        fileStem,
                        indexGeneration,
                        namingPattern.ChromeOption,
                        alignmentPadding);

                    return superTilingResults;
                }));
            }

            Lazy <TimeOffsetSingleLayerSuperTile[]> previous = null;
            Lazy <TimeOffsetSingleLayerSuperTile[]> current  = null;
            Lazy <TimeOffsetSingleLayerSuperTile[]> next     = null;

            for (int minute = 0; minute < minuteCount; minute++)
            {
                Log.Trace("Starting loop for minute" + minute);

                // shift each value back
                previous = current;
                current  = next ?? GenerateStandardSpectrogramGenerator(minute);

                next = minute + 1 < minuteCount?GenerateStandardSpectrogramGenerator(minute + 1) : null;

                // for each scale level of the results
                for (int i = 0; i < current.Value.Length; i++)
                {
                    // finally tile the output
                    Log.Debug("Begin tile production for minute: " + minute);
                    tiler.Tile(previous?.Value[i], current.Value[i], next?.Value[i]);
                    Log.Debug("Begin tile production for minute: " + minute);
                }
            }
        }
        public void TestLeftPaddingInLowerLayers()
        {
            const int TileWidth = 180;
            var       startDate = new DateTimeOffset(2014, 05, 29, 08, 13, 58, TimeSpan.FromHours(10));
            var       boundary  = ZoomTiledSpectrograms.GetPreviousTileBoundary(TileWidth, 0.1, startDate);
            var       padding   = startDate - boundary;

            var profile = new AbsoluteDateTilingProfile(
                "Filename",
                "Tile",
                boundary,
                256,
                TileWidth);

            var tiler = new Tiler(
                this.outputDirectory.ToDirectoryEntry(),
                profile,
                new SortedSet <double>()
            {
                60.0, 0.1
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1, 1
            },
                1.0,
                256);

            var testBitmap = new Bitmap(1200, 256);

            using (var graphics = Graphics.FromImage(testBitmap))
            {
                var points = new[]
                {
                    new Point(0, 0), new Point(180, 256), new Point(360, 0), new Point(540, 256), new Point(720, 0),
                    new Point(900, 256), new Point(1080, 0), new Point(1260, 256),
                };
                graphics.DrawLines(
                    Pens.Red,
                    points);
            }

            var superTile = new TimeOffsetSingleLayerSuperTile(
                padding,
                SpectrogramType.Index,
                0.1.Seconds(),
                testBitmap,
                0.Seconds());

            tiler.Tile(superTile);

            ////Debug.WriteLine(this.outputDirectory.FullName);
            ////Debug.WriteLine(this.outputDirectory.GetFiles().Length);
            var actualFiles = this.outputDirectory.GetFiles().OrderBy(x => x.Name).ToArray();

            Assert.AreEqual(8, actualFiles.Length);

            var expectedFiles = new[]
            {
                "Filename__Tile_20140528T221348Z_0.1.png",
                "Filename__Tile_20140528T221406Z_0.1.png",
                "Filename__Tile_20140528T221424Z_0.1.png",
                "Filename__Tile_20140528T221442Z_0.1.png",
                "Filename__Tile_20140528T221500Z_0.1.png",
                "Filename__Tile_20140528T221518Z_0.1.png",
                "Filename__Tile_20140528T221536Z_0.1.png",
                "Filename__Tile_20140528T221554Z_0.1.png",
            };
            var expectedImages =
                expectedFiles
                .OrderBy(x => x)
                .Select((x, i) => testBitmap.Crop(new Rectangle((i * TileWidth) - 100, 0, TileWidth, 256)))
                .ToArray();

            for (var i = 0; i < expectedImages.Length; i++)
            {
                Assert.AreEqual(expectedFiles[i], actualFiles[i].Name);

                var expectedImage = expectedImages[i];
                var actualImage   = Image.FromFile(actualFiles[i].FullName);
                var areEqual      = TilerTests.BitmapEquals(expectedImage, (Bitmap)actualImage);
                Assert.IsTrue(areEqual, "Bitmaps were not equal {0}, {1}", expectedFiles[i], actualFiles[i]);
            }
        }
Beispiel #18
0
        private void btn_Process_Click(object sender, EventArgs e)
        {
            if (bmpInput == null)
            {
                return;
            }

            denoiseAndDemoisaic.LoadNetwork("epoch_" + learningRate.ToString(CultureInfo.InvariantCulture) + "_" + noiseLevelsFolders[cmb_IsoValue.SelectedIndex] + "_1999.cnn");

            if (bmpInput.PixelFormat == PixelFormat.Format32bppArgb)
            {
                inputImage8uC4.CopyToDeviceRoi(bmpInput, new NppiRect(0, 0, bmpInput.Width, bmpInput.Height));
                //Convert C4 to C3 and BGR to RGB
                inputImage8uC4.Copy(inputImage8uC1, 0);
                inputImage8uC1.Copy(inputImage8uC3, 2);
                inputImage8uC4.Copy(inputImage8uC1, 1);
                inputImage8uC1.Copy(inputImage8uC3, 1);
                inputImage8uC4.Copy(inputImage8uC1, 2);
                inputImage8uC1.Copy(inputImage8uC3, 0);
            }
            else
            {
                inputImage8uC3.CopyToDeviceRoi(bmpInput, new NppiRect(0, 0, bmpInput.Width, bmpInput.Height));
                inputImage8uC3.ColorTwist(twist);
            }

            inputImage8uC3.Convert(inputImage32f);
            inputImage32f.Div(new float[] { 255, 255, 255 });

            NppiRect oldRoi = new NppiRect(0, 0, inputImage32f.WidthRoi, inputImage32f.HeightRoi);
            IEnumerable <Tiler.RoiInputOutput> rois = Tiler.GetROIs(oldRoi, TileSize, 0);

            foreach (var roi in rois)
            {
                inputImage32f.SetRoi(roi.inputROI);
                tile.ResetRoi();
                inputImage32f.Copy(tile);
                tile.SetRoi(roi.outputROI);
                imageBayer.SetRoi(roi.positionInFinalImage);
                createBayerKernel.RunSafe(CuRandStates, tile, imageBayer, noiseLevels[cmb_IsoValue.SelectedIndex], 0);
            }
            imageBayer.SetRoi(oldRoi);
            inputImage32f.SetRoi(oldRoi);

            deBayerGreenKernel.RunSafe(imageBayer, inputImage32f, new float3(), new float3(1, 1, 1));
            deBayerRedBlueKernel.RunSafe(imageBayer, inputImage32f, new float3(), new float3(1, 1, 1));

            inputImage32f.Mul(new float[] { 255, 255, 255 }, noiseImage32f);
            noiseImage32f.Convert(noisyImage8u, NppRoundMode.Near);
            noisyImage8u.ColorTwist(twist);
            noisyImage8u.CopyToHostRoi(bmpNoisy, new NppiRect(0, 0, bmpNoisy.Width, bmpNoisy.Height));

            inputImage32f.Sub(new float[] { 0.5f, 0.5f, 0.5f });

            CudaStopWatch csw = new CudaStopWatch();

            csw.Start();

            denoiseAndDemoisaic.RunImage(inputImage32f, resultImage32f);

            csw.Stop();

            Console.WriteLine("Needed time: " + csw.GetElapsedTime() + " [msec]");
            csw.Dispose();

            resultImage32f.Add(new float[] { 0.5f, 0.5f, 0.5f });
            resultImage32f.Mul(new float[] { 255, 255, 255 });
            resultImage32f.Convert(resultImage8u, NppRoundMode.Near);
            resultImage8u.ColorTwist(twist);
            resultImage8u.SetRoi(0, 0, bmpResult.Width - 16, bmpResult.Height - 16);
            resultImage8u.CopyToHostRoi(bmpResult, new NppiRect(8, 8, bmpResult.Width - 16, bmpResult.Height - 16));

            pictureBox2.Image = bmpNoisy;
            pictureBox3.Image = bmpResult;
        }
        public void TestPaddingANonBlockTime()
        {
            this.tiler = new Tiler(
                this.outputDirectory.ToDirectoryEntry(),
                this.tilingProfileNotRoundStart,
                new SortedSet <double>()
            {
                60.0
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1
            },
                1.0,
                256);

            var testBitmap = new Bitmap(PathHelper.ResolveAssetPath("4c77b524-1857-4550-afaa-c0ebe5e3960a_20101013_000000+1000.ACI-ENT-EVN.png"));
            var superTile  = new DefaultSuperTile()
            {
                Image   = testBitmap,
                OffsetX = 30,

                // starts on a half hour, at 60s/px hence half a tile, hence half 60px
                Scale = 60.0,
            };

            this.tiler.Tile(superTile);

            ////Debug.WriteLine(this.outputDirectory.FullName);
            ////Debug.WriteLine(this.outputDirectory.GetFiles().Length);
            var producedFiles = this.outputDirectory.GetFiles().OrderBy(x => x.Name).ToArray();

            Assert.AreEqual(25, producedFiles.Length);

            var expectedImages =
                new[]
            {
                "TILE_20150410_083000Z_60.00.png", "TILE_20150410_093000Z_60.00.png",
                "TILE_20150410_103000Z_60.00.png", "TILE_20150410_113000Z_60.00.png",
                "TILE_20150410_123000Z_60.00.png", "TILE_20150410_133000Z_60.00.png",
                "TILE_20150410_143000Z_60.00.png", "TILE_20150410_153000Z_60.00.png",
                "TILE_20150410_163000Z_60.00.png", "TILE_20150410_173000Z_60.00.png",
                "TILE_20150409_173000Z_60.00.png", "TILE_20150409_183000Z_60.00.png",
                "TILE_20150409_193000Z_60.00.png", "TILE_20150409_203000Z_60.00.png",
                "TILE_20150409_213000Z_60.00.png", "TILE_20150409_223000Z_60.00.png",
                "TILE_20150409_233000Z_60.00.png", "TILE_20150410_003000Z_60.00.png",
                "TILE_20150410_013000Z_60.00.png", "TILE_20150410_023000Z_60.00.png",
                "TILE_20150410_033000Z_60.00.png", "TILE_20150410_043000Z_60.00.png",
                "TILE_20150410_053000Z_60.00.png", "TILE_20150410_063000Z_60.00.png",
                "TILE_20150410_073000Z_60.00.png",
            }
            .OrderBy(x => x)
            .Select(x => Image.FromFile(PathHelper.ResolveAssetPath(x)))
            .ToArray();

            for (int i = 0; i < expectedImages
                 .ToArray().Length; i++)
            {
                var producedImage = Image.FromFile(producedFiles[i].FullName);
                var areEqual      = TilerTests.BitmapEquals((Bitmap)expectedImages[i], (Bitmap)producedImage);
                Assert.IsTrue(areEqual, "Bitmaps were not equal {0}, {1}", expectedImages[i], producedFiles[i].Name);
            }
        }
 public void SetUp()
 {
     tiler = new MipMapTiler();
     tiler.MaxZoomLevel = 15;
     tiler.NumberOfTiles = 4;
     tiler.ImageFetchFunction = Tiler_Test.FetchFunction;
     expectedReports = 1;
     for (int i = 1; i <= tiler.NumberOfTiles; i *= 2)
     {
         expectedReports += i * i + 1;
     }
 }
Beispiel #21
0
 private Image FetchFlatImage(BackgroundWorker progressReporter, Tiler tiler)
 {
     try
     {
         return tiler.ConstructTiledImage(progressReporter);
     }
     catch (Exception ex)
     {
         Console.WriteLine("" + ex);
         if (this.ErrorReplacementImage != null)
         {
             return new Bitmap(ErrorReplacementImage, ErrorReplacementImage.Width * 2, ErrorReplacementImage.Height * 2);
         }
         else
             throw new Exception("Previous image was null.", ex);
     }
 }
Beispiel #22
0
        /// <summary>
        /// Full Test on Bitmap tiler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnMakeBMTile_Click(object sender, EventArgs e)
        {
            int x    = Convert.ToInt32(txtX2.Text);
            int y    = Convert.ToInt32(txtY2.Text);
            int zoom = Convert.ToInt32(txtZ2.Text);

            listBox1.Items.Add("Fetching DEM...");

            // class to get digital elevation models(DEM)

            //BitmapDEMSource demSrc = new BitmapDEMSource();
            TRexDEMSource demSrc = new TRexDEMSource();

            demSrc.Initalize(new MapHeader()
            {
                GridSize = Convert.ToInt32(txtGridSizeBM.Text), MinElevation = 0, MaxElevation = 1000
            });
            var elevData = await demSrc.GetDemXYZ(x, y, zoom);

            listBox1.Items.Add($"DEM length {elevData.Elev.Length}");
            listBox1.Items.Add("Making Mesh...");

            // This class constructs a cesium quantized mesh from the dem
            var vertices = new Mesh().MakeFakeMesh(ref elevData);

            listBox1.Items.Add("Making Tile...");

            // This class constructs a quantized mesh tile mesh from the original mesh

            var hdr = new TerrainTileHeader()
            {
                BoundingSphereCenterX = elevData.BoundingSphereCenterX,
                BoundingSphereCenterY = elevData.BoundingSphereCenterY,
                BoundingSphereCenterZ = elevData.BoundingSphereCenterZ,
                CenterX = elevData.CenterX,
                CenterY = elevData.CenterY,
                CenterZ = elevData.CenterZ,
                HorizonOcclusionPointX = elevData.HorizonOcclusionPointX,
                HorizonOcclusionPointY = elevData.HorizonOcclusionPointY,
                HorizonOcclusionPointZ = elevData.HorizonOcclusionPointZ,
                BoundingSphereRadius   = elevData.BoundingSphereRadius,
                MinimumHeight          = elevData.MinimumHeight,
                MaximumHeight          = elevData.MaximumHeight
            };

            var tile = new Tiler().MakeTile(vertices, hdr, MapUtil.GridSizeToTriangleCount(elevData.GridSize),
                                            elevData.GridSize);

            listBox1.Items.Add($"Tile Ready. Size:{tile.Length} . Saving to {txtBMPath.Text}");

            var ms = new MemoryStream(tile);

            using (FileStream fs = new FileStream(txtBMPath.Text, FileMode.Create))
                using (GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress, false))
                {
                    zipStream.Write(ms.ToArray(), 0, ms.ToArray().Length); // .Write(bytes, 0, bytes.Length);
                }

            // Open View
            txtView.Text = txtBMPath.Text;
            btnView_Click(sender, e);
        }
Beispiel #23
0
        public void TestLeftPaddingInLowerLayers()
        {
            const int TileWidth = 180;
            var       startDate = new DateTimeOffset(2014, 05, 29, 08, 13, 58, TimeSpan.FromHours(10));
            var       boundary  = ZoomTiledSpectrograms.GetPreviousTileBoundary(TileWidth, 0.1, startDate);
            var       padding   = startDate - boundary;

            var profile = new AbsoluteDateTilingProfile(
                "Filename",
                "Tile",
                boundary,
                256,
                TileWidth);

            var tiler = new Tiler(
                this.outputDirectory,
                profile,
                new SortedSet <double>()
            {
                60.0, 0.1
            },
                60.0,
                1440,
                new SortedSet <double>()
            {
                1, 1
            },
                1.0,
                256);

            var testBitmap = new Image <Rgba32>(1200, 256);

            testBitmap.Mutate(graphics =>
            {
                var points = new[]
                {
                    new PointF(0, 0), new Point(180, 256), new Point(360, 0), new Point(540, 256), new Point(720, 0),
                    new PointF(900, 256), new Point(1080, 0), new Point(1260, 256),
                };
                graphics.DrawLines(
                    new GraphicsOptions(),
                    Brushes.Solid(Color.Red),
                    1,
                    points);
            });

            var superTile = new TimeOffsetSingleLayerSuperTile(
                padding,
                SpectrogramType.Index,
                0.1.Seconds(),
                testBitmap,
                0.Seconds());

            tiler.Tile(superTile);

            ////Trace.WriteLine(this.outputDirectory.FullName);
            ////Trace.WriteLine(this.outputDirectory.GetFiles().Length);
            var actualFiles = this.outputDirectory.GetFiles().OrderBy(x => x.Name).ToArray();

            Assert.AreEqual(8, actualFiles.Length);

            var expectedFiles = new[]
            {
                "Filename__Tile_20140528T221348Z_0.1.png",
                "Filename__Tile_20140528T221406Z_0.1.png",
                "Filename__Tile_20140528T221424Z_0.1.png",
                "Filename__Tile_20140528T221442Z_0.1.png",
                "Filename__Tile_20140528T221500Z_0.1.png",
                "Filename__Tile_20140528T221518Z_0.1.png",
                "Filename__Tile_20140528T221536Z_0.1.png",
                "Filename__Tile_20140528T221554Z_0.1.png",
            };
            var expectedImages =
                expectedFiles
                .OrderBy(x => x)
                .Select((x, i) => testBitmap.CropInverse(new Rectangle((i * TileWidth) - 100, 0, TileWidth, 256)))
                .ToArray();

            for (var i = 0; i < expectedImages.Length; i++)
            {
                Assert.AreEqual(expectedFiles[i], actualFiles[i].Name);

                var expectedImage = expectedImages[i];
                var actualImage   = Image.Load <Rgba32>(actualFiles[i].FullName);
                Assert.That.ImageMatches(expectedImages[i], actualImage, message: $"Bitmaps were not equal {expectedImages[i]}, {actualFiles[i]}");
            }
        }
        /// <summary>
        /// THIS IS ENTRY METHOD FOR TILING SPECTROGRAMS.
        /// </summary>
        public static void DrawTiles(
            AnalysisIoInputDirectory io,
            ZoomParameters common,
            string analysisTag)
        {
            Log.Info("Begin Draw Super Tiles");
            Contract.Requires(common != null, "common can not be null");
            Contract.Requires(common.SpectrogramZoomingConfig != null, "SpectrogramZoomingConfig can not be null");

            var zoomConfig = common.SpectrogramZoomingConfig;
            LdSpectrogramConfig ldsConfig = common.SpectrogramZoomingConfig.LdSpectrogramConfig;
            var distributions             = common.IndexDistributions;
            var indexGenerationData       = common.IndexGenerationData;
            var indexProperties           = zoomConfig.IndexProperties;

            string fileStem = common.OriginalBasename;

            // scales for false color index spectrograms images in seconds per pixel.
            double[] indexScales = zoomConfig.SpectralIndexScale;

            // default scales for standard (FFT) spectrograms in seconds per pixel.
            double[] standardScales = zoomConfig.SpectralFrameScale;

            ValidateScales(indexScales, indexGenerationData.IndexCalculationDuration.TotalSeconds);

            var shouldRenderStandardScale = !standardScales.IsNullOrEmpty();

            if (!shouldRenderStandardScale)
            {
                Log.Warn("Standard spectrograms will not be rendered");
            }

            var allImageScales = indexScales.Concat(standardScales).ToArray();

            Log.Info("Tiling at scales: " + allImageScales.ToCommaSeparatedList());

            // determine what naming format to use for tiles
            var(namingPattern, alignmentPadding) = GetTilingProfile(
                common,
                zoomConfig,
                indexGenerationData,
                indexScales.Max());

            // pad out image so it produces a whole number of tiles
            // this solves the asymmetric right padding of short audio files
            // var paddedWidth = (int)(Math.Ceiling(zoomConfig.TileWidth / xNominalUnitScale) * xNominalUnitScale);

            // create a new tiler
            // pass it scales for x and y-axis
            // also pass it unit scale relations (between unit scale and unit height/width) to use as a reference point
            var tiler = new Tiler(
                new DirectoryInfo(io.OutputBase.FullName),
                namingPattern,
                xScales: new SortedSet <double>(allImageScales),
                xUnitScale: XNominalUnitScale,
                unitWidth: 1440,
                yScales: new SortedSet <double>(allImageScales.Select(x => 1.0)),
                yUnitScale: 1.0,
                unitHeight: namingPattern.TileHeight);

            var(spectra, filteredIndexProperties) = ZoomCommon.LoadSpectra(io, analysisTag, fileStem, zoomConfig.LdSpectrogramConfig, indexProperties);

            // false color index tiles
            GenerateIndexSpectrogramTiles(
                indexScales,
                ldsConfig,
                filteredIndexProperties,
                zoomConfig,
                spectra,
                indexGenerationData,
                fileStem,
                namingPattern,
                tiler,
                alignmentPadding);

            // standard fft frame spectrograms
            if (shouldRenderStandardScale)
            {
                GenerateStandardSpectrogramTiles(
                    spectra,
                    indexGenerationData,
                    ldsConfig,
                    filteredIndexProperties,
                    zoomConfig,
                    standardScales,
                    fileStem,
                    namingPattern,
                    tiler,
                    alignmentPadding);
            }

            Log.Success("Tiling complete");
        }
        /// <summary>
        /// Derives false colour varying-resolution multi-index spectrograms from provided spectral indices.
        /// </summary>
        private static void GenerateIndexSpectrogramTiles(double[] indexScales, LdSpectrogramConfig ldsConfig, Dictionary <string, IndexProperties> filteredIndexProperties, SpectrogramZoomingConfig zoomConfig, Dictionary <string, double[, ]> spectra, IndexGenerationData indexGenerationData, string fileStem, TilingProfile tilingProfile, Tiler tiler, TimeSpan alignmentPadding)
        {
            // TOP MOST ZOOMED-OUT IMAGES
            Log.Info("Begin drawwing zooming indec spectrograms");

            foreach (double scale in indexScales)
            {
                Log.Info("Starting scale: " + scale);

                if (indexGenerationData.RecordingDuration.TotalSeconds < scale)
                {
                    Log.Warn($"Skipping scale step {scale} because recording duration ({indexGenerationData.RecordingDuration}) is less than 1px of scale");
                    continue;
                }

                // TODO: eventual optimisation, remove concept of super tiles
                // TODO: optimisation, cache aggregation layers (currently every layer is reaggregated from base level)
                TimeSpan imageScale = TimeSpan.FromSeconds(scale);
                var      superTiles = DrawSuperTilesAtScaleFromIndexSpectrograms(
                    ldsConfig,
                    filteredIndexProperties,
                    zoomConfig,
                    imageScale,
                    spectra,
                    indexGenerationData,
                    fileStem,
                    tilingProfile.ChromeOption,
                    alignmentPadding);

                // tile images as we go
                Log.Debug("Writing index tiles for " + scale);
                tiler.TileMany(superTiles);
                Log.Debug("Completed writing index tiles for " + scale);
            }
        }
Beispiel #26
0
        internal static void MakeTiling(Tiler.Settings settings)
        {
            Tiler tiler = new Tiler();

            tiler.GenImage(settings);
        }