public void ShouldSetAnArtifactWhenTheMasklightOfTheSettingsIsNotNull()
            {
                CompareSettings settings = new CompareSettings()
                {
                    MasklightColor = MagickColors.Fuchsia,
                };

                using (IMagickImage image = new MagickImage(Files.Builtin.Logo))
                {
                    using (IMagickImage other = new MagickImage(Files.Builtin.Logo))
                    {
                        using (IMagickImage diff = new MagickImage())
                        {
                            image.Compare(other, settings, diff);
                        }
                    }
#if Q8
                    Assert.AreEqual("#FF00FFFF", image.GetArtifact("compare:masklight-color"));
#elif Q16 || Q16HDRI
                    Assert.AreEqual("#FFFF0000FFFFFFFF", image.GetArtifact("compare:masklight-color"));
#else
#error Not implemented!
#endif
                }
            }
        public static void CompareImages()
        {
            var beforeImage = new MagickImage(SampleFiles.ImageCompareBefore)
            {
                ColorFuzz = new Percentage(15)
            };
            var afterImage     = new MagickImage(SampleFiles.ImageCompareAfter);
            var deltaImage     = new MagickImage();
            var threshold      = 0.01;
            var compareSetting = new CompareSettings
            {
                HighlightColor = MagickColors.Red,
                LowlightColor  = MagickColors.White,
                Metric         = ErrorMetric.Fuzz,
            };

            var result = beforeImage.Compare(afterImage, compareSetting, deltaImage);

            if (result > threshold)
            {
                var deltaImagePath = Path.Combine(SampleFiles.OutputDirectory, $"{DateTime.Now.Ticks}.png");
                deltaImage.Write(deltaImagePath);
                Console.WriteLine($"Threshold: {threshold} compare result: {result} Does not match.");
            }
            else
            {
                Console.WriteLine($"Threshold: {threshold} compare result: {result} Matched.");
            }
        }
            public void ShouldReturnNonZeroValueWhenTheImagesAreNotEqual()
            {
                var settings = new CompareSettings
                {
                    Metric         = ErrorMetric.RootMeanSquared,
                    HighlightColor = MagickColors.Yellow,
                    LowlightColor  = MagickColors.Red,
                    MasklightColor = MagickColors.Magenta,
                };

                using (var image = new MagickImage(Files.Builtin.Logo))
                {
                    using (var mask = new MagickImage("xc:white", image.Width, image.Height - 100))
                    {
                        image.SetReadMask(mask);
                    }

                    using (var other = new MagickImage(Files.Builtin.Logo))
                    {
                        other.Rotate(180);

                        using (var diff = new MagickImage())
                        {
                            double result = image.Compare(other, settings, diff);

                            Assert.InRange(result, 0.36, 0.37);
                            ColorAssert.Equal(MagickColors.Yellow, diff, 150, 50);
                            ColorAssert.Equal(MagickColors.Red, diff, 150, 250);
                            ColorAssert.Equal(MagickColors.Magenta, diff, 150, 450);
                        }
                    }
                }
            }
        public void Initialize(ImageManager imageMan, CompareSettings compareSettings)
        {
            SUT           = imageMan;
            Settings      = compareSettings;
            NotEmptyBytes = new byte[1] {
                0x20
            };
            System.Reflection.Assembly a =
                System.Reflection.Assembly.GetExecutingAssembly();
            string fileName = a.GetName().Name + "." + "logoWhite.png";
            Stream s        = a.GetManifestResourceStream(fileName);

            Guard.Against <ArgumentException>(s == null, "Logo White not found");
            using (BinaryReader br = new BinaryReader(s))
            {
                LogoWhite = br.ReadBytes((int)s.Length);
            }

            string logoDarkFilename = a.GetName().Name + "." + "logoDark.png";
            Stream s2 = a.GetManifestResourceStream(logoDarkFilename);

            Guard.Against <ArgumentException>(s2 == null, "Logo Dark not found");
            using (BinaryReader br2 = new BinaryReader(s2))
            {
                LogoDark = br2.ReadBytes((int)s2.Length);
            }
        }
Beispiel #5
0
        public ImageManagerTests(ImageManagerTestsFixture fixture)
        {
            this._fixture = fixture;
            ImageManager    imageMan        = new ImageManager();
            CompareSettings compareSettings = new CompareSettings();

            this._fixture.Initialize(imageMan, compareSettings);
        }
