ImageComparisonTest.cs 10.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Svg.UnitTests
{
    /// <summary>
    /// </summary>
    [TestClass]
    public class ImageComparisonTest
    {
        public TestContext TestContext { get; set; }

        /// <summary>
        /// Compares SVG images against reference PNG images from the W3C SVG 1.1 test suite.
        /// This tests 158 out of 179 passing tests - the rest will not pass
        /// the test for several reasons. 
        /// Note that with the current test there are still a lot of false positives,
        /// so this is not a definitive test for image equality yet.
        /// </summary>
        [TestMethod]
        [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV",
            @"|DataDirectory|\..\..\PassingTests.csv",
            "PassingTests#csv", DataAccessMethod.Sequential)]
        public void CompareSvgImageWithReference()
        {
            var basePath = TestContext.TestRunDirectory;
            while (!basePath.ToLower().EndsWith("svg"))
            {
                basePath = Path.GetDirectoryName(basePath);
            }
            basePath = Path.Combine(basePath, "Tests", "W3CTestSuite");
            var svgBasePath = Path.Combine(basePath, "svg");
            var baseName = TestContext.DataRow[0] as string;
38
39
40
41
42
            bool testSaveLoad = !baseName.StartsWith("#");
            if (!testSaveLoad)
            {
                baseName = baseName.Substring(1);
            }
43
44
45
            var svgPath = Path.Combine(basePath, "svg", baseName + ".svg");
            var pngPath = Path.Combine(basePath, "png", baseName + ".png");
            var pngImage = Image.FromFile(pngPath);
46
47
48
49
            var svgDoc = LoadSvgDocument(svgPath);
            Assert.IsNotNull(svgDoc);
            bool useFixedSize = !baseName.StartsWith("__");
            var svgImage = LoadSvgImage(svgDoc, useFixedSize);
50
51
52
53
54
            Assert.AreNotEqual(null, pngImage, "Failed to load " + pngPath);
            Assert.AreNotEqual(null, svgImage, "Failed to load " + svgPath);
            var difference = svgImage.PercentageDifference(pngImage);
            Assert.IsTrue(difference < 0.05, 
                baseName + ": Difference is " + (difference * 100.0).ToString() + "%");
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
            if (!testSaveLoad)
            {
                // for some images, save/load is still failing
                return;
            }

            // test save/load
            using (var memStream = new MemoryStream())
            {
                svgDoc.Write(memStream);
                memStream.Position = 0;
                var reader = new StreamReader(memStream);
                var tempFilePath = Path.Combine(Path.GetTempPath(), "test.svg");
                File.WriteAllText(tempFilePath, reader.ReadToEnd());
                var baseUri = svgDoc.BaseUri;
                svgDoc = SvgDocument.Open(tempFilePath);
                svgDoc.BaseUri = baseUri;
                svgImage = LoadSvgImage(svgDoc, useFixedSize);
                Assert.IsNotNull(svgImage);
                difference = svgImage.PercentageDifference(pngImage);
                Assert.IsTrue(difference < 0.05,
                    baseName + ": Difference is " + (difference * 100.0).ToString() + "%");
            }
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        }

        /// <summary>
        /// Enable this test to output the calculate percentage difference
        /// of all considered W3C tests.
        /// Can be used to enhance the difference calculation.
        /// </summary>
        // [TestClass]
        public void RecordDiffForAllSvgImagesWithReference()
        {
            var basePath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(
                TestContext.TestRunDirectory)));
            basePath = Path.Combine(basePath, "Tests", "W3CTestSuite");
            var svgBasePath = Path.Combine(basePath, "svg");
            string[] lines = File.ReadAllLines(@"..\..\..\..\Tests\Svg.UnitTests\all.csv");
            foreach (var baseName in lines)
            {
                var svgPath = Path.Combine(basePath, "svg", baseName + ".svg");
                var pngPath = Path.Combine(basePath, "png", baseName + ".png");
                if (File.Exists(pngPath) && File.Exists(svgPath))
                {
                    var pngImage = Image.FromFile(pngPath);
100
101
                    var svgDoc = LoadSvgDocument(svgPath);
                    if (svgPath != null)
102
                    {
103
104
105
106
107
108
109
                        bool useFixedSize = !baseName.StartsWith("__");
                        var svgImage = LoadSvgImage(svgDoc, useFixedSize);
                        if (pngImage != null && svgImage != null)
                        {
                            var difference = svgImage.PercentageDifference(pngImage);
                            Console.WriteLine(baseName + " " + (difference * 100.0).ToString());
                        }
110
111
112
113
114
115
116
117
                    }
                }
            }
        }

        /// <summary>
        /// Load the SVG image the same way as in the SVGW3CTestRunner.
        /// </summary>
