Beispiel #1
0
        private IMagickImage ExecuteMethod1(IMagickImage first, IMagickImage second)
        {
            using (var first_0 = first.Clone())
            {
                first_0.Composite(second, CompositeOperator.Multiply);
                first_0.Modulate(Brightness, Saturation, (Percentage)100);

                using (var third = first.Clone())
                {
                    third.ColorSpace = ColorSpace.Gray;

                    using (var fourth = third.Clone())
                    {
                        fourth.Negate();
                        fourth.Blur(0, _edgeWidth);

                        var result = third.Clone();
                        result.Composite(fourth, CompositeOperator.ColorDodge);
                        result.Evaluate(Channels.All, EvaluateOperator.Pow, EdgeAmount);
                        result.Threshold(_edgeThreshold);
                        result.Statistic(StatisticType.Median, 3, 3);

                        result.Composite(first_0, CompositeOperator.Multiply);

                        return(result);
                    }
                }
            }
        }
Beispiel #2
0
        public IMagickImage Cut(IWebDriver driver, IMagickImage magickImage)
        {
            var elementCoordinates = driver.GetElementCoordinates(_elementByToCut);

            if (!driver.IsElementPartialInViewPort(elementCoordinates.y, elementCoordinates.bottom))
            {
                return(magickImage);
            }
            var width  = magickImage.Width;
            var height = magickImage.Height;

            using (var collection = new MagickImageCollection())
            {
                var heightT = 0 + elementCoordinates.y;
                if (heightT < 0 && height < elementCoordinates.bottom)
                {
                    return(null);
                }
                if (heightT < 0)
                {
                    heightT = elementCoordinates.bottom;
                }
                var firstRectangle  = new Rectangle(0, 0, width, heightT);
                var secondRectangle = new Rectangle(0, elementCoordinates.y + elementCoordinates.height, width,
                                                    magickImage.Height - elementCoordinates.y - elementCoordinates.height);
                var firstPart = elementCoordinates.y <= 0
                        ? null
                        : magickImage.Clone(new MagickGeometry(firstRectangle));
                var secondPart = elementCoordinates.bottom > height
                        ? null
                        : magickImage.Clone(new MagickGeometry(secondRectangle));
                if (firstPart != null)
                {
                    collection.Add(firstPart);
                }
                if (secondPart != null)
                {
                    collection.Add(secondPart);
                }
                if (secondPart == null)
                {
                }
                var overAllImage = collection.Count == 0 ? null : collection.AppendVertically();
                return(overAllImage == null ? null : new MagickImage(overAllImage));
            }

            var rectangle = new Rectangle(0, elementCoordinates.height, width, height - elementCoordinates.height);

            return(magickImage.Clone(new MagickGeometry(rectangle)));
        }
        private static void CompareAgainstFeature(
            ref double[] deltas,
            ref double[] benchmarks,
            DateTime now,
            IMagickImage fileImageComposed,
            CWatcher cWatcher,
            CWatchImage cWatchImage)
        {
            if (!cWatchImage.IsPaused(now))
            {
                var benchmark = TimeStamp.Now;
                using (var fileImageCompare = fileImageComposed.Clone())
                    using (var deltaImage = cWatchImage.MagickImage.Clone())
                    {
                        if (cWatchImage.HasAlpha)
                        {
                            fileImageCompare.Composite(cWatchImage.AlphaChannel, CompositeOperator.Over);
                        }

                        SetDelta(ref deltas, fileImageCompare, deltaImage, cWatcher, cWatchImage);
                        SetBenchmark(ref benchmarks, benchmark, cWatchImage);
                    }
            }
            else
            {
                deltas[cWatchImage.Index]     = double.NaN;
                benchmarks[cWatchImage.Index] = 0;
            }
        }
        /// <summary>
        /// Processses a scanned document of text to clean the text background and enhance the text.
        /// </summary>
        /// <param name="input">The image to execute the script on.</param>
        /// <returns>The resulting image.</returns>
        public IMagickImage Execute(IMagickImage input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            CheckSettings();

            var output = input.Clone();

            RotateImage(output);
            CropImage(output);
            ConvertToGrayscale(output);
            EnhanceImage(output);
            RemoveNoise(output);
            UnrotateImage(output);
            SharpenImage(output);
            SaturateImage(output);
            AdaptiveBlurImage(output);
            TrimImage(output);
            PadImage(output);

            return(output);
        }
        private static IMagickImage CreateRolled(IMagickImage image, int thickness)
        {
            IMagickImage rolled = image.Clone();

            rolled.Roll(thickness, 0);
            return(rolled);
        }
