using System.Buffers.Binary;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Compilation;
using XFEWorkflow.Infrastructure.Communication;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Vision;
namespace XFEWorkflow.Test;
[TestFixture]
public class ImageTemplateTests
{
[Test]
public async Task ScreenButtonTemplateMatchesAfterPngPreviewRoundTrip()
{
await using var workspace = new TestWorkspace();
var path = Path.Combine(workspace.Paths.Temp, "buttons.png");
using var source = new Bitmap(600, 360);
source.SetResolution(144, 144); // WinUI at 150%, Runner at a different DPI.
using (var graphics = Graphics.FromImage(source))
{
graphics.Clear(Color.FromArgb(235, 241, 249)); graphics.FillRectangle(Brushes.CornflowerBlue, 80, 90, 180, 60);
using var font = new Font("Microsoft YaHei UI", 24, FontStyle.Bold, GraphicsUnit.Pixel);
graphics.DrawString("提交订单", font, Brushes.White, 108, 104);
}
source.Save(path, ImageFormat.Png);
using var frozen = new ScreenFrame((Bitmap)source.Clone(), new(-1920, -100, 600, 360), "screen");
var data = TemplateImage.Crop(frozen, new(-1840, -10, 180, 60));
using var template = TemplateImage.Load(data.Value); using var loaded = ScreenCapture.Load(path);
Assert.Equal(1, ImageMatcher.Find(loaded.Bitmap, template.Bitmap, loaded.Region, 0, 5, default).Count);
var matches = ImageMatcher.FindSimilar(loaded.Bitmap, template.Bitmap, loaded.Region, .97, 2, default);
Assert.Equal(1, matches.Count); Assert.Equal(80, matches[0]!.AsObject().Integer("x")); Assert.Equal(90, matches[0]!.AsObject().Integer("y"));
var result = await new VisionAction("xfe.vision.findImage").ExecuteAsync(new() { ["imagePath"] = path, ["templatePath"] = data.Value, ["minimumSimilarity"] = .97 }, TestSupport.Context(), default);
Assert.True(result.Boolean("found"));
}
[Test]
public void FrozenTemplatePreservesPixelsWithNegativeScreenCoordinates()
{
using var bitmap = Fixture(80, 50);
using var frozen = new ScreenFrame((Bitmap)bitmap.Clone(), new(-1920, -100, 80, 50), "screen");
var data = TemplateImage.Crop(frozen, new(-1907, -93, 23, 19));
using var restored = TemplateImage.Load(data.Value);
Assert.Equal(23, data.Width); Assert.Equal(19, data.Height);
for (var y = 0; y < data.Height; y++)
for (var x = 0; x < data.Width; x++) Assert.Equal(bitmap.GetPixel(13 + x, 7 + y).ToArgb(), restored.Bitmap.GetPixel(x, y).ToArgb());
bitmap.SetPixel(13, 7, Color.Magenta);
Assert.False(bitmap.GetPixel(13, 7).ToArgb() == restored.Bitmap.GetPixel(0, 0).ToArgb());
Assert.Throws<ArgumentException>(() => TemplateImage.Crop(frozen, new(-2000, -100, 10, 10)));
}
[Test]
public async Task ImportedTemplatesSurviveSourceDeletionAndWorkflowExport()
{
await using var workspace = new TestWorkspace(); var path = Path.Combine(workspace.Paths.Temp, "模板.png");
using (var bitmap = Fixture(18, 13)) bitmap.Save(path, ImageFormat.Png);
var data = TemplateImage.Import(path); File.Delete(path);
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Parameters = new() { ["templatePath"] = data.Value, ["minimumSimilarity"] = .95 } };
var flow = TestSupport.Graph(node); var repository = new WorkflowRepository(workspace.Paths);
var export = Path.Combine(workspace.Paths.Temp, "portable.xfeworkflow");
await repository.SaveAsync(flow); await repository.ExportAsync(flow, export);
var restored = await repository.ImportAsync(export);
Assert.Equal(data.Value, restored.Graph.Nodes[1].Parameters.String("templatePath"));
using var image = TemplateImage.Load(restored.Graph.Nodes[1].Parameters.String("templatePath"));
Assert.Equal(18, image.Bitmap.Width); Assert.Equal(13, image.Bitmap.Height);
Assert.Equal(data.Value, WorkflowJson.Clone(restored).Graph.Nodes[1].Parameters.String("templatePath"));
}
[Test]
public void EmbeddedTemplatesRejectBadHeadersOversizedImagesAndOtherDataTypes()
{
using var bitmap = Fixture(8, 8); var template = TemplateImage.Encode(bitmap);
Assert.Throws<ArgumentException>(() => TemplateImage.Decode("data:image/jpeg;base64,AA=="));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + "***"));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + Convert.ToBase64String(new byte[40])));
var bytes = TemplateImage.Decode(template.Value); BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(16, 4), 100000);
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + Convert.ToBase64String(bytes)));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + new string('A', TemplateImage.MaxBytes * 2)));
using var large = new Bitmap(1025, 1024);
Assert.Throws<ArgumentException>(() => TemplateImage.Encode(large));
}
[Test]
public void SimilarityUsesEveryPixelAndThresholdActuallyFiltersMatches()
{
using var template = Fixture(9, 7); using var modified = (Bitmap)template.Clone();
modified.SetPixel(3, 3, Color.Magenta);
var expected = Score(modified, template, 0, 0);
var match = ImageMatcher.FindSimilar(modified, template, new(-40, 70, 9, 7), expected - .00001, 1, default);
Assert.Equal(1, match.Count);
Assert.True(Math.Abs(match[0]!["score"]!.GetValue<double>() - expected) < .0001);
Assert.Equal(-40, match[0]!.AsObject().Integer("x")); Assert.Equal(70, match[0]!.AsObject().Integer("y"));
Assert.Equal(0, ImageMatcher.FindSimilar(modified, template, new(0, 0, 9, 7), expected + .00001, 1, default).Count);
Assert.Equal(0, ImageMatcher.FindSimilar(modified, template, new(0, 0, 9, 7), 1, 1, default).Count);
}
[Test]
public void SimilarityReturnsTheBestMatchBeforeEarlierNearMisses()
{
using var template = Fixture(12, 10); using var source = new Bitmap(85, 35);
using (var graphics = Graphics.FromImage(source)) { graphics.Clear(Color.White); graphics.DrawImageUnscaled(template, 2, 3); graphics.DrawImageUnscaled(template, 32, 14); graphics.DrawImageUnscaled(template, 60, 4); }
source.SetPixel(5, 6, Color.Black);
var matches = ImageMatcher.FindSimilar(source, template, new(-85, 80, 85, 35), .98, 3, default);
Assert.Equal(3, matches.Count); Assert.Equal(-25, matches[0]!.AsObject().Integer("x")); Assert.Equal(84, matches[0]!.AsObject().Integer("y"));
Assert.Equal(-53, matches[1]!.AsObject().Integer("x")); Assert.Equal(-83, matches[2]!.AsObject().Integer("x"));
Assert.True(matches[0]!["score"]!.GetValue<double>() > matches[2]!["score"]!.GetValue<double>());
Assert.Equal(2, ImageMatcher.FindSimilar(source, template, new(0, 0, 85, 35), 1, 10, default).Count);
}
[Test]
public void SimilarityMatchesIndependentBruteForceIncludingUnevenBlocksAndFlatColors()
{
foreach (var (tw, th) in new[] { (1, 1), (2, 3), (7, 5), (9, 8) })
{
using var source = Fixture(19, 16); using var template = source.Clone(new Rectangle(6, 4, tw, th), PixelFormat.Format24bppRgb);
var expected = new List<(double Score, int X, int Y)>();
for (var y = 0; y <= source.Height - th; y++)
for (var x = 0; x <= source.Width - tw; x++) { var score = Score(source, template, x, y); if (score >= .7) expected.Add((score, x, y)); }
var chosen = new List<(double Score, int X, int Y)>();
foreach (var candidate in expected.OrderByDescending(x => x.Score))
if (!chosen.Any(m => candidate.X < m.X + tw && candidate.X + tw > m.X && candidate.Y < m.Y + th && candidate.Y + th > m.Y)) chosen.Add(candidate);
var result = ImageMatcher.FindSimilar(source, template, new(0, 0, 19, 16), .7, 100, default);
Assert.Equal(Math.Min(100, chosen.Count), result.Count);
for (var i = 0; i < result.Count; i++) { Assert.Equal(chosen[i].X, result[i]!.AsObject().Integer("x")); Assert.Equal(chosen[i].Y, result[i]!.AsObject().Integer("y")); }
}
using var flat = new Bitmap(4, 4); using var other = new Bitmap(4, 4);
using (var graphics = Graphics.FromImage(flat)) graphics.Clear(Color.FromArgb(10, 10, 10));
using (var graphics = Graphics.FromImage(other)) graphics.Clear(Color.FromArgb(30, 30, 30));
Assert.Equal(1, ImageMatcher.FindSimilar(other, flat, new(0, 0, 4, 4), .9, 1, default).Count);
Assert.Equal(0, ImageMatcher.FindSimilar(other, flat, new(0, 0, 4, 4), .95, 1, default).Count);
}
[Test]
public void SimilaritySupportsCancellationAndRejectsInvalidConfiguration()
{
using var image = Fixture(9, 8); using var cancel = new CancellationTokenSource(); cancel.Cancel();
Assert.Throws<OperationCanceledException>(() => ImageMatcher.FindSimilar(image, image, new(0, 0, 9, 8), .9, 5, cancel.Token));
foreach (var similarity in new[] { double.NaN, double.PositiveInfinity, 0, 1.01 })
Assert.Throws<ArgumentException>(() => ImageMatcher.FindSimilar(image, image, new(0, 0, 9, 8), similarity, 5, default));
using var tooLarge = Fixture(10, 10);
Assert.Equal(0, ImageMatcher.FindSimilar(image, tooLarge, new(0, 0, 9, 8), .9, 5, default).Count);
}
[Test]
public async Task EmbeddedImageMatchingWorksThroughGraphAndCodeAndKeepsLegacyMode()
{
await using var workspace = new TestWorkspace(); var path = Path.Combine(workspace.Paths.Temp, "source.png");
using var template = Fixture(7, 5); using var changed = (Bitmap)template.Clone(); changed.SetPixel(3, 3, Color.Magenta); changed.Save(path, ImageFormat.Png);
var registry = new CapabilityRegistry(); new VisionPlugin().Register(registry); using var compiler = new CodeCompiler();
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Parameters = new() { ["imagePath"] = path, ["templatePath"] = TemplateImage.Encode(template).Value, ["minimumSimilarity"] = .95, ["tolerance"] = 0 } };
var flow = TestSupport.Graph(node); flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = node.Id };
var result = await new WorkflowEngine(compiler, CoreCapabilities.Catalog(registry.Descriptors.Values)).ExecuteAsync(flow, TestSupport.Context(registry), default);
Assert.True(result["result"]!.AsObject().Boolean("found"));
node.Parameters["minimumSimilarity"] = null;
var legacy = await new WorkflowEngine(compiler, CoreCapabilities.Catalog(registry.Descriptors.Values)).ExecuteAsync(flow, TestSupport.Context(registry), default);
Assert.False(legacy["result"]!.AsObject().Boolean("found"));
node.Parameters["minimumSimilarity"] = .95;
var code = """
using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using XFEWorkflow.Abstractions;
public sealed class Workflow : IWorkflow {
public async ValueTask<JsonObject> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken) =>
await context.InvokeAsync("xfe.vision.findImage", context.Inputs, cancellationToken);
}
""";
Assert.True((await compiler.ExecuteAsync(code, false, "找图.cs", TestSupport.Context(registry, WorkflowJson.Copy(node.Parameters)), default)).Boolean("found"));
node.Parameters["minimumSimilarity"] = 1; node.Parameters["timeoutMilliseconds"] = 0;
var wait = await new VisionAction("xfe.vision.waitImage").ExecuteAsync(node.Parameters, TestSupport.Context(), default);
Assert.False(wait.Boolean("found")); Assert.True(wait.Boolean("timedOut"));
}
[Test]
public async Task OversizedWorkflowMessagesFailBeforeWritingOrWaitingForRunner()
{
using var stream = new MemoryStream(); await using var rpc = new RpcPeer(stream);
await Assert.ThrowsAsync<InvalidDataException>(() => rpc.RequestAsync<JsonObject>("run", new { template = new string('A', RpcPeer.MaxMessageCharacters) }));
Assert.Equal(0L, stream.Length);
}
private static Bitmap Fixture(int width, int height)
{
var bitmap = new Bitmap(width, height); var random = new Random(937);
for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) bitmap.SetPixel(x, y, Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
return bitmap;
}
private static double Score(Bitmap source, Bitmap template, int x, int y)
{
long error = 0;
for (var row = 0; row < template.Height; row++) for (var col = 0; col < template.Width; col++)
{ var a = source.GetPixel(x + col, y + row); var b = template.GetPixel(col, row); error += Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B); }
return 1 - error / (template.Width * template.Height * 3d * 255);
}
}
using System.Buffers.Binary;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Compilation;
using XFEWorkflow.Infrastructure.Communication;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Vision;
namespace XFEWorkflow.Test;
[TestFixture]
public class ImageTemplateTests
{
[Test]
public async Task ScreenButtonTemplateMatchesAfterPngPreviewRoundTrip()
{
await using var workspace = new TestWorkspace();
var path = Path.Combine(workspace.Paths.Temp, "buttons.png");
using var source = new Bitmap(600, 360);
source.SetResolution(144, 144); // WinUI at 150%, Runner at a different DPI.
using (var graphics = Graphics.FromImage(source))
{
graphics.Clear(Color.FromArgb(235, 241, 249)); graphics.FillRectangle(Brushes.CornflowerBlue, 80, 90, 180, 60);
using var font = new Font("Microsoft YaHei UI", 24, FontStyle.Bold, GraphicsUnit.Pixel);
graphics.DrawString("提交订单", font, Brushes.White, 108, 104);
}
source.Save(path, ImageFormat.Png);
using var frozen = new ScreenFrame((Bitmap)source.Clone(), new(-1920, -100, 600, 360), "screen");
var data = TemplateImage.Crop(frozen, new(-1840, -10, 180, 60));
using var template = TemplateImage.Load(data.Value); using var loaded = ScreenCapture.Load(path);
Assert.Equal(1, ImageMatcher.Find(loaded.Bitmap, template.Bitmap, loaded.Region, 0, 5, default).Count);
var matches = ImageMatcher.FindSimilar(loaded.Bitmap, template.Bitmap, loaded.Region, .97, 2, default);
Assert.Equal(1, matches.Count); Assert.Equal(80, matches[0]!.AsObject().Integer("x")); Assert.Equal(90, matches[0]!.AsObject().Integer("y"));
var result = await new VisionAction("xfe.vision.findImage").ExecuteAsync(new() { ["imagePath"] = path, ["templatePath"] = data.Value, ["minimumSimilarity"] = .97 }, TestSupport.Context(), default);
Assert.True(result.Boolean("found"));
}
[Test]
public void FrozenTemplatePreservesPixelsWithNegativeScreenCoordinates()
{
using var bitmap = Fixture(80, 50);
using var frozen = new ScreenFrame((Bitmap)bitmap.Clone(), new(-1920, -100, 80, 50), "screen");
var data = TemplateImage.Crop(frozen, new(-1907, -93, 23, 19));
using var restored = TemplateImage.Load(data.Value);
Assert.Equal(23, data.Width); Assert.Equal(19, data.Height);
for (var y = 0; y < data.Height; y++)
for (var x = 0; x < data.Width; x++) Assert.Equal(bitmap.GetPixel(13 + x, 7 + y).ToArgb(), restored.Bitmap.GetPixel(x, y).ToArgb());
bitmap.SetPixel(13, 7, Color.Magenta);
Assert.False(bitmap.GetPixel(13, 7).ToArgb() == restored.Bitmap.GetPixel(0, 0).ToArgb());
Assert.Throws<ArgumentException>(() => TemplateImage.Crop(frozen, new(-2000, -100, 10, 10)));
}
[Test]
public async Task ImportedTemplatesSurviveSourceDeletionAndWorkflowExport()
{
await using var workspace = new TestWorkspace(); var path = Path.Combine(workspace.Paths.Temp, "模板.png");
using (var bitmap = Fixture(18, 13)) bitmap.Save(path, ImageFormat.Png);
var data = TemplateImage.Import(path); File.Delete(path);
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Parameters = new() { ["templatePath"] = data.Value, ["minimumSimilarity"] = .95 } };
var flow = TestSupport.Graph(node); var repository = new WorkflowRepository(workspace.Paths);
var export = Path.Combine(workspace.Paths.Temp, "portable.xfeworkflow");
await repository.SaveAsync(flow); await repository.ExportAsync(flow, export);
var restored = await repository.ImportAsync(export);
Assert.Equal(data.Value, restored.Graph.Nodes[1].Parameters.String("templatePath"));
using var image = TemplateImage.Load(restored.Graph.Nodes[1].Parameters.String("templatePath"));
Assert.Equal(18, image.Bitmap.Width); Assert.Equal(13, image.Bitmap.Height);
Assert.Equal(data.Value, WorkflowJson.Clone(restored).Graph.Nodes[1].Parameters.String("templatePath"));
}
[Test]
public void EmbeddedTemplatesRejectBadHeadersOversizedImagesAndOtherDataTypes()
{
using var bitmap = Fixture(8, 8); var template = TemplateImage.Encode(bitmap);
Assert.Throws<ArgumentException>(() => TemplateImage.Decode("data:image/jpeg;base64,AA=="));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + "***"));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + Convert.ToBase64String(new byte[40])));
var bytes = TemplateImage.Decode(template.Value); BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(16, 4), 100000);
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + Convert.ToBase64String(bytes)));
Assert.Throws<ArgumentException>(() => TemplateImage.Decode(TemplateImage.Prefix + new string('A', TemplateImage.MaxBytes * 2)));
using var large = new Bitmap(1025, 1024);
Assert.Throws<ArgumentException>(() => TemplateImage.Encode(large));
}
[Test]
public void SimilarityUsesEveryPixelAndThresholdActuallyFiltersMatches()
{
using var template = Fixture(9, 7); using var modified = (Bitmap)template.Clone();
modified.SetPixel(3, 3, Color.Magenta);
var expected = Score(modified, template, 0, 0);
var match = ImageMatcher.FindSimilar(modified, template, new(-40, 70, 9, 7), expected - .00001, 1, default);
Assert.Equal(1, match.Count);
Assert.True(Math.Abs(match[0]!["score"]!.GetValue<double>() - expected) < .0001);
Assert.Equal(-40, match[0]!.AsObject().Integer("x")); Assert.Equal(70, match[0]!.AsObject().Integer("y"));
Assert.Equal(0, ImageMatcher.FindSimilar(modified, template, new(0, 0, 9, 7), expected + .00001, 1, default).Count);
Assert.Equal(0, ImageMatcher.FindSimilar(modified, template, new(0, 0, 9, 7), 1, 1, default).Count);
}
[Test]
public void SimilarityReturnsTheBestMatchBeforeEarlierNearMisses()
{
using var template = Fixture(12, 10); using var source = new Bitmap(85, 35);
using (var graphics = Graphics.FromImage(source)) { graphics.Clear(Color.White); graphics.DrawImageUnscaled(template, 2, 3); graphics.DrawImageUnscaled(template, 32, 14); graphics.DrawImageUnscaled(template, 60, 4); }
source.SetPixel(5, 6, Color.Black);
var matches = ImageMatcher.FindSimilar(source, template, new(-85, 80, 85, 35), .98, 3, default);
Assert.Equal(3, matches.Count); Assert.Equal(-25, matches[0]!.AsObject().Integer("x")); Assert.Equal(84, matches[0]!.AsObject().Integer("y"));
Assert.Equal(-53, matches[1]!.AsObject().Integer("x")); Assert.Equal(-83, matches[2]!.AsObject().Integer("x"));
Assert.True(matches[0]!["score"]!.GetValue<double>() > matches[2]!["score"]!.GetValue<double>());
Assert.Equal(2, ImageMatcher.FindSimilar(source, template, new(0, 0, 85, 35), 1, 10, default).Count);
}
[Test]
public void SimilarityMatchesIndependentBruteForceIncludingUnevenBlocksAndFlatColors()
{
foreach (var (tw, th) in new[] { (1, 1), (2, 3), (7, 5), (9, 8) })
{
using var source = Fixture(19, 16); using var template = source.Clone(new Rectangle(6, 4, tw, th), PixelFormat.Format24bppRgb);
var expected = new List<(double Score, int X, int Y)>();
for (var y = 0; y <= source.Height - th; y++)
for (var x = 0; x <= source.Width - tw; x++) { var score = Score(source, template, x, y); if (score >= .7) expected.Add((score, x, y)); }
var chosen = new List<(double Score, int X, int Y)>();
foreach (var candidate in expected.OrderByDescending(x => x.Score))
if (!chosen.Any(m => candidate.X < m.X + tw && candidate.X + tw > m.X && candidate.Y < m.Y + th && candidate.Y + th > m.Y)) chosen.Add(candidate);
var result = ImageMatcher.FindSimilar(source, template, new(0, 0, 19, 16), .7, 100, default);
Assert.Equal(Math.Min(100, chosen.Count), result.Count);
for (var i = 0; i < result.Count; i++) { Assert.Equal(chosen[i].X, result[i]!.AsObject().Integer("x")); Assert.Equal(chosen[i].Y, result[i]!.AsObject().Integer("y")); }
}
using var flat = new Bitmap(4, 4); using var other = new Bitmap(4, 4);
using (var graphics = Graphics.FromImage(flat)) graphics.Clear(Color.FromArgb(10, 10, 10));
using (var graphics = Graphics.FromImage(other)) graphics.Clear(Color.FromArgb(30, 30, 30));
Assert.Equal(1, ImageMatcher.FindSimilar(other, flat, new(0, 0, 4, 4), .9, 1, default).Count);
Assert.Equal(0, ImageMatcher.FindSimilar(other, flat, new(0, 0, 4, 4), .95, 1, default).Count);
}
[Test]
public void SimilaritySupportsCancellationAndRejectsInvalidConfiguration()
{
using var image = Fixture(9, 8); using var cancel = new CancellationTokenSource(); cancel.Cancel();
Assert.Throws<OperationCanceledException>(() => ImageMatcher.FindSimilar(image, image, new(0, 0, 9, 8), .9, 5, cancel.Token));
foreach (var similarity in new[] { double.NaN, double.PositiveInfinity, 0, 1.01 })
Assert.Throws<ArgumentException>(() => ImageMatcher.FindSimilar(image, image, new(0, 0, 9, 8), similarity, 5, default));
using var tooLarge = Fixture(10, 10);
Assert.Equal(0, ImageMatcher.FindSimilar(image, tooLarge, new(0, 0, 9, 8), .9, 5, default).Count);
}
[Test]
public async Task EmbeddedImageMatchingWorksThroughGraphAndCodeAndKeepsLegacyMode()
{
await using var workspace = new TestWorkspace(); var path = Path.Combine(workspace.Paths.Temp, "source.png");
using var template = Fixture(7, 5); using var changed = (Bitmap)template.Clone(); changed.SetPixel(3, 3, Color.Magenta); changed.Save(path, ImageFormat.Png);
var registry = new CapabilityRegistry(); new VisionPlugin().Register(registry); using var compiler = new CodeCompiler();
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Parameters = new() { ["imagePath"] = path, ["templatePath"] = TemplateImage.Encode(template).Value, ["minimumSimilarity"] = .95, ["tolerance"] = 0 } };
var flow = TestSupport.Graph(node); flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = node.Id };
var result = await new WorkflowEngine(compiler, CoreCapabilities.Catalog(registry.Descriptors.Values)).ExecuteAsync(flow, TestSupport.Context(registry), default);
Assert.True(result["result"]!.AsObject().Boolean("found"));
node.Parameters["minimumSimilarity"] = null;
var legacy = await new WorkflowEngine(compiler, CoreCapabilities.Catalog(registry.Descriptors.Values)).ExecuteAsync(flow, TestSupport.Context(registry), default);
Assert.False(legacy["result"]!.AsObject().Boolean("found"));
node.Parameters["minimumSimilarity"] = .95;
var code = """
using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using XFEWorkflow.Abstractions;
public sealed class Workflow : IWorkflow {
public async ValueTask<JsonObject> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken) =>
await context.InvokeAsync("xfe.vision.findImage", context.Inputs, cancellationToken);
}
""";
Assert.True((await compiler.ExecuteAsync(code, false, "找图.cs", TestSupport.Context(registry, WorkflowJson.Copy(node.Parameters)), default)).Boolean("found"));
node.Parameters["minimumSimilarity"] = 1; node.Parameters["timeoutMilliseconds"] = 0;
var wait = await new VisionAction("xfe.vision.waitImage").ExecuteAsync(node.Parameters, TestSupport.Context(), default);
Assert.False(wait.Boolean("found")); Assert.True(wait.Boolean("timedOut"));
}
[Test]
public async Task OversizedWorkflowMessagesFailBeforeWritingOrWaitingForRunner()
{
using var stream = new MemoryStream(); await using var rpc = new RpcPeer(stream);
await Assert.ThrowsAsync<InvalidDataException>(() => rpc.RequestAsync<JsonObject>("run", new { template = new string('A', RpcPeer.MaxMessageCharacters) }));
Assert.Equal(0L, stream.Length);
}
private static Bitmap Fixture(int width, int height)
{
var bitmap = new Bitmap(width, height); var random = new Random(937);
for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) bitmap.SetPixel(x, y, Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
return bitmap;
}
private static double Score(Bitmap source, Bitmap template, int x, int y)
{
long error = 0;
for (var row = 0; row < template.Height; row++) for (var col = 0; col < template.Width; col++)
{ var a = source.GetPixel(x + col, y + row); var b = template.GetPixel(col, row); error += Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B); }
return 1 - error / (template.Width * template.Height * 3d * 255);
}
}