Exemplo n.º 1
0
        private static void Main(string[] args)
        {
            string source = args[0];
            var    bytes  = File.ReadAllBytes(source);

            // First convert image to 32 bit, then reduce to 8bit
            using (var original = GetBitmapFromBytes(bytes))
                using (var cloned32 = new Bitmap(
                           original.Width,
                           original.Height,
                           PixelFormat.Format32bppPArgb))
                {
                    using (var graphics = Graphics.FromImage(cloned32))
                    {
                        graphics.DrawImage(
                            original,
                            new Rectangle(0, 0, cloned32.Width, cloned32.Height));
                    }

                    using (Image compressedImage = new WuQuantizer().QuantizeImage(cloned32))
                    {
                        compressedImage.Save(args[1], ImageFormat.Png);
                    }
                }
        }
Exemplo n.º 2
0
        public override void Compress(FileInfo oldImage, string oldBaseFolder, string newBaseFolder)
        {
            var quantizer     = new WuQuantizer();
            var imageFullPath = oldImage.FullName;

            using (Bitmap bmp1 = new Bitmap(imageFullPath))
            {
                var bitMap = bmp1;
                if (bmp1.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                {
                    ConvertTo32bppAndDisposeOriginal(ref bitMap);
                }
                using (var quantized = quantizer.QuantizeImage(bitMap))
                {
                    var newPath       = GetNewPath(oldImage.FullName, oldBaseFolder, newBaseFolder);
                    var newFolderPath = GetNewPath(oldImage.DirectoryName, oldBaseFolder, newBaseFolder);
                    if (!Directory.Exists(newFolderPath))
                    {
                        Directory.CreateDirectory(newFolderPath);
                    }
                    quantized.Save(newPath, ImageFormat.Png);
                }
            }

            Console.WriteLine($"PngCompressService: Compress Done {oldImage.Name}");
        }
Exemplo n.º 3
0
        public void QuantizersDitherByDefault()
        {
            var werner  = new WernerPaletteQuantizer();
            var webSafe = new WebSafePaletteQuantizer();
            var octree  = new OctreeQuantizer();
            var wu      = new WuQuantizer();

            Assert.NotNull(werner.Options.Dither);
            Assert.NotNull(webSafe.Options.Dither);
            Assert.NotNull(octree.Options.Dither);
            Assert.NotNull(wu.Options.Dither);

            using (IQuantizer <Rgba32> quantizer = werner.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration))
            {
                Assert.NotNull(quantizer.Options.Dither);
            }

            using (IQuantizer <Rgba32> quantizer = webSafe.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration))
            {
                Assert.NotNull(quantizer.Options.Dither);
            }

            using (IQuantizer <Rgba32> quantizer = octree.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration))
            {
                Assert.NotNull(quantizer.Options.Dither);
            }

            using (IQuantizer <Rgba32> quantizer = wu.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration))
            {
                Assert.NotNull(quantizer.Options.Dither);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Processes a single item.
        /// </summary>
        /// <param name="input">The input to process.</param>
        /// <returns>The output of the process.</returns>
        public override IAssetFile Process(IAssetFile input)
        {
            try
            {
                // Minify css
                var quantizer = new WuQuantizer();
                using (var bitmap = new Bitmap(Bitmap.FromStream(input.Content.AsStream())))
                {
                    using (var quantized = quantizer.QuantizeImage(bitmap, 10, 70))
                        using (var output = new MemoryStream())
                        {
                            // Save to the output stream
                            quantized.Save(output, ImageFormat.Png);

                            // Minified successfully
                            Tracing.Info("PNG", "Optimized " + input.RelativeName);

                            // Return processed output
                            return(AssetOutputFile.Create(input, output));
                        }
                }
            }
            catch (Exception ex)
            {
                // We didn't manage to create anything
                Tracing.Error("PNG", ex);
                return(null);
            }
        }
Exemplo n.º 5
0
        public override IOptimizerResult Optimize(MediaStream stream)
        {
            var quantizer = new WuQuantizer();

            var memoryStream = new MemoryStream();

            using (var bitmap = new Bitmap(stream.Stream))
            {
                var bitDepth = Image.GetPixelFormatSize(bitmap.PixelFormat);
                if (bitDepth != 32)
                {
                    return(OptimizerFailureResult("the image you are attempting to quantize does not contain a 32 bit ARGB palette. This image has a bit depth of {0} with {1} colors".FormatWith(bitDepth, bitmap.Palette.Entries.Length)));
                }

                using (var quantized = quantizer.QuantizeImage(bitmap))
                {
                    quantized.Save(memoryStream, ImageFormat.Png);
                }

                // rewind the stream
                memoryStream.Seek(0, SeekOrigin.Begin);

                var result = new PngQuantOptimizerResult();
                result.Success      = true;
                result.SizeBefore   = (int)stream.Length;
                result.SizeAfter    = (int)memoryStream.Length;
                result.ResultStream = memoryStream;

                return(OptimizationSuccessful(result));
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// This method pre-seeds the WuQuantizer in the AoT compiler for iOS.
 /// </summary>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 private static void AotCompileWuQuantizer <TPixel>()
     where TPixel : unmanaged, IPixel <TPixel>
 {
     using (var test = new WuQuantizer <TPixel>(Configuration.Default, new WuQuantizer().Options))
     {
         var frame = new ImageFrame <TPixel>(Configuration.Default, 1, 1);
         test.QuantizeFrame(frame, frame.Bounds());
     }
 }
Exemplo n.º 7
0
        public void QuantizersDitherByDefault()
        {
            var palette = new PaletteQuantizer <Rgba32>();
            var octree  = new OctreeQuantizer <Rgba32>();
            var wu      = new WuQuantizer <Rgba32>();

            Assert.True(palette.Dither);
            Assert.True(octree.Dither);
            Assert.True(wu.Dither);
        }
        protected void CompressAndSave(System.Drawing.Image img, string path, string extension)
        {
            //try
            //{
            //    // If jpg is extension then remove png equivalent of it
            //    // because if extension is same it'll be overridden
            //    string delFilePath = path;
            //    if (extension == ".png")
            //    {
            //        delFilePath = delFilePath.Substring(0, delFilePath.Length - 3) + "jpg";
            //    }
            //    else
            //    {
            //        delFilePath = delFilePath.Substring(0, delFilePath.Length - 3) + "png";
            //    }
            //    if (System.IO.File.Exists(delFilePath))
            //    {
            //        System.IO.File.Delete(delFilePath);
            //    }
            //}
            //catch { }
            if (extension == ".jpg" || extension == ".jpeg")
            {
                using (Bitmap bitmap = new Bitmap(img))
                {
                    ImageCodecInfo imageEncoder = null;
                    imageEncoder = GetEncoder(ImageFormat.Jpeg);
                    // Create an Encoder object based on the GUID
                    // for the Quality parameter category.
                    Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

                    // Create an EncoderParameters object.
                    // An EncoderParameters object has an array of EncoderParameter
                    // objects. In this case, there is only one
                    // EncoderParameter object in the array.
                    EncoderParameters encodingParams = new EncoderParameters(1);

                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
                    encodingParams.Param[0] = myEncoderParameter;
                    bitmap.Save(path, imageEncoder, encodingParams);
                }
            }
            else
            {
                var quantizer = new WuQuantizer();
                using (var bitmap = new Bitmap(img))
                {
                    using (var quantized = quantizer.QuantizeImage(bitmap)) //, alphaTransparency, alphaFader))
                    {
                        quantized.Save(path, ImageFormat.Png);
                    }
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 转换 PNG 格式的图片为 8 bit 格式的 PNG 图片,比改变图片的尺寸,但大量减少文件大小。质量有损失
        /// </summary>
        /// <param name="sourceImageUrl"></param>
        /// <param name="targetImageUrl"></param>
        public static void ConvertPngTo8Bit(string sourceImageUrl, string targetImageUrl)
        {
            var quantizer = new WuQuantizer();

            using (var bitmap = new Bitmap(sourceImageUrl))
            {
                using (var quantized = quantizer.QuantizeImage(bitmap))
                {
                    quantized.Save(targetImageUrl, ImageFormat.Png);
                }
            }
        }
Exemplo n.º 10
0
        private unsafe byte[] BitmapToRawIndexed(Bitmap source, int maxColors, out byte[][] palette)
        {
            Bitmap img = source;

            byte[] destination = new byte[img.Width * img.Height];

            // If this is not a 32-bit ARGB bitmap, convert it to one
            if (img.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                Bitmap newImage = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newImage))
                {
                    g.DrawImage(img, 0, 0, img.Width, img.Height);
                }
                img = newImage;
            }

            // Quantize the image
            WuQuantizer quantizer = new WuQuantizer();

            m_palette = quantizer.CreatePalette(img, maxColors);
            img       = (Bitmap)quantizer.QuantizeImage(img, m_palette);

            // Copy over the data to the destination. We need to use Stride in this case, as it may not
            // always be equal to Width.
            BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat);

            byte *pointer = (byte *)bitmapData.Scan0;

            for (int y = 0; y < bitmapData.Height; y++)
            {
                for (int x = 0; x < bitmapData.Width; x++)
                {
                    destination[(y * img.Width) + x] = pointer[(y * bitmapData.Stride) + x];
                }
            }

            img.UnlockBits(bitmapData);

            // Copy over the palette
            palette = new byte[maxColors][];
            for (int i = 0; i < maxColors; i++)
            {
                palette[i] = new byte[4];

                palette[i][3] = img.Palette.Entries[i].A;
                palette[i][2] = img.Palette.Entries[i].R;
                palette[i][1] = img.Palette.Entries[i].G;
                palette[i][0] = img.Palette.Entries[i].B;
            }

            return(destination);
        }
Exemplo n.º 11
0
        public void SinglePixelTransparent()
        {
            Configuration config    = Configuration.Default;
            var           quantizer = new WuQuantizer(false);

            using (var image = new Image <Rgba32>(config, 1, 1, default(Rgba32)))
                using (IQuantizedFrame <Rgba32> result = quantizer.CreateFrameQuantizer <Rgba32>(config).QuantizeFrame(image.Frames[0]))
                {
                    Assert.Equal(1, result.Palette.Length);
                    Assert.Equal(1, result.GetPixelSpan().Length);

                    Assert.Equal(default, result.Palette.Span[0]);
Exemplo n.º 12
0
 /// <summary>
 ///	Optimized and processes the .png image.
 /// /// </summary>
 /// <param name="path">Absolute path to image file.</param>
 /// <returns>The processed image stream.</returns>
 public Stream ShrinkPNG(string path)
 {
     using (var bitmap = (Bitmap)System.Drawing.Image.FromFile(path)) {
         const int alphaTransparency = 0;
         const int alphaFader        = 0;
         var       quantizer         = new WuQuantizer();
         var       retMS             = new MemoryStream();
         using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader)) {
             quantized.Save(retMS, ImageFormat.Png);
         }
         return(retMS);
     }
 }
Exemplo n.º 13
0
        static void Run(Options cfg)
        {
            Image originalImage;

            if (String.IsNullOrWhiteSpace(cfg.InputImage) || !System.IO.File.Exists(cfg.InputImage))
            {
                originalImage = GenerateRandomBitmap();
            }
            else
            {
                originalImage = Image.FromFile(cfg.InputImage);
            }

            Color c = Color.FromName(cfg.ColorName);

            if (c.ToArgb() == 0)
            {
                c = Color.HotPink;
            }

            var quantizer = new WuQuantizer();

            using (Bitmap drawingBitmap = new Bitmap(originalImage.Width, originalImage.Height))
                using (Graphics gfx = Graphics.FromImage(drawingBitmap))
                    using (Font fnt = new Font(cfg.FontName, cfg.FontSize))
                        using (Brush b = new SolidBrush(c))
                        {
                            gfx.DrawImage(originalImage, 0, 0);

                            SizeF sz = gfx.VisibleClipBounds.Size;
                            gfx.TranslateTransform(sz.Width / 2, sz.Height / 2);
                            gfx.RotateTransform(cfg.Angle);
                            sz = gfx.MeasureString(cfg.Text, fnt);
                            gfx.DrawString(cfg.Text, fnt, b, -(sz.Width / 2), -(sz.Height / 2));

                            gfx.ResetTransform();
                            if (cfg.UseQuantizer)
                            {
                                using (var q = quantizer.QuantizeImage(drawingBitmap))
                                {
                                    q.Save(cfg.OutImage);
                                }
                            }
                            else
                            {
                                drawingBitmap.Save(cfg.OutImage);
                            }
                        }

            originalImage.Dispose();
        }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bmp"></param>
        public static Bitmap ReduceColors(Bitmap bitmap, int colorCount)
        {
            if (bitmap.Width <= 16 && bitmap.Height <= 16) // no need
            {
                return(bitmap);
            }

            var quantizer = new WuQuantizer();

            using (var quantized = quantizer.QuantizeImage(bitmap, 10, 70, colorCount))
            {
                return(new Bitmap(quantized));
            }
        }
Exemplo n.º 15
0
    private void ProcessTexture(Texture2D texture, string outputPath, bool compress)
    {
        if (thumbnailBackgroundTexture)
        {
            var texturePixels    = texture.GetPixels();
            var backgroundPixels = thumbnailBackgroundTexture.GetPixels();
            for (var i = 0; i < texturePixels.Length; i++)
            {
                texturePixels[i] = Color.Lerp(backgroundPixels[i], texturePixels[i], texturePixels[i].a);
            }
            texture.SetPixels(texturePixels);
        }

        if (thumbnailForegroundTexture)
        {
            var texturePixels    = texture.GetPixels();
            var foregroundPixels = thumbnailForegroundTexture.GetPixels();
            for (var i = 0; i < texturePixels.Length; i++)
            {
                texturePixels[i] = Color.Lerp(texturePixels[i], foregroundPixels[i], foregroundPixels[i].a);
            }
            texture.SetPixels(texturePixels);
        }

        if (compress)
        {
            var quantize = new WuQuantizer();
            var bitmap   = new Bitmap(128, 128);
            var index    = 0;
            foreach (var pixel in texture.GetPixels())
            {
                var x = index % 128;
                var y = 127 - index / 128;
                bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb(
                                    Mathf.CeilToInt(Mathf.Clamp(pixel.a * 255, 0, 255)),
                                    Mathf.CeilToInt(Mathf.Clamp(pixel.r * 255, 0, 255)),
                                    Mathf.CeilToInt(Mathf.Clamp(pixel.g * 255, 0, 255)),
                                    Mathf.CeilToInt(Mathf.Clamp(pixel.b * 255, 0, 255))
                                    ));
                index++;
            }

            var image = quantize.QuantizeImage(bitmap);
            image.Save(outputPath);
        }
        else
        {
            File.WriteAllBytes(outputPath, texture.EncodeToPNG());
        }
    }
Exemplo n.º 16
0
        public void QuantizersDitherByDefault()
        {
            var palette = new PaletteQuantizer();
            var octree  = new OctreeQuantizer();
            var wu      = new WuQuantizer();

            Assert.NotNull(palette.Diffuser);
            Assert.NotNull(octree.Diffuser);
            Assert.NotNull(wu.Diffuser);

            Assert.True(palette.CreateFrameQuantizer <Rgba32>().Dither);
            Assert.True(octree.CreateFrameQuantizer <Rgba32>().Dither);
            Assert.True(wu.CreateFrameQuantizer <Rgba32>().Dither);
        }
Exemplo n.º 17
0
        public static void SquishNewlyUploadedPNGs(
            Stream input,
            Stream output)
        {
            var quantizer = new WuQuantizer();

            using (var bitmap = new Bitmap(input))
            {
                using (var quantized = quantizer.QuantizeImage(bitmap))
                {
                    quantized.Save(output, ImageFormat.Png);
                }
            }
        }
Exemplo n.º 18
0
        public static void SquishNewlyUploadedPNGs(
            [BlobTrigger("processimageincloud/{name}")] Stream input,
            [Blob("processimageincloudoutput/{name}", FileAccess.Write)] Stream output)
        {
            var quantizer = new WuQuantizer();

            using (var bitmap = new Bitmap(input))
            {
                using (var quantized = quantizer.QuantizeImage(bitmap))
                {
                    quantized.Save(output, ImageFormat.Png);
                }
            }
        }
Exemplo n.º 19
0
        public void Load(Stream mystream, int SamplePercentage)
        {
            PalletPixelCount.Clear();

            Image <Rgba32> image = Image.Load <Rgba32>(mystream);

            var quantizer = new WuQuantizer <Rgba32>();

            var quantizationResults = quantizer.Quantize(image.Frames.RootFrame, PaletteCount);

            PalletPixelCount = quantizationResults.Pixels.GroupBy(P => P)
                               .Select(group => new KeyValuePair <Rgba32, int>(quantizationResults.Palette[group.Key], group.Count()))
                               .OrderByDescending(I => I.Value)
                               .ToList();
        }
Exemplo n.º 20
0
 public void  To8BitPng(string path, Bitmap image)
 {
     try
     {
         var quantizer = new WuQuantizer();
         using (var quantized = quantizer.QuantizeImage(image))
         {
             quantized.Save(path, ImageFormat.Png);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Encodes a bitmap into an indexed bitmap with a per-pixel palette color index using a specified number of colors in the palette.
        /// </summary>
        /// <param name="bitmap">The bitmap to encode.</param>
        /// <param name="paletteColorCount">The number of colors to be present in the palette.</param>
        /// <param name="indices">The per-pixel palette color indices.</param>
        /// <param name="palette">The <see cref="Color"/> array containing the palette colors of the indexed bitmap.</param>
        public static void QuantizeBitmap(Bitmap bitmap, int paletteColorCount, out byte[] indices, out Color[] palette)
        {
            int bitDepth = Image.GetPixelFormatSize(bitmap.PixelFormat);

            if (bitDepth != 32)
            {
                bitmap = ConvertTo32Bpp(bitmap);
            }

            WuQuantizer quantizer   = new WuQuantizer();
            Bitmap      quantBitmap = (Bitmap)quantizer.QuantizeImage(bitmap, paletteColorCount, 0, 1);

            palette = GetPalette(quantBitmap, paletteColorCount);
            indices = GetIndices(quantBitmap);
        }
Exemplo n.º 22
0
        public void SinglePixelOpaque()
        {
            Configuration config    = Configuration.Default;
            var           quantizer = new WuQuantizer(false);

            using (var image = new Image <Rgba32>(config, 1, 1, Color.Black))
                using (IQuantizedFrame <Rgba32> result = quantizer.CreateFrameQuantizer <Rgba32>(config).QuantizeFrame(image.Frames[0]))
                {
                    Assert.Equal(1, result.Palette.Length);
                    Assert.Equal(1, result.GetPixelSpan().Length);

                    Assert.Equal(Color.Black, (Color)result.Palette.Span[0]);
                    Assert.Equal(0, result.GetPixelSpan()[0]);
                }
        }
Exemplo n.º 23
0
 public Image Apply(Image sourceImage, Matrix matrix)
 {
     using (WuQuantizer quantizer = new WuQuantizer((Bitmap)sourceImage)) {
         int colorCount = quantizer.GetColorCount();
         if (colorCount > Colors)
         {
             try {
                 return(quantizer.GetQuantizedImage(Colors));
             } catch (Exception e) {
                 LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
             }
         }
     }
     return(null);
 }
Exemplo n.º 24
0
        public static Bitmap Quantize(Image img)
        {
            WuQuantizer q = new WuQuantizer();

            using (var bitmap = new Bitmap(img))
            {
                using (var quantized = q.QuantizeImage(bitmap))
                {
                    using (MemoryStream _stream = new MemoryStream())
                    {
                        quantized.Save(_stream, ImageFormat.Bmp);
                        return(new Bitmap(_stream));
                    }
                }
            }
        }
Exemplo n.º 25
0
 //[Benchmark]
 public void WuQuantizer()
 {
     using (var bitmap = BitmapFactory.CreateEmpty(400, 400, PixelFormat.Format24bppRgb, Color.White))
     {
         using (var graphics = Graphics.FromImage(bitmap))
             using (var pen = new SolidBrush(Color.Blue))
             {
                 graphics.FillRectangle(pen, new Rectangle(30, 30, 340, 340));
             }
         var quantizer = new WuQuantizer(bitmap);
         using (var quantizedImage = quantizer.GetQuantizedImage())
         {
             quantizedImage.Save(@"quantized.png", ImageFormat.Png);
         }
     }
 }
Exemplo n.º 26
0
 public static Image2 Quantize(this Image2 source, Quantization mode = Quantization.Octree, int maxColors = 256)
 {
     IQuantizer quantizer;
     switch (mode){
         case Quantization.Wu:
             quantizer = new WuQuantizer();
             break;
         case Quantization.Palette:
             quantizer = new PaletteQuantizer();
             break;
         default:
             quantizer = new OctreeQuantizer();
             break;
     }
     return Quantize(source, quantizer, maxColors);
 }
Exemplo n.º 27
0
        public static async Task To8BitPng(string path, Bitmap image)
        {
            try
            {
                var quantizer = new WuQuantizer();
                using (var quantized = quantizer.QuantizeImage(image))
                {
                    quantized.Save(path, ImageFormat.Png);
                }

                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 28
0
        public void SinglePixelTransparent()
        {
            Configuration config    = Configuration.Default;
            var           quantizer = new WuQuantizer(new QuantizerOptions {
                Dither = null
            });

            using var image = new Image <Rgba32>(config, 1, 1, default(Rgba32));
            ImageFrame <Rgba32> frame = image.Frames.RootFrame;

            using IFrameQuantizer <Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer <Rgba32>(config);
            using QuantizedFrame <Rgba32> result          = frameQuantizer.QuantizeFrame(frame, frame.Bounds());

            Assert.Equal(1, result.Palette.Length);
            Assert.Equal(1, result.GetPixelSpan().Length);

            Assert.Equal(default, result.Palette.Span[0]);
Exemplo n.º 29
0
        public void QuantizersDitherByDefault()
        {
            var werner  = new WernerPaletteQuantizer();
            var webSafe = new WebSafePaletteQuantizer();
            var octree  = new OctreeQuantizer();
            var wu      = new WuQuantizer();

            Assert.NotNull(werner.Diffuser);
            Assert.NotNull(webSafe.Diffuser);
            Assert.NotNull(octree.Diffuser);
            Assert.NotNull(wu.Diffuser);

            Assert.True(werner.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither);
            Assert.True(webSafe.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither);
            Assert.True(octree.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither);
            Assert.True(wu.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither);
        }
Exemplo n.º 30
0
        public string Apply(string input_dir, string output_dir, string fn, int k, int tn)
        {
            try
            {
                string fn_only = Path.GetFileNameWithoutExtension(fn);

                //MeanShift
                Log.WriteLine("Meanshift in progress...");
                MeanShiftMultiThreads mt = new MeanShiftMultiThreads();
                string ms_path           = output_dir + fn_only + "_ms.png";
                mt.ApplyYIQMT(input_dir + fn, tn, 3, 3, ms_path);
                mt = null;
                GC.Collect();
                Log.WriteLine("Meanshift finished");

                // Median Cut
                Log.WriteLine("Median Cut in progress...");
                int    mc_colors = 256;
                string mc_path   = output_dir + fn_only + "_mc" + mc_colors.ToString() + ".png";

                using (Bitmap msimg = new Bitmap(output_dir + fn_only + "_ms.png"))
                {
                    WuQuantizer wq = new WuQuantizer();
                    wq.QuantizeImage(msimg).Save(mc_path, ImageFormat.Png);
                }
                Log.WriteLine("Median Cut finished");

                // KMeans
                Log.WriteLine("KMeans in progress...");
                MyKMeans kmeans      = new MyKMeans();
                string   kmeans_path = output_dir + fn_only + "_mc" + mc_colors + "_k" + k + ".png";
                kmeans.Apply(k, mc_path, kmeans_path);
                kmeans = null;
                GC.Collect();
                Log.WriteLine("KMeans finished");
                return(kmeans_path);
            }
            catch (Exception e)
            {
                Log.WriteLine("ColorSegmentationWorker: " + e.Message);
                Log.WriteLine(e.Source);
                Log.WriteLine(e.StackTrace);
                throw;
            }
        }
Exemplo n.º 31
0
        public void WuQuantizerYieldsCorrectTransparentPixel <TPixel>(TestImageProvider <TPixel> provider, bool dither)
            where TPixel : struct, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage())
            {
                Assert.True(image[0, 0].Equals(default(TPixel)));

                var quantizer = new WuQuantizer(dither);

                foreach (ImageFrame <TPixel> frame in image.Frames)
                {
                    QuantizedFrame <TPixel> quantized = quantizer.CreateFrameQuantizer <TPixel>().QuantizeFrame(frame);

                    int index = this.GetTransparentIndex(quantized);
                    Assert.Equal(index, quantized.GetPixelSpan()[0]);
                }
            }
        }
Exemplo n.º 32
0
        public void EndToEndTest(string pngFileName)
        {
            const string testFilePath = "output_nquant.png";
            if (File.Exists(testFilePath)) { File.Delete(testFilePath); }
            var sw = new Stopwatch();
            var originalFilePath = Path.Combine(@"../../../samples", pngFileName);
            using (var bitmap = (Bitmap)Image.FromFile(originalFilePath))
            {
                const int alphaTransparency = 0;
                const int alphaFader = 0;
                var quantizer = new WuQuantizer ();
                sw.Start ();

                using (var quantized = quantizer.QuantizeImage (bitmap, alphaTransparency, alphaFader))
                    quantized.Save (testFilePath, ImageFormat.Png);
            }

            Debug.WriteLine(string.Format("nQuant: {0} ms/image", sw.ElapsedMilliseconds));
            Assert.True(File.Exists(testFilePath));
            var fileLength = new FileInfo(testFilePath).Length;
            Assert.True(fileLength > 0);
            Assert.True(fileLength < new FileInfo(originalFilePath).Length);
        }