using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; using ImageSharpBgra32 = SixLabors.ImageSharp.PixelFormats.Bgra32; using ImageSharpL8 = SixLabors.ImageSharp.PixelFormats.L8; namespace ComputeSharp.Tests { [TestClass] [TestCategory("Imaging")] public class ImagingTests { [CombinatorialTestMethod] [AllDevices] public void LoadAsRgba32FromFile(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(path); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } [CombinatorialTestMethod] [AllDevices] public void LoadAsBgra32FromFile(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(path); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); } [CombinatorialTestMethod] [AllDevices] public void LoadAsBgra32FromFileWithSameFormat(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", "CityAfter1024x1024Sampling.png"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(path); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); } [CombinatorialTestMethod] [AllDevices] public void LoadAsR8FromFile(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(path); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); TolerantImageComparer.AssertEqual(original, loaded, 0.000039f); } [CombinatorialTestMethod] [AllDevices] public void LoadAsRgba32FromBuffer(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); byte[] buffer = File.ReadAllBytes(path); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(buffer); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } [CombinatorialTestMethod] [AllDevices] public void SaveRgba32AsJpeg(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), expectedPath = Path.Combine(path, "city.jpg"), actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(expectedPath); texture.Save(actualPath); TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); } [CombinatorialTestMethod] [AllDevices] public void SaveBgra32AsJpeg(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), expectedPath = Path.Combine(path, "city.jpg"), actualPath = Path.Combine(path, "city_bgra32_saved.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(expectedPath); texture.Save(actualPath); TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); } [CombinatorialTestMethod] [AllDevices] public void SaveR8AsJpeg(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), sourcePath = Path.Combine(path, "city.jpg"), expectedPath = Path.Combine(path, "city_r8_reference.jpg"), actualPath = Path.Combine(path, "city_r8_saved.jpg"); using ReadOnlyTexture2D texture = device.Get().LoadReadOnlyTexture2D(sourcePath); texture.Save(actualPath); using Image original = Image.Load(sourcePath); original.Save(expectedPath); TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00004037f); } /// /// An tolerant image comparer type, from ImageSharp. /// internal static class TolerantImageComparer { /// /// Asserts that two images are equal. /// /// The path to the reference image. /// The path to the expected image. /// The allowed difference threshold for the normalized delta. public static void AssertEqual(string expectedPath, string actualPath, float threshold) { using var expected = Image.Load(expectedPath); using var actual = Image.Load(actualPath); AssertEqual(expected, actual, threshold); } /// /// Asserts that two images are equal. /// /// The type of image pixels to analyze. /// The reference image. /// The expected image. /// The allowed difference threshold for the normalized delta. public static void AssertEqual(Image expected, Image actual, float threshold) where TPixel : unmanaged, IPixel { if (expected.Size() != actual.Size()) { Assert.Fail($"The input images have different sizes: {expected.Size()} and {actual.Size()}"); } if (expected.Frames.Count != actual.Frames.Count || expected.Frames.Count != 1 || actual.Frames.Count != 1) { Assert.Fail("The two input images must have 1 frame each"); } int width = actual.Width; float totalDifference = 0F; var differences = new List(20); Span aBuffer = new ImageSharpRgba32[actual.Width]; Span bBuffer = new ImageSharpRgba32[actual.Width]; for (int y = 0; y < actual.Height; y++) { Span aSpan = expected.GetPixelRowSpan(y); Span bSpan = actual.GetPixelRowSpan(y); PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), aSpan, aBuffer); PixelOperations.Instance.ToRgba32(actual.GetConfiguration(), bSpan, bBuffer); for (int x = 0; x < width; x++) { [MethodImpl(MethodImplOptions.AggressiveInlining)] static int GetManhattanDistanceInRgbaSpace(ref ImageSharpRgba32 a, ref ImageSharpRgba32 b) { [MethodImpl(MethodImplOptions.AggressiveInlining)] static int Diff(ushort a, ushort b) => Math.Abs(a - b); return Diff(a.R, b.R) + Diff(a.G, b.G) + Diff(a.B, b.B) + Diff(a.A, b.A); } int d = GetManhattanDistanceInRgbaSpace(ref aBuffer[x], ref bBuffer[x]); if (d > 0) { if (differences.Count < 20) { var diff = new PixelDifference(new Point(x, y), aBuffer[x], bBuffer[x]); differences.Add(diff); } totalDifference += d; } } } float normalizedDifference = totalDifference / (actual.Width * (float)actual.Height); normalizedDifference /= 4F * 65535F; if (normalizedDifference > threshold) { StringBuilder builder = new(); builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%"); builder.AppendLine($"First {differences.Count} pixel deltas:"); foreach (var delta in differences) { builder.AppendLine(delta.ToString()); } Assert.Fail(builder.ToString()); } } /// /// A simple model repressenting info about a difference between two pixels. /// private readonly struct PixelDifference { public PixelDifference(Point position, ImageSharpRgba32 expected, ImageSharpRgba32 actual) { this.Position = position; this.RedDifference = actual.R - expected.R; this.GreenDifference = actual.G - expected.G; this.BlueDifference = actual.B - expected.B; this.AlphaDifference = actual.A - expected.A; } public readonly Point Position; public readonly int RedDifference; public readonly int GreenDifference; public readonly int BlueDifference; public readonly int AlphaDifference; /// public override string ToString() { return $"[delta({RedDifference},{GreenDifference},{BlueDifference},{AlphaDifference}) @ ({Position.X},{Position.Y})]"; } } } } }