Add GPU batch processing support in NumberRecognitionEngine
This commit is contained in:
parent
20d8803f54
commit
3bde2c607f
1 changed files with 450 additions and 2 deletions
|
|
@ -475,6 +475,10 @@ namespace AIFotoONLUS.Core
|
|||
/// <param name="DetectionOutputs">Array describing detection net outputs.</param>
|
||||
public record DiagnosticResult(ImageResult Result, DetectionOutput[] DetectionOutputs);
|
||||
|
||||
private sealed record ImageBatchItem(string FilePath, string FileName, Mat Image);
|
||||
|
||||
private sealed record CropBatchItem(int ImageIndex, Mat Crop, Rect BoundingBox, string Context);
|
||||
|
||||
/// <summary>
|
||||
/// Process a single image file and return the recognition result together
|
||||
/// with detection network forward output shapes for diagnostics. This
|
||||
|
|
@ -567,14 +571,19 @@ namespace AIFotoONLUS.Core
|
|||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var bag = new ConcurrentBag<ImageResult>();
|
||||
|
||||
var dop = maxDegreeOfParallelism.GetValueOrDefault();
|
||||
if (dop <= 0)
|
||||
{
|
||||
dop = Environment.ProcessorCount;
|
||||
}
|
||||
|
||||
if (_cfg.UseGpu)
|
||||
{
|
||||
return await ProcessFilesGpuBatchedAsync(files, skipTextNegative, dop, progress, resultProgress, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var bag = new ConcurrentBag<ImageResult>();
|
||||
|
||||
var total = files.Length;
|
||||
var processed = 0;
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
|
|
@ -707,6 +716,445 @@ namespace AIFotoONLUS.Core
|
|||
return bag.OrderBy(b => b.FileName).ToList();
|
||||
}
|
||||
|
||||
private async Task<IEnumerable<ImageResult>> ProcessFilesGpuBatchedAsync(string[] files, bool skipTextNegative, int batchSize, IProgress<ProcessingStats>? progress, IProgress<ImageResult>? resultProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
var effectiveFiles = files
|
||||
.Where(f => !skipTextNegative || !Path.GetFileName(f).StartsWith("tn_", StringComparison.OrdinalIgnoreCase))
|
||||
.ToArray();
|
||||
var results = new ConcurrentBag<ImageResult>();
|
||||
var total = effectiveFiles.Length;
|
||||
var processed = 0;
|
||||
var sw = Stopwatch.StartNew();
|
||||
var pipeline = ResolveGpuPipelineSettings(batchSize);
|
||||
var recognitionBatchSize = Math.Clamp(pipeline.BatchSize * 4, pipeline.BatchSize, 128);
|
||||
var fileBatches = effectiveFiles
|
||||
.Chunk(pipeline.BatchSize)
|
||||
.Select(chunk => chunk.ToArray())
|
||||
.ToArray();
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var netsBag = new ConcurrentBag<(Net DetectionNet, Net RecognitionNet)>();
|
||||
var threadLocalNets = new ThreadLocal<(Net DetectionNet, Net RecognitionNet)>(() =>
|
||||
{
|
||||
var detectionNet = CvDnn.ReadNetFromDarknet(_cfg.DetectionCfg, _cfg.DetectionWeights);
|
||||
var recognitionNet = CvDnn.ReadNetFromDarknet(_cfg.RecognitionCfg, _cfg.RecognitionWeights);
|
||||
ConfigureNetRuntime(detectionNet, useGpu: true);
|
||||
ConfigureNetRuntime(recognitionNet, useGpu: true);
|
||||
netsBag.Add((detectionNet, recognitionNet));
|
||||
return (detectionNet, recognitionNet);
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
Parallel.ForEach(fileBatches, new ParallelOptions { MaxDegreeOfParallelism = pipeline.WorkerCount, CancellationToken = cancellationToken }, batchFiles =>
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var nets = threadLocalNets.Value;
|
||||
IReadOnlyList<ImageResult> batchResults;
|
||||
try
|
||||
{
|
||||
batchResults = ProcessGpuImageBatch(batchFiles, nets.DetectionNet, nets.RecognitionNet, recognitionBatchSize, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogWarning(ex, "GPU batch OCR failed for {Count} image(s); retrying the batch one image at a time", batchFiles.Length);
|
||||
batchResults = ProcessGpuImagesIndividually(batchFiles, cancellationToken);
|
||||
}
|
||||
|
||||
foreach (var result in batchResults)
|
||||
{
|
||||
results.Add(result);
|
||||
resultProgress?.Report(result);
|
||||
|
||||
var proc = Interlocked.Increment(ref processed);
|
||||
if (progress != null)
|
||||
{
|
||||
var elapsed = Math.Max(1, sw.ElapsedMilliseconds);
|
||||
progress.Report(new ProcessingStats(total, proc, proc * 1000.0 / elapsed));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
while (netsBag.TryTake(out var nets))
|
||||
{
|
||||
try { nets.DetectionNet.Dispose(); } catch { }
|
||||
try { nets.RecognitionNet.Dispose(); } catch { }
|
||||
}
|
||||
|
||||
threadLocalNets.Dispose();
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return results.OrderBy(r => r.FileName).ToList();
|
||||
}
|
||||
|
||||
private static (int BatchSize, int WorkerCount) ResolveGpuPipelineSettings(int targetInFlightImages)
|
||||
{
|
||||
var target = Math.Clamp(targetInFlightImages, 1, 96);
|
||||
var workerCount = target switch
|
||||
{
|
||||
<= 8 => 1,
|
||||
<= 16 => 2,
|
||||
_ => 4
|
||||
};
|
||||
var batchSize = Math.Clamp((int)Math.Ceiling(target / (double)workerCount), 1, 16);
|
||||
return (batchSize, workerCount);
|
||||
}
|
||||
|
||||
private IReadOnlyList<ImageResult> ProcessGpuImagesIndividually(IReadOnlyList<string> files, CancellationToken cancellationToken)
|
||||
{
|
||||
var results = new List<ImageResult>(files.Count);
|
||||
foreach (var file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
results.Add(ProcessImage(file));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogError(ex, "Error processing image {file}", Path.GetFileName(file));
|
||||
results.Add(new ImageResult(Path.GetFileName(file), string.Empty, file));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private IReadOnlyList<ImageResult> ProcessGpuImageBatch(IReadOnlyList<string> files, Net detectionNet, Net recognitionNet, int recognitionBatchSize, CancellationToken cancellationToken)
|
||||
{
|
||||
var images = new List<ImageBatchItem>(files.Count);
|
||||
var crops = new List<CropBatchItem>();
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var image = Cv2.ImRead(file);
|
||||
if (image.Empty())
|
||||
{
|
||||
image.Dispose();
|
||||
throw new InvalidOperationException($"OpenCV could not read image: {file}");
|
||||
}
|
||||
|
||||
images.Add(new ImageBatchItem(file, Path.GetFileName(file), image));
|
||||
}
|
||||
|
||||
var regionsByImage = DetectTextRegionsBatch(detectionNet, images.Select(i => i.Image).ToArray());
|
||||
var textsByImage = Enumerable.Range(0, images.Count).Select(_ => new List<string>()).ToArray();
|
||||
|
||||
for (var imageIndex = 0; imageIndex < images.Count; imageIndex++)
|
||||
{
|
||||
foreach (var region in regionsByImage[imageIndex])
|
||||
{
|
||||
var boundingBox = ClampRect(region.BoundingBox, images[imageIndex].Image.Width, images[imageIndex].Image.Height);
|
||||
if (boundingBox.Width <= 0 || boundingBox.Height <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var crop = new Mat(images[imageIndex].Image, boundingBox);
|
||||
var context = $"{images[imageIndex].FileName}_{boundingBox.X}_{boundingBox.Y}_{boundingBox.Width}x{boundingBox.Height}";
|
||||
crops.Add(new CropBatchItem(imageIndex, crop, boundingBox, context));
|
||||
}
|
||||
}
|
||||
|
||||
for (var offset = 0; offset < crops.Count; offset += recognitionBatchSize)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var cropBatch = crops.Skip(offset).Take(recognitionBatchSize).ToArray();
|
||||
var recognizedTexts = RecognizeDigitsBatch(recognitionNet, cropBatch);
|
||||
for (var i = 0; i < cropBatch.Length; i++)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(recognizedTexts[i]))
|
||||
{
|
||||
textsByImage[cropBatch[i].ImageIndex].Add(recognizedTexts[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return images
|
||||
.Select((image, index) => new ImageResult(image.FileName, string.Join(",", textsByImage[index]), image.FilePath))
|
||||
.ToList();
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var crop in crops)
|
||||
{
|
||||
crop.Crop.Dispose();
|
||||
}
|
||||
|
||||
foreach (var image in images)
|
||||
{
|
||||
image.Image.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<DetectedRegion[]> DetectTextRegionsBatch(Net detectionNet, IReadOnlyList<Mat> images)
|
||||
{
|
||||
using var blob = CvDnn.BlobFromImages(images, 0.00392, _cfg.DetectionInputSize, new Scalar(0, 0, 0), true, false);
|
||||
detectionNet.SetInput(blob);
|
||||
|
||||
var outs = ForwardNet(detectionNet, "Detection batch fallback forward failed for {name}");
|
||||
try
|
||||
{
|
||||
return images
|
||||
.Select((image, batchIndex) => ParseDetectedRegions(outs, batchIndex, images.Count, image.Width, image.Height))
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
DisposeMats(outs);
|
||||
}
|
||||
}
|
||||
|
||||
private string[] RecognizeDigitsBatch(Net recognitionNet, IReadOnlyList<CropBatchItem> crops)
|
||||
{
|
||||
if (crops.Count == 0)
|
||||
{
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
|
||||
if (_cfg.EnableCropSaving)
|
||||
{
|
||||
SaveDiagnosticCrops(crops);
|
||||
}
|
||||
|
||||
using var blob = CvDnn.BlobFromImages(crops.Select(c => c.Crop), 0.00392, _cfg.RecognitionInputSize, new Scalar(0, 0, 0), true, false);
|
||||
recognitionNet.SetInput(blob);
|
||||
|
||||
var outs = ForwardNet(recognitionNet, "Recognition batch fallback forward failed for {name}");
|
||||
try
|
||||
{
|
||||
return crops
|
||||
.Select((crop, batchIndex) => ParseRecognizedDigits(outs, batchIndex, crops.Count, crop.Crop.Width, crop.Crop.Height))
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
DisposeMats(outs);
|
||||
}
|
||||
}
|
||||
|
||||
private Mat[] ForwardNet(Net net, string fallbackFailureMessage)
|
||||
{
|
||||
var outNames = GetOutputLayerNames(net);
|
||||
var outsList = new List<Mat>();
|
||||
net.Forward(outsList, outNames);
|
||||
var outs = outsList.ToArray();
|
||||
|
||||
if (outs.Length == 0 && outNames != null)
|
||||
{
|
||||
var fallback = new List<Mat>();
|
||||
foreach (var name in outNames)
|
||||
{
|
||||
try
|
||||
{
|
||||
fallback.Add(net.Forward(name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogError(ex, fallbackFailureMessage, name);
|
||||
}
|
||||
}
|
||||
|
||||
if (fallback.Count > 0)
|
||||
{
|
||||
outs = fallback.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
return outs;
|
||||
}
|
||||
|
||||
private DetectedRegion[] ParseDetectedRegions(Mat[] outs, int batchIndex, int batchCount, int imageWidth, int imageHeight)
|
||||
{
|
||||
var boxes = new List<Rect>();
|
||||
var confidences = new List<float>();
|
||||
var classIds = new List<int>();
|
||||
var centerXList = new List<double>();
|
||||
|
||||
foreach (var outMat in outs)
|
||||
{
|
||||
var rows = GetYoloRows(outMat, batchCount);
|
||||
var cols = GetYoloCols(outMat);
|
||||
for (var row = 0; row < rows; row++)
|
||||
{
|
||||
var cx = GetYoloValue(outMat, batchIndex, batchCount, row, 0) * imageWidth;
|
||||
var cy = GetYoloValue(outMat, batchIndex, batchCount, row, 1) * imageHeight;
|
||||
var width = GetYoloValue(outMat, batchIndex, batchCount, row, 2) * imageWidth;
|
||||
var height = GetYoloValue(outMat, batchIndex, batchCount, row, 3) * imageHeight;
|
||||
var objectness = GetYoloValue(outMat, batchIndex, batchCount, row, 4);
|
||||
var maxScore = 0f;
|
||||
var bestClass = -1;
|
||||
|
||||
for (var col = 5; col < cols; col++)
|
||||
{
|
||||
var score = objectness * GetYoloValue(outMat, batchIndex, batchCount, row, col);
|
||||
if (score > maxScore)
|
||||
{
|
||||
maxScore = score;
|
||||
bestClass = col - 5;
|
||||
}
|
||||
}
|
||||
|
||||
if (maxScore > _cfg.ConfidenceThreshold)
|
||||
{
|
||||
var x = (int)Math.Max(0, Math.Round(cx - width / 2));
|
||||
var y = (int)Math.Max(0, Math.Round(cy - height / 2));
|
||||
boxes.Add(new Rect(x, y, (int)Math.Round(width), (int)Math.Round(height)));
|
||||
confidences.Add(maxScore);
|
||||
classIds.Add(bestClass);
|
||||
centerXList.Add(cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (boxes.Count == 0)
|
||||
{
|
||||
return Array.Empty<DetectedRegion>();
|
||||
}
|
||||
|
||||
CvDnn.NMSBoxes(boxes, confidences, (float)_cfg.ConfidenceThreshold, (float)_cfg.NmsThreshold, out int[] indices);
|
||||
return indices
|
||||
.Select(index =>
|
||||
{
|
||||
var box = boxes[index];
|
||||
return new DetectedRegion(box, confidences[index], classIds[index], box.X + box.Width / 2.0);
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private string ParseRecognizedDigits(Mat[] outs, int batchIndex, int batchCount, int cropWidth, int cropHeight)
|
||||
{
|
||||
var boxes = new List<Rect>();
|
||||
var confidences = new List<float>();
|
||||
var classIds = new List<int>();
|
||||
var centerXList = new List<double>();
|
||||
|
||||
foreach (var outMat in outs)
|
||||
{
|
||||
var rows = GetYoloRows(outMat, batchCount);
|
||||
var cols = GetYoloCols(outMat);
|
||||
for (var row = 0; row < rows; row++)
|
||||
{
|
||||
var cx = GetYoloValue(outMat, batchIndex, batchCount, row, 0) * cropWidth;
|
||||
var cy = GetYoloValue(outMat, batchIndex, batchCount, row, 1) * cropHeight;
|
||||
var width = GetYoloValue(outMat, batchIndex, batchCount, row, 2) * cropWidth;
|
||||
var height = GetYoloValue(outMat, batchIndex, batchCount, row, 3) * cropHeight;
|
||||
var objectness = GetYoloValue(outMat, batchIndex, batchCount, row, 4);
|
||||
var maxScore = 0f;
|
||||
var bestClass = -1;
|
||||
|
||||
for (var col = 5; col < cols; col++)
|
||||
{
|
||||
var score = objectness * GetYoloValue(outMat, batchIndex, batchCount, row, col);
|
||||
if (score > maxScore)
|
||||
{
|
||||
maxScore = score;
|
||||
bestClass = col - 5;
|
||||
}
|
||||
}
|
||||
|
||||
if (maxScore > _cfg.ConfidenceThreshold)
|
||||
{
|
||||
boxes.Add(new Rect(
|
||||
(int)Math.Max(0, Math.Round(cx - width / 2)),
|
||||
(int)Math.Max(0, Math.Round(cy - height / 2)),
|
||||
(int)Math.Round(width),
|
||||
(int)Math.Round(height)));
|
||||
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);
|
||||
return string.Concat(keep
|
||||
.Select(index => new { CenterX = centerXList[index], ClassId = classIds[index] })
|
||||
.OrderBy(item => item.CenterX)
|
||||
.Where(item => item.ClassId >= 0 && item.ClassId < _cfg.NumberClasses.Length)
|
||||
.Select(item => _cfg.NumberClasses[item.ClassId]));
|
||||
}
|
||||
|
||||
private static int GetYoloRows(Mat output, int batchCount)
|
||||
{
|
||||
if (output.Dims >= 3)
|
||||
{
|
||||
return output.Size(1);
|
||||
}
|
||||
|
||||
return batchCount > 1 && output.Rows % batchCount == 0
|
||||
? output.Rows / batchCount
|
||||
: output.Rows;
|
||||
}
|
||||
|
||||
private static int GetYoloCols(Mat output)
|
||||
{
|
||||
return output.Dims >= 3 ? output.Size(2) : output.Cols;
|
||||
}
|
||||
|
||||
private static float GetYoloValue(Mat output, int batchIndex, int batchCount, int row, int col)
|
||||
{
|
||||
if (output.Dims >= 3)
|
||||
{
|
||||
return output.At<float>(batchIndex, row, col);
|
||||
}
|
||||
|
||||
if (batchCount > 1 && output.Rows % batchCount == 0)
|
||||
{
|
||||
return output.At<float>(batchIndex * (output.Rows / batchCount) + row, col);
|
||||
}
|
||||
|
||||
return output.At<float>(row, col);
|
||||
}
|
||||
|
||||
private static Rect ClampRect(Rect rect, int imageWidth, int imageHeight)
|
||||
{
|
||||
var x = Math.Clamp(rect.X, 0, imageWidth);
|
||||
var y = Math.Clamp(rect.Y, 0, imageHeight);
|
||||
var right = Math.Clamp(rect.X + rect.Width, 0, imageWidth);
|
||||
var bottom = Math.Clamp(rect.Y + rect.Height, 0, imageHeight);
|
||||
return new Rect(x, y, Math.Max(0, right - x), Math.Max(0, bottom - y));
|
||||
}
|
||||
|
||||
private void SaveDiagnosticCrops(IEnumerable<CropBatchItem> crops)
|
||||
{
|
||||
try
|
||||
{
|
||||
var cropsDir = Path.Combine("logs", "crops");
|
||||
Directory.CreateDirectory(cropsDir);
|
||||
foreach (var crop in crops)
|
||||
{
|
||||
var fileName = $"{SanitizeFileName(crop.Context)}_{DateTime.UtcNow:yyyyMMdd_HHmmss_fff}_{Guid.NewGuid():N}.jpg";
|
||||
Cv2.ImWrite(Path.Combine(cropsDir, fileName), crop.Crop);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogError(ex, "Failed saving batched crops for diagnostics");
|
||||
}
|
||||
}
|
||||
|
||||
private static void DisposeMats(IEnumerable<Mat> mats)
|
||||
{
|
||||
foreach (var mat in mats)
|
||||
{
|
||||
mat.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ImageResult>> ProcessDirectoryAsync(string directoryPath, bool skipTextNegative = false, bool recursive = false, IProgress<ProcessingStats>? progress = null, IProgress<ImageResult>? resultProgress = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!Directory.Exists(directoryPath)) throw new DirectoryNotFoundException(directoryPath);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue