Skip to content

Add shape wrapper - #1857

Merged
shimat merged 2 commits into
mainfrom
add_shape
Apr 3, 2026
Merged

Add shape wrapper#1857
shimat merged 2 commits into
mainfrom
add_shape

Conversation

@shimat

@shimat shimat commented Apr 3, 2026

Copy link
Copy Markdown
Owner

Fix #1758


This pull request adds comprehensive support for the OpenCV "shape" module to the OpenCvSharp library. It introduces new classes for shape transformers and histogram cost extractors, provides factory methods for easy creation, and implements the necessary P/Invoke bindings to the native OpenCV functions. The changes enable advanced shape matching and transformation features in managed code.

New shape transformers and histogram cost extractors:

  • Added new managed classes for shape transformers (AffineTransformer, ThinPlateSplineShapeTransformer) and for histogram cost extractors (NormHistogramCostExtractor, EMDHistogramCostExtractor, ChiHistogramCostExtractor, EMDL1HistogramCostExtractor), each wrapping the corresponding native OpenCV functionality. (AffineTransformer.cs [1] ChiHistogramCostExtractor.cs [2] EMDHistogramCostExtractor.cs [3] EMDL1HistogramCostExtractor.cs [4] HistogramCostExtractor.cs [5]

  • Implemented the abstract base class HistogramCostExtractor with core properties and methods such as BuildCostMatrix, NDummies, and DefaultCost. (HistogramCostExtractor.cs src/OpenCvSharp/Modules/shape/HistogramCostExtractor.csR1-R87)

P/Invoke and native bindings:

  • Added P/Invoke declarations for all relevant shape module functions, including creation, property access, and upcasting for both transformers and histogram cost extractors. (NativeMethods_shape_HistogramCostExtractor.cs [1] NativeMethods_shape_ShapeTransformer.cs [2] NativeMethods_shape_ShapeDistanceExtractor.cs [3]

API surface and usability improvements:

  • Introduced the CvShape static class with factory methods for creating all supported transformers and cost extractors, as well as a managed wrapper for the EMDL1 free function. (CvShape.cs src/OpenCvSharp/Modules/shape/CvShape.csR1-R103)

Integration and extensibility:

  • Provided internal logic for smart pointer management and upcasting to ensure correct resource handling and extensibility for future shape-related features. (AffineTransformer.cs [1] NativeMethods_shape_ShapeTransformer.cs [2]

These changes significantly expand the capabilities of OpenCvSharp for shape analysis and matching, making advanced OpenCV shape algorithms available to .NET developers.

Summary by CodeRabbit

Release Notes

  • New Features
    • Added shape transformer classes (ThinPlateSplineShapeTransformer, AffineTransformer) for estimating and applying shape transformations.
    • Added histogram cost extractor classes (NormHistogramCostExtractor, EMDHistogramCostExtractor, ChiHistogramCostExtractor, EMDL1HistogramCostExtractor) for advanced shape matching and distance computation.
    • Enhanced ShapeContextDistanceExtractor with SetCostExtractor() and SetTransformAlgorithm() configuration methods.
    • Added EMDL1() function for computing Earth Mover's Distance-based shape distances.

@shimat shimat self-assigned this Apr 3, 2026
@shimat
shimat marked this pull request as ready for review April 3, 2026 21:17
@coderabbitai

coderabbitai Bot commented Apr 3, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR implements shape transformers and histogram cost extractors for OpenCvSharp, adding P/Invoke bindings, C++ interop wrappers, and managed C# classes that expose functionality for computing shape distances and transformations using thin-plate splines and affine transformers, plus multiple histogram-based cost extractor variants.

Changes

Cohort / File(s) Summary
P/Invoke Histogram Cost Extractor Bindings
src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_HistogramCostExtractor.cs
Added 16 P/Invoke entry points for HistogramCostExtractor and derived classes (NormHistogramCostExtractor, EMDHistogramCostExtractor, ChiHistogramCostExtractor, EMDL1HistogramCostExtractor), including construction, lifetime management (delete/get), property accessors (NDummies, DefaultCost, NormFlag), and cost matrix building.
P/Invoke Shape Distance/Transformer Bindings
src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_ShapeDistanceExtractor.cs, src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_ShapeTransformer.cs
Added P/Invoke for SetCostExtractor on ShapeContextDistanceExtractor and 17 P/Invoke entry points for shape transformers (ShapeTransformer, ThinPlateSplineShapeTransformer, AffineTransformer), including creation, transformation estimation/application, image warping, property access, and base pointer upcasting.
C++ Interop Headers
src/OpenCvSharpExtern/shape_HistogramCostExtractor.h, src/OpenCvSharpExtern/shape_ShapeTransformer.h, src/OpenCvSharpExtern/shape_ShapeDistanceExtractor.h, src/OpenCvSharpExtern/shape.cpp
Added two new C++ wrapper headers with 38+ CVAPI functions wrapping OpenCV shape histogram cost and transformer functionality; activated previously commented SetCostExtractor wrapper and updated includes.
Shape Transformer Base Class
src/OpenCvSharp/Modules/shape/ShapeTransformer.cs
Added abstract ShapeTransformer class with virtual methods for estimating transformations, applying transformations, and warping images, plus internal abstract hook CreateBaseSmartPtr() for derived classes.
Shape Transformer Implementations
src/OpenCvSharp/Modules/shape/ThinPlateSplineShapeTransformer.cs, src/OpenCvSharp/Modules/shape/AffineTransformer.cs
Added two concrete transformer classes with factory methods, configuration properties (RegularizationParameter, FullAffine), and base pointer upcasting.
Histogram Cost Extractor Base Class
src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs
Added abstract HistogramCostExtractor class with BuildCostMatrix method and properties for NDummies and DefaultCost.
Histogram Cost Extractor Implementations
src/OpenCvSharp/Modules/shape/NormHistogramCostExtractor.cs, src/OpenCvSharp/Modules/shape/EMDHistogramCostExtractor.cs, src/OpenCvSharp/Modules/shape/ChiHistogramCostExtractor.cs, src/OpenCvSharp/Modules/shape/EMDL1HistogramCostExtractor.cs
Added four concrete cost extractor classes with factory methods and norm flag configuration properties (where applicable).
ShapeContextDistanceExtractor Extensions
src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs
Added SetCostExtractor(HistogramCostExtractor) and SetTransformAlgorithm(ShapeTransformer) methods to integrate transformers and cost extractors.
Factory API
src/OpenCvSharp/Modules/shape/CvShape.cs
Added static factory methods for creating transformers and cost extractors, plus EMDL1(InputArray, InputArray) distance computation function.
Comprehensive Test Suites
test/OpenCvSharp.Tests/shape/ThinPlateSplineShapeTransformerTest.cs, test/OpenCvSharp.Tests/shape/HistogramCostExtractorTest.cs, test/OpenCvSharp.Tests/shape/ShapeContextDistanceExtractorTest.cs, test/OpenCvSharp.Tests/shape/HausdorffDistanceExtractorTest.cs
Added 45+ xUnit test methods covering creation, property round-trips, transformation estimation/application, image warping, cost matrix building, and distance computation with identity/non-overlapping contour scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • PR #1833: Both PRs modify shape_ShapeContextDistanceExtractor_setCostExtractor P/Invoke and native wrappers, adding/activating the integration point for histogram cost extractors with distance extractors.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 34.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add shape wrapper' refers to the main change in the PR, which adds comprehensive shape module support including transformers, cost extractors, and related wrappers to OpenCvSharp.
Linked Issues check ✅ Passed The PR fully addresses issue #1758 by implementing ThinPlateSplineShapeTransformer support [#1758], plus extends the implementation with additional shape transformers (AffineTransformer) and histogram cost extractors (NormHistogramCostExtractor, EMDHistogramCostExtractor, ChiHistogramCostExtractor, EMDL1HistogramCostExtractor), base classes, and factory methods.
Out of Scope Changes check ✅ Passed All changes in this PR are directly related to implementing shape module support (transformers and cost extractors) as required by the linked issue. No unrelated or extraneous code modifications were introduced.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add_shape

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
test/OpenCvSharp.Tests/shape/HistogramCostExtractorTest.cs (1)

66-67: Optional: avoid repeated inline array allocations in test data.

These literals trigger CA1861; moving them to static readonly fields keeps the test cleaner and removes analyzer noise.

♻️ Suggested refactor
 public class HistogramCostExtractorTest : TestBase
 {
+    private static readonly float[] NormHist1 = { 0.5f, 0.3f, 0.2f };
+    private static readonly float[] NormHist2 = { 0.4f, 0.4f, 0.2f };
+
@@
     public void Norm_BuildCostMatrix()
     {
         using var ext = NormHistogramCostExtractor.Create();
-        using var hist1 = Mat.FromArray(new float[] { 0.5f, 0.3f, 0.2f });
-        using var hist2 = Mat.FromArray(new float[] { 0.4f, 0.4f, 0.2f });
+        using var hist1 = Mat.FromArray(NormHist1);
+        using var hist2 = Mat.FromArray(NormHist2);
         using var costMat = new Mat();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/OpenCvSharp.Tests/shape/HistogramCostExtractorTest.cs` around lines 66 -
67, Move the inline float[] literals used to create Mat objects into static
readonly fields to avoid repeated allocations and CA1861 warnings; e.g., add
static readonly float[] fields (e.g., SampleHist1, SampleHist2) to the
HistogramCostExtractorTest class and use Mat.FromArray(SampleHist1) and
Mat.FromArray(SampleHist2) instead of new float[] { ... } in the test setup
(replace usages that create hist1 and hist2).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/OpenCvSharp.Tests/shape/HistogramCostExtractorTest.cs`:
- Around line 66-67: Move the inline float[] literals used to create Mat objects
into static readonly fields to avoid repeated allocations and CA1861 warnings;
e.g., add static readonly float[] fields (e.g., SampleHist1, SampleHist2) to the
HistogramCostExtractorTest class and use Mat.FromArray(SampleHist1) and
Mat.FromArray(SampleHist2) instead of new float[] { ... } in the test setup
(replace usages that create hist1 and hist2).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e1eb3dc7-5463-484c-8d1e-b0fd04d43a36

📥 Commits

Reviewing files that changed from the base of the PR and between ee2a308 and d55f85c.

📒 Files selected for processing (21)
  • src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_HistogramCostExtractor.cs
  • src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_ShapeDistanceExtractor.cs
  • src/OpenCvSharp/Internal/PInvoke/NativeMethods/shape/NativeMethods_shape_ShapeTransformer.cs
  • src/OpenCvSharp/Modules/shape/AffineTransformer.cs
  • src/OpenCvSharp/Modules/shape/ChiHistogramCostExtractor.cs
  • src/OpenCvSharp/Modules/shape/CvShape.cs
  • src/OpenCvSharp/Modules/shape/EMDHistogramCostExtractor.cs
  • src/OpenCvSharp/Modules/shape/EMDL1HistogramCostExtractor.cs
  • src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs
  • src/OpenCvSharp/Modules/shape/NormHistogramCostExtractor.cs
  • src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs
  • src/OpenCvSharp/Modules/shape/ShapeTransformer.cs
  • src/OpenCvSharp/Modules/shape/ThinPlateSplineShapeTransformer.cs
  • src/OpenCvSharpExtern/shape.cpp
  • src/OpenCvSharpExtern/shape_HistogramCostExtractor.h
  • src/OpenCvSharpExtern/shape_ShapeDistanceExtractor.h
  • src/OpenCvSharpExtern/shape_ShapeTransformer.h
  • test/OpenCvSharp.Tests/shape/HausdorffDistanceExtractorTest.cs
  • test/OpenCvSharp.Tests/shape/HistogramCostExtractorTest.cs
  • test/OpenCvSharp.Tests/shape/ShapeContextDistanceExtractorTest.cs
  • test/OpenCvSharp.Tests/shape/ThinPlateSplineShapeTransformerTest.cs

@shimat
shimat merged commit 149aaff into main Apr 3, 2026
10 checks passed
@shimat
shimat deleted the add_shape branch April 3, 2026 21:44
@shimat shimat added the enhancement New feature or improvement to OpenCvSharp label Jul 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or improvement to OpenCvSharp

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thin Plate Spline

1 participant