Beispiel #6
0
        private void ApplyWhiteBalance(IMagickImage image)
        {
            using (var mask = image.Clone())
            {
                mask.ColorSpace = ColorSpace.HSB;
                mask.Negate(Channels.Green);

                using (var newMask = mask.Separate(Channels.Green).First())
                {
                    using (var maskBlue = mask.Separate(Channels.Blue).First())
                    {
                        newMask.Composite(maskBlue, CompositeOperator.Multiply);
                    }

                    newMask.ContrastStretch((Percentage)0, WhiteBalance);
                    newMask.InverseOpaque(new MagickColor("white"), new MagickColor("black"));

                    double maskMean = GetMean(newMask);

                    double redRatio   = GetRatio(image, Channels.Red, newMask, maskMean);
                    double greenRatio = GetRatio(image, Channels.Green, newMask, maskMean);
                    double blueRatio  = GetRatio(image, Channels.Blue, newMask, maskMean);

                    var matrix = new MagickColorMatrix(3, redRatio, 0, 0, 0, greenRatio, 0, 0, 0, blueRatio);

                    image.ColorMatrix(matrix);
                }
            }
        }
        private static IMagickImage ExtractAlpha(IMagickImage image, MagickColor color)
        {
            var alpha = image.Clone();

            alpha.InverseTransparent(color);
            alpha.Alpha(AlphaOption.Extract);
            return(alpha);
        }
Beispiel #8
0
        private static IMagickImage SelectiveBlur(IMagickImage image)
        {
            IMagickImage result = image.Clone();

            result.SelectiveBlur(0, 5, new Percentage(10));

            return(result);
        }
Beispiel #9
0
        /// <summary>
        /// Transforms an image to place it in a region of a tshirt image. The transformed image will
        /// display hightlights from the tshirt image and be distorted to match the wrinkles in the
        /// tshirt image.
        /// </summary>
        /// <param name="tshirt">The image of the shirt to put the overlay on.</param>
        /// <param name="overlay">The overlay to put on top of the shirt.</param>
        /// <returns>The resulting image.</returns>
        public IMagickImage Execute(IMagickImage tshirt, IMagickImage overlay)
        {
            if (tshirt == null)
            {
                throw new ArgumentNullException("tshirt");
            }

            if (overlay == null)
            {
                throw new ArgumentNullException("overlay");
            }

            CheckSettings(tshirt);

            var x        = _coords[1].X - _coords[0].X;
            var y        = _coords[1].Y - _coords[0].Y;
            var topWidth = Math.Sqrt((x * x) + (y * y));
            var scale    = (overlay.Width - 1) / (topWidth / 1);

            var overlayCoordinates = CreateOverlayCoordinates(overlay, scale);
            var tshirtCoordinates  = CreateTshirtCoordinates(overlay, scale, topWidth);

            var alpha = ExtractAlpha(tshirt);
            var gray  = ToGrayScale(tshirt);
            var mean  = SubtractMean(gray, tshirtCoordinates);

            ApplyLighting(mean);
            var light = mean.Clone();

            mean.Dispose();

            var blur = gray.Clone();

            ApplyBlur(blur);

            var distorted = DistortOverlay(gray, overlay, overlayCoordinates, tshirtCoordinates);

            var displaced = DisplaceOverlay(distorted, light, blur);

            distorted.Dispose();
            light.Dispose();
            blur.Dispose();

            var output = tshirt.Clone();

            output.Composite(displaced, CompositeOperator.Over);
            displaced.Dispose();

            if (alpha != null)
            {
                output.Alpha(AlphaOption.Off);
                output.Composite(alpha, CompositeOperator.CopyAlpha);

                alpha.Dispose();
            }

            return(output);
        }
