8.9 KiB
Plan: Migrate YOLO Number Recognition to .NET 10
Summary:
Port the existing Python YOLO-based number detection/recognition system to .NET 10 using OpenCvSharp4. This library provides 1:1 API mapping to the Python cv2.dnn code, requires no model conversion, and works directly with the existing Darknet .cfg/.weights files. The solution will consist of three projects: a core library for model inference, a console application for batch processing, and a WPF frontend for interactive use. OpenCvSharp was selected over alternatives (ONNX Runtime, Emgu.CV) because it requires minimal code changes and no model conversion workflow.
Steps
-
Create Solution Structure
- Create .NET 10 solution with three projects:
AIFotoONLUS.Core- Class library (.NET 10)AIFotoONLUS.Console- Console app (.NET 10)AIFotoONLUS.WPF- WPF application (.NET 10)
- Add NuGet packages to Core project:
OpenCvSharp4(latest 4.x)OpenCvSharp4.runtime.win(for Windows deployment)
- Reference Core library from Console and WPF projects
- Create .NET 10 solution with three projects:
-
Implement Core Library - Model Management
- Create
ModelConfigurationclass to store model paths and inference parameters- Properties: detection model path/config, recognition model path/config
- Confidence threshold (0.5), NMS threshold (0.4)
- Input sizes: detection (416×416), recognition (140×120)
- Number classes array: ['0'-'9']
- Create
NumberRecognitionEngineclass as main entry point- Constructor: loads both networks using
CvDnn.ReadNetFromDarknet() - Store loaded
Netobjects as private fields - Implement
IDisposableto properly dispose OpenCV resources
- Constructor: loads both networks using
- Create
-
Implement Core Library - Detection Logic
- Port
recog_text()function toDetectTextRegions()method inNumberRecognitionEngine- Input:
Matimage object - Create blob with
CvDnn.BlobFromImage(image, 0.00392, new Size(416,416), ...) - Run inference:
detectionNet.Forward(GetOutputLayers(detectionNet)) - Parse output layers to extract bounding boxes, confidences, class IDs, center Y coordinates
- Apply NMS:
CvDnn.NMSBoxes(boxes, confidences, 0.5f, 0.4f, out indices) - Return
List<DetectedRegion>with bounding box data
- Input:
- Create helper method
GetOutputLayers()- equivalent to Python'sget_output_layers()- Get
Net.GetLayerNames()and unconnected output layers - Return array of layer names
- Get
- Port
-
Implement Core Library - Recognition Logic
- Port
recog_number()toRecognizeDigits()method inNumberRecognitionEngine- Input: cropped
Matimage (text region) - Create blob with size (140×120) and scale 0.00392
- Run inference through recognition network
- Extract digit detections with confidence > 0.5
- Apply NMS on detected digits
- Sort digits left-to-right by center X coordinate (bubble sort from Python)
- Return recognized string (concatenated digit classes)
- Input: cropped
- Implement
CropImage()helper method- Port boundary checking logic:
check_min_value(),check_X_max_value(),check_Y_max_value() - Add 10% padding around detected region as in Python version
- Port boundary checking logic:
- Create
DetectedRegionandRecognitionResultdata classes for type safety
- Port
-
Implement Core Library - End-to-End Pipeline
- Create
ProcessImage()method inNumberRecognitionEngine- Input: file path (string)
- Load image using
Cv2.ImRead() - Call
DetectTextRegions()to find text boxes - For each detected region, crop and call
RecognizeDigits() - Return
ImageResultobject containing filename and list of recognized text strings
- Create
ProcessDirectory()method for batch operations- Input: directory path, recursive flag, output CSV path, optional text-negative filter
- Scan for .jpg/.JPG files (match Python behavior)
- Process each image with
ProcessImage() - Aggregate results into
List<ImageResult> - Return results for caller to handle output
- Create
-
Implement Console Application
- Create command-line argument parser (use
System.CommandLineNuGet package)-d/--directory: source directory path-c/--csv: output CSV file path-tn/--textnegative: skip files starting with "tn_" (optional flag)
- Main logic:
- Parse arguments and validate (directory exists, CSV has .csv extension)
- Instantiate
ModelConfigurationwith hardcoded model paths (models/detection., models/recognition.) - Create
NumberRecognitionEngineinstance - Call
ProcessDirectory()with parsed parameters - Write results to CSV file using
CsvHelperNuGet package or manual CSV writing- CSV format: filename, text (comma-separated if multiple detections)
- Match Python output format from
det.pyline 289
- Display progress/results to console (e.g., "Processing image X of Y")
- Create command-line argument parser (use
-
Implement WPF Application - Main Window
- Create
MainWindow.xamlwith MVVM pattern:- Top section: Model configuration panel
- Labels and TextBoxes for: detection model .cfg/.weights paths, recognition model .cfg/.weights paths
- "Load Models" button
- Middle section: Input selection panel
- "Select Directory" button with directory browser dialog
- "Select Files" button with file picker (multi-select)
- Checkbox for recursive directory scanning
- Checkbox for text-negative filtering
- Bottom section: Results panel
- DataGrid to display results (columns: Filename, Recognized Text)
- "Process" button to start inference
- "Export CSV" button to save results
- Progress bar and status text
- Top section: Model configuration panel
- Create
MainViewModelwith properties/commands:- Observable properties for all UI bindings
ICommandfor LoadModels, SelectDirectory, SelectFiles, Process, ExportCsv- Bind button states to model loaded status
- Create
-
Implement WPF Application - Image Processing
- In
MainViewModel.ProcessCommand:- Validate models are loaded and input is selected
- Run processing on background thread using
Task.Run()to avoid UI freeze - Update progress bar via
IProgress<T>andProgress<T> - Call
NumberRecognitionEngine.ProcessDirectory()or process individual files - Update observable collection bound to DataGrid with results
- Handle exceptions and display errors via MessageBox
- Implement CSV export functionality:
- Use SaveFileDialog to get output path
- Write DataGrid results to CSV matching console app format
- Optional: Add image preview panel showing currently processed image with bounding boxes
- Convert OpenCV Mat to WPF BitmapSource using
OpenCvSharp.Extensionsmethods
- Convert OpenCV Mat to WPF BitmapSource using
- In
-
Configuration and Deployment
- Create
appsettings.jsonfor both Console and WPF apps with default model paths- Parse using
Microsoft.Extensions.ConfigurationNuGet package - Allow override via UI (WPF) or command-line (Console)
- Parse using
- Copy models directory (detection.cfg/.weights, recognition.cfg/.weights) to output directory
- Set "Copy to Output Directory" = "Copy if newer" in project files
- Create
README.mdwith usage instructions for both applications - Add error handling for missing model files with clear error messages
- Create
-
Testing and Validation
- Create unit test project targeting Core library (optional but recommended)
- Integration test: Run console app with
images/onlusdirectory - Compare CSV output with Python script results to verify parity
- Test WPF app with single file and directory modes
- Verify image dimensions are read correctly (Python uses
image.shape) - Confirm NMS and sorting produce same results as Python
Verification
- Run console app:
AIFotoONLUS.Console.exe -d ./images/onlus -c test_output.csv - Compare output CSV with results from Python
python det.py -d ./images/onlus -c python_output.csv - Launch WPF app, load models, process same directory, verify DataGrid shows matching results
- Verify model files load successfully (no exceptions during
ReadNetFromDarknet) - Test with various image sizes to ensure cropping/boundary logic works correctly
- Check that digit sorting (left-to-right) produces correctly ordered number strings
Decisions
- OpenCvSharp4 over ONNX Runtime: Chose OpenCvSharp for direct Darknet .cfg/.weights support without model conversion, enabling faster migration with existing model files
- MVVM pattern for WPF: Enables clean separation of concerns and testability vs code-behind approach
- Separate Core library: Allows reuse across Console and WPF, enables future integration (web API, other frontends)
- .NET 10: Latest LTS version with long-term support through November 2028
- System.CommandLine for CLI: Modern, type-safe command-line parsing vs manual args parsing
- Background threading in WPF: Prevents UI freeze during long-running inference operations on large image sets