Add initial test data in CSV format for image analysis
Some checks failed
Build And Publish AIFotoONLUS.Core / build (push) Failing after 1m0s
Build And Publish AIFotoONLUS.Core / publish (push) Has been skipped

This commit is contained in:
Maddo 2026-11-30 19:32:39 +01:00
commit 5202369356
10 changed files with 43964 additions and 292 deletions

View file

@ -238,7 +238,10 @@ namespace AIFotoONLUS.Core
{
if (image is null) throw new ArgumentNullException(nameof(image));
return DetectTextRegions(_detectionNet, image);
lock (_detectionLock)
{
return DetectTextRegions(_detectionNet, image);
}
}
// Internal variant that accepts a Net instance so it can be used from parallel workers
@ -247,104 +250,15 @@ namespace AIFotoONLUS.Core
using var blob = CvDnn.BlobFromImage(image, 0.00392, _cfg.DetectionInputSize, new Scalar(0, 0, 0), true, false);
detectionNet.SetInput(blob);
var outNames = GetOutputLayerNames(detectionNet);
var outsList = new List<Mat>();
detectionNet.Forward(outsList, outNames);
Mat[] outs = outsList.ToArray();
if (outs.Length == 0)
{
// Try per-output Forward calls as a fallback; use their results for detection
if (outNames != null)
{
var fallback = new List<Mat>();
for (int on = 0; on < outNames.Length; on++)
{
try
{
var single = detectionNet.Forward(outNames[on]);
fallback.Add(single);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Fallback Forward failed for {name}", outNames[on]);
}
}
if (fallback.Count > 0)
{
outs = fallback.ToArray();
}
}
}
// Diagnostic: dump outs shapes and a sample of values to help debugging
var outs = ForwardNet(detectionNet, "Detection fallback forward failed for {name}");
try
{
// diagnostic dumping removed for performance; keep errors only
return ParseDetectedRegions(outs, 0, 1, image.Width, image.Height);
}
catch (Exception ex)
finally
{
_logger?.LogError(ex, "Error dumping outs");
DisposeMats(outs);
}
var boxes = new List<Rect>();
var confidences = new List<float>();
var classIds = new List<int>();
var centerXList = new List<double>();
int imgW = image.Width;
int imgH = image.Height;
foreach (var outMat in outs)
{
for (int i = 0; i < outMat.Rows; i++)
{
float cx = outMat.At<float>(i, 0) * imgW;
float cy = outMat.At<float>(i, 1) * imgH;
float w = outMat.At<float>(i, 2) * imgW;
float h = outMat.At<float>(i, 3) * imgH;
// YOLO output layout: [cx, cy, w, h, objectness, class1, class2, ...]
float objectness = outMat.At<float>(i, 4);
float maxScore = 0f;
int bestClass = -1;
for (int c = 5; c < outMat.Cols; c++)
{
float classProb = outMat.At<float>(i, c);
float score = objectness * classProb; // combine objectness and class probability
if (score > maxScore)
{
maxScore = score;
bestClass = c - 5;
}
}
if (maxScore > _cfg.ConfidenceThreshold)
{
int x = (int)Math.Max(0, Math.Round(cx - w / 2));
int y = (int)Math.Max(0, Math.Round(cy - h / 2));
var rect = new Rect(x, y, (int)Math.Round(w), (int)Math.Round(h));
boxes.Add(rect);
confidences.Add(maxScore);
classIds.Add(bestClass);
centerXList.Add(cx);
}
}
}
if (boxes.Count == 0) return Enumerable.Empty<DetectedRegion>();
CvDnn.NMSBoxes(boxes, confidences, (float)_cfg.ConfidenceThreshold, (float)_cfg.NmsThreshold, out int[] indices);
var results = new List<DetectedRegion>();
foreach (var idx in indices)
{
var b = boxes[idx];
double centerX = b.X + b.Width / 2.0;
results.Add(new DetectedRegion(b, confidences[idx], classIds[idx], centerX));
}
return results;
}
/// <summary>
@ -363,6 +277,16 @@ namespace AIFotoONLUS.Core
{
if (croppedImage is null) throw new ArgumentNullException(nameof(croppedImage));
lock (_recognitionLock)
{
return RecognizeDigits(croppedImage, _recognitionNet, context);
}
}
private string RecognizeDigits(Mat croppedImage, Net recognitionNet, string? context = null)
{
if (croppedImage is null) throw new ArgumentNullException(nameof(croppedImage));
// Optionally save crop image for diagnostics when enabled in configuration
if (_cfg.EnableCropSaving)
{
@ -381,79 +305,17 @@ namespace AIFotoONLUS.Core
}
using var blob = CvDnn.BlobFromImage(croppedImage, 0.00392, _cfg.RecognitionInputSize, new Scalar(0, 0, 0), true, false);
_recognitionNet.SetInput(blob);
recognitionNet.SetInput(blob);
var outNames = GetOutputLayerNames(_recognitionNet);
var outsList = new List<Mat>();
_recognitionNet.Forward(outsList, outNames);
Mat[] outs = outsList.ToArray();
// Fallback: try per-output Forward if no mats were returned
if (outs.Length == 0 && outNames != null)
var outs = ForwardNet(recognitionNet, "Recognition fallback forward failed for {name}");
try
{
var fallback = new List<Mat>();
foreach (var n in outNames)
{
try
{
var m = _recognitionNet.Forward(n);
fallback.Add(m);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Recognition fallback forward failed for {name}", n);
}
}
if (fallback.Count > 0) outs = fallback.ToArray();
return ParseRecognizedDigits(outs, 0, 1, croppedImage.Width, croppedImage.Height);
}
var boxes = new List<Rect>();
var confidences = new List<float>();
var classIds = new List<int>();
var centerXList = new List<double>();
int imgW = croppedImage.Width;
int imgH = croppedImage.Height;
foreach (var outMat in outs)
finally
{
for (int i = 0; i < outMat.Rows; i++)
{
float cx = outMat.At<float>(i, 0) * imgW;
float cy = outMat.At<float>(i, 1) * imgH;
float w = outMat.At<float>(i, 2) * imgW;
float h = outMat.At<float>(i, 3) * imgH;
float objectness = outMat.At<float>(i, 4);
float maxScore = 0f;
int bestClass = -1;
for (int c = 5; c < outMat.Cols; c++)
{
float classProb = outMat.At<float>(i, c);
float score = objectness * classProb;
if (score > maxScore)
{
maxScore = score;
bestClass = c - 5;
}
}
if (maxScore > _cfg.ConfidenceThreshold)
{
int x = (int)Math.Max(0, Math.Round(cx - w / 2));
int y = (int)Math.Max(0, Math.Round(cy - h / 2));
boxes.Add(new Rect(x, y, (int)Math.Round(w), (int)Math.Round(h)));
confidences.Add(maxScore);
classIds.Add(bestClass);
centerXList.Add(cx);
}
}
DisposeMats(outs);
}
if (classIds.Count == 0) return string.Empty;
CvDnn.NMSBoxes(boxes, confidences, (float)_cfg.ConfidenceThreshold, (float)_cfg.NmsThreshold, out int[] keep);
var ordered = keep.Select(i => new { Idx = i, Cx = centerXList[i], ClassId = classIds[i] })
.OrderBy(x => x.Cx)
.Select(x => _cfg.NumberClasses[x.ClassId]);
return string.Concat(ordered);
}
/// <summary>
@ -945,7 +807,16 @@ namespace AIFotoONLUS.Core
{
var outNames = GetOutputLayerNames(net);
var outsList = new List<Mat>();
net.Forward(outsList, outNames);
try
{
net.Forward(outsList, outNames);
}
catch
{
DisposeMats(outsList);
throw;
}
var outs = outsList.ToArray();
if (outs.Length == 0 && outNames != null)
@ -1166,122 +1037,5 @@ namespace AIFotoONLUS.Core
return await ProcessFilesAsync(files, skipTextNegative, maxDegreeOfParallelism: null, progress, resultProgress, cancellationToken).ConfigureAwait(false);
}
// Overload RecognizeDigits that accepts a Net for worker threads
/// <summary>
/// Worker overload of <see cref="RecognizeDigits(Mat,string?)"/> that
/// accepts a <see cref="Net"/> instance. This is used by the parallel
/// processing pipeline where each worker owns its own Net instance.
/// </summary>
/// <param name="croppedImage">Cropped region to recognize.</param>
/// <param name="recognitionNet">Recognition <see cref="Net"/> to execute
/// the forward pass with.</param>
/// <param name="context">Optional context string for diagnostics.</param>
/// <returns>Recognized digit sequence or empty string.</returns>
private string RecognizeDigits(Mat croppedImage, Net recognitionNet, string? context = null)
{
if (croppedImage is null) throw new ArgumentNullException(nameof(croppedImage));
// Optionally save crop image for diagnostics when enabled in configuration
if (_cfg.EnableCropSaving)
{
try
{
var cropsDir = Path.Combine("logs", "crops");
Directory.CreateDirectory(cropsDir);
var fname = $"{(string.IsNullOrEmpty(context) ? "crop" : SanitizeFileName(context))}_{DateTime.UtcNow:yyyyMMdd_HHmmss_fff}_{Guid.NewGuid():N}.jpg";
var full = Path.Combine(cropsDir, fname);
Cv2.ImWrite(full, croppedImage);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Failed saving crop for diagnostics");
}
}
using var blob = CvDnn.BlobFromImage(croppedImage, 0.00392, _cfg.RecognitionInputSize, new Scalar(0, 0, 0), true, false);
recognitionNet.SetInput(blob);
var outNames = GetOutputLayerNames(recognitionNet);
var outsList = new List<Mat>();
recognitionNet.Forward(outsList, outNames);
Mat[] outs = outsList.ToArray();
var boxes = new List<Rect>();
var confidences = new List<float>();
var classIds = new List<int>();
var centerXList = new List<double>();
int imgW = croppedImage.Width;
int imgH = croppedImage.Height;
// Diagnostic: if no outs, try per-output Forward
if (outs.Length == 0 && outNames != null)
{
var fallback = new List<Mat>();
foreach (var n in outNames)
{
try
{
var m = recognitionNet.Forward(n);
fallback.Add(m);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Recognition fallback forward failed for {name}", n);
}
}
if (fallback.Count > 0) outs = fallback.ToArray();
}
// Diagnostic: dump outs shapes and a sample of values to help debugging
try
{
// diagnostic dumping removed for performance; keep errors only
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error dumping recognition outs");
}
foreach (var outMat in outs)
{
for (int i = 0; i < outMat.Rows; i++)
{
float cx = outMat.At<float>(i, 0) * imgW;
float cy = outMat.At<float>(i, 1) * imgH;
float w = outMat.At<float>(i, 2) * imgW;
float h = outMat.At<float>(i, 3) * imgH;
float objectness = outMat.At<float>(i, 4);
float maxScore = 0f;
int bestClass = -1;
for (int c = 5; c < outMat.Cols; c++)
{
float classProb = outMat.At<float>(i, c);
float score = objectness * classProb;
if (score > maxScore)
{
maxScore = score;
bestClass = c - 5;
}
}
if (maxScore > _cfg.ConfidenceThreshold)
{
int x = (int)Math.Max(0, Math.Round(cx - w / 2));
int y = (int)Math.Max(0, Math.Round(cy - h / 2));
boxes.Add(new Rect(x, y, (int)Math.Round(w), (int)Math.Round(h)));
confidences.Add(maxScore);
classIds.Add(bestClass);
centerXList.Add(cx);
}
}
}
if (classIds.Count == 0) return string.Empty;
CvDnn.NMSBoxes(boxes, confidences, (float)_cfg.ConfidenceThreshold, (float)_cfg.NmsThreshold, out int[] keep);
var ordered = keep.Select(i => new { Idx = i, Cx = centerXList[i], ClassId = classIds[i] })
.OrderBy(x => x.Cx)
.Select(x => _cfg.NumberClasses[x.ClassId]);
return string.Concat(ordered);
}
}
}