Beispiel #10
0
        private static IMagickImage ToGrayScale(IMagickImage image)
        {
            var gray = image.Clone();

            gray.Alpha(AlphaOption.Off);
            gray.ColorSpace = ColorSpace.Gray;

            return(gray);
        }
Beispiel #11
0
        public AImage Crop(int x, int y, int width, int height)
        {
            var rect = new MagickGeometry(x, y, width, height);

            rect.IgnoreAspectRatio = true;
            var ai = _current.Clone();

            ai.Crop(rect);
            return(new AImage(ai));
        }
Beispiel #12
0
        private ushort[] GetGrayChannel(IMagickImage image)
        {
            using (var images = new MagickImageCollection())
            {
                images.Add(image.Clone());
                images.Add(image.Clone());
                images.Add(image.Clone());

                using (var depolar = images.AppendHorizontally())
                {
                    if (Smooth != 0.0)
                    {
                        depolar.Blur(0, Smooth);
                    }

                    if (Sharpen != 0.0)
                    {
                        depolar.Sharpen(0, Sharpen);
                    }

                    if (_method == UnperspectiveMethod.Derivative)
                    {
                        depolar.VirtualPixelMethod = VirtualPixelMethod.Tile;
                        depolar.SetArtifact("convolve:scale", "50%!");
                        depolar.SetArtifact("convolve:bias", "50%");
                        depolar.Morphology(MorphologyMethod.Convolve, "3x1: -1,0,1");
                        depolar.AutoLevel();

                        depolar.SetArtifact("convolve:bias", "0");
                        depolar.Morphology(MorphologyMethod.Convolve, "3x1: 1,0,-1");
                        depolar.AutoLevel();
                        depolar.Crop(image.Width, 1, Gravity.Center);
                    }

                    depolar.Depth = 16;

                    using (var pixels = depolar.GetPixels())
                    {
                        return(pixels.ToShortArray(0, 0, depolar.Width, 1, "R"));
                    }
                }
            }
        }
        private static IMagickImage CreateCroppedPattern(IMagickImage image, IMagickImage pattern, double angle)
        {
            var croppedPattern = pattern.Clone();

            croppedPattern.Rotate(angle);
            croppedPattern.RePage();
            croppedPattern.Crop(image.Width, image.Height, Gravity.Center);
            croppedPattern.RePage();
            return(croppedPattern);
        }
Beispiel #14
0
        // May need to update to support multiple channels.
        private static IMagickImage GetComposedImage(IMagickImage input, int channelIndex)
        {
            IMagickImage mi = input.Clone();

            if (channelIndex > -1)
            {
                mi = mi.Separate().ToArray()[channelIndex];
            }
            return(mi);
        }
Beispiel #15
0
        /// <summary>
        ///     Performs a circular crop on an image.
        /// </summary>
        /// <param name="image">The image to crop.</param>
        internal static void CircularCrop(IMagickImage image)
        {
            using var copy = image.Clone();
            copy.Distort(DistortMethod.DePolar, 0);
            copy.VirtualPixelMethod = VirtualPixelMethod.HorizontalTile;
            copy.BackgroundColor    = MagickColors.None;
            copy.Distort(DistortMethod.Polar, 0);

            image.Composite(copy, CompositeOperator.CopyAlpha);
        }
Beispiel #16
0
        private static IMagickImage CreateDepolar(IMagickImage image, double maxRad)
        {
            var depolar = image.Clone();

            depolar.VirtualPixelMethod = VirtualPixelMethod.Black;
            depolar.Distort(DistortMethod.DePolar, maxRad);
            depolar.Scale(new MagickGeometry(depolar.Width + "x" + 1 + "!"));
            depolar.VirtualPixelMethod = VirtualPixelMethod.Undefined;

            return(depolar);
        }
Beispiel #17
0
        private IMagickImage DisplaceOverlay(IMagickImage overlay, IMagickImage light, IMagickImage blur)
        {
            var mergedAlpha = overlay.Clone();

            mergedAlpha.Alpha(AlphaOption.Extract);

            var output = overlay.Clone();

            output.Composite(light, CompositeOperator.HardLight);

            output.Alpha(AlphaOption.Off);
            output.Composite(mergedAlpha, CompositeOperator.CopyAlpha);
            mergedAlpha.Dispose();

            var args = string.Format(CultureInfo.InvariantCulture, "{0},{0}", -Displace);

            output.Composite(blur, 0, 0, CompositeOperator.Displace, args);

            return(output);
        }