Beispiel #6
0
        private static void CompareSatelliteImageExample()
        {
            ImageManager imageMan = new ImageManager();
            MagickImage  imageA   = imageMan.GetMagickImageFromFile(
                new FileInfo(DataRootPath + @"Tuktoyaktuk\Radarsat1_Images\RS1_m0700829_S7_19970329_151016_HH_SGF\RS1_m0700829_S7_19970329_151016_HH_SGF.tif"));
            MagickImage imageB = imageMan.GetMagickImageFromFile(
                new FileInfo(DataRootPath + @"Tuktoyaktuk\Radarsat1_Images\RS1_m0700835_S5_20120919_152932_HH_SGF\RS1_m0700835_S5_20120919_152932_HH_SGF.tif"));
            CompareSettings compareSettings = new CompareSettings()
            {
                Metric         = ErrorMetric.Absolute,
                HighlightColor = MagickColor.FromRgb(255, 255, 255), // white
                LowlightColor  = MagickColor.FromRgb(0, 0, 0),       // black
            };
            FileInfo info = new FileInfo(DataRootPath + @"Tuktoyaktuk\compareA.tif");

            byte[]   diffImage  = imageMan.CompareImages(imageA, imageB, compareSettings);
            byte[]   thumbImage = imageMan.GetThumbnailFromImage(diffImage, ImageManager.ThumbnailSize.Large);
            FileInfo thumbFile  = new FileInfo(DataRootPath + @"Tuktoyaktuk\compareA_thumb_medium.jpeg");

            if (diffImage.Length > 0)
            {
                using (FileStream fs = new FileStream(info.FullName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(diffImage, 0, diffImage.Length);
                }
            }
            if (thumbImage.Length > 0)
            {
                using (FileStream fs = new FileStream(thumbFile.FullName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(thumbImage, 0, thumbImage.Length);
                }
            }

            compareSettings.Metric = ErrorMetric.Fuzz;
            FileInfo info2 = new FileInfo(DataRootPath + @"Tuktoyaktuk\compareFuzz.tif");

            diffImage = imageMan.CompareImages(imageA, imageB, compareSettings);
            if (diffImage.Length > 0)
            {
                using (FileStream fs = new FileStream(info.FullName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(diffImage, 0, diffImage.Length);
                }
            }
            compareSettings.Metric = ErrorMetric.MeanAbsolute;
            FileInfo info3 = new FileInfo(DataRootPath + @"Tuktoyaktuk\compareMeanAbsolute.tif");

            diffImage = imageMan.CompareImages(imageA, imageB, compareSettings);
            if (diffImage.Length > 0)
            {
                using (FileStream fs = new FileStream(info.FullName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(diffImage, 0, diffImage.Length);
                }
            }
        }
        public ThumbnailGeneratorTests(ThumbnailGeneratorTestsFixture fixture)
        {
            this._fixture = fixture;

            ThumbnailGenerator generator       = new ThumbnailGenerator();
            CompareSettings    compareSettings = new CompareSettings();

            this._fixture.Initialize(generator, compareSettings);
        }
Beispiel #8
0
            public void ShouldNotSetTheAttributesWhenTheyAreNotSpecified()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings();

                    settings.SetImageArtifacts(image);

                    Assert.Empty(image.ArtifactNames);
                }
            }
Beispiel #9
0
        /// <summary>
        /// Utility method to compare two images
        /// </summary>
        /// <param name="imageA">A reference to the first image which will be compared against, in MagickImage format</param>
        /// <param name="imageB">A reference to the second image which will be compared against, in MagickImage format</param>
        /// <returns>A byte array of a new image displaying the differences, if any</returns>
        public byte[] Compare(MagickImage imageA, MagickImage imageB, CompareSettings compareSettings)
        {
            using (MagickImage magicDiffImage = new MagickImage())
            {
                magicDiffImage.Format = MagickFormat.Tif;
                imageA.ColorFuzz      = new Percentage(50); // set a fairly low percentage to identify differences, without picking up every tiny artefact

                imageA.Compare(imageB, compareSettings, magicDiffImage);
                return(magicDiffImage.ToByteArray());
            }
        }
Beispiel #10
0
            public void ShouldNotSetTheAttributesWhenTheyAreNotSpecified()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings();

                    settings.SetImageArtifacts(image);

                    Assert.IsNull(image.GetArtifact("compare:highlight-color"));
                    Assert.IsNull(image.GetArtifact("compare:lowlight-color"));
                    Assert.IsNull(image.GetArtifact("compare:masklight-color"));
                }
            }