118
        private static Image LoadSvgImage(SvgDocument svgDoc, bool usedFixedSize)
119
120
121
122
        {
            Image svgImage;
            try
            {
123
                if (usedFixedSize)
124
                {
125
126
127
                    var img = new Bitmap(480, 360);
                    svgDoc.Draw(img);
                    svgImage = img;
128
129
130
                }
                else
                {
131
                    svgImage = svgDoc.Draw();
132
                }
133
134
135
136
137
138
139
            }
            catch (Exception)
            {
                svgImage = null;
            }
            return svgImage;
        }
140
141
142
143
144
145
146
147
148
149
150
151
152

        private static SvgDocument LoadSvgDocument(string svgPath)
        {
            try
            {
                return SvgDocument.Open(svgPath);
            }
            catch (Exception)
            {
                return null;
            }
        }

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    }

    /// <summary>
    /// Taken from https://web.archive.org/web/20130111215043/http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale
    /// and slightly modified.
    /// Image width and height, default threshold and handling of alpha values have been adapted.
    /// </summary>
    public static class ExtensionMethods
    {
        private static int ImageWidth = 64;
        private static int ImageHeight = 64;

        public static float PercentageDifference(this Image img1, Image img2, byte threshold = 10)
        {
            byte[,] differences = img1.GetDifferences(img2);

            int diffPixels = 0;

            foreach (byte b in differences)
            {
                if (b > threshold) { diffPixels++; }
            }

            return diffPixels / (float)(ImageWidth * ImageHeight);
        }

        public static Image Resize(this Image originalImage, int newWidth, int newHeight)
        {
            Image smallVersion = new Bitmap(newWidth, newHeight);
            using (Graphics g = Graphics.FromImage(smallVersion))
            {
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.DrawImage(originalImage, 0, 0, newWidth, newHeight);
            }

            return smallVersion;
        }

        public static byte[,] GetGrayScaleValues(this Image img)
        {
            using (Bitmap thisOne = (Bitmap)img.Resize(ImageWidth, ImageHeight).GetGrayScaleVersion())
            {
                byte[,] grayScale = new byte[ImageWidth, ImageHeight];

                for (int y = 0; y < ImageHeight; y++)
                {
                    for (int x = 0; x < ImageWidth; x++)
                    {
                        var pixel = thisOne.GetPixel(x, y);
                        var alpha = thisOne.GetPixel(x, y).A;
                        var gray = thisOne.GetPixel(x, y).R;
                        grayScale[x, y] = (byte)Math.Abs(gray * alpha / 255);
                    }
                }
                return grayScale;
            }
        }

        //the colormatrix needed to grayscale an image
        static readonly ColorMatrix ColorMatrix = new ColorMatrix(new float[][]
        {
            new float[] {.3f, .3f, .3f, 0, 0},
            new float[] {.59f, .59f, .59f, 0, 0},
            new float[] {.11f, .11f, .11f, 0, 0},
            new float[] {0, 0, 0, 1, 0},
            new float[] {0, 0, 0, 0, 1}
        });

        public static Image GetGrayScaleVersion(this Image original)
        {
            //create a blank bitmap the same size as original
            //https://web.archive.org/web/20130111215043/http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);

            //get a graphics object from the new image
            using (Graphics g = Graphics.FromImage(newBitmap))
            {
                //create some image attributes
                ImageAttributes attributes = new ImageAttributes();

                //set the color matrix attribute
                attributes.SetColorMatrix(ColorMatrix);

                //draw the original image on the new image
                //using the grayscale color matrix
                g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                   0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
            }
            return newBitmap;

        }

        public static byte[,] GetDifferences(this Image img1, Image img2)
        {
            Bitmap thisOne = (Bitmap)img1.Resize(ImageWidth, ImageHeight).GetGrayScaleVersion();
            Bitmap theOtherOne = (Bitmap)img2.Resize(ImageWidth, ImageHeight).GetGrayScaleVersion();
            byte[,] differences = new byte[ImageWidth, ImageHeight];
            byte[,] firstGray = thisOne.GetGrayScaleValues();
            byte[,] secondGray = theOtherOne.GetGrayScaleValues();

            for (int y = 0; y < ImageHeight; y++)
            {
                for (int x = 0; x < ImageWidth; x++)
                {
                    differences[x, y] = (byte)Math.Abs(firstGray[x, y] - secondGray[x, y]);
                }
            }
            thisOne.Dispose();
            theOtherOne.Dispose();
            return differences;
        }
    }
}