Beispiel #18
0
        private IMagickImage ExecuteMethod4(IMagickImage first, IMagickImage second)
        {
            var result = first.Clone();

            result.Composite(second, CompositeOperator.Multiply);
            result.Modulate(Brightness, Saturation, (Percentage)100);

            using (var third = first.Clone())
            {
                third.ColorSpace = ColorSpace.Gray;
                third.SetArtifact("convolve:scale", "!");
                third.Morphology(MorphologyMethod.Edge, "diamond:1");
                third.Negate();
                third.Evaluate(Channels.All, EvaluateOperator.Pow, EdgeAmount);
                third.WhiteThreshold(_edgeThreshold);

                result.Composite(third, CompositeOperator.Multiply);
                return(result);
            }
        }
        private static Bitmap ToBitmap <TQuantumType>(this IMagickImage <TQuantumType> self, bool useDensity)
            where TQuantumType : struct
        {
            Throw.IfNull(nameof(self), self);

            IMagickImage <TQuantumType> image = self;

            var format = PixelFormat.Format24bppRgb;

            try
            {
                if (!IssRGBCompatibleColorspace(image.ColorSpace))
                {
                    image            = self.Clone();
                    image.ColorSpace = ColorSpace.sRGB;
                }

                if (image.HasAlpha)
                {
                    format = PixelFormat.Format32bppArgb;
                }

                using (var pixels = image.GetPixelsUnsafe())
                {
                    var mapping = GetMapping(format);

                    var bitmap = new Bitmap(image.Width, image.Height, format);
                    for (int y = 0; y < image.Height; y++)
                    {
                        var row         = new Rectangle(0, y, image.Width, 1);
                        var data        = bitmap.LockBits(row, ImageLockMode.WriteOnly, format);
                        var destination = data.Scan0;

                        var bytes = pixels.ToByteArray(0, y, image.Width, 1, mapping);
                        if (bytes != null)
                        {
                            Marshal.Copy(bytes, 0, destination, bytes.Length);
                        }

                        bitmap.UnlockBits(data);
                    }

                    SetBitmapDensity(self, bitmap, useDensity);
                    return(bitmap);
                }
            }
            finally
            {
                if (!ReferenceEquals(self, image))
                {
                    image.Dispose();
                }
            }
        }
Beispiel #20
0
        private static async Task <byte[]> CreateFacePreview(DetectedFace detectedFace, IMagickImage <byte> image, double photoScale)
        {
            await using (var stream = new MemoryStream())
            {
                var faceImage = image.Clone();
                faceImage.Crop(GetMagickGeometry(detectedFace, photoScale));
                await faceImage.WriteAsync(stream);

                return(stream.ToArray());
            }
        }
