AIFotoOnlus/plan-migrateYoloToNet10.prompt.md
Maddo 5202369356
Some checks failed
Build And Publish AIFotoONLUS.Core / build (push) Failing after 1m0s
Build And Publish AIFotoONLUS.Core / publish (push) Has been skipped
Add initial test data in CSV format for image analysis
2026-11-30 19:32:39 +01:00

151 lines
8.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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**
1. **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
2. **Implement Core Library - Model Management**
- Create `ModelConfiguration` class 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 `NumberRecognitionEngine` class as main entry point
- Constructor: loads both networks using `CvDnn.ReadNetFromDarknet()`
- Store loaded `Net` objects as private fields
- Implement `IDisposable` to properly dispose OpenCV resources
3. **Implement Core Library - Detection Logic**
- Port `recog_text()` function to `DetectTextRegions()` method in `NumberRecognitionEngine`
- Input: `Mat` image 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
- Create helper method `GetOutputLayers()` - equivalent to Python's `get_output_layers()`
- Get `Net.GetLayerNames()` and unconnected output layers
- Return array of layer names
4. **Implement Core Library - Recognition Logic**
- Port `recog_number()` to `RecognizeDigits()` method in `NumberRecognitionEngine`
- Input: cropped `Mat` image (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)
- 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
- Create `DetectedRegion` and `RecognitionResult` data classes for type safety
5. **Implement Core Library - End-to-End Pipeline**
- Create `ProcessImage()` method in `NumberRecognitionEngine`
- Input: file path (string)
- Load image using `Cv2.ImRead()`
- Call `DetectTextRegions()` to find text boxes
- For each detected region, crop and call `RecognizeDigits()`
- Return `ImageResult` object 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
6. **Implement Console Application**
- Create command-line argument parser (use `System.CommandLine` NuGet 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 `ModelConfiguration` with hardcoded model paths (models/detection.*, models/recognition.*)
- Create `NumberRecognitionEngine` instance
- Call `ProcessDirectory()` with parsed parameters
- Write results to CSV file using `CsvHelper` NuGet package or manual CSV writing
- CSV format: filename, text (comma-separated if multiple detections)
- Match Python output format from `det.py` line 289
- Display progress/results to console (e.g., "Processing image X of Y")
7. **Implement WPF Application - Main Window**
- Create `MainWindow.xaml` with 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
- Create `MainViewModel` with properties/commands:
- Observable properties for all UI bindings
- `ICommand` for LoadModels, SelectDirectory, SelectFiles, Process, ExportCsv
- Bind button states to model loaded status
8. **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>` and `Progress<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.Extensions` methods
9. **Configuration and Deployment**
- Create `appsettings.json` for both Console and WPF apps with default model paths
- Parse using `Microsoft.Extensions.Configuration` NuGet package
- Allow override via UI (WPF) or command-line (Console)
- 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.md` with usage instructions for both applications
- Add error handling for missing model files with clear error messages
10. **Testing and Validation**
- Create unit test project targeting Core library (optional but recommended)
- Integration test: Run console app with `images/onlus` directory
- 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