Beispiel #11
0
        public static ComparisonResult Compare(IMagickImage original, IMagickImage updated)
        {
            var compareResult = new ComparisonResult();
            // https://github.com/dlemstra/Magick.NET/blob/9943055423b90ac35933dde602b3af9aab746a8a/Source/Magick.NET/Shared/Enums/ErrorMetric.cs
            // https://www.imagemagick.org/script/command-line-options.php#metric
            var compareSettings = new CompareSettings()
            {
                HighlightColor = MagickColors.White,//MagickColor.FromRgba(255, 20, 147, 255),
                LowlightColor  = MagickColors.Black,
                Metric         = ErrorMetric.Absolute
            };

            using (IMagickImage originalMImage = new MagickImage(original))
            {
                // Set Fuzzing Level
                originalMImage.ColorFuzz  = new Percentage(8);
                compareResult.TotalPixels = originalMImage.Height * originalMImage.Width;
                using (IMagickImage diffMImage = new MagickImage())
                {
                    using (IMagickImage updatedMImage = new MagickImage(updated))
                    {
                        compareResult.ChangedPixels = originalMImage.Compare(updatedMImage, compareSettings, diffMImage);
                    }

                    // flatten the colors
                    diffMImage.AutoLevel();
                    // bold the diff, make the changes pop
                    diffMImage.Morphology(new MorphologySettings
                    {
                        Kernel          = Kernel.Octagon,
                        KernelArguments = "5",
                        Method          = MorphologyMethod.Dilate
                    });

                    // flip the colors
                    diffMImage.Opaque(MagickColors.White, MagickColors.Red);
                    diffMImage.Opaque(MagickColors.Black, MagickColors.Transparent);

                    using (var origFadeImg = new MagickImage(original))
                    {
                        origFadeImg.Colorize(MagickColors.White, new Percentage(75));
                        using (IMagickImageCollection collection = new MagickImageCollection(origFadeImg.ToByteArray()))
                        {
                            collection.Add(diffMImage);
                            compareResult.DiffImage = new MagickImage(collection.Merge());
                        }
                    }
                }
            }
            return(compareResult);
        }
            public void ShouldRemoveTheLowlightColor()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings()
                    {
                        LowlightColor = MagickColors.Magenta,
                    };

                    settings.SetImageArtifacts(image);
                    settings.RemoveImageArtifacts(image);

                    EnumerableAssert.IsEmpty(image.ArtifactNames);
                }
            }
                public void ShouldRemoveTheLowlightColor()
                {
                    using (var image = new MagickImage())
                    {
                        var settings = new CompareSettings
                        {
                            LowlightColor = MagickColors.Magenta,
                        };

                        ArtifactsHelper.SetImageArtifacts(image, settings);
                        ArtifactsHelper.RemoveImageArtifacts(image, settings);

                        Assert.Empty(image.ArtifactNames);
                    }
                }
Beispiel #14
0
            public void ShouldRemoveTheMasklightColor()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings()
                    {
                        MasklightColor = MagickColors.Magenta,
                    };

                    settings.SetImageArtifacts(image);
                    settings.RemoveImageArtifacts(image);

                    Assert.IsNull(image.GetArtifact("compare:masklight-color"));
                }
            }
Beispiel #15
0
            public void ShouldRemoveTheMasklightColor()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings
                    {
                        MasklightColor = MagickColors.Magenta,
                    };

                    settings.SetImageArtifacts(image);
                    settings.RemoveImageArtifacts(image);

                    Assert.Empty(image.ArtifactNames);
                }
            }
Beispiel #16
0
            public void ShouldSetTheMasklightColor()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings()
                    {
                        MasklightColor = MagickColors.Magenta,
                    };

                    settings.SetImageArtifacts(image);

#if Q8
                    Assert.AreEqual("#FF00FFFF", image.GetArtifact("compare:masklight-color"));
#else
                    Assert.AreEqual("#FFFF0000FFFFFFFF", image.GetArtifact("compare:masklight-color"));
#endif
                }
            }
 /// <summary>
 /// Compare two images, using the provided comparison settings
 /// </summary>
 /// <param name="imageA">The first image in the comparison, in MagickImage native format</param>
 /// <param name="imageB">The second image in the comparison, in MagickImage native format</param>
 /// <param name="settings">ImageMagick comparison settings</param>
 /// <returns>A byte array containing a new image that represents the *difference* between image a and b</returns>
 public byte[] CompareImages(MagickImage imageA, MagickImage imageB, CompareSettings settings)
 {
     Guard.Against <NullReferenceException>(imageA == null, DeploySoftware_LaunchPad_Images_Resources.Guard_ImageManager_Thumbnail_ImageA_NullReferenceException);
     Guard.Against <NullReferenceException>(imageB == null, DeploySoftware_LaunchPad_Images_Resources.Guard_ImageManager_Thumbnail_ImageB_NullReferenceException);
     byte[] diffImage;
     try
     {
         diffImage = _comparer.Compare(imageA, imageB, settings);
     }
     catch (MagickMissingDelegateErrorException ex)
     {
         Logger.Error(
             DeploySoftware_LaunchPad_Images_Resources.Exception_ImageManager_CompareImages_MagickMissingDelegateErrorException
             + " : "
             + ex.Message
             );
         throw new ArgumentException(DeploySoftware_LaunchPad_Images_Resources.Exception_ImageManager_CompareImages_MagickMissingDelegateErrorException);
     }
     return(diffImage);
 }
            public void ShouldReturnZeroWhenTheImagesAreEqual()
            {
                var settings = new CompareSettings
                {
                    Metric = ErrorMetric.RootMeanSquared,
                };

                using (var image = new MagickImage(Files.Builtin.Logo))
                {
                    using (var other = new MagickImage(Files.Builtin.Logo))
                    {
                        using (var diff = new MagickImage())
                        {
                            double result = image.Compare(other, settings, diff);

                            Assert.Equal(0, result);
                        }
                    }
                }
            }
Beispiel #19
0
            public void ShouldSetTheLowlightColor()
            {
                using (var image = new MagickImage())
                {
                    var settings = new CompareSettings
                    {
                        LowlightColor = MagickColors.Magenta,
                    };

                    settings.SetImageArtifacts(image);

                    Assert.Single(image.ArtifactNames);

#if Q8
                    Assert.Equal("#FF00FFFF", image.GetArtifact("compare:lowlight-color"));
#else
                    Assert.Equal("#FFFF0000FFFFFFFF", image.GetArtifact("compare:lowlight-color"));
#endif
                }
            }
Beispiel #20
0
        private static IEnumerable <object> CompareImages(IMagickImage image1, IMagickImage image2)
        {
            using (image1)
            {
                using (image2)
                {
                    using (var imgWithDiff = new MagickImage())
                    {
                        var compareSettings = new CompareSettings
                        {
                            HighlightColor = new MagickColor(MagickColor.FromRgb(255, 0, 0)),
                            Metric         = ErrorMetric.Absolute
                        };
                        image1.ColorFuzz = new Percentage(3);
                        var doubleRes = image1.Compare(image2, compareSettings, imgWithDiff);
                        yield return(doubleRes);

                        yield return(new MagickImage(imgWithDiff));
                    }
                }
            }
        }
 public void Initialize(ThumbnailGenerator generator, CompareSettings compareSettings)
 {
     SUT      = generator;
     Settings = compareSettings;
 }
