< Summary

Line coverage
100%
Covered lines: 54
Uncovered lines: 0
Coverable lines: 54
Total lines: 139
Line coverage: 100%
Branch coverage
100%
Covered branches: 16
Total branches: 16
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .cctor()100%11100%
File 2: .ctor(...)100%11100%
File 2: ScoreAsync()100%44100%
File 2: Forget()100%11100%
File 2: DescribeAsync()100%44100%
File 2: Describe(...)100%22100%
File 2: Score(...)100%66100%
File 2: ToDouble(...)100%11100%
File 2: GoodMatches(...)100%11100%

File(s)

/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs

File '/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs' does not exist (any more).

/home/runner/work/anichron/anichron/src/Anichron.Worker/Bursts/OrbThumbnailMatcher.cs

#LineLine coverage
 1using Anichron.Core;
 2using OpenCvSharp;
 3using System.IO.Abstractions;
 4
 5namespace Anichron.Worker.Bursts;
 6
 7/// <summary>ORB keypoints, a ratio test and a RANSAC homography, as measured on #296 (ADR 0009).</summary>
 8/// <param name="fileSystem">Reads the stored thumbnails.</param>
 9/// <param name="logger">Reports unreadable thumbnails.</param>
 1110internal sealed partial class OrbThumbnailMatcher(IFileSystem fileSystem, ILogger<OrbThumbnailMatcher> logger)
 11    : IThumbnailMatcher
 12{
 13    internal const int Features = 500;
 14    internal const int DescriptorBytes = 32;
 15    internal const int MinimumKeypoints = 10;
 16    internal const double Ratio = 0.75;
 17    internal const int MinimumGoodMatches = 8;
 18    internal const double RansacThresholdPixels = 5.0;
 19
 1120    private readonly Dictionary<string, Described?> described = [];
 21
 22    /// <summary>A thumbnail's ORB keypoints, kept as managed copies so nothing native outlives a score.</summary>
 23    /// <param name="Points">Each keypoint's position.</param>
 24    /// <param name="Descriptors">Each keypoint's descriptor, <see cref="DescriptorBytes"/> bytes per point, in point or
 25    internal sealed record Described(Point2f[] Points, byte[] Descriptors);
 26
 27    public async Task<double> ScoreAsync(string thumbnailA, string thumbnailB, CancellationToken ct)
 1328        => await DescribeAsync(thumbnailA, ct) is { } a && await DescribeAsync(thumbnailB, ct) is { } b
 1329            ? Score(a, b)
 1330            : 0;
 31
 132    public void Forget() => described.Clear();
 33
 34    private async Task<Described?> DescribeAsync(string thumbnail, CancellationToken ct)
 2335    {
 2336        if (described.TryGetValue(thumbnail, out var known))
 337            return known;
 38
 39        Described? features;
 40        try
 2041        {
 2042            features = StoragePath.ResolveProxy(thumbnail) is { } path
 2043                ? Describe(await fileSystem.File.ReadAllBytesAsync(path, ct))
 2044                : null;
 1745        }
 346        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 347        {
 348            Log.Unreadable(logger, thumbnail, ex);
 349            features = null;
 350        }
 51
 2052        described[thumbnail] = features;
 2053        return features;
 2354    }
 55
 56    /// <summary>The thumbnail's keypoints, or null when the bytes are not an image.</summary>
 57    /// <param name="encoded">The encoded thumbnail.</param>
 58    internal static Described? Describe(byte[] encoded)
 1859    {
 1860        using var gray = Cv2.ImDecode(encoded, ImreadModes.Grayscale);
 1861        if (gray.Empty())
 162            return null;
 63
 1764        using var orb = ORB.Create(Features);
 1765        using var descriptors = new Mat();
 1766        orb.DetectAndCompute(gray, null, out var keypoints, descriptors);
 1767        descriptors.GetArray(out byte[] bytes);
 1768        return new Described([.. keypoints.Select(k => k.Pt)], bytes);
 1869    }
 70
 71    internal static double Score(Described a, Described b)
 1672    {
 1673        if (a.Points.Length < MinimumKeypoints || b.Points.Length < MinimumKeypoints)
 474            return 0;
 75
 1276        using var descriptorsA = Mat.FromPixelData(a.Points.Length, DescriptorBytes, MatType.CV_8UC1, a.Descriptors);
 1277        using var descriptorsB = Mat.FromPixelData(b.Points.Length, DescriptorBytes, MatType.CV_8UC1, b.Descriptors);
 1278        using var matcher = new BFMatcher(NormTypes.Hamming);
 1279        var good = GoodMatches(matcher.KnnMatch(descriptorsA, descriptorsB, 2));
 1280        if (good.Count < MinimumGoodMatches)
 381            return 0;
 82
 983        using var inliers = new Mat();
 984        using var homography = Cv2.FindHomography(
 985            InputArray.Create(good.Select(m => ToDouble(a.Points[m.QueryIdx]))),
 986            InputArray.Create(good.Select(m => ToDouble(b.Points[m.TrainIdx]))),
 987            HomographyMethods.Ransac,
 988            RansacThresholdPixels,
 989            inliers);
 990        return (double)Cv2.CountNonZero(inliers) / Math.Min(a.Points.Length, b.Points.Length);
 1691    }
 92
 208293    private static Point2d ToDouble(Point2f point) => new(point.X, point.Y);
 94
 95    /// <summary>Each query's best match, kept only when clearly better than its second best.</summary>
 96    /// <param name="knn">Each query's two nearest matches.</param>
 97    internal static List<DMatch> GoodMatches(DMatch[][] knn)
 1398        => [.. knn.Where(m => m.Length == 2 && m[0].Distance < Ratio * m[1].Distance).Select(m => m[0])];
 99
 100    private static partial class Log
 101    {
 102        [LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Warning, Message = "Could not read thumbnail {Thumb
 103        public static partial void Unreadable(ILogger logger, string thumbnail, Exception exception);
 104    }
 105}