-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitmapProcessing.cs
More file actions
210 lines (185 loc) · 8.7 KB
/
Copy pathBitmapProcessing.cs
File metadata and controls
210 lines (185 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
using CapCognition.Net;
using CapCognition.Net.BarcodeScanning.Common;
using CapCognition.Net.Core.Processing.Common;
using CapCognition.Net.LicensePlateDetection.Common;
using CapCognition.Net.LicensePlateDetection.Common.Extensions;
using CapCognitionNetLTS_Samples.OwnProcessor;
using SkiaSharp;
using System.Text;
namespace CapCognitionNetLTS_Samples;
public class BitmapProcessing
{
/// <summary>
/// Processes the image sequentially
/// </summary>
/// <param name="recognizer"></param>
/// <param name="bitmap"></param>
/// <param name="resultPath"></param>
/// <returns>A list of results</returns>
public static List<string> ProcessImageSequentially(Recognizer recognizer, SKBitmap bitmap, string resultPath)
{
var resultList = new List<string>();
var result = recognizer.ProcessImageAsync(bitmap, _resultDrawingOptions, disableBitmapDisposal: true).GetAwaiter().GetResult();
if (result == null)
{
Console.WriteLine("Failed to recognize image for {resultPath}");
return resultList;
}
if (result.Results.Count == 0)
{
Console.WriteLine("No elements could be recognized for {resultPath}");
return resultList;
}
Console.WriteLine($"Successfully recognized {result.Results.Count} elements for {resultPath}, Detections: {string.Join(", ", result.Results.Select(r => r.GetType().Name))}");
var data = bitmap.Encode(SKEncodedImageFormat.Png, 90);
var outputImg = Path.Combine(Path.GetDirectoryName(resultPath)!, $"{Path.GetFileName(resultPath)}_sequential_result.png");
File.WriteAllBytes(outputImg, data.ToArray());
AddResultsToList(out resultList, result);
return resultList;
}
/// <summary>
/// Processes the image in parallel
/// </summary>
/// <param name="recognizer"></param>
/// <param name="bitmap"></param>
/// <param name="resultPath"></param>
/// <returns>A list of results</returns>
public static List<string> ProcessImageParallel(Recognizer recognizer, SKBitmap bitmap, string resultPath)
{
//parallel processing
var sem = new SemaphoreSlim(0, 1);
var resultList = new List<string>();
recognizer.ProcessImageParallelAsync(bitmap,
(resultBmp, result) =>
{
Console.WriteLine($"Successfully recognized {result.Results.Count} elements for {resultPath}, Detections: {string.Join(", ", result.Results.Select(r => r.GetType().Name))}");
var data = resultBmp.Encode(SKEncodedImageFormat.Png, 90);
var resultType = result.Results.FirstOrDefault()?.GetType().Name;
var outputImg = Path.Combine(Path.GetDirectoryName(resultPath)!, $"{Path.GetFileName(resultPath)}_parallel_{resultType}_result.png");
File.WriteAllBytes(outputImg, data.ToArray());
AddResultsToList(out resultList, result);
sem.Release();
},
_resultDrawingOptions).GetAwaiter().GetResult();
sem.Wait();
return resultList;
}
/// <summary>
/// Prepares the processor for the image recognition
/// </summary>
/// <param name="recognizer"></param>
/// <param name="bitmap"></param>
/// <param name="useBarcodeDetection"></param>
/// <param name="useLicensePlateDetection"></param>
/// <returns></returns>
public static bool PrepareProcessor(out Recognizer recognizer, SKBitmap bitmap, bool useBarcodeDetection = true, bool useLicensePlateDetection = true, bool useOwnProcessor = false, bool downloadModelsFromInternet = true)
{
if (_options != null)
{
_options.Dispose();
_options = null;
}
recognizer = new Recognizer();
var optionBuilder = new RecognitionOptionBuilder();
var resultDrawingOptionBuilder = new ResultDrawingOptionsBuilder();
if (useBarcodeDetection)
{
optionBuilder.AddBarcodeRecognitionOption()
.EnableMultiCodeReader()
.UseFastRecognition(false)
.TryInverted()
.SetBinarizer(BarcodeRecognitionOptions.BinarizerType.HybridBinarizer)
.SetBarcodeFormats(new[] { BarcodeRecognitionOptions.BarcodeFormat.QRCode })
.SetEncoding(Encoding.UTF8)
.Done();
resultDrawingOptionBuilder.AddBarcodeDrawingOptions()
.DrawBoundingBox()
.BoundingBoxColor(SKColors.Blue)
.BoundingBoxStyle(SKPaintStyle.Stroke)
.BoundingBoxStrokeWidth(3f)
.Done();
}
if (useLicensePlateDetection)
{
var lprOptionBuilder = optionBuilder.AddLicensePlateDetectionRecognitionOption()
.UseCudaProvider(false)
.UseCroppedImageForRecognition()
.DoAutomaticDetectionOptimization()
.SetRecognitionQuality(LicensePlateDetectionRecognitionOptionBuilder.RecognitionQuality.Medium);
resultDrawingOptionBuilder.AddLicensePlateDetectionDrawingOptions()
.DisplayVehicleSurroundingBox()
.VehicleSurroundingRectColor(new SKColor(0, 255, 0, 40))
.VehicleSurroundingRectStyle(SKPaintStyle.Fill)
.VehicleSurroundingRectStrokeWidth(1f)
.LicensePlateSurroundingRectColor(SKColors.Green)
.LicensePlateSurroundingRectStyle(SKPaintStyle.Stroke)
.LicensePlateSurroundingRectStrokeWidth(2f)
.LicensePlateNonValidatedSurroundingRectColor(SKColors.Red)
.Done();
if (downloadModelsFromInternet)
{
lprOptionBuilder.SetRecognitionQuality(LicensePlateDetectionRecognitionOptionBuilder.RecognitionQuality.Medium);
//use one of the following recognition modes:
lprOptionBuilder.UseRecognitionModeNoCountryLicencePlateThenVehicle();
//lprOptionBuilder.UseRecognitionModeCountryLicencePlateThenVehicle();
//lprOptionBuilder.UseRecognitionModeVehicleOnly();
//lprOptionBuilder.UseRecognitionModeVehicleThenCountryLicencePlate();
}
else
{
lprOptionBuilder.UseLocalModelsForRecognitionMode(LicensePlateDetectionRecognitionOptions.RecognitionModeType.CountryLicencePlateThenVehicle)
.SetLocalModelBasePath("Models")
.UseLocalLicensePlateModelFromType(LPModelType.LPModelType640n)
.UseLocalLicensePlateTextModelFromType(LPTextModelType.LPTextModelType640n)
.UseLocalVehicleModelFromType(VehicleModelType.VehicleModelType640n)
.Done();
}
lprOptionBuilder.ConfigureOption(option =>
{
//only clear old models from cache to free up storage space
option.ClearOldModelsFromCacheFolder();
option.CreateAndPrepareModelsAsync().GetAwaiter().GetResult();
});
lprOptionBuilder.Done();
}
_options = optionBuilder.Build();
if (useOwnProcessor)
{
_options.Add(OwnProcessorOption);
}
_resultDrawingOptions = resultDrawingOptionBuilder.Build();
var success = recognizer.PrepareProcessorsAsync(bitmap.Width, bitmap.Height, _options).GetAwaiter().GetResult();
if (!success)
{
Console.WriteLine("Failed to prepare recognition processors");
}
return success;
}
private static void AddResultsToList(out List<string> resultList, RecognitionResult result)
{
resultList = new List<string>();
foreach (var res in result.Results)
{
if (res is RecognitionProcessorBarcodeResult barcodeResult)
{
if (barcodeResult.Value == null)
{
continue;
}
resultList.Add(barcodeResult.Value);
}
else if (res is RecognitionProcessorLicensePlateDetectionResult licensePlateResult)
{
var plateNumber = $"Type:{licensePlateResult.VehicleType} Country:{licensePlateResult.PlateCountryCode} Plate:{licensePlateResult.PlateNumberValidated ?? licensePlateResult.PlateNumberRaw}";
resultList.Add(plateNumber);
}
}
}
private static RecognitionProcessorResult.ResultDrawingOptions[]? _resultDrawingOptions;
private static List<RecognitionOptions>? _options;
private static readonly OwnProcessorOption OwnProcessorOption = new()
{
EnableOwnOption = true,
OwnOption = OwnProcessorOption.OwnOptionEnum.OwnOption1
};
}