Beispiel #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="compose"></param>
        /// <returns></returns>
        private async Task <MagickImage> Compare(MagickImage source, MagickImage target, bool compose = false)
        {
            MagickImage result = null;
            await Dispatcher.InvokeAsync(async() =>
            {
                var st  = Stopwatch.StartNew();
                var tip = new List <string>();
                try
                {
                    if (source is MagickImage && target is MagickImage)
                    {
                        var fuzzy = Math.Min(Math.Max(ImageCompareFuzzy.Minimum, ImageCompareFuzzy.Value), ImageCompareFuzzy.Maximum);
                        if (source.ColorFuzz.ToDouble() != fuzzy)
                        {
                            source.ColorFuzz = new Percentage(fuzzy);
                        }
                        if (target.ColorFuzz.ToDouble() != fuzzy)
                        {
                            target.ColorFuzz = new Percentage(fuzzy);
                        }

                        if (compose)
                        {
                            using (MagickImage diff = new MagickImage(target.Clone()))
                            {
                                diff.Composite(source, CompositeMode, CompareImageChannels);
                                tip.Add($"{"ResultTipMode".T()} {CompositeMode.ToString()}");
                                result = new MagickImage(diff);
                                await Task.Delay(1);
                                DoEvents();
                            }
                        }
                        else
                        {
                            using (MagickImage diff = new MagickImage())
                            {
                                var setting = new CompareSettings()
                                {
                                    Metric         = ErrorMetricMode,
                                    HighlightColor = HighlightColor,
                                    LowlightColor  = LowlightColor,
                                    MasklightColor = MasklightColor
                                };
                                var distance = source.Compare(target, setting, diff, CompareImageChannels);
                                tip.Add($"{"ResultTipMode".T()} {ErrorMetricMode.ToString()}");
                                tip.Add($"{"ResultTipDifference".T()} {distance:F4}");
                                result = new MagickImage(diff);
                                //result.Comment = "NetCharm Created";
                                await Task.Delay(1);
                                DoEvents();
                            }
                        }
                    }
                }
                catch (Exception ex) { ex.ShowMessage(); }
                finally
                {
                    st.Stop();
                    tip.Add($"{"ResultTipElapsed".T()} {TimeSpan.FromTicks(st.ElapsedTicks).TotalSeconds:F4} s");
                    if (compose)
                    {
                        ImageCompose.ToolTip = tip.Count > 1 ? string.Join(Environment.NewLine, tip) : DefaultComposeToolTip;
                        ImageCompare.ToolTip = DefaultCompareToolTip;
                    }
                    else
                    {
                        ImageCompare.ToolTip = tip.Count > 1 ? string.Join(Environment.NewLine, tip) : DefaultCompareToolTip;
                        ImageCompose.ToolTip = DefaultComposeToolTip;
                    }
                }
            }, DispatcherPriority.Render);

            return(result);
        }
Beispiel #23
0
        /// <summary>
        /// Compare two image and save the result of the comparision
        /// </summary>
        /// <param name="sourcePath">The source Image path</param>
        /// <param name="targetPath">The target Image path</param>
        /// <param name="diffSavePath">The path where the result of the comparision will be saved. If null, the result will be not saved</param>
        /// <returns>Returns the percentage of differences between the two images</returns>
        public double Compare(string sourcePath, string targetPath, int fuzziness, string diffSavePath = null, string highlightColor = "FF0000")
        {
            if (string.IsNullOrEmpty(sourcePath))
            {
                throw new ArgumentException("The parameter is required", nameof(sourcePath));
            }

            if (string.IsNullOrEmpty(targetPath))
            {
                throw new ArgumentException("The parameter is required", nameof(targetPath));
            }

            if (fuzziness < 0)
            {
                throw new ArgumentException("The parameter must be a positive integer", nameof(fuzziness));
            }

            double distortionPercentage = -1;

            using (var magickSource = new MagickImage(sourcePath))
                using (var magickTarget = new MagickImage(targetPath))
                    using (var diffImage = new MagickImage())
                    {
                        MagickColor magicHighlightColor;
                        try
                        {
                            highlightColor      = Regex.Replace(highlightColor, "[0-9A-F]{3,6}", "#$0");
                            magicHighlightColor = new MagickColor(highlightColor);
                        }
                        catch
                        {
                            _logger.LogError(EventIds.InvalidColor, $"The color '{highlightColor}' is not a valid color. You can use html colors withou prefixed or a color name.");
                            throw;
                        }


                        var compareSettigns = new CompareSettings()
                        {
                            HighlightColor = magicHighlightColor,
                            //LowlightColor = new MagickColor("blue"),
                            //MasklightColor = new MagickColor("yellow"),
                            Metric = ErrorMetric.Absolute
                        };

                        if (fuzziness > 0)
                        {
                            magickSource.ColorFuzz = new Percentage(fuzziness);
                        }

                        //Distortion = the number Of Pixel of differences
                        var distortion = magickSource.Compare(magickTarget, compareSettigns, diffImage);
                        var imageSize  = magickSource.BaseHeight * magickSource.BaseWidth;
                        distortionPercentage = (100.0 / imageSize) * distortion;

                        if (!string.IsNullOrEmpty(diffSavePath))
                        {
                            if (File.Exists(diffSavePath)) //If already exist remove it
                            {
                                File.Delete(diffSavePath);
                            }
                            diffImage.Write(diffSavePath);
                        }
                    }
            return(distortionPercentage);
        }