C
C#2mo ago
Tsuka

What do you think of my code to identify images, do you have any suggestions

What do you think of my code to identify images, do you have any suggestions, I think it's not very accurate?
public Task<List<ImageMatch>> FindTemplateAsync(
Bitmap source,
Bitmap template,
double threshold = 0.7,
int minMatchWidth = 10,
int minMatchHeight = 10)
{
return Task.Run(() =>
{
using var srcMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(source);
using var tplMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(template);

using var srcProcessed = EnsureValidMat(srcMat);
using var tplProcessed = EnsureValidMat(tplMat);


using var result = new Mat();
Cv2.MatchTemplate(srcProcessed, tplProcessed, result, TemplateMatchModes.SqDiffNormed);

Cv2.MinMaxLoc(result, out double minVal, out _, out _, out OpenCvSharp.Point minLoc);
if (minVal > threshold) // threshold para SqDiffNormed
return new List<ImageMatch>();

// Pega o melhor match global
Cv2.MinMaxLoc(result, out _, out double maxVal, out _, out OpenCvSharp.Point maxLoc);
Console.WriteLine($"maxVal={maxVal}, maxLoc=({maxLoc.X},{maxLoc.Y})");

if (maxVal < threshold)
return new List<ImageMatch>();

var bestMatch = new ImageMatch(
new Rectangle(maxLoc.X, maxLoc.Y, tplProcessed.Width, tplProcessed.Height),
maxVal,
new System.Drawing.Point(maxLoc.X + tplProcessed.Width / 2, maxLoc.Y + tplProcessed.Height / 2)
);

return new List<ImageMatch> { bestMatch };
});
}
public Task<List<ImageMatch>> FindTemplateAsync(
Bitmap source,
Bitmap template,
double threshold = 0.7,
int minMatchWidth = 10,
int minMatchHeight = 10)
{
return Task.Run(() =>
{
using var srcMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(source);
using var tplMat = OpenCvSharp.Extensions.BitmapConverter.ToMat(template);

using var srcProcessed = EnsureValidMat(srcMat);
using var tplProcessed = EnsureValidMat(tplMat);


using var result = new Mat();
Cv2.MatchTemplate(srcProcessed, tplProcessed, result, TemplateMatchModes.SqDiffNormed);

Cv2.MinMaxLoc(result, out double minVal, out _, out _, out OpenCvSharp.Point minLoc);
if (minVal > threshold) // threshold para SqDiffNormed
return new List<ImageMatch>();

// Pega o melhor match global
Cv2.MinMaxLoc(result, out _, out double maxVal, out _, out OpenCvSharp.Point maxLoc);
Console.WriteLine($"maxVal={maxVal}, maxLoc=({maxLoc.X},{maxLoc.Y})");

if (maxVal < threshold)
return new List<ImageMatch>();

var bestMatch = new ImageMatch(
new Rectangle(maxLoc.X, maxLoc.Y, tplProcessed.Width, tplProcessed.Height),
maxVal,
new System.Drawing.Point(maxLoc.X + tplProcessed.Width / 2, maxLoc.Y + tplProcessed.Height / 2)
);

return new List<ImageMatch> { bestMatch };
});
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?