Beispiel #21
0
        private static Bitmap ToBitmap <TQuantumType>(this IMagickImage <TQuantumType> self, bool useDensity)
            where TQuantumType : struct
        {
            Throw.IfNull(nameof(self), self);

            IMagickImage <TQuantumType> image = self;

            var isGray = image.ChannelCount == 1 && image.ColorSpace == ColorSpace.Gray;
            var format = isGray ? PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb;

            try
            {
                if (!isGray)
                {
                    if (image.ColorSpace != ColorSpace.sRGB)
                    {
                        image            = self.Clone();
                        image.ColorSpace = ColorSpace.sRGB;
                    }

                    if (image.HasAlpha)
                    {
                        format = PixelFormat.Format32bppArgb;
                    }
                }

                using (var pixels = image.GetPixelsUnsafe())
                {
                    var bitmap = new Bitmap(image.Width, image.Height, format);

                    if (typeof(TQuantumType) == typeof(byte) && isGray)
                    {
                        CopyGrayPixels(image, pixels, format, bitmap);
                    }
                    else
                    {
                        CopyPixels(image, pixels, format, bitmap);
                    }

                    SetBitmapDensity(self, bitmap, useDensity);
                    return(bitmap);
                }
            }
            finally
            {
                if (!ReferenceEquals(self, image))
                {
                    image.Dispose();
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// Applies a Dragan-like effect to an image to enhance wrinkles creating a "gritty" effect.
        /// </summary>
        /// <param name="input">The image to execute the script on.</param>
        /// <returns>The resulting image.</returns>
        public IMagickImage Execute(IMagickImage input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            CheckSettings();

            using (var first = input.Clone())
            {
                ApplyBrightness(first);
                ApplyContrast(first);
                ApplySaturation(first);

                using (var second = first.Clone())
                {
                    second.Modulate((Percentage)100, (Percentage)0, (Percentage)100);
                    double darkness = 3 / Darkness;
                    if (darkness != 1)
                    {
                        second.Evaluate(Channels.All, EvaluateOperator.Multiply, darkness);
                        second.Clamp();
                    }

                    first.Composite(second, CompositeOperator.Multiply);
                    first.Clamp();
                }

                var output = first.Clone();

                using (var third = first.Clone())
                {
                    third.SetArtifact("convolve:bias", "50%");
                    third.SetArtifact("convolve:scale", "1");
                    third.Morphology(MorphologyMethod.Convolve, Kernel.DoG, "0,0,5");
                    third.Clamp();

                    output.Composite(third, CompositeOperator.Overlay);

                    using (var fourth = first.Clone())
                    {
                        fourth.Modulate((Percentage)100, (Percentage)0, (Percentage)100);

                        output.Composite(fourth, CompositeOperator.HardLight);
                        return(output);
                    }
                }
            }
        }
Beispiel #23
0
        private static IMagickImage SubtractMean(IMagickImage image, PointD[] coords)
        {
            using (var img = image.Clone())
            {
                int minX = (int)Math.Min(Math.Min(coords[0].X, coords[1].X), Math.Min(coords[2].X, coords[3].X));
                int minY = (int)Math.Min(Math.Min(coords[0].Y, coords[1].Y), Math.Min(coords[2].Y, coords[3].Y));
                int maxX = (int)Math.Max(Math.Max(coords[0].X, coords[1].X), Math.Max(coords[2].X, coords[3].X));
                int maxY = (int)Math.Max(Math.Max(coords[0].Y, coords[1].Y), Math.Max(coords[2].Y, coords[3].Y));

                int width  = maxX - minX + 1;
                int height = maxY - minY + 1;

                img.Crop(minX, minY, width, height);
                img.RePage();

                var    statistics = img.Statistics();
                double mean       = (statistics.Composite().Mean / Quantum.Max) - 0.5;

                var result = image.Clone();
                result.Evaluate(Channels.All, EvaluateOperator.Subtract, mean * Quantum.Max);
                return(result);
            }
        }
Beispiel #24
0
        private static BitmapSource ToBitmapSource <TQuantumType>(this IMagickImage <TQuantumType> self, bool useDensity)
            where TQuantumType : struct
        {
            Throw.IfNull(nameof(self), self);

            IMagickImage <TQuantumType> image = self;

            var mapping = "RGB";
            var format  = MediaPixelFormats.Rgb24;

            try
            {
                if (self.ColorSpace == ColorSpace.CMYK && !image.HasAlpha)
                {
                    mapping = "CMYK";
                    format  = MediaPixelFormats.Cmyk32;
                }
                else
                {
                    if (image.ColorSpace != ColorSpace.sRGB)
                    {
                        image            = self.Clone();
                        image.ColorSpace = ColorSpace.sRGB;
                    }

                    if (image.HasAlpha)
                    {
                        mapping = "BGRA";
                        format  = MediaPixelFormats.Bgra32;
                    }
                }

                var step   = format.BitsPerPixel / 8;
                var stride = image.Width * step;

                using (var pixels = image.GetPixelsUnsafe())
                {
                    var bytes = pixels.ToByteArray(mapping);
                    var dpi   = image.GetDefaultDensity(useDensity ? DensityUnit.PixelsPerInch : DensityUnit.Undefined);
                    return(BitmapSource.Create(image.Width, image.Height, dpi.X, dpi.Y, format, null, bytes, stride));
                }
            }
            finally
            {
                if (!ReferenceEquals(self, image))
                {
                    image.Dispose();
                }
            }
        }
Beispiel #25
0
        static public IMagickColor <byte> GetDominantColor(this IMagickImage <byte> image)
        {
            using var img = image.Clone();
            img.InterpolativeResize(32, 32, PixelInterpolateMethod.Average);
            img.Quantize(new QuantizeSettings()
            {
                Colors = 8
            });
            var histogram = img.Histogram();

            var dominantColor = histogram.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;

            return(dominantColor);
        }
        /// <summary>
        /// Applies an embroidery effect to each color in an image. The image must have limited number
        /// of colors or only the top most frequent colors will be used. Each color will get the same
        /// pattern, but at different rotation angles.
        /// </summary>
        /// <param name="input">The image to execute the script on.</param>
        /// <returns>The resulting image.</returns>
        public IMagickImage Execute(IMagickImage input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            CheckSettings();

            using (var image = input.Clone())
            {
                var colors = image.Histogram().OrderByDescending(kv => kv.Value).Select(kv => kv.Key).Take(NumberOfColors).ToArray();

                RemapColors(image, colors);

                using (var texture = CreateTexture())
                {
                    var pattern = CreatePattern(image.Width * 2, image.Height * 2, texture);

                    using (IMagickImage nearBlackWhite = ToNearBlackWhite(image))
                    {
                        using (var images = new MagickImageCollection())
                        {
                            double angle = (Pattern == EmbroideryPattern.Linear ? -45 : -90) + Angle;

                            foreach (var color in colors)
                            {
                                bool useBevel = Bevel != 0 && color != colors.First();

                                using (var croppedPattern = CreateCroppedPattern(image, pattern, angle))
                                {
                                    using (var alpha = ExtractAlpha(image, color))
                                    {
                                        var colorImage = CreateColor(alpha, croppedPattern, nearBlackWhite, useBevel);
                                        images.Add(colorImage);
                                    }
                                }

                                angle += Range / (double)colors.Length;
                            }

                            var result = images.Flatten();
                            result.Crop(input.Width, input.Height, Gravity.Center);
                            return(result);
                        }
                    }
                }
            }
        }
Beispiel #27
0
        private IMagickImage CropOverlay(IMagickImage image, PointD[] coords)
        {
            var result = image.Clone();

            if (Fit == TshirtFit.Crop)
            {
                int height = (int)coords[2].Y + 1;
                if (image.Height > height)
                {
                    result.Crop(image.Width, height, Gravity);
                }
            }

            return(result);
        }
Beispiel #28
0
        public void CastShadow(IMagickImage caster, int offsetX, int offsetY, double size, Percentage alpha, MagickColor color, bool extendCasterWithBorder = true)
        {
            using (IMagickImage shadow = caster.Clone())
            {
                shadow.Shadow(offsetX, offsetY, size, alpha, color);

                if (extendCasterWithBorder)
                {
                    caster.BorderColor = MagickColors.Transparent;
                    caster.Border((int)size);
                }

                caster.Composite(shadow, 0, 0, CompositeOperator.DstOver);
            }
        }
Beispiel #29
0
        private IMagickImage ExtractAlpha(IMagickImage image)
        {
            if (!image.HasAlpha)
            {
                return(null);
            }

            var alpha = image.Clone();

            alpha.Alpha(AlphaOption.Extract);
            alpha.Blur(0, AntiAlias);
            alpha.Level((Percentage)50, (Percentage)100);

            return(alpha);
        }
        private IMagickImage ToNearBlackWhite(IMagickImage image)
        {
            IMagickImage result = image.Clone();

            if (GrayLimit == 0 && ColorFuzz == (Percentage)0)
            {
                return(result);
            }

            result.ColorFuzz = ColorFuzz;
            result.Opaque(MagickColors.White, new MagickColor("gray(" + (100 - GrayLimit) + "%)"));
            result.Opaque(MagickColors.Black, new MagickColor("gray(" + GrayLimit + "%)"));
            result.ColorFuzz = (Percentage)0;

            return(result);
        }