| | | 1 | | using Anichron.Core; |
| | | 2 | | using OpenCvSharp; |
| | | 3 | | using System.IO.Abstractions; |
| | | 4 | | |
| | | 5 | | namespace 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> |
| | 11 | 10 | | internal 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 | | |
| | 11 | 20 | | 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) |
| | 13 | 28 | | => await DescribeAsync(thumbnailA, ct) is { } a && await DescribeAsync(thumbnailB, ct) is { } b |
| | 13 | 29 | | ? Score(a, b) |
| | 13 | 30 | | : 0; |
| | | 31 | | |
| | 1 | 32 | | public void Forget() => described.Clear(); |
| | | 33 | | |
| | | 34 | | private async Task<Described?> DescribeAsync(string thumbnail, CancellationToken ct) |
| | 23 | 35 | | { |
| | 23 | 36 | | if (described.TryGetValue(thumbnail, out var known)) |
| | 3 | 37 | | return known; |
| | | 38 | | |
| | | 39 | | Described? features; |
| | | 40 | | try |
| | 20 | 41 | | { |
| | 20 | 42 | | features = StoragePath.ResolveProxy(thumbnail) is { } path |
| | 20 | 43 | | ? Describe(await fileSystem.File.ReadAllBytesAsync(path, ct)) |
| | 20 | 44 | | : null; |
| | 17 | 45 | | } |
| | 3 | 46 | | catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| | 3 | 47 | | { |
| | 3 | 48 | | Log.Unreadable(logger, thumbnail, ex); |
| | 3 | 49 | | features = null; |
| | 3 | 50 | | } |
| | | 51 | | |
| | 20 | 52 | | described[thumbnail] = features; |
| | 20 | 53 | | return features; |
| | 23 | 54 | | } |
| | | 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) |
| | 18 | 59 | | { |
| | 18 | 60 | | using var gray = Cv2.ImDecode(encoded, ImreadModes.Grayscale); |
| | 18 | 61 | | if (gray.Empty()) |
| | 1 | 62 | | return null; |
| | | 63 | | |
| | 17 | 64 | | using var orb = ORB.Create(Features); |
| | 17 | 65 | | using var descriptors = new Mat(); |
| | 17 | 66 | | orb.DetectAndCompute(gray, null, out var keypoints, descriptors); |
| | 17 | 67 | | descriptors.GetArray(out byte[] bytes); |
| | 17 | 68 | | return new Described([.. keypoints.Select(k => k.Pt)], bytes); |
| | 18 | 69 | | } |
| | | 70 | | |
| | | 71 | | internal static double Score(Described a, Described b) |
| | 16 | 72 | | { |
| | 16 | 73 | | if (a.Points.Length < MinimumKeypoints || b.Points.Length < MinimumKeypoints) |
| | 4 | 74 | | return 0; |
| | | 75 | | |
| | 12 | 76 | | using var descriptorsA = Mat.FromPixelData(a.Points.Length, DescriptorBytes, MatType.CV_8UC1, a.Descriptors); |
| | 12 | 77 | | using var descriptorsB = Mat.FromPixelData(b.Points.Length, DescriptorBytes, MatType.CV_8UC1, b.Descriptors); |
| | 12 | 78 | | using var matcher = new BFMatcher(NormTypes.Hamming); |
| | 12 | 79 | | var good = GoodMatches(matcher.KnnMatch(descriptorsA, descriptorsB, 2)); |
| | 12 | 80 | | if (good.Count < MinimumGoodMatches) |
| | 3 | 81 | | return 0; |
| | | 82 | | |
| | 9 | 83 | | using var inliers = new Mat(); |
| | 9 | 84 | | using var homography = Cv2.FindHomography( |
| | 9 | 85 | | InputArray.Create(good.Select(m => ToDouble(a.Points[m.QueryIdx]))), |
| | 9 | 86 | | InputArray.Create(good.Select(m => ToDouble(b.Points[m.TrainIdx]))), |
| | 9 | 87 | | HomographyMethods.Ransac, |
| | 9 | 88 | | RansacThresholdPixels, |
| | 9 | 89 | | inliers); |
| | 9 | 90 | | return (double)Cv2.CountNonZero(inliers) / Math.Min(a.Points.Length, b.Points.Length); |
| | 16 | 91 | | } |
| | | 92 | | |
| | 2082 | 93 | | 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) |
| | 13 | 98 | | => [.. 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 | | } |