From 94011a1cc29bc8d752fa38a7a28d9ddcf2533760 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 14:32:13 +0900 Subject: [PATCH 01/29] Remove dead OutputArray List<> write-back scaffolding (issue #1976 step 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OutputArrayOfMatList/OutputArrayOfStructList and their backing OutputArray(IEnumerable) ctor / Create(List) / Create(List) factories let a caller collect a variable-length Mat/struct result into a managed List<> after a native call. This is incompatible with turning OutputArray into a ref struct (a ref struct cannot be subclassed, and cannot itself hold a heap List<> across a call boundary the way these required), so it has to go before the final class -> ref struct flip. Every real variable-length Mat output (Split, FindContours, calibration rvecs/tvecs, etc.) already goes through the independent VectorOfMat SafeHandle type instead of OutputArray, so OutputArrayOfMatList had zero callers (and IsReady() unconditionally returned false for it, meaning AssignResult() would have thrown even if it were called - dead and already broken). OutputArrayOfStructList had exactly one caller (SolveEquationTest.ByNormalArray, collecting Cv2.Solve's result into a List); switched it to a Mat output, matching the sibling ByMat test and the only other Cv2.Solve overload. Drops the two now-unused native functions backing the Mat-list ctor/ read-back (core_OutputArray_new_byVectorOfMat, core_OutputArray_ getVectorOfMat) and their P/Invoke declarations. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- .../core/NativeMethods_core_OutputArray.cs | 6 -- src/OpenCvSharp/Modules/core/OutputArray.cs | 69 +------------------ .../Modules/core/OutputArrayOfMatList.cs | 48 ------------- .../Modules/core/OutputArrayOfStructList.cs | 45 ------------ src/OpenCvSharpExtern/core_OutputArray.h | 21 ------ .../core/SolveEquationTest.cs | 8 +-- 6 files changed, 6 insertions(+), 191 deletions(-) delete mode 100644 src/OpenCvSharp/Modules/core/OutputArrayOfMatList.cs delete mode 100644 src/OpenCvSharp/Modules/core/OutputArrayOfStructList.cs diff --git a/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_OutputArray.cs b/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_OutputArray.cs index 8c16bae6b..e6e4f756a 100644 --- a/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_OutputArray.cs +++ b/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_OutputArray.cs @@ -20,9 +20,6 @@ static partial class NativeMethods [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] public static partial ExceptionStatus core_OutputArray_new_byScalar(Scalar val, out IntPtr returnValue); - [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] - public static partial ExceptionStatus core_OutputArray_new_byVectorOfMat(IntPtr vector, out IntPtr returnValue); - [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] public static partial ExceptionStatus core_OutputArray_delete(IntPtr oa); @@ -31,7 +28,4 @@ static partial class NativeMethods [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] public static partial ExceptionStatus core_OutputArray_getScalar(IntPtr oa, out Scalar returnValue); - - [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] - public static partial ExceptionStatus core_OutputArray_getVectorOfMat(OpenCvSafeHandle oa, IntPtr vector); } diff --git a/src/OpenCvSharp/Modules/core/OutputArray.cs b/src/OpenCvSharp/Modules/core/OutputArray.cs index e2699c29b..128897d32 100644 --- a/src/OpenCvSharp/Modules/core/OutputArray.cs +++ b/src/OpenCvSharp/Modules/core/OutputArray.cs @@ -1,13 +1,10 @@ using System.Diagnostics.CodeAnalysis; using OpenCvSharp.Internal; -using OpenCvSharp.Internal.Vectors; - -#pragma warning disable CA1002 // Do not expose generic lists namespace OpenCvSharp; /// -/// Proxy datatype for passing Mat's and List<>'s as output parameters +/// Proxy datatype for passing Mat's as output parameters /// public class OutputArray : CvObject { @@ -50,24 +47,6 @@ internal OutputArray(UMat mat) InitSafeHandle(p); } - /// - /// Constructor - /// - /// - internal OutputArray(IEnumerable mat) - { - if (mat is null) - throw new ArgumentNullException(nameof(mat)); - IntPtr p; - using (var matVector = new VectorOfMat(mat)) - { - NativeMethods.HandleException( - NativeMethods.core_OutputArray_new_byVectorOfMat(matVector.CvPtr, out p)); - } - obj = mat; - InitSafeHandle(p); - } - /// /// Releases unmanaged resources /// @@ -136,25 +115,7 @@ public bool IsUMat() } /// - /// - /// - /// - public bool IsVectorOfMat() - { - return obj is IEnumerable; - } - - /// - /// - /// - /// - public virtual IEnumerable? GetVectorOfMat() - { - return obj as IEnumerable; - } - - /// - /// + /// /// public virtual void AssignResult() { @@ -212,31 +173,5 @@ public static OutputArray Create(UMat mat) return new (mat); } - /// - /// Creates a proxy class of the specified list - /// - /// - /// - /// - public static OutputArrayOfStructList Create(List list) - where T : unmanaged - { - if (list is null) - throw new ArgumentNullException(nameof(list)); - return new OutputArrayOfStructList(list); - } - - /// - /// Creates a proxy class of the specified list - /// - /// - /// - public static OutputArrayOfMatList Create(List list) - { - if (list is null) - throw new ArgumentNullException(nameof(list)); - return new OutputArrayOfMatList(list); - } - #endregion } diff --git a/src/OpenCvSharp/Modules/core/OutputArrayOfMatList.cs b/src/OpenCvSharp/Modules/core/OutputArrayOfMatList.cs deleted file mode 100644 index 12a967cd8..000000000 --- a/src/OpenCvSharp/Modules/core/OutputArrayOfMatList.cs +++ /dev/null @@ -1,48 +0,0 @@ -using OpenCvSharp.Internal; -using OpenCvSharp.Internal.Vectors; - -namespace OpenCvSharp; - -/// -/// Proxy datatype for passing Mat's and List<>'s as output parameters -/// -public sealed class OutputArrayOfMatList : OutputArray -{ - private readonly List list; - - /// - /// - /// - /// - internal OutputArrayOfMatList(List list) - : base(list) - { - this.list = list ?? throw new ArgumentNullException(nameof(list)); - } - - /// - /// - /// - /// - public override IEnumerable GetVectorOfMat() - { - return list; - } - - /// - /// - /// - public override void AssignResult() - { - if (!IsReady()) - throw new NotSupportedException(); - - using var vectorOfMat = new VectorOfMat(); - NativeMethods.HandleException( - NativeMethods.core_OutputArray_getVectorOfMat(Handle, vectorOfMat.CvPtr)); - // getVectorOfMat copies into vectorOfMat; nothing dereferences this afterwards, - // and the Handle keeps it alive for the call's duration. - list.Clear(); - list.AddRange(vectorOfMat.ToArray()); - } -} diff --git a/src/OpenCvSharp/Modules/core/OutputArrayOfStructList.cs b/src/OpenCvSharp/Modules/core/OutputArrayOfStructList.cs deleted file mode 100644 index 307d1c455..000000000 --- a/src/OpenCvSharp/Modules/core/OutputArrayOfStructList.cs +++ /dev/null @@ -1,45 +0,0 @@ -using OpenCvSharp.Internal; - -namespace OpenCvSharp; - -/// -/// Proxy datatype for passing Mat's and List<>'s as output parameters -/// -public sealed class OutputArrayOfStructList : OutputArray - where T : unmanaged -{ - private readonly List list; - - /// - /// - /// - /// - internal OutputArrayOfStructList(List list) - : base(new Mat()) - { - this.list = list ?? throw new ArgumentNullException(nameof(list)); - } - - /// - /// - /// - public override void AssignResult() - { - if (!IsReady()) - throw new NotSupportedException(); - - NativeMethods.HandleException( - NativeMethods.core_OutputArray_getMat(Handle, out var matPtr)); - using var mat = new Mat(matPtr); - - var size = mat.Rows * mat.Cols; - - list.Clear(); - unsafe - { - list.AddRange(new ReadOnlySpan(mat.DataPointer, size)); - } - // matPtr/mat aliases native memory owned by this OutputArray; keep it alive across the copy. - GC.KeepAlive(this); - } -} diff --git a/src/OpenCvSharpExtern/core_OutputArray.h b/src/OpenCvSharpExtern/core_OutputArray.h index 6f91773ad..231dfef24 100644 --- a/src/OpenCvSharpExtern/core_OutputArray.h +++ b/src/OpenCvSharpExtern/core_OutputArray.h @@ -37,14 +37,6 @@ CVAPI(ExceptionStatus) core_OutputArray_new_byScalar(interop::Scalar scalar, cv: }); } -CVAPI(ExceptionStatus) core_OutputArray_new_byVectorOfMat(std::vector *vector, cv::_OutputArray **returnValue) -{ - return cvTry([&] { - const cv::_OutputArray ia(*vector); - *returnValue = new cv::_OutputArray(ia); - }); -} - CVAPI(ExceptionStatus) core_OutputArray_delete(cv::_OutputArray *oa) { return cvTry([&] { @@ -69,16 +61,3 @@ CVAPI(ExceptionStatus) core_OutputArray_getScalar(cv::_OutputArray *oa, interop: }); } -CVAPI(ExceptionStatus) core_OutputArray_getVectorOfMat(cv::_OutputArray *oa, std::vector *vector) -{ - return cvTry([&] { - std::vector temp; - oa->getMatVector(temp); - - vector->resize(temp.size()); - for (size_t i = 0; i < temp.size(); i++) - { - (*vector)[i] = new cv::Mat(temp[i]); - } - }); -} diff --git a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs index 1a9d33ab6..e99ccb3ed 100644 --- a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs +++ b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs @@ -48,15 +48,15 @@ public void ByNormalArray() {2, 3}}; double[] y = [10, 26]; - var x = new List(); + using var x = new Mat(); using var ia = InputArray.Create(a); using var iy = InputArray.Create(y); using var ox = OutputArray.Create(x); Cv2.Solve(ia, iy, ox, DecompTypes.LU); - testOutputHelper.WriteLine("X1 = {0}, X2 = {1}", x[0], x[1]); - Assert.Equal(4, x[0], 6); - Assert.Equal(6, x[1], 6); + testOutputHelper.WriteLine("X1 = {0}, X2 = {1}", x.At(0), x.At(1)); + Assert.Equal(4, x.At(0), 6); + Assert.Equal(6, x.At(1), 6); } } From 95aff4c6fea30bb7b5d042119aa68272f5476cb6 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 14:47:56 +0900 Subject: [PATCH 02/29] Remove dead InputArray(IEnumerable) vector-of-Mat scaffolding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Symmetric with the OutputArray cleanup above: InputArray's IEnumerable ctor / Create(IEnumerable) factory / explicit (InputArray)List and (InputArray)Mat[] cast operators had zero callers. Every real "sequence of Mat" input (StereoCalibrate, Rectify3Collinear, CalibrateCamera, DrawContours, FastNlMeansDenoisingMulti, SaveMesh, etc.) already passes a raw Mat*[] pointer array or a VectorOfMat handle straight to the native extern, never by wrapping the sequence in an InputArray first. Drops the now-unused core_InputArray_new_byVectorOfMat native function and its P/Invoke declaration. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- .../core/NativeMethods_core_InputArray.cs | 2 -- src/OpenCvSharp/Modules/core/InputArray.cs | 28 ------------------- src/OpenCvSharpExtern/core_InputArray.h | 7 ----- 3 files changed, 37 deletions(-) diff --git a/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_InputArray.cs b/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_InputArray.cs index 912824f6f..4c08e7e31 100644 --- a/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_InputArray.cs +++ b/src/OpenCvSharp/Internal/PInvoke/NativeMethods/core/NativeMethods_core_InputArray.cs @@ -19,8 +19,6 @@ static partial class NativeMethods public static partial ExceptionStatus core_InputArray_new_byScalar(Scalar val, out IntPtr handle, out IntPtr returnValue); [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] public static partial ExceptionStatus core_InputArray_new_byDouble(IntPtr valPointer, out IntPtr returnValue); - [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] - public static partial ExceptionStatus core_InputArray_new_byVectorOfMat(IntPtr vector, out IntPtr returnValue); [LibraryImport(DllExtern), UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] public static partial ExceptionStatus core_InputArray_new_byVecb(IntPtr vec, int n, out IntPtr returnValue); diff --git a/src/OpenCvSharp/Modules/core/InputArray.cs b/src/OpenCvSharp/Modules/core/InputArray.cs index 87b6655a6..5f8d38693 100644 --- a/src/OpenCvSharp/Modules/core/InputArray.cs +++ b/src/OpenCvSharp/Modules/core/InputArray.cs @@ -268,23 +268,6 @@ internal InputArray(double[] vec) })); } - /// - /// - /// - /// - internal InputArray(IEnumerable mat) - { - if (mat is null) - throw new ArgumentNullException(nameof(mat)); - using var matVector = new VectorOfMat(mat); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVectorOfMat(matVector.CvPtr, out var p)); - obj = mat; - if (p != IntPtr.Zero) - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete(ptr))); - } - /// /// Releases managed resources /// @@ -336,13 +319,6 @@ protected override void DisposeManaged() /// public static InputArray Create(double val) => new(val); - /// - /// Creates a proxy class of the specified array of Mat - /// - /// - /// - public static InputArray Create(IEnumerable matVector) => new(matVector); - /// /// Creates a proxy class of the specified list /// @@ -618,10 +594,6 @@ private static MatType EstimateType(Type t) public static implicit operator InputArray(Scalar val) => Create(val); public static implicit operator InputArray(double val) => Create(val); - - public static explicit operator InputArray(List mats) => Create(mats); - - public static explicit operator InputArray(Mat[] mats) => Create(mats); public static implicit operator InputArray(Vec2b vec) => Create(vec); public static implicit operator InputArray(Vec3b vec) => Create(vec); diff --git a/src/OpenCvSharpExtern/core_InputArray.h b/src/OpenCvSharpExtern/core_InputArray.h index 5c2b7de7e..c2436448d 100644 --- a/src/OpenCvSharpExtern/core_InputArray.h +++ b/src/OpenCvSharpExtern/core_InputArray.h @@ -42,13 +42,6 @@ CVAPI(ExceptionStatus) core_InputArray_new_byDouble(double *handle, cv::_InputAr }); } -CVAPI(ExceptionStatus) core_InputArray_new_byVectorOfMat(std::vector *vector, cv::_InputArray **returnValue) -{ - return cvTry([&] { - *returnValue = new cv::_InputArray(*vector); - }); -} - #pragma region new_byVec CVAPI(ExceptionStatus) core_InputArray_new_byVecb(uchar *vec, int n, cv::_InputArray **returnValue) From a77d916bdebf77b9213d96597d8fd6415d619bb5 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 15:44:35 +0900 Subject: [PATCH 03/29] Extend InputArrayRef with Create/IVec factory parity (issue #1976 step 5, phase A) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ports the class-based InputArray's remaining public factory surface onto the ref-struct InputArrayRef/OutputArrayRef/InputOutputArrayRef foundation, ahead of the module-by-module migration: - Create(Mat/UMat/MatExpr/Scalar/double) explicit-call parity with the existing implicit operators, plus the same for OutputArrayRef/ InputOutputArrayRef (Create(Mat)/Create(UMat)). - Create(IVec): dispatches onto the existing zero-alloc inline Vec operators instead of the class-based path's native _InputArray allocation - a net improvement, not just parity. - Create(T[]/T[,]), with/without an explicit MatType: ported unchanged from InputArray.cs (materializes a Mat via Mat.FromPixelData, same as the class-based version - not allocation-free, matching the inherent cost of turning a managed array into a Mat). Investigation while porting found InputArray's ~25-method introspection surface (GetMat/GetMatVector/GetUMat/Kind/Dims/Cols/Rows/Size/Total/Type/ Depth/Channels/IsMat/IsUMat/IsVector/etc.) has zero internal callers and no test coverage anywhere in the repo - InputArray values are only ever built and immediately passed to a native call, never queried afterward. Not porting them to InputArrayRef; they get dropped along with the class at the final rename step, same as the already-removed OutputArray List<> scaffold. This also means the raw GCHandle-pinned native-vector constructors (InputArray(byte[]/short[]/.../double[])) don't need porting either - their only caller, Create(IVec), now goes through the zero-alloc inline path instead - so InputArrayRef needs no new native-handle-owning code path and no Dispose(). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Modules/core/InputArrayRef.cs | 175 ++++++++++++++++++ .../core/InputArrayRefTest.cs | 64 +++++++ 2 files changed, 239 insertions(+) diff --git a/src/OpenCvSharp/Modules/core/InputArrayRef.cs b/src/OpenCvSharp/Modules/core/InputArrayRef.cs index c5c42a981..193b1a2aa 100644 --- a/src/OpenCvSharp/Modules/core/InputArrayRef.cs +++ b/src/OpenCvSharp/Modules/core/InputArrayRef.cs @@ -213,6 +213,169 @@ private static InputArrayRef FromVec(T vec, int depth, int length) where T : public static implicit operator InputArrayRef(Vec4d v) => FromVec(v, DepthF64, 4); /// Wraps a value (no allocation; travels inline). public static implicit operator InputArrayRef(Vec6d v) => FromVec(v, DepthF64, 6); + + #region Create (explicit-call parity with the implicit operators above) + + /// Wraps a (no allocation). + public static InputArrayRef Create(Mat? mat) => mat!; + + /// Wraps a (no allocation). + public static InputArrayRef Create(UMat mat) => mat; + + /// Wraps a (materializes it to a native cv::MatExpr). + public static InputArrayRef Create(MatExpr node) => node; + + /// Wraps a value (no allocation; travels inline). + public static InputArrayRef Create(Scalar val) => val; + + /// Wraps a value (no allocation; travels inline). + public static InputArrayRef Create(double val) => val; + + /// Wraps a fixed-length value (no allocation; travels inline). + public static InputArrayRef Create(IVec vec) + { + ArgumentNullException.ThrowIfNull(vec); + return vec switch + { + Vec2b v => (InputArrayRef)v, + Vec3b v => (InputArrayRef)v, + Vec4b v => (InputArrayRef)v, + Vec6b v => (InputArrayRef)v, + Vec2s v => (InputArrayRef)v, + Vec3s v => (InputArrayRef)v, + Vec4s v => (InputArrayRef)v, + Vec6s v => (InputArrayRef)v, + Vec2w v => (InputArrayRef)v, + Vec3w v => (InputArrayRef)v, + Vec4w v => (InputArrayRef)v, + Vec6w v => (InputArrayRef)v, + Vec2i v => (InputArrayRef)v, + Vec3i v => (InputArrayRef)v, + Vec4i v => (InputArrayRef)v, + Vec6i v => (InputArrayRef)v, + Vec2f v => (InputArrayRef)v, + Vec3f v => (InputArrayRef)v, + Vec4f v => (InputArrayRef)v, + Vec6f v => (InputArrayRef)v, + Vec2d v => (InputArrayRef)v, + Vec3d v => (InputArrayRef)v, + Vec4d v => (InputArrayRef)v, + Vec6d v => (InputArrayRef)v, + _ => throw new ArgumentException($"Not supported type: '{vec.GetType().Name}'", nameof(vec)), + }; + } + + /// + /// Wraps a 1-D array by copying it into a freshly-created of the given + /// (not allocation-free: this materializes a real Mat, same as the + /// class-based InputArray.Create<T> it replaces). + /// + public static InputArrayRef Create(T[] array, MatType type) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(array); + if (array.Length == 0) + throw new ArgumentException("array.Length == 0", nameof(array)); + return Mat.FromPixelData(array.Length, 1, type, array); + } + + /// Wraps a 1-D array, inferring the from . + public static InputArrayRef Create(T[] array) where T : unmanaged => + Create(array, EstimateType(typeof(T))); + + /// + /// Wraps a 2-D array by copying it into a freshly-created of the given + /// . + /// + public static InputArrayRef Create(T[,] array, MatType type) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(array); + var rows = array.GetLength(0); + var cols = array.GetLength(1); + if (rows == 0) + throw new ArgumentException("array.GetLength(0) == 0", nameof(array)); + if (cols == 0) + throw new ArgumentException("array.GetLength(1) == 0", nameof(array)); + return Mat.FromPixelData(rows, cols, type, array); + } + + /// Wraps a 2-D array, inferring the from . + public static InputArrayRef Create(T[,] array) where T : unmanaged => + Create(array, EstimateType(typeof(T))); + + /// Wraps a sequence, inferring the from . + public static InputArrayRef Create(IEnumerable enumerable) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(enumerable); + return Create(new List(enumerable).ToArray()); + } + + /// Wraps a sequence by copying it into a freshly-created of the given + /// . + public static InputArrayRef Create(IEnumerable enumerable, MatType type) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(enumerable); + return Create(new List(enumerable).ToArray(), type); + } + + // Maps a raw/OpenCV struct element type to the single-column MatType used to host it in the + // Mat built by Create(T[]/T[,]) above. Ported unchanged from the class-based InputArray. + private static MatType EstimateType(Type t) + { + var code = Type.GetTypeCode(t); + switch (code) + { + case TypeCode.Byte: return MatType.CV_8UC1; + case TypeCode.SByte: return MatType.CV_8SC1; + case TypeCode.UInt16: return MatType.CV_16UC1; + case TypeCode.Int16: + case TypeCode.Char: return MatType.CV_16SC1; + case TypeCode.UInt32: + case TypeCode.Int32: return MatType.CV_32SC1; + case TypeCode.Single: return MatType.CV_32FC1; + case TypeCode.Double: return MatType.CV_64FC1; + } + + if (t == typeof(Point)) return MatType.CV_32SC2; + if (t == typeof(Point2f)) return MatType.CV_32FC2; + if (t == typeof(Point2d)) return MatType.CV_64FC2; + if (t == typeof(Point3i)) return MatType.CV_32SC3; + if (t == typeof(Point3f)) return MatType.CV_32FC3; + if (t == typeof(Point3d)) return MatType.CV_64FC3; + if (t == typeof(Range)) return MatType.CV_32SC2; + if (t == typeof(Rangef)) return MatType.CV_32FC2; + if (t == typeof(Rect)) return MatType.CV_32SC4; + if (t == typeof(Size)) return MatType.CV_32SC2; + if (t == typeof(Size2f)) return MatType.CV_32FC2; + + if (t == typeof(Vec2b)) return MatType.CV_8UC2; + if (t == typeof(Vec3b)) return MatType.CV_8UC3; + if (t == typeof(Vec4b)) return MatType.CV_8UC4; + if (t == typeof(Vec6b)) return MatType.CV_8UC(6); + if (t == typeof(Vec2s)) return MatType.CV_16SC2; + if (t == typeof(Vec3s)) return MatType.CV_16SC3; + if (t == typeof(Vec4s)) return MatType.CV_16SC4; + if (t == typeof(Vec6s)) return MatType.CV_16SC(6); + if (t == typeof(Vec2w)) return MatType.CV_16UC2; + if (t == typeof(Vec3w)) return MatType.CV_16UC3; + if (t == typeof(Vec4w)) return MatType.CV_16UC4; + if (t == typeof(Vec6w)) return MatType.CV_16UC(6); + if (t == typeof(Vec2i)) return MatType.CV_32SC2; + if (t == typeof(Vec3i)) return MatType.CV_32SC3; + if (t == typeof(Vec4i)) return MatType.CV_32SC4; + if (t == typeof(Vec6i)) return MatType.CV_32SC(6); + if (t == typeof(Vec2f)) return MatType.CV_32FC2; + if (t == typeof(Vec3f)) return MatType.CV_32FC3; + if (t == typeof(Vec4f)) return MatType.CV_32FC4; + if (t == typeof(Vec6f)) return MatType.CV_32FC(6); + if (t == typeof(Vec2d)) return MatType.CV_64FC2; + if (t == typeof(Vec3d)) return MatType.CV_64FC3; + if (t == typeof(Vec4d)) return MatType.CV_64FC4; + if (t == typeof(Vec6d)) return MatType.CV_64FC(6); + + throw new ArgumentException("Not supported value type for InputArrayRef"); + } + + #endregion } /// @@ -245,6 +408,12 @@ public static implicit operator OutputArrayRef(UMat mat) mat.ThrowIfDisposed(); return new OutputArrayRef(mat, new OutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); } + + /// Wraps a output (no allocation). + public static OutputArrayRef Create(Mat mat) => mat; + + /// Wraps a output (no allocation). + public static OutputArrayRef Create(UMat mat) => mat; } /// @@ -277,4 +446,10 @@ public static implicit operator InputOutputArrayRef(UMat mat) mat.ThrowIfDisposed(); return new InputOutputArrayRef(mat, new InputOutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); } + + /// Wraps a in/out target (no allocation). + public static InputOutputArrayRef Create(Mat mat) => mat; + + /// Wraps a in/out target (no allocation). + public static InputOutputArrayRef Create(UMat mat) => mat; } diff --git a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs index 33b72b57b..9ba4c8133 100644 --- a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs +++ b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs @@ -201,4 +201,68 @@ public void CompleteSymmRef_IsAllocationFree() Assert.Equal(0, after - before); } + + [Fact] + public void Create_FromVec_MatchesClassBased() + { + var v = new Vec3d(1, 2, 3); + + using var actual = new Mat(); + Cv2.TransposeRef(InputArrayRef.Create(v), actual); + + using var expected = new Mat(); + using var classInputArray = InputArray.Create(v); + Cv2.Transpose(classInputArray, expected); + + ImageEquals(expected, actual); + } + + [Fact] + public void Create_From2DArray_MatchesClassBased() + { + double[,] a = + { + { 1, 2, 3 }, + { 4, 5, 6 }, + { 7, 8, 9 }, + }; + + using var actual = new Mat(); + Cv2.TransposeRef(InputArrayRef.Create(a), actual); + + using var expected = new Mat(); + using var classInputArray = InputArray.Create(a); + Cv2.Transpose(classInputArray, expected); + + ImageEquals(expected, actual); + } + + [Fact] + public void Create_From1DArray_MatchesClassBased() + { + double[] a = [1, 2, 3, 4, 5, 6]; + + using var actual = new Mat(); + Cv2.TransposeRef(InputArrayRef.Create(a), actual); + + using var expected = new Mat(); + using var classInputArray = InputArray.Create(a); + Cv2.Transpose(classInputArray, expected); + + ImageEquals(expected, actual); + } + + [Fact] + public void Create_FromMat_MatchesImplicitConversion() + { + using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); + + using var actual = new Mat(); + Cv2.TransposeRef(InputArrayRef.Create(src), actual); + + using var expected = new Mat(); + Cv2.TransposeRef(src, expected); + + ImageEquals(expected, actual); + } } From 6775ba0fbacef92571b586ac5261f8d9bbaaf710 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 15:51:14 +0900 Subject: [PATCH 04/29] Migration: quality module to InputArrayRef/OutputArrayRef (issue #1976 step 5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit First real (non-foundation) module converted to the ref-struct proxy types: QualityBase/QualityMSE/QualityPSNR/QualityGMSD/QualitySSIM/QualityBRISQUE. Pilot for the mechanical recipe that the rest of the ~226 files will follow: - InputArray/OutputArray -> InputArrayRef/OutputArrayRef in every public signature. - .ToInputProxy()/.ToOutputProxy() -> .Proxy. - Drop is-null guards and .ThrowIfDisposed()/.ThrowIfNotReady()/.Fix() - the ref struct's own implicit conversion operators already null-check and disposed-check the incoming Mat/UMat, and there is no write-back to flush (native writes straight through the Mat). - GC.KeepAlive(x) -> GC.KeepAlive(x.Source) (a ref struct can't convert to object, and x.Source is what actually needs keeping alive). - OutputArray? qualityMap (required-but-nullable) -> OutputArrayRef qualityMap = default (optional, skippable) - the null-conditional operators this displaces are no longer needed since default already means "not provided" (Kind == None, which native already treats as cv::noArray()). No native changes: every quality extern was already migrated to the ArrayProxy ABI, so this is a pure C#-side signature/body edit. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- .../Modules/quality/QualityBRISQUE.cs | 25 +++++---------- .../Modules/quality/QualityBase.cs | 19 ++++------- .../Modules/quality/QualityGMSD.cs | 30 ++++++----------- src/OpenCvSharp/Modules/quality/QualityMSE.cs | 30 ++++++----------- .../Modules/quality/QualityPSNR.cs | 32 ++++++------------- .../Modules/quality/QualitySSIM.cs | 30 ++++++----------- .../quality/QualityGMSDTest.cs | 2 +- .../quality/QualityMSETest.cs | 2 +- .../quality/QualityPSNRTest.cs | 2 +- .../quality/QualitySSIMTest.cs | 2 +- 10 files changed, 55 insertions(+), 119 deletions(-) diff --git a/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs b/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs index 6412e58c1..0e35dca81 100644 --- a/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs +++ b/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs @@ -72,20 +72,17 @@ public static QualityBRISQUE Create(SVM model, Mat range) /// String which contains a path to the BRISQUE model data, eg. /path/to/brisque_model_live.yml /// cv::String which contains a path to the BRISQUE range data, eg. /path/to/brisque_range_live.yml /// cv::Scalar with the score in the first element. The score ranges from 0 (best quality) to 100 (worst quality) - public static Scalar Compute(InputArray img, string modelFilePath, string rangeFilePath) + public static Scalar Compute(InputArrayRef img, string modelFilePath, string rangeFilePath) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (string.IsNullOrEmpty(modelFilePath)) throw new ArgumentNullException(nameof(modelFilePath)); if (string.IsNullOrEmpty(rangeFilePath)) throw new ArgumentNullException(nameof(rangeFilePath)); - img.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.quality_QualityBRISQUE_staticCompute(img.ToInputProxy(), modelFilePath, rangeFilePath, out var ret)); + NativeMethods.quality_QualityBRISQUE_staticCompute(img.Proxy, modelFilePath, rangeFilePath, out var ret)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return ret; } @@ -94,18 +91,12 @@ public static Scalar Compute(InputArray img, string modelFilePath, string rangeF /// /// image (BGR(A) or grayscale) for which to compute features /// output row vector of features to cv::Mat or cv::UMat - public static void ComputeFeatures(InputArray img, OutputArray features) + public static void ComputeFeatures(InputArrayRef img, OutputArrayRef features) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (features is null) - throw new ArgumentNullException(nameof(features)); - NativeMethods.HandleException( - NativeMethods.quality_QualityBRISQUE_computeFeatures(img.ToInputProxy(), features.ToOutputProxy())); - - GC.KeepAlive(img); - GC.KeepAlive(features); - } + NativeMethods.quality_QualityBRISQUE_computeFeatures(img.Proxy, features.Proxy)); + GC.KeepAlive(img.Source); + GC.KeepAlive(features.Source); } +} diff --git a/src/OpenCvSharp/Modules/quality/QualityBase.cs b/src/OpenCvSharp/Modules/quality/QualityBase.cs index 6ac68368d..673606a95 100644 --- a/src/OpenCvSharp/Modules/quality/QualityBase.cs +++ b/src/OpenCvSharp/Modules/quality/QualityBase.cs @@ -31,14 +31,11 @@ public override bool Empty /// Returns output quality map that was generated during computation, if supported by the algorithm /// /// - public virtual void GetQualityMap(OutputArray dst) + public virtual void GetQualityMap(OutputArrayRef dst) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.quality_QualityBase_getQualityMap(Handle, dst.ToOutputProxy())); - dst.Fix(); + NativeMethods.quality_QualityBase_getQualityMap(Handle, dst.Proxy)); + GC.KeepAlive(dst.Source); } /// @@ -46,15 +43,11 @@ public virtual void GetQualityMap(OutputArray dst) /// See specific algorithm for interpreting result scores /// /// comparison image, or image to evaluate for no-reference quality algorithms - public virtual Scalar Compute(InputArray img) + public virtual Scalar Compute(InputArrayRef img) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.quality_QualityBase_compute(Handle, img.ToInputProxy(), out var ret)); - GC.KeepAlive(img); + NativeMethods.quality_QualityBase_compute(Handle, img.Proxy, out var ret)); + GC.KeepAlive(img.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/quality/QualityGMSD.cs b/src/OpenCvSharp/Modules/quality/QualityGMSD.cs index 6b8708f6d..08c7bc5a9 100644 --- a/src/OpenCvSharp/Modules/quality/QualityGMSD.cs +++ b/src/OpenCvSharp/Modules/quality/QualityGMSD.cs @@ -22,15 +22,11 @@ private QualityGMSD(IntPtr smartPtr, IntPtr rawPtr) /// /// input image to use as the source for comparison /// - public static QualityGMSD Create(InputArray @ref) + public static QualityGMSD Create(InputArrayRef @ref) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - @ref.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.quality_createQualityGMSD(@ref.ToInputProxy(), out var smartPtr)); - GC.KeepAlive(@ref); + NativeMethods.quality_createQualityGMSD(@ref.Proxy, out var smartPtr)); + GC.KeepAlive(@ref.Source); NativeMethods.HandleException(NativeMethods.quality_Ptr_QualityGMSD_get(smartPtr, out var rawPtr)); return new QualityGMSD(smartPtr, rawPtr); } @@ -40,25 +36,17 @@ public static QualityGMSD Create(InputArray @ref) /// /// /// - /// output quality map, or null + /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray? qualityMap) + public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - if (cmp is null) - throw new ArgumentNullException(nameof(cmp)); - @ref.ThrowIfDisposed(); - cmp.ThrowIfDisposed(); - qualityMap?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.quality_QualityGMSD_staticCompute( - @ref.ToInputProxy(), cmp.ToInputProxy(), qualityMap?.ToOutputProxy() ?? default, out var ret)); + @ref.Proxy, cmp.Proxy, qualityMap.Proxy, out var ret)); - GC.KeepAlive(@ref); - GC.KeepAlive(cmp); - qualityMap?.Fix(); + GC.KeepAlive(@ref.Source); + GC.KeepAlive(cmp.Source); + GC.KeepAlive(qualityMap.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/quality/QualityMSE.cs b/src/OpenCvSharp/Modules/quality/QualityMSE.cs index 61481f0a9..077bd6dea 100644 --- a/src/OpenCvSharp/Modules/quality/QualityMSE.cs +++ b/src/OpenCvSharp/Modules/quality/QualityMSE.cs @@ -19,16 +19,12 @@ private QualityMSE(IntPtr smartPtr, IntPtr rawPtr) /// /// input image to use as the source for comparison /// - public static QualityMSE Create(InputArray @ref) + public static QualityMSE Create(InputArrayRef @ref) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - @ref.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.quality_createQualityMSE(@ref.ToInputProxy(), out var smartPtr)); + NativeMethods.quality_createQualityMSE(@ref.Proxy, out var smartPtr)); - GC.KeepAlive(@ref); + GC.KeepAlive(@ref.Source); NativeMethods.HandleException(NativeMethods.quality_Ptr_QualityMSE_get(smartPtr, out var rawPtr)); return new QualityMSE(smartPtr, rawPtr); } @@ -41,25 +37,17 @@ public static QualityMSE Create(InputArray @ref) /// /// /// - /// output quality map, or null + /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray? qualityMap) + public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - if (cmp is null) - throw new ArgumentNullException(nameof(cmp)); - @ref.ThrowIfDisposed(); - cmp.ThrowIfDisposed(); - qualityMap?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.quality_QualityMSE_staticCompute( - @ref.ToInputProxy(), cmp.ToInputProxy(), qualityMap?.ToOutputProxy() ?? default, out var ret)); + @ref.Proxy, cmp.Proxy, qualityMap.Proxy, out var ret)); - GC.KeepAlive(@ref); - GC.KeepAlive(cmp); - qualityMap?.Fix(); + GC.KeepAlive(@ref.Source); + GC.KeepAlive(cmp.Source); + GC.KeepAlive(qualityMap.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/quality/QualityPSNR.cs b/src/OpenCvSharp/Modules/quality/QualityPSNR.cs index 3fd5c0cf7..14abc6965 100644 --- a/src/OpenCvSharp/Modules/quality/QualityPSNR.cs +++ b/src/OpenCvSharp/Modules/quality/QualityPSNR.cs @@ -44,44 +44,32 @@ public double MaxPixelValue /// input image to use as the source for comparison /// maximum per-channel value for any individual pixel; eg 255 for uint8 image /// - public static QualityPSNR Create(InputArray @ref, double maxPixelValue = MaxPixelValueDefault) + public static QualityPSNR Create(InputArrayRef @ref, double maxPixelValue = MaxPixelValueDefault) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - @ref.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.quality_createQualityPSNR(@ref.ToInputProxy(), maxPixelValue, out var smartPtr)); - GC.KeepAlive(@ref); + NativeMethods.quality_createQualityPSNR(@ref.Proxy, maxPixelValue, out var smartPtr)); + GC.KeepAlive(@ref.Source); NativeMethods.HandleException(NativeMethods.quality_Ptr_QualityPSNR_get(smartPtr, out var rawPtr)); return new QualityPSNR(smartPtr, rawPtr); } - + /// /// static method for computing quality /// /// /// - /// output quality map, or null + /// output quality map, or default to skip it /// maximum per-channel value for any individual pixel; eg 255 for uint8 image /// PSNR value, or double.PositiveInfinity if the MSE between the two images == 0 - public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray? qualityMap, double maxPixelValue = MaxPixelValueDefault) + public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default, double maxPixelValue = MaxPixelValueDefault) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - if (cmp is null) - throw new ArgumentNullException(nameof(cmp)); - @ref.ThrowIfDisposed(); - cmp.ThrowIfDisposed(); - qualityMap?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.quality_QualityPSNR_staticCompute( - @ref.ToInputProxy(), cmp.ToInputProxy(), qualityMap?.ToOutputProxy() ?? default, maxPixelValue, out var ret)); + @ref.Proxy, cmp.Proxy, qualityMap.Proxy, maxPixelValue, out var ret)); - GC.KeepAlive(@ref); - GC.KeepAlive(cmp); - qualityMap?.Fix(); + GC.KeepAlive(@ref.Source); + GC.KeepAlive(cmp.Source); + GC.KeepAlive(qualityMap.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/quality/QualitySSIM.cs b/src/OpenCvSharp/Modules/quality/QualitySSIM.cs index fdf32ca1b..35b31c554 100644 --- a/src/OpenCvSharp/Modules/quality/QualitySSIM.cs +++ b/src/OpenCvSharp/Modules/quality/QualitySSIM.cs @@ -21,15 +21,11 @@ private QualitySSIM(IntPtr smartPtr, IntPtr rawPtr) /// /// input image to use as the source for comparison /// - public static QualitySSIM Create(InputArray @ref) + public static QualitySSIM Create(InputArrayRef @ref) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - @ref.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.quality_createQualitySSIM(@ref.ToInputProxy(), out var smartPtr)); - GC.KeepAlive(@ref); + NativeMethods.quality_createQualitySSIM(@ref.Proxy, out var smartPtr)); + GC.KeepAlive(@ref.Source); NativeMethods.HandleException(NativeMethods.quality_Ptr_QualitySSIM_get(smartPtr, out var rawPtr)); return new QualitySSIM(smartPtr, rawPtr); } @@ -39,25 +35,17 @@ public static QualitySSIM Create(InputArray @ref) /// /// /// - /// output quality map, or null + /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray? qualityMap) + public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) { - if (@ref is null) - throw new ArgumentNullException(nameof(@ref)); - if (cmp is null) - throw new ArgumentNullException(nameof(cmp)); - @ref.ThrowIfDisposed(); - cmp.ThrowIfDisposed(); - qualityMap?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.quality_QualitySSIM_staticCompute( - @ref.ToInputProxy(), cmp.ToInputProxy(), qualityMap?.ToOutputProxy() ?? default, out var ret)); + @ref.Proxy, cmp.Proxy, qualityMap.Proxy, out var ret)); - GC.KeepAlive(@ref); - GC.KeepAlive(cmp); - qualityMap?.Fix(); + GC.KeepAlive(@ref.Source); + GC.KeepAlive(cmp.Source); + GC.KeepAlive(qualityMap.Source); return ret; } } diff --git a/test/OpenCvSharp.Tests/quality/QualityGMSDTest.cs b/test/OpenCvSharp.Tests/quality/QualityGMSDTest.cs index e1a2de950..6c1bb8f9b 100644 --- a/test/OpenCvSharp.Tests/quality/QualityGMSDTest.cs +++ b/test/OpenCvSharp.Tests/quality/QualityGMSDTest.cs @@ -29,7 +29,7 @@ public void StaticCompute() { Cv2.GaussianBlur(refImage, targetImage, new Size(5, 5), 15); - var value = QualityGMSD.Compute(refImage, targetImage, null); + var value = QualityGMSD.Compute(refImage, targetImage); Assert.Equal(0.0616, value[0], 4); Assert.Equal(0.0711, value[1], 4); Assert.Equal(0.05983, value[2], 5); diff --git a/test/OpenCvSharp.Tests/quality/QualityMSETest.cs b/test/OpenCvSharp.Tests/quality/QualityMSETest.cs index 57883dcd9..0628d1d22 100644 --- a/test/OpenCvSharp.Tests/quality/QualityMSETest.cs +++ b/test/OpenCvSharp.Tests/quality/QualityMSETest.cs @@ -29,7 +29,7 @@ public void StaticCompute() { Cv2.GaussianBlur(refImage, targetImage, new Size(5, 5), 15); - var value = QualityMSE.Compute(refImage, targetImage, null); + var value = QualityMSE.Compute(refImage, targetImage); Assert.Equal(83.89224, value[0], 6); Assert.Equal(96.848604, value[1], 6); Assert.Equal(50.611845, value[2], 6); diff --git a/test/OpenCvSharp.Tests/quality/QualityPSNRTest.cs b/test/OpenCvSharp.Tests/quality/QualityPSNRTest.cs index 1e4ad253d..fa442e715 100644 --- a/test/OpenCvSharp.Tests/quality/QualityPSNRTest.cs +++ b/test/OpenCvSharp.Tests/quality/QualityPSNRTest.cs @@ -32,7 +32,7 @@ public void StaticCompute() { Cv2.GaussianBlur(refImage, targetImage, new Size(5, 5), 15); - var value = QualityPSNR.Compute(refImage, targetImage, null); + var value = QualityPSNR.Compute(refImage, targetImage); Assert.Equal(28.893586, value[0], 6); Assert.Equal(28.26987, value[1], 6); Assert.Equal(31.088282, value[2], 6); diff --git a/test/OpenCvSharp.Tests/quality/QualitySSIMTest.cs b/test/OpenCvSharp.Tests/quality/QualitySSIMTest.cs index 1bfe5e814..51b0ff7a2 100644 --- a/test/OpenCvSharp.Tests/quality/QualitySSIMTest.cs +++ b/test/OpenCvSharp.Tests/quality/QualitySSIMTest.cs @@ -46,7 +46,7 @@ public void StaticCompute() { Cv2.GaussianBlur(refImage, targetImage, new Size(5, 5), 15); - var value = QualitySSIM.Compute(refImage, targetImage, null); + var value = QualitySSIM.Compute(refImage, targetImage); Assert.Equal(0.72, value[0], 3); Assert.Equal(0.793, value[1], 3); Assert.Equal(0.863, value[2], 3); From 25c8d7e902a69392cef0172eeb82b3bf5f1370fc Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 15:58:58 +0900 Subject: [PATCH 05/29] Migration: Cv2_core.cs arithmetic ops (Add/Subtract/Multiply/Divide/LUT/...) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Converts CopyMakeBorder/Add/Subtract/Multiply/Divide/ScaleAdd/AddWeighted/ ConvertScaleAbs/LUT following the recipe established on the quality module. Also fixes the two ripple-effect call sites this broke (Cv2_core.cs's methods are called from all over the codebase, not just "core" files): Mat.LUT(InputArray) -> Mat.LUT(InputArrayRef), and a CoreTest.cs assertion using InputArray.Create(10.0) -> InputArrayRef.Create(10.0). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 264 ++++++------------ .../Modules/core/Mat/Mat_CvMethods.cs | 2 +- test/OpenCvSharp.Tests/core/CoreTest.cs | 2 +- 3 files changed, 81 insertions(+), 187 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index d074b26b8..87ab49e2b 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -43,23 +43,16 @@ public static int BorderInterpolate(int p, int len, BorderTypes borderType) /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate /// The border type /// The border value if borderType == Constant - public static void CopyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, + public static void CopyMakeBorder(InputArrayRef src, OutputArrayRef dst, int top, int bottom, int left, int right, BorderTypes borderType, Scalar? value = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var value0 = value.GetValueOrDefault(new Scalar()); NativeMethods.HandleException( NativeMethods.core_copyMakeBorder( - src.ToInputProxy(), dst.ToOutputProxy(), top, bottom, left, right, (int)borderType, value0)); + src.Proxy, dst.Proxy, top, bottom, left, right, (int)borderType, value0)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -68,30 +61,20 @@ public static void CopyMakeBorder(InputArray src, OutputArray dst, int top, int /// The first source array /// The second source array. It must have the same size and same type as src1 /// The destination array; it will have the same size and same type as src1 - /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is null] + /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Add(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null, + public static void Add(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, int dtype = -1) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_add( - src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), - mask?.ToInputProxy() ?? default, dtype)); + src1.Proxy, src2.Proxy, dst.Proxy, + mask.Proxy, dtype)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(dst.Source); } /// @@ -100,30 +83,20 @@ public static void Add(InputArray src1, InputArray src2, OutputArray dst, InputA /// The first source array /// The second source array. It must have the same size and same type as src1 /// The destination array; it will have the same size and same type as src1 - /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is null] + /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null, + public static void Subtract(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, int dtype = -1) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_subtract_InputArray2( - src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), - mask?.ToInputProxy() ?? default, dtype)); + src1.Proxy, src2.Proxy, dst.Proxy, + mask.Proxy, dtype)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -132,26 +105,19 @@ public static void Subtract(InputArray src1, InputArray src2, OutputArray dst, I /// The first source array /// The second source array. It must have the same size and same type as src1 /// The destination array; it will have the same size and same type as src1 - /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is null] + /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(InputArray src1, Scalar src2, OutputArray dst, InputArray? mask = null, + public static void Subtract(InputArrayRef src1, Scalar src2, OutputArrayRef dst, InputArrayRef mask = default, int dtype = -1) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_subtract_InputArrayScalar( - src1.ToInputProxy(), src2, dst.ToOutputProxy(), - mask?.ToInputProxy() ?? default, dtype)); + src1.Proxy, src2, dst.Proxy, + mask.Proxy, dtype)); - GC.KeepAlive(src1); - dst.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -160,28 +126,21 @@ public static void Subtract(InputArray src1, Scalar src2, OutputArray dst, Input /// The first source array /// The second source array. It must have the same size and same type as src1 /// The destination array; it will have the same size and same type as src1 - /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is null] + /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(Scalar src1, InputArray src2, OutputArray dst, InputArray? mask = null, + public static void Subtract(Scalar src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, int dtype = -1) { - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_subtract_ScalarInputArray( - src1, src2.ToInputProxy(), dst.ToOutputProxy(), - mask?.ToInputProxy() ?? default, dtype)); + src1, src2.Proxy, dst.Proxy, + mask.Proxy, dtype)); - GC.KeepAlive(src2); - dst.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } - + /// /// Calculates the per-element scaled product of two arrays /// @@ -190,25 +149,15 @@ public static void Subtract(Scalar src1, InputArray src2, OutputArray dst, Input /// The destination array; will have the same size and the same type as src1 /// The optional scale factor. [By default this is 1] /// - public static void Multiply(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1) + public static void Multiply(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, double scale = 1, int dtype = -1) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_multiply( - src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), scale, dtype)); + src1.Proxy, src2.Proxy, dst.Proxy, scale, dtype)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -219,25 +168,15 @@ public static void Multiply(InputArray src1, InputArray src2, OutputArray dst, d /// The destination array; will have the same size and same type as src2 /// Scale factor [By default this is 1] /// - public static void Divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, MatType? dtype = null) + public static void Divide(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, double scale = 1, MatType? dtype = null) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_divide2( - src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), scale, dtype?.Value ?? -1)); + src1.Proxy, src2.Proxy, dst.Proxy, scale, dtype?.Value ?? -1)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -247,20 +186,13 @@ public static void Divide(InputArray src1, InputArray src2, OutputArray dst, dou /// The first source array /// The destination array; will have the same size and same type as src2 /// - public static void Divide(double scale, InputArray src2, OutputArray dst, int dtype = -1) + public static void Divide(double scale, InputArrayRef src2, OutputArrayRef dst, int dtype = -1) { - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_divide1(scale, src2.ToInputProxy(), dst.ToOutputProxy(), dtype)); + NativeMethods.core_divide1(scale, src2.Proxy, dst.Proxy, dtype)); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -270,24 +202,14 @@ public static void Divide(double scale, InputArray src2, OutputArray dst, int dt /// /// /// - public static void ScaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst) + public static void ScaleAdd(InputArrayRef src1, double alpha, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_scaleAdd(src1.ToInputProxy(), alpha, src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_scaleAdd(src1.Proxy, alpha, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -300,26 +222,16 @@ public static void ScaleAdd(InputArray src1, double alpha, InputArray src2, Outp /// /// /// - public static void AddWeighted(InputArray src1, double alpha, InputArray src2, - double beta, double gamma, OutputArray dst, int dtype = -1) + public static void AddWeighted(InputArrayRef src1, double alpha, InputArrayRef src2, + double beta, double gamma, OutputArrayRef dst, int dtype = -1) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_addWeighted( - src1.ToInputProxy(), alpha, src2.ToInputProxy(), beta, gamma, dst.ToOutputProxy(), dtype)); + src1.Proxy, alpha, src2.Proxy, beta, gamma, dst.Proxy, dtype)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -329,66 +241,48 @@ public static void AddWeighted(InputArray src1, double alpha, InputArray src2, /// The destination array /// The optional scale factor. [By default this is 1] /// The optional delta added to the scaled values. [By default this is 0] - public static void ConvertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0) + public static void ConvertScaleAbs(InputArrayRef src, OutputArrayRef dst, double alpha = 1, double beta = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_convertScaleAbs(src.ToInputProxy(), dst.ToOutputProxy(), alpha, beta)); + NativeMethods.core_convertScaleAbs(src.Proxy, dst.Proxy, alpha, beta)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// /// transforms array of numbers using a lookup table: dst(i)=lut(src(i)) /// /// Source array of 8-bit elements - /// Look-up table of 256 elements. - /// In the case of multi-channel source array, the table should either have + /// Look-up table of 256 elements. + /// In the case of multi-channel source array, the table should either have /// a single channel (in this case the same table is used for all channels) /// or the same number of channels as in the source array - /// Destination array; - /// will have the same size and the same number of channels as src, + /// Destination array; + /// will have the same size and the same number of channels as src, /// and the same depth as lut - public static void LUT(InputArray src, InputArray lut, OutputArray dst) + public static void LUT(InputArrayRef src, InputArrayRef lut, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (lut is null) - throw new ArgumentNullException(nameof(lut)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - lut.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_LUT(src.ToInputProxy(), lut.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_LUT(src.Proxy, lut.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(lut); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(lut.Source); + GC.KeepAlive(dst.Source); } /// /// transforms array of numbers using a lookup table: dst(i)=lut(src(i)) /// /// Source array of 8-bit elements - /// Look-up table of 256 elements. - /// In the case of multi-channel source array, the table should either have - /// a single channel (in this case the same table is used for all channels) + /// Look-up table of 256 elements. + /// In the case of multi-channel source array, the table should either have + /// a single channel (in this case the same table is used for all channels) /// or the same number of channels as in the source array - /// Destination array; - /// will have the same size and the same number of channels as src, + /// Destination array; + /// will have the same size and the same number of channels as src, /// and the same depth as lut - public static void LUT(InputArray src, byte[] lut, OutputArray dst) + public static void LUT(InputArrayRef src, byte[] lut, OutputArrayRef dst) { if (lut is null) throw new ArgumentNullException(nameof(lut)); diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 1de632afd..8f1ef7a70 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -36,7 +36,7 @@ public Mat ConvertScaleAbs(double alpha = 1, double beta = 0) /// a single channel (in this case the same table is used for all channels) /// or the same number of channels as in the source array /// - public Mat LUT(InputArray lut) + public Mat LUT(InputArrayRef lut) { var dst = new Mat(); Cv2.LUT(this, lut, dst); diff --git a/test/OpenCvSharp.Tests/core/CoreTest.cs b/test/OpenCvSharp.Tests/core/CoreTest.cs index 77bc53b06..8e2b10ea9 100644 --- a/test/OpenCvSharp.Tests/core/CoreTest.cs +++ b/test/OpenCvSharp.Tests/core/CoreTest.cs @@ -51,7 +51,7 @@ public void AddScalar() Assert.Equal(13, dst.At(1, 0)); Assert.Equal(14, dst.At(1, 1)); - using var inputArray = InputArray.Create(10.0); + var inputArray = InputArrayRef.Create(10.0); Cv2.Add(src, inputArray, dst); Assert.Equal(11, dst.At(0, 0)); Assert.Equal(12, dst.At(0, 1)); From 9f60449bc54d890dbae0de9c6371733574f869d3 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:05:16 +0900 Subject: [PATCH 06/29] Migration: Cv2_core.cs statistics ops (MeanStdDev/Norm/PSNR/BatchDistance/Normalize/ReduceArgMax/ReduceArgMin/MinMaxLoc/MinMaxIdx) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the ripple-effect call sites in Mat_CvMethods.cs (MeanStdDev/Norm/ Normalize/MinMaxLoc instance wrappers) and CoreTest.cs (NormVecb using InputArray.Create(vec) explicitly). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 224 ++++++------------ .../Modules/core/Mat/Mat_CvMethods.cs | 8 +- test/OpenCvSharp.Tests/core/CoreTest.cs | 2 +- 3 files changed, 74 insertions(+), 160 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 87ab49e2b..16ad6c054 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -381,52 +381,35 @@ public static Scalar Mean(InputArray src, InputArray? mask = null) /// The output parameter: computed standard deviation /// The optional operation mask public static void MeanStdDev( - InputArray src, OutputArray mean, OutputArray stddev, InputArray? mask = null) + InputArrayRef src, OutputArrayRef mean, OutputArrayRef stddev, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (stddev is null) - throw new ArgumentNullException(nameof(stddev)); - src.ThrowIfDisposed(); - mean.ThrowIfNotReady(); - stddev.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_meanStdDev_OutputArray( - src.ToInputProxy(), mean.ToOutputProxy(), stddev.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + src.Proxy, mean.Proxy, stddev.Proxy, mask.Proxy)); - mean.Fix(); - stddev.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(mean); - GC.KeepAlive(stddev); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(stddev.Source); + GC.KeepAlive(mask.Source); } /// /// computes mean value and standard deviation of all or selected array elements /// - /// The source array; it should have 1 to 4 channels + /// The source array; it should have 1 to 4 channels /// (so that the results can be stored in Scalar's) /// The output parameter: computed mean value /// The output parameter: computed standard deviation /// The optional operation mask public static void MeanStdDev( - InputArray src, out Scalar mean, out Scalar stddev, InputArray? mask = null) + InputArrayRef src, out Scalar mean, out Scalar stddev, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - - src.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.core_meanStdDev_Scalar( - src.ToInputProxy(), out mean, out stddev, mask?.ToInputProxy() ?? default)); + src.Proxy, out mean, out stddev, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// @@ -436,18 +419,14 @@ public static void MeanStdDev( /// Type of the norm /// The optional operation mask /// - public static double Norm(InputArray src1, - NormTypes normType = NormTypes.L2, InputArray? mask = null) + public static double Norm(InputArrayRef src1, + NormTypes normType = NormTypes.L2, InputArrayRef mask = default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - src1.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_norm1(src1.ToInputProxy(), (int)normType, mask?.ToInputProxy() ?? default, out var ret)); + NativeMethods.core_norm1(src1.Proxy, (int)normType, mask.Proxy, out var ret)); - GC.KeepAlive(src1); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(mask.Source); return ret; } @@ -459,29 +438,22 @@ public static double Norm(InputArray src1, /// Type of the norm /// The optional operation mask /// - public static double Norm(InputArray src1, InputArray src2, - NormTypes normType = NormTypes.L2, InputArray? mask = null) + public static double Norm(InputArrayRef src1, InputArrayRef src2, + NormTypes normType = NormTypes.L2, InputArrayRef mask = default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_norm2(src1.ToInputProxy(), src2.ToInputProxy(), (int)normType, mask?.ToInputProxy() ?? default, out var ret)); + NativeMethods.core_norm2(src1.Proxy, src2.Proxy, (int)normType, mask.Proxy, out var ret)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(mask.Source); return ret; } /// /// Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. - /// - /// This function calculates the Peak Signal-to-Noise Ratio(PSNR) image quality metric in decibels(dB), + /// + /// This function calculates the Peak Signal-to-Noise Ratio(PSNR) image quality metric in decibels(dB), /// between two input arrays src1 and src2.The arrays must have the same type. /// /// first input array. @@ -489,20 +461,13 @@ public static double Norm(InputArray src1, InputArray src2, /// the maximum pixel value (255 by default) /// // ReSharper disable once InconsistentNaming - public static double PSNR(InputArray src1, InputArray src2, double r = 255.0) + public static double PSNR(InputArrayRef src1, InputArrayRef src2, double r = 255.0) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_PSNR(src1.ToInputProxy(), src2.ToInputProxy(), r, out var ret)); + NativeMethods.core_PSNR(src1.Proxy, src2.Proxy, r, out var ret)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); return ret; } @@ -519,73 +484,50 @@ public static double PSNR(InputArray src1, InputArray src2, double r = 255.0) /// /// /// - public static void BatchDistance(InputArray src1, InputArray src2, + public static void BatchDistance(InputArrayRef src1, InputArrayRef src2, // ReSharper disable once IdentifierTypo - OutputArray dist, int dtype, OutputArray nidx, + OutputArrayRef dist, int dtype, OutputArrayRef nidx, NormTypes normType = NormTypes.L2, - int k = 0, InputArray? mask = null, + int k = 0, InputArrayRef mask = default, int update = 0, bool crosscheck = false) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dist is null) - throw new ArgumentNullException(nameof(dist)); - if (nidx is null) - throw new ArgumentNullException(nameof(nidx)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dist.ThrowIfNotReady(); - nidx.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_batchDistance( - src1.ToInputProxy(), src2.ToInputProxy(), dist.ToOutputProxy(), dtype, nidx.ToOutputProxy(), - (int) normType, k, mask?.ToInputProxy() ?? default, update, crosscheck ? 1 : 0)); + src1.Proxy, src2.Proxy, dist.Proxy, dtype, nidx.Proxy, + (int) normType, k, mask.Proxy, update, crosscheck ? 1 : 0)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dist); - GC.KeepAlive(nidx); - dist.Fix(); - nidx.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dist.Source); + GC.KeepAlive(nidx.Source); + GC.KeepAlive(mask.Source); } /// - /// scales and shifts array elements so that either the specified norm (alpha) + /// scales and shifts array elements so that either the specified norm (alpha) /// or the minimum (alpha) and maximum (beta) array values get the specified values /// /// The source array /// The destination array; will have the same size as src - /// The norm value to normalize to or the lower range boundary + /// The norm value to normalize to or the lower range boundary /// in the case of range normalization - /// The upper range boundary in the case of range normalization; + /// The upper range boundary in the case of range normalization; /// not used for norm normalization /// The normalization type - /// When the parameter is negative, - /// the destination array will have the same type as src, + /// When the parameter is negative, + /// the destination array will have the same type as src, /// otherwise it will have the same number of channels as src and the depth =CV_MAT_DEPTH(rtype) /// The optional operation mask - public static void Normalize(InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, - NormTypes normType = NormTypes.L2, int dtype = -1, InputArray? mask = null) + public static void Normalize(InputArrayRef src, InputOutputArrayRef dst, double alpha = 1, double beta = 0, + NormTypes normType = NormTypes.L2, int dtype = -1, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.core_normalize( - src.ToInputProxy(), dst.ToInputOutputProxy(), alpha, beta, (int)normType, dtype, mask?.ToInputProxy() ?? default)); + src.Proxy, dst.Proxy, alpha, beta, (int)normType, dtype, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -596,21 +538,13 @@ public static void Normalize(InputArray src, InputOutputArray dst, double alpha /// except for axis being reduced - it should be set to 1. /// Axis to reduce along /// Whether to get the index of first or last occurrence of max - public static void ReduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false) + public static void ReduceArgMax(InputArrayRef src, OutputArrayRef dst, int axis, bool lastIndex = false) { - if (src == null) - throw new ArgumentNullException(nameof(src)); - if (dst == null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_reduceArgMax(src.ToInputProxy(), dst.ToOutputProxy(), axis, lastIndex)); + NativeMethods.core_reduceArgMax(src.Proxy, dst.Proxy, axis, lastIndex)); - dst.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -621,21 +555,13 @@ public static void ReduceArgMax(InputArray src, OutputArray dst, int axis, bool /// except for axis being reduced - it should be set to 1. /// Axis to reduce along /// Whether to get the index of first or last occurrence of min - public static void ReduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false) + public static void ReduceArgMin(InputArrayRef src, OutputArrayRef dst, int axis, bool lastIndex = false) { - if (src == null) - throw new ArgumentNullException(nameof(src)); - if (dst == null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_reduceArgMin(src.ToInputProxy(), dst.ToOutputProxy(), axis, lastIndex)); + NativeMethods.core_reduceArgMin(src.Proxy, dst.Proxy, axis, lastIndex)); - dst.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -644,16 +570,12 @@ public static void ReduceArgMin(InputArray src, OutputArray dst, int axis, bool /// The source single-channel array /// Pointer to returned minimum value /// Pointer to returned maximum value - public static void MinMaxLoc(InputArray src, out double minVal, out double maxVal) + public static void MinMaxLoc(InputArrayRef src, out double minVal, out double maxVal) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_minMaxLoc1(src.ToInputProxy(), out minVal, out maxVal)); + NativeMethods.core_minMaxLoc1(src.Proxy, out minVal, out maxVal)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); } /// @@ -662,7 +584,7 @@ public static void MinMaxLoc(InputArray src, out double minVal, out double maxVa /// The source single-channel array /// Pointer to returned minimum location /// Pointer to returned maximum location - public static void MinMaxLoc(InputArray src, out Point minLoc, out Point maxLoc) + public static void MinMaxLoc(InputArrayRef src, out Point minLoc, out Point maxLoc) { MinMaxLoc(src, out _, out _, out minLoc, out maxLoc); } @@ -676,19 +598,15 @@ public static void MinMaxLoc(InputArray src, out Point minLoc, out Point maxLoc) /// Pointer to returned minimum location /// Pointer to returned maximum location /// The optional mask used to select a sub-array - public static void MinMaxLoc(InputArray src, out double minVal, out double maxVal, - out Point minLoc, out Point maxLoc, InputArray? mask = null) + public static void MinMaxLoc(InputArrayRef src, out double minVal, out double maxVal, + out Point minLoc, out Point maxLoc, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.core_minMaxLoc2( - src.ToInputProxy(), out minVal, out maxVal, out minLoc, out maxLoc, mask?.ToInputProxy() ?? default)); + src.Proxy, out minVal, out maxVal, out minLoc, out maxLoc, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// @@ -697,16 +615,12 @@ public static void MinMaxLoc(InputArray src, out double minVal, out double maxVa /// The source single-channel array /// Pointer to returned minimum value /// Pointer to returned maximum value - public static void MinMaxIdx(InputArray src, out double minVal, out double maxVal) + public static void MinMaxIdx(InputArrayRef src, out double minVal, out double maxVal) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_minMaxIdx1(src.ToInputProxy(), out minVal, out maxVal)); + NativeMethods.core_minMaxIdx1(src.Proxy, out minVal, out maxVal)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 8f1ef7a70..4ab7078f0 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -103,7 +103,7 @@ public Scalar Mean(InputArray? mask = null) /// The output parameter: computed mean value /// The output parameter: computed standard deviation /// The optional operation mask - public void MeanStdDev(OutputArray mean, OutputArray stddev, InputArray? mask = null) + public void MeanStdDev(OutputArrayRef mean, OutputArrayRef stddev, InputArrayRef mask = default) { Cv2.MeanStdDev(this, mean, stddev, mask); } @@ -114,7 +114,7 @@ public void MeanStdDev(OutputArray mean, OutputArray stddev, InputArray? mask = /// Type of the norm /// The optional operation mask /// - public double Norm(NormTypes normType = NormTypes.L2, InputArray? mask = null) + public double Norm(NormTypes normType = NormTypes.L2, InputArrayRef mask = default) { return Cv2.Norm(this, normType, mask); } @@ -134,7 +134,7 @@ public double Norm(NormTypes normType = NormTypes.L2, InputArray? mask = null) /// The optional operation mask /// public Mat Normalize(double alpha = 1, double beta = 0, - NormTypes normType = NormTypes.L2, int dtype = -1, InputArray? mask = null) + NormTypes normType = NormTypes.L2, int dtype = -1, InputArrayRef mask = default) { var dst = new Mat(); Cv2.Normalize(this, dst, alpha, beta, normType, dtype, mask); @@ -170,7 +170,7 @@ public void MinMaxLoc(out Point minLoc, out Point maxLoc) /// Pointer to returned maximum location /// The optional mask used to select a sub-array public void MinMaxLoc(out double minVal, out double maxVal, - out Point minLoc, out Point maxLoc, InputArray? mask = null) + out Point minLoc, out Point maxLoc, InputArrayRef mask = default) { Cv2.MinMaxLoc(this, out minVal, out maxVal, out minLoc, out maxLoc, mask); } diff --git a/test/OpenCvSharp.Tests/core/CoreTest.cs b/test/OpenCvSharp.Tests/core/CoreTest.cs index 8e2b10ea9..5cc78984b 100644 --- a/test/OpenCvSharp.Tests/core/CoreTest.cs +++ b/test/OpenCvSharp.Tests/core/CoreTest.cs @@ -414,7 +414,7 @@ public void Norm() public void NormVecb() { var vec = new Vec3b(10, 20, 30); - using var ia = InputArray.Create(vec); + var ia = InputArrayRef.Create(vec); var norm = Cv2.Norm(ia, NormTypes.L1); Assert.Equal(60, norm); } From c55f5917788909320c07db01fc5fdd0d860b1e55 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:09:28 +0900 Subject: [PATCH 07/29] Migration: Cv2_core.cs channel/geometry ops (MinMaxIdx/Reduce/ExtractChannel/InsertChannel/Flip/Rotate/Repeat) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the Mat_CvMethods.cs MinMaxIdx/InsertChannel instance wrappers this broke. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 118 ++++++------------ .../Modules/core/Mat/Mat_CvMethods.cs | 4 +- 2 files changed, 37 insertions(+), 85 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 16ad6c054..3ce672ab0 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -629,7 +629,7 @@ public static void MinMaxIdx(InputArrayRef src, out double minVal, out double ma /// The source single-channel array /// /// - public static void MinMaxIdx(InputArray src, int[] minIdx, int[] maxIdx) + public static void MinMaxIdx(InputArrayRef src, int[] minIdx, int[] maxIdx) { MinMaxIdx(src, out _, out _, minIdx, maxIdx); } @@ -643,50 +643,40 @@ public static void MinMaxIdx(InputArray src, int[] minIdx, int[] maxIdx) /// /// /// - public static void MinMaxIdx(InputArray src, out double minVal, out double maxVal, - int[] minIdx, int[] maxIdx, InputArray? mask = null) + public static void MinMaxIdx(InputArrayRef src, out double minVal, out double maxVal, + int[] minIdx, int[] maxIdx, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); if (minIdx is null) throw new ArgumentNullException(nameof(minIdx)); if (maxIdx is null) throw new ArgumentNullException(nameof(maxIdx)); - src.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.core_minMaxIdx2( - src.ToInputProxy(), out minVal, out maxVal, minIdx, maxIdx, mask?.ToInputProxy() ?? default)); + src.Proxy, out minVal, out maxVal, minIdx, maxIdx, mask.Proxy)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// /// transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows /// /// The source 2D matrix - /// The destination vector. + /// The destination vector. /// Its size and type is defined by dim and dtype parameters - /// The dimension index along which the matrix is reduced. + /// The dimension index along which the matrix is reduced. /// 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column /// - /// When it is negative, the destination vector will have + /// When it is negative, the destination vector will have /// the same type as the source matrix, otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), mtx.channels()) - public static void Reduce(InputArray src, OutputArray dst, ReduceDimension dim, ReduceTypes rtype, int dtype) + public static void Reduce(InputArrayRef src, OutputArrayRef dst, ReduceDimension dim, ReduceTypes rtype, int dtype) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_reduce(src.ToInputProxy(), dst.ToOutputProxy(), (int)dim, (int)rtype, dtype)); + NativeMethods.core_reduce(src.Proxy, dst.Proxy, (int)dim, (int)rtype, dtype)); - dst.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -801,21 +791,13 @@ public static void MixChannels(ReadOnlySpan src, ReadOnlySpan dst, int /// /// /// - public static void ExtractChannel(InputArray src, OutputArray dst, int coi) + public static void ExtractChannel(InputArrayRef src, OutputArrayRef dst, int coi) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_extractChannel(src.ToInputProxy(), dst.ToOutputProxy(), coi)); + NativeMethods.core_extractChannel(src.Proxy, dst.Proxy, coi)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -824,21 +806,13 @@ public static void ExtractChannel(InputArray src, OutputArray dst, int coi) /// /// /// - public static void InsertChannel(InputArray src, InputOutputArray dst, int coi) + public static void InsertChannel(InputArrayRef src, InputOutputArrayRef dst, int coi) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_insertChannel(src.ToInputProxy(), dst.ToInputOutputProxy(), coi)); + NativeMethods.core_insertChannel(src.Proxy, dst.Proxy, coi)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -846,23 +820,16 @@ public static void InsertChannel(InputArray src, InputOutputArray dst, int coi) /// /// The source array /// The destination array; will have the same size and same type as src - /// Specifies how to flip the array: - /// 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, + /// Specifies how to flip the array: + /// 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, /// and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas. - public static void Flip(InputArray src, OutputArray dst, FlipMode flipCode) + public static void Flip(InputArrayRef src, OutputArrayRef dst, FlipMode flipCode) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_flip(src.ToInputProxy(), dst.ToOutputProxy(), (int) flipCode)); + NativeMethods.core_flip(src.Proxy, dst.Proxy, (int) flipCode)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -873,20 +840,13 @@ public static void Flip(InputArray src, OutputArray dst, FlipMode flipCode) /// The size is the same with ROTATE_180, and the rows and cols are switched for /// ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE. /// an enum to specify how to rotate the array. - public static void Rotate(InputArray src, OutputArray dst, RotateFlags rotateCode) + public static void Rotate(InputArrayRef src, OutputArrayRef dst, RotateFlags rotateCode) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_rotate(src.ToInputProxy(), dst.ToOutputProxy(), (int)rotateCode)); + NativeMethods.core_rotate(src.Proxy, dst.Proxy, (int)rotateCode)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -896,21 +856,13 @@ public static void Rotate(InputArray src, OutputArray dst, RotateFlags rotateCod /// How many times the src is repeated along the vertical axis /// How many times the src is repeated along the horizontal axis /// The destination array; will have the same type as src - public static void Repeat(InputArray src, int ny, int nx, OutputArray dst) + public static void Repeat(InputArrayRef src, int ny, int nx, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_repeat1(src.ToInputProxy(), ny, nx, dst.ToOutputProxy())); + NativeMethods.core_repeat1(src.Proxy, ny, nx, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 4ab7078f0..56d536fa0 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -204,7 +204,7 @@ public void MinMaxIdx(int[] minIdx, int[] maxIdx) /// /// public void MinMaxIdx(out double minVal, out double maxVal, - int[] minIdx, int[] maxIdx, InputArray? mask = null) + int[] minIdx, int[] maxIdx, InputArrayRef mask = default) { Cv2.MinMaxIdx(this, out minVal, out maxVal, minIdx, maxIdx, mask); } @@ -252,7 +252,7 @@ public Mat ExtractChannel(int coi) /// /// /// - public void InsertChannel(InputOutputArray dst, int coi) + public void InsertChannel(InputOutputArrayRef dst, int coi) { Cv2.InsertChannel(this, dst, coi); } From f539396d93d99223be71fefca6f086790083ae4d Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:13:54 +0900 Subject: [PATCH 08/29] Migration: Cv2_core.cs concat/bitwise/compare/min-max ops (HConcat/VConcat/BitwiseAnd/Or/Xor/Not/Absdiff/CopyTo/InRange/Compare/Min/Max) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the Mat.InRange(InputArray,InputArray) instance wrapper this broke. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 290 +++++------------- .../Modules/core/Mat/Mat_CvMethods.cs | 2 +- 2 files changed, 75 insertions(+), 217 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 3ce672ab0..99eff8551 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -890,10 +890,8 @@ public static Mat Repeat(Mat src, int ny, int nx) /// /// input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. /// output array. It has the same number of rows and depth as the src, and the sum of cols of the src. - public static void HConcat(ReadOnlySpan src, OutputArray dst) + public static void HConcat(ReadOnlySpan src, OutputArrayRef dst) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); if (src.Length == 0) throw new ArgumentException("src is empty", nameof(src)); @@ -907,12 +905,11 @@ public static void HConcat(ReadOnlySpan src, OutputArray dst) } NativeMethods.HandleException( - NativeMethods.core_hconcat1(srcPtr, (uint) src.Length, dst.ToOutputProxy())); + NativeMethods.core_hconcat1(srcPtr, (uint) src.Length, dst.Proxy)); foreach (var m in src) GC.KeepAlive(m); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// @@ -921,25 +918,14 @@ public static void HConcat(ReadOnlySpan src, OutputArray dst) /// first input array to be considered for horizontal concatenation. /// second input array to be considered for horizontal concatenation. /// output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. - public static void HConcat(InputArray src1, InputArray src2, OutputArray dst) + public static void HConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_hconcat2(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_hconcat2(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -947,10 +933,8 @@ public static void HConcat(InputArray src1, InputArray src2, OutputArray dst) /// /// input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. /// output array. It has the same number of cols and depth as the src, and the sum of rows of the src. - public static void VConcat(ReadOnlySpan src, OutputArray dst) + public static void VConcat(ReadOnlySpan src, OutputArrayRef dst) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); if (src.Length == 0) throw new ArgumentException("src.Count == 0", nameof(src)); @@ -964,12 +948,11 @@ public static void VConcat(ReadOnlySpan src, OutputArray dst) } NativeMethods.HandleException( - NativeMethods.core_vconcat1(srcPtr, (uint)src.Length, dst.ToOutputProxy())); + NativeMethods.core_vconcat1(srcPtr, (uint)src.Length, dst.Proxy)); foreach (var m in src) GC.KeepAlive(m); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// @@ -978,25 +961,14 @@ public static void VConcat(ReadOnlySpan src, OutputArray dst) /// first input array to be considered for vertical concatenation. /// second input array to be considered for vertical concatenation. /// output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. - public static void VConcat(InputArray src1, InputArray src2, OutputArray dst) + public static void VConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_vconcat2(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_vconcat2(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -1006,25 +978,15 @@ public static void VConcat(InputArray src1, InputArray src2, OutputArray dst) /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseAnd(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + public static void BitwiseAnd(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_bitwise_and(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.core_bitwise_and(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - GC.KeepAlive(mask); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1034,26 +996,15 @@ public static void BitwiseAnd(InputArray src1, InputArray src2, OutputArray dst, /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseOr(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + public static void BitwiseOr(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_bitwise_or(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.core_bitwise_or(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1063,26 +1014,15 @@ public static void BitwiseOr(InputArray src1, InputArray src2, OutputArray dst, /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseXor(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + public static void BitwiseXor(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_bitwise_xor(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.core_bitwise_xor(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1091,22 +1031,14 @@ public static void BitwiseXor(InputArray src1, InputArray src2, OutputArray dst, /// input array. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseNot(InputArray src, OutputArray dst, InputArray? mask = null) + public static void BitwiseNot(InputArrayRef src, OutputArrayRef dst, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_bitwise_not(src.ToInputProxy(), dst.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.core_bitwise_not(src.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1115,25 +1047,14 @@ public static void BitwiseNot(InputArray src, OutputArray dst, InputArray? mask /// first input array or a scalar. /// second input array or a scalar. /// output array that has the same size and type as input arrays. - public static void Absdiff(InputArray src1, InputArray src2, OutputArray dst) + public static void Absdiff(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_absdiff(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_absdiff(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -1144,22 +1065,14 @@ public static void Absdiff(InputArray src1, InputArray src2, OutputArray dst) /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask of the same size as \*this. Its non-zero elements indicate which matrix /// elements need to be copied.The mask has to be of type CV_8U and can have 1 or multiple channels. - public static void CopyTo(InputArray src, OutputArray dst, InputArray? mask = null) + public static void CopyTo(InputArrayRef src, OutputArrayRef dst, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_copyTo(src.ToInputProxy(), dst.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.core_copyTo(src.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1169,29 +1082,15 @@ public static void CopyTo(InputArray src, OutputArray dst, InputArray? mask = nu /// inclusive lower boundary array or a scalar. /// inclusive upper boundary array or a scalar. /// output array of the same size as src and CV_8U type. - public static void InRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst) + public static void InRange(InputArrayRef src, InputArrayRef lowerb, InputArrayRef upperb, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (lowerb is null) - throw new ArgumentNullException(nameof(lowerb)); - if (upperb is null) - throw new ArgumentNullException(nameof(upperb)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - lowerb.ThrowIfDisposed(); - upperb.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_inRange_InputArray(src.ToInputProxy(), lowerb.ToInputProxy(), upperb.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_inRange_InputArray(src.Proxy, lowerb.Proxy, upperb.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(lowerb); - GC.KeepAlive(upperb); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(lowerb.Source); + GC.KeepAlive(upperb.Source); + GC.KeepAlive(dst.Source); } /// @@ -1201,21 +1100,13 @@ public static void InRange(InputArray src, InputArray lowerb, InputArray upperb, /// inclusive lower boundary array or a scalar. /// inclusive upper boundary array or a scalar. /// output array of the same size as src and CV_8U type. - public static void InRange(InputArray src, Scalar lowerb, Scalar upperb, OutputArray dst) + public static void InRange(InputArrayRef src, Scalar lowerb, Scalar upperb, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_inRange_Scalar(src.ToInputProxy(), lowerb, upperb, dst.ToOutputProxy())); + NativeMethods.core_inRange_Scalar(src.Proxy, lowerb, upperb, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1226,25 +1117,14 @@ public static void InRange(InputArray src, Scalar lowerb, Scalar upperb, OutputA /// output array of type ref CV_8U that has the same size and the same number of channels as the input arrays. /// a flag, that specifies correspondence between the arrays (cv::CmpTypes) // ReSharper disable once IdentifierTypo - public static void Compare(InputArray src1, InputArray src2, OutputArray dst, CmpTypes cmpop) + public static void Compare(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, CmpTypes cmpop) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_compare(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), (int) cmpop)); + NativeMethods.core_compare(src1.Proxy, src2.Proxy, dst.Proxy, (int) cmpop)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -1253,25 +1133,14 @@ public static void Compare(InputArray src1, InputArray src2, OutputArray dst, Cm /// /// /// - public static void Min(InputArray src1, InputArray src2, OutputArray dst) + public static void Min(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_min1(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_min1(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -1328,25 +1197,14 @@ public static void Min(Mat src1, double src2, Mat dst) /// /// /// - public static void Max(InputArray src1, InputArray src2, OutputArray dst) + public static void Max(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_max1(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_max1(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 56d536fa0..e04848693 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -290,7 +290,7 @@ public Mat Repeat(int ny, int nx) /// inclusive lower boundary array or a scalar. /// inclusive upper boundary array or a scalar. /// The destination array, will have the same size as src and CV_8U type - public Mat InRange(InputArray lowerb, InputArray upperb) + public Mat InRange(InputArrayRef lowerb, InputArrayRef upperb) { var dst = new Mat(); Cv2.InRange(this, lowerb, upperb, dst); From ec2c966feb39baa4b8135cc6cabc6bd7f69274e6 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:19:55 +0900 Subject: [PATCH 09/29] Migration: Cv2_core.cs math/transform ops (Pow/Exp/Log/PolarToCart/CartToPolar/Phase/Magnitude/CheckRange/PatchNaNs/Gemm/MulTransposed/Transpose/Transform/PerspectiveTransform) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes the Mat_CvMethods.cs MulTransposed/Transform/PerspectiveTransform instance wrappers, and rewrites 3 InputArrayRefTest.cs parity tests that compared InputArrayRef.Create(...) against the class-based InputArray.Create (...) via Cv2.Transpose - that comparison is no longer possible now that Transpose itself takes InputArrayRef, so they compare against a directly -built Mat instead (equally rigorous, and no longer coupled to the soon-to-be-deleted class). Note: Cv2.Transpose is now byte-identical to the foundation's Cv2.TransposeRef (same signature, same native call) - cleanup (delete the redundant *Ref foundation methods once Add/CompleteSymm are migrated too) deferred to a dedicated pass so as not to disrupt the in-progress module sweep. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 297 +++++------------- .../Modules/core/Mat/Mat_CvMethods.cs | 6 +- .../core/InputArrayRefTest.cs | 17 +- 3 files changed, 91 insertions(+), 229 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 99eff8551..d1000c102 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -1283,21 +1283,13 @@ public static void Sqrt(InputArray src, OutputArray dst) /// The source array /// The exponent of power /// The destination array; will have the same size and the same type as src - public static void Pow(InputArray src, double power, OutputArray dst) + public static void Pow(InputArrayRef src, double power, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_pow_Mat(src.ToInputProxy(), power, dst.ToOutputProxy())); + NativeMethods.core_pow_Mat(src.Proxy, power, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1305,21 +1297,13 @@ public static void Pow(InputArray src, double power, OutputArray dst) /// /// The source array /// The destination array; will have the same size and same type as src - public static void Exp(InputArray src, OutputArray dst) + public static void Exp(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_exp_Mat(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_exp_Mat(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1327,23 +1311,15 @@ public static void Exp(InputArray src, OutputArray dst) /// /// The source array /// The destination array; will have the same size and same type as src - public static void Log(InputArray src, OutputArray dst) + public static void Log(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_log_Mat(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_log_Mat(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } - /// /// Calculates x and y coordinates of 2D vectors from their magnitude and angle. /// @@ -1354,31 +1330,16 @@ public static void Log(InputArray src, OutputArray dst) /// output array of x-coordinates of 2D vectors; it has the same size and type as angle. /// output array of y-coordinates of 2D vectors; it has the same size and type as angle. /// when true, the input angles are measured in degrees, otherwise, they are measured in radians. - public static void PolarToCart(InputArray magnitude, InputArray angle, - OutputArray x, OutputArray y, bool angleInDegrees = false) - { - if (magnitude is null) - throw new ArgumentNullException(nameof(magnitude)); - if (angle is null) - throw new ArgumentNullException(nameof(angle)); - if (x is null) - throw new ArgumentNullException(nameof(x)); - if (y is null) - throw new ArgumentNullException(nameof(y)); - magnitude.ThrowIfDisposed(); - angle.ThrowIfDisposed(); - x.ThrowIfNotReady(); - y.ThrowIfNotReady(); - + public static void PolarToCart(InputArrayRef magnitude, InputArrayRef angle, + OutputArrayRef x, OutputArrayRef y, bool angleInDegrees = false) + { NativeMethods.HandleException( - NativeMethods.core_polarToCart(magnitude.ToInputProxy(), angle.ToInputProxy(), x.ToOutputProxy(), y.ToOutputProxy(), angleInDegrees ? 1 : 0)); + NativeMethods.core_polarToCart(magnitude.Proxy, angle.Proxy, x.Proxy, y.Proxy, angleInDegrees ? 1 : 0)); - GC.KeepAlive(magnitude); - GC.KeepAlive(angle); - GC.KeepAlive(x); - GC.KeepAlive(y); - x.Fix(); - y.Fix(); + GC.KeepAlive(magnitude.Source); + GC.KeepAlive(angle.Source); + GC.KeepAlive(x.Source); + GC.KeepAlive(y.Source); } /// @@ -1390,31 +1351,16 @@ public static void PolarToCart(InputArray magnitude, InputArray angle, /// output array of angles that has the same size and type as x; /// the angles are measured in radians(from 0 to 2\*Pi) or in degrees(0 to 360 degrees). /// a flag, indicating whether the angles are measured in radians(which is by default), or in degrees. - public static void CartToPolar(InputArray x, InputArray y, - OutputArray magnitude, OutputArray angle, bool angleInDegrees = false) + public static void CartToPolar(InputArrayRef x, InputArrayRef y, + OutputArrayRef magnitude, OutputArrayRef angle, bool angleInDegrees = false) { - if (x is null) - throw new ArgumentNullException(nameof(x)); - if (y is null) - throw new ArgumentNullException(nameof(y)); - if (magnitude is null) - throw new ArgumentNullException(nameof(magnitude)); - if (angle is null) - throw new ArgumentNullException(nameof(angle)); - x.ThrowIfDisposed(); - y.ThrowIfDisposed(); - magnitude.ThrowIfNotReady(); - angle.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_cartToPolar(x.ToInputProxy(), y.ToInputProxy(), magnitude.ToOutputProxy(), angle.ToOutputProxy(), angleInDegrees ? 1 : 0)); + NativeMethods.core_cartToPolar(x.Proxy, y.Proxy, magnitude.Proxy, angle.Proxy, angleInDegrees ? 1 : 0)); - GC.KeepAlive(x); - GC.KeepAlive(y); - GC.KeepAlive(magnitude); - GC.KeepAlive(angle); - magnitude.Fix(); - angle.Fix(); + GC.KeepAlive(x.Source); + GC.KeepAlive(y.Source); + GC.KeepAlive(magnitude.Source); + GC.KeepAlive(angle.Source); } /// @@ -1424,25 +1370,14 @@ public static void CartToPolar(InputArray x, InputArray y, /// input array of y-coordinates of 2D vectors; it must have the same size and the same type as x. /// output array of vector angles; it has the same size and same type as x. /// when true, the function calculates the angle in degrees, otherwise, they are measured in radians. - public static void Phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false) + public static void Phase(InputArrayRef x, InputArrayRef y, OutputArrayRef angle, bool angleInDegrees = false) { - if (x is null) - throw new ArgumentNullException(nameof(x)); - if (y is null) - throw new ArgumentNullException(nameof(y)); - if (angle is null) - throw new ArgumentNullException(nameof(angle)); - x.ThrowIfDisposed(); - y.ThrowIfDisposed(); - angle.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_phase(x.ToInputProxy(), y.ToInputProxy(), angle.ToOutputProxy(), angleInDegrees ? 1 : 0)); + NativeMethods.core_phase(x.Proxy, y.Proxy, angle.Proxy, angleInDegrees ? 1 : 0)); - GC.KeepAlive(x); - GC.KeepAlive(y); - GC.KeepAlive(angle); - angle.Fix(); + GC.KeepAlive(x.Source); + GC.KeepAlive(y.Source); + GC.KeepAlive(angle.Source); } /// @@ -1451,36 +1386,25 @@ public static void Phase(InputArray x, InputArray y, OutputArray angle, bool ang /// floating-point array of x-coordinates of the vectors. /// floating-point array of y-coordinates of the vectors; it must have the same size as x. /// output array of the same size and type as x. - public static void Magnitude(InputArray x, InputArray y, OutputArray magnitude) + public static void Magnitude(InputArrayRef x, InputArrayRef y, OutputArrayRef magnitude) { - if (x is null) - throw new ArgumentNullException(nameof(x)); - if (y is null) - throw new ArgumentNullException(nameof(y)); - if (magnitude is null) - throw new ArgumentNullException(nameof(magnitude)); - x.ThrowIfDisposed(); - y.ThrowIfDisposed(); - magnitude.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_magnitude_Mat(x.ToInputProxy(), y.ToInputProxy(), magnitude.ToOutputProxy())); + NativeMethods.core_magnitude_Mat(x.Proxy, y.Proxy, magnitude.Proxy)); - GC.KeepAlive(x); - GC.KeepAlive(y); - GC.KeepAlive(magnitude); - magnitude.Fix(); + GC.KeepAlive(x.Source); + GC.KeepAlive(y.Source); + GC.KeepAlive(magnitude.Source); } - + /// /// checks that each matrix element is within the specified range. /// /// The array to check - /// The flag indicating whether the functions quietly - /// return false when the array elements are out of range, + /// The flag indicating whether the functions quietly + /// return false when the array elements are out of range, /// or they throw an exception. /// - public static bool CheckRange(InputArray src, bool quiet = true) + public static bool CheckRange(InputArrayRef src, bool quiet = true) { return CheckRange(src, quiet, out _); } @@ -1489,44 +1413,36 @@ public static bool CheckRange(InputArray src, bool quiet = true) /// checks that each matrix element is within the specified range. /// /// The array to check - /// The flag indicating whether the functions quietly - /// return false when the array elements are out of range, + /// The flag indicating whether the functions quietly + /// return false when the array elements are out of range, /// or they throw an exception. - /// The optional output parameter, where the position of + /// The optional output parameter, where the position of /// the first outlier is stored. /// The inclusive lower boundary of valid values range /// The exclusive upper boundary of valid values range /// - public static bool CheckRange(InputArray src, bool quiet, out Point pos, + public static bool CheckRange(InputArrayRef src, bool quiet, out Point pos, double minVal = double.MinValue, double maxVal = double.MaxValue) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_checkRange(src.ToInputProxy(), quiet ? 1 : 0, out pos, minVal, maxVal, out var ret)); - GC.KeepAlive(src); + NativeMethods.core_checkRange(src.Proxy, quiet ? 1 : 0, out pos, minVal, maxVal, out var ret)); + GC.KeepAlive(src.Source); return ret != 0; } - + /// /// converts NaN's to the given number /// /// /// - public static void PatchNaNs(InputOutputArray a, double val = 0) + public static void PatchNaNs(InputOutputArrayRef a, double val = 0) { - if (a is null) - throw new ArgumentNullException(nameof(a)); - a.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_patchNaNs(a.ToInputOutputProxy(), val)); + NativeMethods.core_patchNaNs(a.Proxy, val)); - GC.KeepAlive(a); + GC.KeepAlive(a.Source); } - + /// /// implements generalized matrix product algorithm GEMM from BLAS /// @@ -1538,30 +1454,16 @@ public static void PatchNaNs(InputOutputArray a, double val = 0) /// /// // ReSharper disable once IdentifierTypo - public static void Gemm(InputArray src1, InputArray src2, double alpha, - InputArray src3, double gamma, OutputArray dst, GemmFlags flags = GemmFlags.None) + public static void Gemm(InputArrayRef src1, InputArrayRef src2, double alpha, + InputArrayRef src3, double gamma, OutputArrayRef dst, GemmFlags flags = GemmFlags.None) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (src3 is null) - throw new ArgumentNullException(nameof(src3)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - src3.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_gemm(src1.ToInputProxy(), src2.ToInputProxy(), alpha, src3.ToInputProxy(), gamma, dst.ToOutputProxy(), (int) flags)); + NativeMethods.core_gemm(src1.Proxy, src2.Proxy, alpha, src3.Proxy, gamma, dst.Proxy, (int) flags)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(src3); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(src3.Source); + GC.KeepAlive(dst.Source); } /// @@ -1580,23 +1482,15 @@ public static void Gemm(InputArray src1, InputArray src2, double alpha, /// When it’s negative, the destination matrix will have the /// same type as src . Otherwise, it will have type=CV_MAT_DEPTH(rtype), /// which should be either CV_32F or CV_64F - public static void MulTransposed(InputArray src, OutputArray dst, bool aTa, - InputArray? delta = null, double scale = 1, int dtype = -1) + public static void MulTransposed(InputArrayRef src, OutputArrayRef dst, bool aTa, + InputArrayRef delta = default, double scale = 1, int dtype = -1) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_mulTransposed(src.ToInputProxy(), dst.ToOutputProxy(), aTa ? 1 : 0, delta?.ToInputProxy() ?? default, scale, dtype)); + NativeMethods.core_mulTransposed(src.Proxy, dst.Proxy, aTa ? 1 : 0, delta.Proxy, scale, dtype)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(delta); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(delta.Source); } /// @@ -1604,22 +1498,13 @@ public static void MulTransposed(InputArray src, OutputArray dst, bool aTa, /// /// The source array /// The destination array of the same type as src - public static void Transpose(InputArray src, OutputArray dst) + public static void Transpose(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - - NativeMethods.HandleException( - NativeMethods.core_transpose(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_transpose(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1628,53 +1513,31 @@ public static void Transpose(InputArray src, OutputArray dst) /// The source array; must have as many channels (1 to 4) as mtx.cols or mtx.cols-1 /// The destination array; will have the same size and depth as src and as many channels as mtx.rows /// The transformation matrix - public static void Transform(InputArray src, OutputArray dst, InputArray m) + public static void Transform(InputArrayRef src, OutputArrayRef dst, InputArrayRef m) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (m is null) - throw new ArgumentNullException(nameof(m)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - m.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_transform(src.ToInputProxy(), dst.ToOutputProxy(), m.ToInputProxy())); + NativeMethods.core_transform(src.Proxy, dst.Proxy, m.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(m); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(m.Source); } /// /// performs perspective transformation of each element of multi-channel input matrix /// - /// The source two-channel or three-channel floating-point array; + /// The source two-channel or three-channel floating-point array; /// each element is 2D/3D vector to be transformed /// The destination array; it will have the same size and same type as src /// 3x3 or 4x4 transformation matrix - public static void PerspectiveTransform(InputArray src, OutputArray dst, InputArray m) + public static void PerspectiveTransform(InputArrayRef src, OutputArrayRef dst, InputArrayRef m) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (m is null) - throw new ArgumentNullException(nameof(m)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - m.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_perspectiveTransform(src.ToInputProxy(), dst.ToOutputProxy(), m.ToInputProxy())); + NativeMethods.core_perspectiveTransform(src.Proxy, dst.Proxy, m.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(m); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(m.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index e04848693..7fd244e97 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -408,7 +408,7 @@ public void PatchNaNs(double val = 0) /// When it’s negative, the destination matrix will have the /// same type as src . Otherwise, it will have type=CV_MAT_DEPTH(rtype), /// which should be either CV_32F or CV_64F - public Mat MulTransposed(bool aTa, InputArray? delta = null, double scale = 1, int dtype = -1) + public Mat MulTransposed(bool aTa, InputArrayRef delta = default, double scale = 1, int dtype = -1) { var dst = new Mat(); Cv2.MulTransposed(this, dst, aTa, delta, scale, dtype); @@ -431,7 +431,7 @@ public Mat Transpose() /// /// The transformation matrix /// The destination array; will have the same size and depth as src and as many channels as mtx.rows - public Mat Transform(InputArray m) + public Mat Transform(InputArrayRef m) { var dst = new Mat(); Cv2.Transform(this, dst, m); @@ -443,7 +443,7 @@ public Mat Transform(InputArray m) /// /// 3x3 or 4x4 transformation matrix /// The destination array; it will have the same size and same type as src - public Mat PerspectiveTransform(InputArray m) + public Mat PerspectiveTransform(InputArrayRef m) { var dst = new Mat(); Cv2.PerspectiveTransform(this, dst, m); diff --git a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs index 9ba4c8133..a7379a338 100644 --- a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs +++ b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs @@ -203,7 +203,7 @@ public void CompleteSymmRef_IsAllocationFree() } [Fact] - public void Create_FromVec_MatchesClassBased() + public void Create_FromVec_MatchesImplicitConversion() { var v = new Vec3d(1, 2, 3); @@ -211,14 +211,13 @@ public void Create_FromVec_MatchesClassBased() Cv2.TransposeRef(InputArrayRef.Create(v), actual); using var expected = new Mat(); - using var classInputArray = InputArray.Create(v); - Cv2.Transpose(classInputArray, expected); + Cv2.TransposeRef(v, expected); ImageEquals(expected, actual); } [Fact] - public void Create_From2DArray_MatchesClassBased() + public void Create_From2DArray_MatchesManuallyBuiltMat() { double[,] a = { @@ -230,24 +229,24 @@ public void Create_From2DArray_MatchesClassBased() using var actual = new Mat(); Cv2.TransposeRef(InputArrayRef.Create(a), actual); + using var src = Mat.FromPixelData(3, 3, MatType.CV_64FC1, a); using var expected = new Mat(); - using var classInputArray = InputArray.Create(a); - Cv2.Transpose(classInputArray, expected); + Cv2.TransposeRef(src, expected); ImageEquals(expected, actual); } [Fact] - public void Create_From1DArray_MatchesClassBased() + public void Create_From1DArray_MatchesManuallyBuiltMat() { double[] a = [1, 2, 3, 4, 5, 6]; using var actual = new Mat(); Cv2.TransposeRef(InputArrayRef.Create(a), actual); + using var src = Mat.FromPixelData(6, 1, MatType.CV_64FC1, a); using var expected = new Mat(); - using var classInputArray = InputArray.Create(a); - Cv2.Transpose(classInputArray, expected); + Cv2.TransposeRef(src, expected); ImageEquals(expected, actual); } From 22fcccc53e8e7b4a593ac9109df97c7db1c2079a Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:23:19 +0900 Subject: [PATCH 10/29] Migration: Cv2_core.cs linear algebra ops (CompleteSymm/SetIdentity/Determinant/Trace/Invert/Solve/SolveLP/Sort/SortIdx) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes SolveEquationTest.ByNormalArray, which explicitly built InputArray/ OutputArray via Create(...) rather than relying on an implicit conversion. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 149 +++++------------- .../core/SolveEquationTest.cs | 6 +- 2 files changed, 46 insertions(+), 109 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index d1000c102..8dd5eba25 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -1643,71 +1643,53 @@ public static Point3d[] PerspectiveTransform(IEnumerable src, Mat m) /// If true, the lower half is copied to the upper half, /// otherwise the upper half is copied to the lower half // ReSharper disable once IdentifierTypo - public static void CompleteSymm(InputOutputArray mtx, bool lowerToUpper = false) + public static void CompleteSymm(InputOutputArrayRef mtx, bool lowerToUpper = false) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - mtx.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_completeSymm(mtx.ToInputOutputProxy(), lowerToUpper ? 1 : 0)); + NativeMethods.core_completeSymm(mtx.Proxy, lowerToUpper ? 1 : 0)); - GC.KeepAlive(mtx); - mtx.Fix(); + GC.KeepAlive(mtx.Source); } - + /// /// initializes scaled identity matrix /// /// The matrix to initialize (not necessarily square) /// The value to assign to the diagonal elements - public static void SetIdentity(InputOutputArray mtx, Scalar? s = null) + public static void SetIdentity(InputOutputArrayRef mtx, Scalar? s = null) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - mtx.ThrowIfNotReady(); - var s0 = s.GetValueOrDefault(new Scalar(1)); NativeMethods.HandleException( - NativeMethods.core_setIdentity(mtx.ToInputOutputProxy(), s0)); + NativeMethods.core_setIdentity(mtx.Proxy, s0)); - GC.KeepAlive(mtx); - mtx.Fix(); + GC.KeepAlive(mtx.Source); } - + /// /// computes determinant of a square matrix /// /// The input matrix; must have CV_32FC1 or CV_64FC1 type and square size /// determinant of the specified matrix. - public static double Determinant(InputArray mtx) + public static double Determinant(InputArrayRef mtx) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - mtx.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_determinant(mtx.ToInputProxy(), out var ret)); + NativeMethods.core_determinant(mtx.Proxy, out var ret)); - GC.KeepAlive(mtx); + GC.KeepAlive(mtx.Source); return ret; } - + /// /// computes trace of a matrix /// /// The source matrix /// - public static Scalar Trace(InputArray mtx) + public static Scalar Trace(InputArrayRef mtx) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - mtx.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_trace(mtx.ToInputProxy(), out var ret)); + NativeMethods.core_trace(mtx.Proxy, out var ret)); - GC.KeepAlive(mtx); + GC.KeepAlive(mtx.Source); return ret; } @@ -1718,25 +1700,17 @@ public static Scalar Trace(InputArray mtx) /// The destination matrix; will have NxM size and the same type as src /// The inversion method /// - public static double Invert(InputArray src, OutputArray dst, + public static double Invert(InputArrayRef src, OutputArrayRef dst, DecompTypes flags = DecompTypes.LU) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_invert(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags, out var ret)); + NativeMethods.core_invert(src.Proxy, dst.Proxy, (int) flags, out var ret)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return ret; } - + /// /// solves linear system or a least-square problem /// @@ -1745,84 +1719,55 @@ public static double Invert(InputArray src, OutputArray dst, /// /// /// - public static bool Solve(InputArray src1, InputArray src2, OutputArray dst, + public static bool Solve(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, DecompTypes flags = DecompTypes.LU) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_solve(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), (int) flags, out var ret)); + NativeMethods.core_solve(src1.Proxy, src2.Proxy, dst.Proxy, (int) flags, out var ret)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); return ret != 0; } - + /// /// Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). /// - /// This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). + /// This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). /// It should contain 32- or 64-bit floating point numbers.As a convenience, column-vector may be also submitted, /// in the latter case it is understood to correspond to \f$c^T\f$. - /// `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above + /// `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above /// and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers. - /// The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the + /// The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the /// formulation above.It will contain 64-bit floating point numbers. /// // ReSharper disable once InconsistentNaming // ReSharper disable once IdentifierTypo - public static SolveLPResult SolveLP(InputArray func, InputArray constr, OutputArray z) + public static SolveLPResult SolveLP(InputArrayRef func, InputArrayRef constr, OutputArrayRef z) { - if (func is null) - throw new ArgumentNullException(nameof(func)); - if (constr is null) - throw new ArgumentNullException(nameof(constr)); - if (z is null) - throw new ArgumentNullException(nameof(z)); - func.ThrowIfDisposed(); - constr.ThrowIfDisposed(); - z.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_solveLP(func.ToInputProxy(), constr.ToInputProxy(), z.ToOutputProxy(), out var ret)); + NativeMethods.core_solveLP(func.Proxy, constr.Proxy, z.Proxy, out var ret)); - GC.KeepAlive(func); - GC.KeepAlive(constr); - z.Fix(); + GC.KeepAlive(func.Source); + GC.KeepAlive(constr.Source); + GC.KeepAlive(z.Source); return (SolveLPResult) ret; } - + /// /// sorts independently each matrix row or each matrix column /// /// The source single-channel array /// The destination array of the same size and the same type as src /// The operation flags, a combination of the SortFlag values - public static void Sort(InputArray src, OutputArray dst, SortFlags flags) + public static void Sort(InputArrayRef src, OutputArrayRef dst, SortFlags flags) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_sort(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags)); + NativeMethods.core_sort(src.Proxy, dst.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1831,21 +1776,13 @@ public static void Sort(InputArray src, OutputArray dst, SortFlags flags) /// The source single-channel array /// The destination integer array of the same size as src /// The operation flags, a combination of SortFlag values - public static void SortIdx(InputArray src, OutputArray dst, SortFlags flags) + public static void SortIdx(InputArrayRef src, OutputArrayRef dst, SortFlags flags) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_sortIdx(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags)); + NativeMethods.core_sortIdx(src.Proxy, dst.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// diff --git a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs index e99ccb3ed..183a0b87d 100644 --- a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs +++ b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs @@ -50,9 +50,9 @@ public void ByNormalArray() using var x = new Mat(); - using var ia = InputArray.Create(a); - using var iy = InputArray.Create(y); - using var ox = OutputArray.Create(x); + var ia = InputArrayRef.Create(a); + var iy = InputArrayRef.Create(y); + var ox = OutputArrayRef.Create(x); Cv2.Solve(ia, iy, ox, DecompTypes.LU); testOutputHelper.WriteLine("X1 = {0}, X2 = {1}", x.At(0), x.At(1)); From 07cfbb9720aebe4ac0afdae10ad1cd81ae4eb5a2 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:26:14 +0900 Subject: [PATCH 11/29] Migration: Cv2_core.cs polynomial/eigen/covariance/PCA ops (SolveCubic/SolvePoly/Eigen/EigenNonSymmetric/CalcCovarMatrix/PCACompute/PCAComputeVar) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 192 +++++++++----------------------- 1 file changed, 52 insertions(+), 140 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 8dd5eba25..9a0e09333 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -1791,21 +1791,13 @@ public static void SortIdx(InputArrayRef src, OutputArrayRef dst, SortFlags flag /// The equation coefficients, an array of 3 or 4 elements /// The destination array of real roots which will have 1 or 3 elements /// - public static int SolveCubic(InputArray coeffs, OutputArray roots) + public static int SolveCubic(InputArrayRef coeffs, OutputArrayRef roots) { - if (coeffs is null) - throw new ArgumentNullException(nameof(coeffs)); - if (roots is null) - throw new ArgumentNullException(nameof(roots)); - coeffs.ThrowIfDisposed(); - roots.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_solveCubic(coeffs.ToInputProxy(), roots.ToOutputProxy(), out var ret)); + NativeMethods.core_solveCubic(coeffs.Proxy, roots.Proxy, out var ret)); - GC.KeepAlive(coeffs); - GC.KeepAlive(roots); - roots.Fix(); + GC.KeepAlive(coeffs.Source); + GC.KeepAlive(roots.Source); return ret; } @@ -1816,55 +1808,35 @@ public static int SolveCubic(InputArray coeffs, OutputArray roots) /// The destination (complex) array of roots /// The maximum number of iterations the algorithm does /// - public static double SolvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300) + public static double SolvePoly(InputArrayRef coeffs, OutputArrayRef roots, int maxIters = 300) { - if (coeffs is null) - throw new ArgumentNullException(nameof(coeffs)); - if (roots is null) - throw new ArgumentNullException(nameof(roots)); - coeffs.ThrowIfDisposed(); - roots.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_solvePoly(coeffs.ToInputProxy(), roots.ToOutputProxy(), maxIters, out var ret)); + NativeMethods.core_solvePoly(coeffs.Proxy, roots.Proxy, maxIters, out var ret)); - GC.KeepAlive(coeffs); - GC.KeepAlive(roots); - roots.Fix(); + GC.KeepAlive(coeffs.Source); + GC.KeepAlive(roots.Source); return ret; } - + /// /// Computes eigenvalues and eigenvectors of a symmetric matrix. /// - /// The input matrix; must have CV_32FC1 or CV_64FC1 type, + /// The input matrix; must have CV_32FC1 or CV_64FC1 type, /// square size and be symmetric: src^T == src - /// The output vector of eigenvalues of the same type as src; + /// The output vector of eigenvalues of the same type as src; /// The eigenvalues are stored in the descending order. - /// The output matrix of eigenvectors; - /// It will have the same size and the same type as src; The eigenvectors are stored + /// The output matrix of eigenvectors; + /// It will have the same size and the same type as src; The eigenvectors are stored /// as subsequent matrix rows, in the same order as the corresponding eigenvalues /// - public static bool Eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors) + public static bool Eigen(InputArrayRef src, OutputArrayRef eigenvalues, OutputArrayRef eigenvectors) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (eigenvalues is null) - throw new ArgumentNullException(nameof(eigenvalues)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - src.ThrowIfDisposed(); - eigenvalues.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_eigen(src.ToInputProxy(), eigenvalues.ToOutputProxy(), eigenvectors.ToOutputProxy(), out var ret)); + NativeMethods.core_eigen(src.Proxy, eigenvalues.Proxy, eigenvectors.Proxy, out var ret)); - eigenvalues.Fix(); - eigenvectors.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(eigenvalues); - GC.KeepAlive(eigenvectors); + GC.KeepAlive(src.Source); + GC.KeepAlive(eigenvalues.Source); + GC.KeepAlive(eigenvectors.Source); return ret != 0; } @@ -1874,29 +1846,16 @@ public static bool Eigen(InputArray src, OutputArray eigenvalues, OutputArray ei /// input matrix (CV_32FC1 or CV_64FC1 type). /// output vector of eigenvalues (type is the same type as src). /// output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. - public static void EigenNonSymmetric(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors) + public static void EigenNonSymmetric(InputArrayRef src, OutputArrayRef eigenvalues, OutputArrayRef eigenvectors) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (eigenvalues is null) - throw new ArgumentNullException(nameof(eigenvalues)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - src.ThrowIfDisposed(); - eigenvalues.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_eigenNonSymmetric(src.ToInputProxy(), eigenvalues.ToOutputProxy(), eigenvectors.ToOutputProxy())); + NativeMethods.core_eigenNonSymmetric(src.Proxy, eigenvalues.Proxy, eigenvectors.Proxy)); - eigenvalues.Fix(); - eigenvectors.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(eigenvalues); - GC.KeepAlive(eigenvectors); + GC.KeepAlive(src.Source); + GC.KeepAlive(eigenvalues.Source); + GC.KeepAlive(eigenvectors.Source); } - /// /// computes covariation matrix of a set of samples /// @@ -1941,32 +1900,20 @@ public static void CalcCovarMatrix( /// operation flags - see CovarFlags. /// type of the matrixl; it equals 'CV_64F' by default. public static void CalcCovarMatrix( - InputArray samples, OutputArray covar, - InputOutputArray mean, CovarFlags flags, MatType? ctype = null) + InputArrayRef samples, OutputArrayRef covar, + InputOutputArrayRef mean, CovarFlags flags, MatType? ctype = null) { - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - if (covar is null) - throw new ArgumentNullException(nameof(covar)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - samples.ThrowIfDisposed(); - covar.ThrowIfNotReady(); - mean.ThrowIfNotReady(); - var ctypeValue = ctype.GetValueOrDefault(MatType.CV_64F); NativeMethods.HandleException( - NativeMethods.core_calcCovarMatrix_InputArray(samples.ToInputProxy(), covar.ToOutputProxy(), mean.ToInputOutputProxy(), (int) flags, ctypeValue.Value)); + NativeMethods.core_calcCovarMatrix_InputArray(samples.Proxy, covar.Proxy, mean.Proxy, (int) flags, ctypeValue.Value)); - GC.KeepAlive(samples); - GC.KeepAlive(covar); - GC.KeepAlive(mean); - covar.Fix(); - mean.Fix(); + GC.KeepAlive(samples.Source); + GC.KeepAlive(covar.Source); + GC.KeepAlive(mean.Source); } - + /// - /// PCA of the supplied dataset. + /// PCA of the supplied dataset. /// /// input samples stored as the matrix rows or as the matrix columns. /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @@ -1974,29 +1921,19 @@ public static void CalcCovarMatrix( /// Number of components that PCA should /// retain; by default, all the components are retained. public static void PCACompute( - InputArray data, InputOutputArray mean, - OutputArray eigenvectors, int maxComponents = 0) + InputArrayRef data, InputOutputArrayRef mean, + OutputArrayRef eigenvectors, int maxComponents = 0) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - data.ThrowIfDisposed(); - mean.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCACompute(data.ToInputProxy(), mean.ToInputOutputProxy(), eigenvectors.ToOutputProxy(), maxComponents)); + NativeMethods.core_PCACompute(data.Proxy, mean.Proxy, eigenvectors.Proxy, maxComponents)); - GC.KeepAlive(data); - mean.Fix(); - eigenvectors.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); } /// - /// PCA of the supplied dataset. + /// PCA of the supplied dataset. /// /// input samples stored as the matrix rows or as the matrix columns. /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @@ -2005,33 +1942,20 @@ public static void PCACompute( /// Number of components that PCA should /// retain; by default, all the components are retained. public static void PCACompute( - InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, int maxComponents = 0) + InputArrayRef data, InputOutputArrayRef mean, + OutputArrayRef eigenvectors, OutputArrayRef eigenvalues, int maxComponents = 0) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - if (eigenvalues is null) - throw new ArgumentNullException(nameof(eigenvalues)); - data.ThrowIfDisposed(); - mean.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - eigenvalues.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCACompute2(data.ToInputProxy(), mean.ToInputOutputProxy(), eigenvectors.ToOutputProxy(), eigenvalues.ToOutputProxy(), maxComponents)); + NativeMethods.core_PCACompute2(data.Proxy, mean.Proxy, eigenvectors.Proxy, eigenvalues.Proxy, maxComponents)); - GC.KeepAlive(data); - mean.Fix(); - eigenvectors.Fix(); - eigenvalues.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); + GC.KeepAlive(eigenvalues.Source); } /// - /// PCA of the supplied dataset. + /// PCA of the supplied dataset. /// /// input samples stored as the matrix rows or as the matrix columns. /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. @@ -2039,27 +1963,15 @@ public static void PCACompute( /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. public static void PCAComputeVar( - InputArray data, InputOutputArray mean, - OutputArray eigenvectors, double retainedVariance) + InputArrayRef data, InputOutputArrayRef mean, + OutputArrayRef eigenvectors, double retainedVariance) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - data.ThrowIfDisposed(); - mean.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCAComputeVar(data.ToInputProxy(), mean.ToInputOutputProxy(), eigenvectors.ToOutputProxy(), retainedVariance)); + NativeMethods.core_PCAComputeVar(data.Proxy, mean.Proxy, eigenvectors.Proxy, retainedVariance)); - GC.KeepAlive(data); - GC.KeepAlive(mean); - GC.KeepAlive(eigenvectors); - mean.Fix(); - eigenvectors.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); } /// From 2dfb851e7303c0262f7188c5e61a1fdb55688cb0 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:29:25 +0900 Subject: [PATCH 12/29] Migration: Cv2_core.cs PCA project/SVD/Mahalanobis/DFT/DCT ops (PCAProject/PCABackProject/SVDecomp/SVBackSubst/Mahalanobis/Dft/Idft/Dct/Idct) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 235 +++++++++----------------------- 1 file changed, 66 insertions(+), 169 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 9a0e09333..fc696f678 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -2016,30 +2016,16 @@ public static void PCAComputeVar( /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. /// eigenvectors of the covariation matrix /// output vectors - public static void PCAProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result) + public static void PCAProject(InputArrayRef data, InputArrayRef mean, + InputArrayRef eigenvectors, OutputArrayRef result) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); - eigenvectors.ThrowIfDisposed(); - result.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCAProject(data.ToInputProxy(), mean.ToInputProxy(), eigenvectors.ToInputProxy(), result.ToOutputProxy())); + NativeMethods.core_PCAProject(data.Proxy, mean.Proxy, eigenvectors.Proxy, result.Proxy)); - GC.KeepAlive(data); - GC.KeepAlive(mean); - GC.KeepAlive(eigenvectors); - GC.KeepAlive(result); - result.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); + GC.KeepAlive(result.Source); } /// @@ -2049,30 +2035,16 @@ public static void PCAProject(InputArray data, InputArray mean, /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. /// eigenvectors of the covariation matrix /// output vectors - public static void PCABackProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result) + public static void PCABackProject(InputArrayRef data, InputArrayRef mean, + InputArrayRef eigenvectors, OutputArrayRef result) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); - eigenvectors.ThrowIfDisposed(); - result.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCABackProject(data.ToInputProxy(), mean.ToInputProxy(), eigenvectors.ToInputProxy(), result.ToOutputProxy())); + NativeMethods.core_PCABackProject(data.Proxy, mean.Proxy, eigenvectors.Proxy, result.Proxy)); - GC.KeepAlive(data); - GC.KeepAlive(mean); - GC.KeepAlive(eigenvectors); - GC.KeepAlive(result); - result.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); + GC.KeepAlive(result.Source); } /// @@ -2086,32 +2058,16 @@ public static void PCABackProject(InputArray data, InputArray mean, // ReSharper disable once InconsistentNaming // ReSharper disable once IdentifierTypo public static void SVDecomp( - InputArray src, OutputArray w, - OutputArray u, OutputArray vt, SVD.Flags flags = SVD.Flags.None) + InputArrayRef src, OutputArrayRef w, + OutputArrayRef u, OutputArrayRef vt, SVD.Flags flags = SVD.Flags.None) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (u is null) - throw new ArgumentNullException(nameof(u)); - if (vt is null) - throw new ArgumentNullException(nameof(vt)); - src.ThrowIfDisposed(); - w.ThrowIfNotReady(); - u.ThrowIfNotReady(); - vt.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_SVDecomp(src.ToInputProxy(), w.ToOutputProxy(), u.ToOutputProxy(), vt.ToOutputProxy(), (int) flags)); + NativeMethods.core_SVDecomp(src.Proxy, w.Proxy, u.Proxy, vt.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(w); - GC.KeepAlive(u); - GC.KeepAlive(vt); - w.Fix(); - u.Fix(); - vt.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(w.Source); + GC.KeepAlive(u.Source); + GC.KeepAlive(vt.Source); } /// @@ -2124,36 +2080,19 @@ public static void SVDecomp( /// output // ReSharper disable once InconsistentNaming public static void SVBackSubst( - InputArray w, InputArray u, InputArray vt, - InputArray rhs, OutputArray dst) - { - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (u is null) - throw new ArgumentNullException(nameof(u)); - if (vt is null) - throw new ArgumentNullException(nameof(vt)); - if (rhs is null) - throw new ArgumentNullException(nameof(rhs)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - w.ThrowIfDisposed(); - u.ThrowIfDisposed(); - vt.ThrowIfDisposed(); - rhs.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - + InputArrayRef w, InputArrayRef u, InputArrayRef vt, + InputArrayRef rhs, OutputArrayRef dst) + { NativeMethods.HandleException( - NativeMethods.core_SVBackSubst(w.ToInputProxy(), u.ToInputProxy(), vt.ToInputProxy(), rhs.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_SVBackSubst(w.Proxy, u.Proxy, vt.Proxy, rhs.Proxy, dst.Proxy)); - GC.KeepAlive(w); - GC.KeepAlive(u); - GC.KeepAlive(vt); - GC.KeepAlive(rhs); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(w.Source); + GC.KeepAlive(u.Source); + GC.KeepAlive(vt.Source); + GC.KeepAlive(rhs.Source); + GC.KeepAlive(dst.Source); } - + /// /// Calculates the Mahalanobis distance between two vectors. /// @@ -2161,54 +2100,36 @@ public static void SVBackSubst( /// second 1D input vector. /// inverse covariance matrix. /// - public static double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar) - { - if (v1 is null) - throw new ArgumentNullException(nameof(v1)); - if (v2 is null) - throw new ArgumentNullException(nameof(v2)); - if (icovar is null) - throw new ArgumentNullException(nameof(icovar)); - v1.ThrowIfDisposed(); - v2.ThrowIfDisposed(); - icovar.ThrowIfDisposed(); - - NativeMethods.HandleException( - NativeMethods.core_Mahalanobis(v1.ToInputProxy(), v2.ToInputProxy(), icovar.ToInputProxy(), out var ret)); - - GC.KeepAlive(v1); - GC.KeepAlive(v2); - GC.KeepAlive(icovar); + public static double Mahalanobis(InputArrayRef v1, InputArrayRef v2, InputArrayRef icovar) + { + NativeMethods.HandleException( + NativeMethods.core_Mahalanobis(v1.Proxy, v2.Proxy, icovar.Proxy, out var ret)); + + GC.KeepAlive(v1.Source); + GC.KeepAlive(v2.Source); + GC.KeepAlive(icovar.Source); return ret; } - + /// /// Performs a forward Discrete Fourier transform of 1D or 2D floating-point array. /// /// The source array, real or complex /// The destination array, which size and type depends on the flags /// Transformation flags, a combination of the DftFlag2 values - /// When the parameter != 0, the function assumes that - /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) - /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, - /// thus the function can handle the rest of the rows more efficiently and - /// thus save some time. This technique is very useful for computing array cross-correlation + /// When the parameter != 0, the function assumes that + /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) + /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, + /// thus the function can handle the rest of the rows more efficiently and + /// thus save some time. This technique is very useful for computing array cross-correlation /// or convolution using DFT - public static void Dft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + public static void Dft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_dft(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags, nonzeroRows)); + NativeMethods.core_dft(src.Proxy, dst.Proxy, (int) flags, nonzeroRows)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2217,27 +2138,19 @@ public static void Dft(InputArray src, OutputArray dst, DftFlags flags = DftFlag /// The source array, real or complex /// The destination array, which size and type depends on the flags /// Transformation flags, a combination of the DftFlag2 values - /// When the parameter != 0, the function assumes that - /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) - /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, - /// thus the function can handle the rest of the rows more efficiently and - /// thus save some time. This technique is very useful for computing array cross-correlation + /// When the parameter != 0, the function assumes that + /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) + /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, + /// thus the function can handle the rest of the rows more efficiently and + /// thus save some time. This technique is very useful for computing array cross-correlation /// or convolution using DFT - public static void Idft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + public static void Idft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_idft(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags, nonzeroRows)); + NativeMethods.core_idft(src.Proxy, dst.Proxy, (int) flags, nonzeroRows)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2246,21 +2159,13 @@ public static void Idft(InputArray src, OutputArray dst, DftFlags flags = DftFla /// The source floating-point array /// The destination array; will have the same size and same type as src /// Transformation flags, a combination of DctFlag2 values - public static void Dct(InputArray src, OutputArray dst, DctFlags flags = DctFlags.None) + public static void Dct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = DctFlags.None) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_dct(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags)); + NativeMethods.core_dct(src.Proxy, dst.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2269,21 +2174,13 @@ public static void Dct(InputArray src, OutputArray dst, DctFlags flags = DctFlag /// The source floating-point array /// The destination array; will have the same size and same type as src /// Transformation flags, a combination of DctFlag2 values - public static void Idct(InputArray src, OutputArray dst, DctFlags flags = DctFlags.None) + public static void Idct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = DctFlags.None) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_idct(src.ToInputProxy(), dst.ToOutputProxy(), (int) flags)); + NativeMethods.core_idct(src.Proxy, dst.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// From a5b7b9c453e964b87600b78b48f0cceb267d57b6 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:33:07 +0900 Subject: [PATCH 13/29] Migration: Cv2_core.cs spectrum/random/kmeans ops (MulSpectrums/Randu/Randn/RandShuffle/Kmeans) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the #region core.hpp block in Cv2_core.cs. Fixes the Mat_CvMethods.cs Randu/Randn instance wrappers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 140 +++++------------- .../Modules/core/Mat/Mat_CvMethods.cs | 4 +- 2 files changed, 41 insertions(+), 103 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index fc696f678..bc2d23597 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -2193,26 +2193,15 @@ public static void Idct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = /// each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. /// optional flag that conjugates the second input array before the multiplication (true) or not (false). public static void MulSpectrums( - InputArray a, InputArray b, OutputArray c, + InputArrayRef a, InputArrayRef b, OutputArrayRef c, DftFlags flags, bool conjB = false) { - if (a is null) - throw new ArgumentNullException(nameof(a)); - if (b is null) - throw new ArgumentNullException(nameof(b)); - if (c is null) - throw new ArgumentNullException(nameof(c)); - a.ThrowIfDisposed(); - b.ThrowIfDisposed(); - c.ThrowIfNotReady(); - - NativeMethods.HandleException( - NativeMethods.core_mulSpectrums(a.ToInputProxy(), b.ToInputProxy(), c.ToOutputProxy(), (int) flags, conjB ? 1 : 0)); + NativeMethods.HandleException( + NativeMethods.core_mulSpectrums(a.Proxy, b.Proxy, c.Proxy, (int) flags, conjB ? 1 : 0)); - GC.KeepAlive(a); - GC.KeepAlive(b); - GC.KeepAlive(c); - c.Fix(); + GC.KeepAlive(a.Source); + GC.KeepAlive(b.Source); + GC.KeepAlive(c.Source); } /// @@ -2257,114 +2246,77 @@ public static RNG SetTheRNG(ulong state) /// The array must be pre-allocated and have 1 to 4 channels /// The inclusive lower boundary of the generated random numbers /// The exclusive upper boundary of the generated random numbers - public static void Randu(InputOutputArray dst, InputArray low, InputArray high) + public static void Randu(InputOutputArrayRef dst, InputArrayRef low, InputArrayRef high) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (low is null) - throw new ArgumentNullException(nameof(low)); - if (high is null) - throw new ArgumentNullException(nameof(high)); - dst.ThrowIfNotReady(); - low.ThrowIfDisposed(); - high.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_randu_InputArray(dst.ToInputOutputProxy(), low.ToInputProxy(), high.ToInputProxy())); + NativeMethods.core_randu_InputArray(dst.Proxy, low.Proxy, high.Proxy)); - GC.KeepAlive(dst); - GC.KeepAlive(low); - GC.KeepAlive(high); - dst.Fix(); + GC.KeepAlive(dst.Source); + GC.KeepAlive(low.Source); + GC.KeepAlive(high.Source); } /// /// fills array with uniformly-distributed random numbers from the range [low, high) /// - /// The output array of random numbers. + /// The output array of random numbers. /// The array must be pre-allocated and have 1 to 4 channels /// The inclusive lower boundary of the generated random numbers /// The exclusive upper boundary of the generated random numbers // ReSharper disable once IdentifierTypo - public static void Randu(InputOutputArray dst, Scalar low, Scalar high) + public static void Randu(InputOutputArrayRef dst, Scalar low, Scalar high) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_randu_Scalar(dst.ToInputOutputProxy(), low, high)); + NativeMethods.core_randu_Scalar(dst.Proxy, low, high)); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// /// fills array with normally-distributed random numbers with the specified mean and the standard deviation /// - /// The output array of random numbers. + /// The output array of random numbers. /// The array must be pre-allocated and have 1 to 4 channels /// The mean value (expectation) of the generated random numbers /// The standard deviation of the generated random numbers // ReSharper disable once IdentifierTypo - public static void Randn(InputOutputArray dst, InputArray mean, InputArray stddev) + public static void Randn(InputOutputArrayRef dst, InputArrayRef mean, InputArrayRef stddev) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (stddev is null) - throw new ArgumentNullException(nameof(stddev)); - dst.ThrowIfNotReady(); - mean.ThrowIfDisposed(); - stddev.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_randn_InputArray(dst.ToInputOutputProxy(), mean.ToInputProxy(), stddev.ToInputProxy())); + NativeMethods.core_randn_InputArray(dst.Proxy, mean.Proxy, stddev.Proxy)); - GC.KeepAlive(dst); - GC.KeepAlive(mean); - GC.KeepAlive(stddev); - dst.Fix(); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(stddev.Source); } /// /// fills array with normally-distributed random numbers with the specified mean and the standard deviation /// - /// The output array of random numbers. + /// The output array of random numbers. /// The array must be pre-allocated and have 1 to 4 channels /// The mean value (expectation) of the generated random numbers /// The standard deviation of the generated random numbers - public static void Randn(InputOutputArray dst, Scalar mean, Scalar stddev) + public static void Randn(InputOutputArrayRef dst, Scalar mean, Scalar stddev) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_randn_Scalar(dst.ToInputOutputProxy(), mean, stddev)); + NativeMethods.core_randn_Scalar(dst.Proxy, mean, stddev)); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } - + /// /// shuffles the input array elements /// /// The input/output numerical 1D array /// The scale factor that determines the number of random swap operations. // ReSharper disable once IdentifierTypo - public static void RandShuffle(InputOutputArray dst, double iterFactor) + public static void RandShuffle(InputOutputArrayRef dst, double iterFactor) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_randShuffle(dst.ToInputOutputProxy(), iterFactor, IntPtr.Zero)); + NativeMethods.core_randShuffle(dst.Proxy, iterFactor, IntPtr.Zero)); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// @@ -2372,22 +2324,17 @@ public static void RandShuffle(InputOutputArray dst, double iterFactor) /// /// The input/output numerical 1D array /// The scale factor that determines the number of random swap operations. - /// The optional random number generator used for shuffling. + /// The optional random number generator used for shuffling. /// If it is null, theRng() is used instead. // ReSharper disable once IdentifierTypo - public static void RandShuffle(InputOutputArray dst, double iterFactor, ref RNG rng) + public static void RandShuffle(InputOutputArrayRef dst, double iterFactor, ref RNG rng) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); - var state = rng.State; NativeMethods.HandleException( - NativeMethods.core_randShuffle(dst.ToInputOutputProxy(), iterFactor, ref state)); + NativeMethods.core_randShuffle(dst.Proxy, iterFactor, ref state)); rng = new RNG(state); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// @@ -2409,25 +2356,16 @@ public static void RandShuffle(InputOutputArray dst, double iterFactor, ref RNG /// value are returned by the function. Basically, you can use only the core of the function, /// set the number of attempts to 1, initialize labels each time using a custom algorithm, /// pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. - public static double Kmeans(InputArray data, int k, InputOutputArray bestLabels, - TermCriteria criteria, int attempts, KMeansFlags flags, OutputArray? centers = null) + public static double Kmeans(InputArrayRef data, int k, InputOutputArrayRef bestLabels, + TermCriteria criteria, int attempts, KMeansFlags flags, OutputArrayRef centers = default) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (bestLabels is null) - throw new ArgumentNullException(nameof(bestLabels)); - data.ThrowIfDisposed(); - bestLabels.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.core_kmeans( - data.ToInputProxy(), k, bestLabels.ToInputOutputProxy(), criteria, attempts, (int) flags, centers?.ToOutputProxy() ?? default, out var ret)); + data.Proxy, k, bestLabels.Proxy, criteria, attempts, (int) flags, centers.Proxy, out var ret)); - bestLabels.Fix(); - centers?.Fix(); - GC.KeepAlive(data); - GC.KeepAlive(bestLabels); - GC.KeepAlive(centers); + GC.KeepAlive(data.Source); + GC.KeepAlive(bestLabels.Source); + GC.KeepAlive(centers.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 7fd244e97..49dbaf710 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -577,7 +577,7 @@ public Mat Idct(DctFlags flags = 0) /// /// The inclusive lower boundary of the generated random numbers /// The exclusive upper boundary of the generated random numbers - public void Randu(InputArray low, InputArray high) + public void Randu(InputArrayRef low, InputArrayRef high) { Cv2.Randu(this, low, high); } @@ -597,7 +597,7 @@ public void Randu(Scalar low, Scalar high) /// /// The mean value (expectation) of the generated random numbers /// The standard deviation of the generated random numbers - public void Randn(InputArray mean, InputArray stddev) + public void Randn(InputArrayRef mean, InputArrayRef stddev) { Cv2.Randn(this, mean, stddev); } From e31afd52ddba4a4a4f8fc582096a88bc12b58b00 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 16:57:50 +0900 Subject: [PATCH 14/29] Migration: Cv2_core.cs remaining stragglers (Sum/CountNonZero/FindNonZero/Mean/Sqrt/PCAComputeVar overload/Format) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the InputArrayRef/OutputArrayRef/InputOutputArrayRef conversion of Cv2_core.cs - these were missed by earlier batches (out of file order or in a second overload). Fixes the Mat.Mean(InputArray?) instance wrapper. Verified: zero remaining InputArray/OutputArray/InputOutputArray parameter declarations in Cv2_core.cs (only native extern function names containing those substrings remain, e.g. core_meanStdDev_OutputArray). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5 --- src/OpenCvSharp/Cv2/Cv2_core.cs | 102 +++++------------- .../Modules/core/Mat/Mat_CvMethods.cs | 2 +- 2 files changed, 30 insertions(+), 74 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index bc2d23597..86e8b419e 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -298,34 +298,26 @@ public static void LUT(InputArrayRef src, byte[] lut, OutputArrayRef dst) /// /// The source array; must have 1 to 4 channels /// - public static Scalar Sum(InputArray src) + public static Scalar Sum(InputArrayRef src) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_sum(src.ToInputProxy(), out var ret)); + NativeMethods.core_sum(src.Proxy, out var ret)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); return ret; } - + /// /// computes the number of nonzero array elements /// /// Single-channel array /// number of non-zero elements in mtx - public static int CountNonZero(InputArray mtx) + public static int CountNonZero(InputArrayRef mtx) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - mtx.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_countNonZero(mtx.ToInputProxy(), out var ret)); + NativeMethods.core_countNonZero(mtx.Proxy, out var ret)); - GC.KeepAlive(mtx); + GC.KeepAlive(mtx.Source); return ret; } @@ -334,21 +326,13 @@ public static int CountNonZero(InputArray mtx) /// /// /// - public static void FindNonZero(InputArray src, OutputArray idx) + public static void FindNonZero(InputArrayRef src, OutputArrayRef idx) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (idx is null) - throw new ArgumentNullException(nameof(idx)); - src.ThrowIfDisposed(); - idx.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_findNonZero(src.ToInputProxy(), idx.ToOutputProxy())); + NativeMethods.core_findNonZero(src.Proxy, idx.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(idx); - idx.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(idx.Source); } /// @@ -358,17 +342,13 @@ public static void FindNonZero(InputArray src, OutputArray idx) /// (so that the result can be stored in Scalar) /// The optional operation mask /// - public static Scalar Mean(InputArray src, InputArray? mask = null) + public static Scalar Mean(InputArrayRef src, InputArrayRef mask = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_mean(src.ToInputProxy(), mask?.ToInputProxy() ?? default, out var ret)); + NativeMethods.core_mean(src.Proxy, mask.Proxy, out var ret)); - GC.KeepAlive(src); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); return ret; } @@ -1260,21 +1240,13 @@ public static void Max(Mat src1, double src2, Mat dst) /// /// The source floating-point array /// The destination array; will have the same size and the same type as src - public static void Sqrt(InputArray src, OutputArray dst) + public static void Sqrt(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_sqrt(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.core_sqrt(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1984,29 +1956,16 @@ public static void PCAComputeVar( /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. public static void PCAComputeVar( - InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, double retainedVariance) + InputArrayRef data, InputOutputArrayRef mean, + OutputArrayRef eigenvectors, OutputArrayRef eigenvalues, double retainedVariance) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (eigenvectors is null) - throw new ArgumentNullException(nameof(eigenvectors)); - if (eigenvalues is null) - throw new ArgumentNullException(nameof(eigenvalues)); - data.ThrowIfDisposed(); - mean.ThrowIfNotReady(); - eigenvectors.ThrowIfNotReady(); - eigenvalues.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.core_PCAComputeVar2(data.ToInputProxy(), mean.ToInputOutputProxy(), eigenvectors.ToOutputProxy(), eigenvalues.ToOutputProxy(), retainedVariance)); + NativeMethods.core_PCAComputeVar2(data.Proxy, mean.Proxy, eigenvectors.Proxy, eigenvalues.Proxy, retainedVariance)); - GC.KeepAlive(data); - mean.Fix(); - eigenvectors.Fix(); - eigenvalues.Fix(); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(eigenvectors.Source); + GC.KeepAlive(eigenvalues.Source); } /// @@ -2748,15 +2707,12 @@ public static bool SetBreakOnError(bool flag) /// /// /// - public static string Format(InputArray mtx, FormatType format = FormatType.Default) + public static string Format(InputArrayRef mtx, FormatType format = FormatType.Default) { - if (mtx is null) - throw new ArgumentNullException(nameof(mtx)); - using var buf = new StdString(); NativeMethods.HandleException( - NativeMethods.core_format(mtx.ToInputProxy(), (int) format, buf.CvPtr)); - GC.KeepAlive(mtx); + NativeMethods.core_format(mtx.Proxy, (int) format, buf.CvPtr)); + GC.KeepAlive(mtx.Source); return buf.ToString(); } diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs index 49dbaf710..7de1a0769 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -92,7 +92,7 @@ public Mat FindNonZero() /// /// The optional operation mask /// - public Scalar Mean(InputArray? mask = null) + public Scalar Mean(InputArrayRef mask = default) { return Cv2.Mean(this, mask); } From 7178945f9d75a832ff82478d96435a24286001bc Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 17:46:17 +0900 Subject: [PATCH 15/29] Migration: Mat.cs instance methods (CopyTo/ConvertTo/SetTo/Mul/Cross/Dot) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 11) Mul() captures the InputArrayRef's proxy/source by value before handing off to MatExpr.FromExpr's deferred delegate, since ref structs cannot be captured by a closure. --- src/OpenCvSharp/Modules/core/Mat/Mat.cs | 102 +++++++++--------------- test/OpenCvSharp.Tests/core/MatTest.cs | 2 +- 2 files changed, 39 insertions(+), 65 deletions(-) diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat.cs b/src/OpenCvSharp/Modules/core/Mat/Mat.cs index 67a4ec1a2..532ebd955 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat.cs @@ -1275,27 +1275,15 @@ public Mat Clone(Rect roi) /// /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(OutputArray m, InputArray? mask = null) + public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - if (mask is null) - { - NativeMethods.HandleException( - NativeMethods.core_Mat_copyTo1(Handle, m.ToOutputProxy())); - } - else - { - NativeMethods.HandleException( - NativeMethods.core_Mat_copyTo2(Handle, m.ToOutputProxy(), mask.ToInputProxy())); - } + NativeMethods.HandleException( + NativeMethods.core_Mat_copyTo2(Handle, m.Proxy, mask.Proxy)); - m.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(m.Source); + GC.KeepAlive(mask.Source); } /// @@ -1303,27 +1291,18 @@ public void CopyTo(OutputArray m, InputArray? mask = null) /// /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(Mat m, InputArray? mask = null) + public void CopyTo(Mat m, InputArrayRef mask = default) { ThrowIfDisposed(); if (m is null) throw new ArgumentNullException(nameof(m)); m.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); - if (mask is null) - { - NativeMethods.HandleException( - NativeMethods.core_Mat_copyTo_toMat1(Handle, m.CvPtr)); - } - else - { - NativeMethods.HandleException( - NativeMethods.core_Mat_copyTo_toMat2(Handle, m.CvPtr, mask.ToInputProxy())); - } + NativeMethods.HandleException( + NativeMethods.core_Mat_copyTo_toMat2(Handle, m.CvPtr, mask.Proxy)); GC.KeepAlive(m); - GC.KeepAlive(mask); + GC.KeepAlive(mask.Source); } /// @@ -1334,17 +1313,14 @@ public void CopyTo(Mat m, InputArray? mask = null) /// if rtype is negative, the output matrix will have the same type as the input. /// optional scale factor. /// optional delta added to the scaled values. - public void ConvertTo(OutputArray m, MatType rtype, double alpha = 1, double beta = 0) + public void ConvertTo(OutputArrayRef m, MatType rtype, double alpha = 1, double beta = 0) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_Mat_convertTo(Handle, m.ToOutputProxy(), rtype, alpha, beta)); + NativeMethods.core_Mat_convertTo(Handle, m.Proxy, rtype, alpha, beta)); - m.Fix(); + GC.KeepAlive(m.Source); } /// @@ -1388,18 +1364,15 @@ public Mat SetTo(Scalar value, Mat? mask = null) /// /// /// - public Mat SetTo(InputArray value, Mat? mask = null) + public Mat SetTo(InputArrayRef value, Mat? mask = null) { ThrowIfDisposed(); - if (value is null) - throw new ArgumentNullException(nameof(value)); - value.ThrowIfDisposed(); var maskPtr = Cv2.ToPtr(mask); NativeMethods.HandleException( - NativeMethods.core_Mat_setTo_InputArray(Handle, value.ToInputProxy(), maskPtr)); + NativeMethods.core_Mat_setTo_InputArray(Handle, value.Proxy, maskPtr)); - GC.KeepAlive(value); + GC.KeepAlive(value.Source); GC.KeepAlive(mask); return this; } @@ -1476,19 +1449,20 @@ public Mat Reshape(int cn, MatShape newShape) /// /// /// - public MatExpr Mul(InputArray m, double scale = 1) + public MatExpr Mul(InputArrayRef m, double scale = 1) { - if (m is null) - throw new ArgumentNullException(nameof(m)); + // MatExpr.FromExpr defers evaluation via a captured delegate, and ref structs cannot be + // captured by a closure — so the proxy and its keepalive source are captured by value instead. + var proxy = m.Proxy; + var source = m.Source; return MatExpr.FromExpr(() => { ThrowIfDisposed(); - m.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_Mat_mul(Handle, m.ToInputProxy(), scale, out var ret)); + NativeMethods.core_Mat_mul(Handle, proxy, scale, out var ret)); GC.KeepAlive(this); - GC.KeepAlive(m); + GC.KeepAlive(source); return new NativeMatExpr(ret); }); } @@ -1498,17 +1472,14 @@ public MatExpr Mul(InputArray m, double scale = 1) /// /// Another cross-product operand. /// - public Mat Cross(InputArray m) + public Mat Cross(InputArrayRef m) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_Mat_cross(Handle, m.ToInputProxy(), out var ret)); + NativeMethods.core_Mat_cross(Handle, m.Proxy, out var ret)); - GC.KeepAlive(m); + GC.KeepAlive(m.Source); var retVal = new Mat(ret); return retVal; } @@ -1518,17 +1489,14 @@ public Mat Cross(InputArray m) /// /// another dot-product operand. /// - public double Dot(InputArray m) + public double Dot(InputArrayRef m) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_Mat_dot(Handle, m.ToInputProxy(), out var ret)); + NativeMethods.core_Mat_dot(Handle, m.Proxy, out var ret)); - GC.KeepAlive(m); + GC.KeepAlive(m.Source); return ret; } @@ -3342,8 +3310,11 @@ public bool SetRectangularArray(T[,] data) /// Encodes an image into a memory buffer. /// Format-specific parameters. /// - public byte[] ToBytes(string ext = ".png", int[]? prms = null) - => ImEncode(ext, prms); + public byte[] ToBytes(string ext = ".png", int[]? prms = null) + { + Cv2.ImEncode(ext, this, out var buf, prms); + return buf; + } /// /// Encodes an image into a memory buffer. @@ -3351,8 +3322,11 @@ public byte[] ToBytes(string ext = ".png", int[]? prms = null) /// Encodes an image into a memory buffer. /// Format-specific parameters. /// - public byte[] ToBytes(string ext = ".png", params ImageEncodingParam[] prms) - => ImEncode(ext, prms); + public byte[] ToBytes(string ext = ".png", params ImageEncodingParam[] prms) + { + Cv2.ImEncode(ext, this, out var buf, prms); + return buf; + } /// /// Converts Mat to System.IO.MemoryStream diff --git a/test/OpenCvSharp.Tests/core/MatTest.cs b/test/OpenCvSharp.Tests/core/MatTest.cs index d05bf9de4..dae4567b5 100644 --- a/test/OpenCvSharp.Tests/core/MatTest.cs +++ b/test/OpenCvSharp.Tests/core/MatTest.cs @@ -239,7 +239,7 @@ public void CopyTo() using Mat mask = src.GreaterThan(128); src.CopyTo(dst, mask); ShowImagesWhenDebugMode(dst); - src.CopyTo(dst, null); + src.CopyTo(dst, default); ShowImagesWhenDebugMode(dst); } From 446c36b8e90bfb7292244342fd60ab00e2810510 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 17:46:55 +0900 Subject: [PATCH 16/29] Remove Mat_CvMethods.cs fluent Cv2 wrappers (Mat instance methods) These wrapped Cv2 static methods as Mat instance methods purely for chainable call syntax (e.g. mat.GaussianBlur(...).CvtColor(...)). The duplication doubled the maintenance surface of every Cv2 static method, and intermediate Mats produced mid-chain cannot be captured with `using`, so they leaked into non-deterministic GC-driven native cleanup -- the same class of problem InputArray/OutputArray ref-structification and the MatExpr lazy-tree rework were addressing elsewhere. Call sites now use Cv2.Xxx(...) directly. This is a breaking change for OpenCvSharp5. --- .../Modules/core/Mat/Mat_CvMethods.cs | 2313 ----------------- .../BitmapSourceConverterTest.cs | 24 +- test/OpenCvSharp.Tests/aruco/ArucoTest.cs | 6 +- .../core/MatExprParityTest.cs | 2 +- test/OpenCvSharp.Tests/core/MatTest.cs | 12 +- test/OpenCvSharp.Tests/dnn/ModelTest.cs | 2 +- test/OpenCvSharp.Tests/dnn/TensorflowTest.cs | 2 +- .../face/LBPHFaceRecognizerTest.cs | 3 +- .../img_hash/AverageHashTest.cs | 15 +- .../img_hash/BlockMeanHashTest.cs | 15 +- .../img_hash/ColorMomentHashTest.cs | 15 +- .../img_hash/MarrHildrethHashTest.cs | 15 +- test/OpenCvSharp.Tests/img_hash/PHashTest.cs | 15 +- .../img_hash/RadialVarianceHashTest.cs | 26 +- test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs | 20 +- test/OpenCvSharp.Tests/photo/PhotoTest.cs | 8 +- .../stitching/StitchingTest.cs | 8 +- .../text/TextDetectorTest.cs | 2 +- .../tracking/TrackerTestBase.cs | 3 +- test/OpenCvSharp.Tests/video/KalmanTest.cs | 2 +- .../ximgproc/StructuredEdgeDetectionTest.cs | 2 +- .../ximgproc/XimgProcTest.cs | 6 +- 22 files changed, 110 insertions(+), 2406 deletions(-) delete mode 100644 src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs deleted file mode 100644 index 7de1a0769..000000000 --- a/src/OpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs +++ /dev/null @@ -1,2313 +0,0 @@ -using OpenCvSharp.Internal.Vectors; - -namespace OpenCvSharp; - -partial class Mat -{ - #region core - - /// - /// Computes absolute value of each matrix element - /// - /// - public MatExpr Abs() - { - return Cv2.Abs(this); - } - - /// - /// Scales, computes absolute values and converts the result to 8-bit. - /// - /// The optional scale factor. [By default this is 1] - /// The optional delta added to the scaled values. [By default this is 0] - /// - public Mat ConvertScaleAbs(double alpha = 1, double beta = 0) - { - var dst = new Mat(); - Cv2.ConvertScaleAbs(this, dst, alpha, beta); - return dst; - } - - /// - /// transforms array of numbers using a lookup table: dst(i)=lut(src(i)) - /// - /// Look-up table of 256 elements. - /// In the case of multi-channel source array, the table should either have - /// a single channel (in this case the same table is used for all channels) - /// or the same number of channels as in the source array - /// - public Mat LUT(InputArrayRef lut) - { - var dst = new Mat(); - Cv2.LUT(this, lut, dst); - return dst; - } - - /// - /// transforms array of numbers using a lookup table: dst(i)=lut(src(i)) - /// - /// Look-up table of 256 elements. - /// In the case of multi-channel source array, the table should either have - /// a single channel (in this case the same table is used for all channels) - /// or the same number of channels as in the source array - /// - public Mat LUT(byte[] lut) - { - var dst = new Mat(); - Cv2.LUT(this, lut, dst); - return dst; - } - - /// - /// computes sum of array elements - /// - /// - public Scalar Sum() - { - return Cv2.Sum(this); - } - - /// - /// computes the number of nonzero array elements - /// - /// number of non-zero elements in mtx - public int CountNonZero() - { - return Cv2.CountNonZero(this); - } - - /// - /// returns the list of locations of non-zero pixels - /// - /// - public Mat FindNonZero() - { - var idx = new Mat(); - Cv2.FindNonZero(this, idx); - return idx; - } - - /// - /// computes mean value of selected array elements - /// - /// The optional operation mask - /// - public Scalar Mean(InputArrayRef mask = default) - { - return Cv2.Mean(this, mask); - } - - /// - /// computes mean value and standard deviation of all or selected array elements - /// - /// The output parameter: computed mean value - /// The output parameter: computed standard deviation - /// The optional operation mask - public void MeanStdDev(OutputArrayRef mean, OutputArrayRef stddev, InputArrayRef mask = default) - { - Cv2.MeanStdDev(this, mean, stddev, mask); - } - - /// - /// computes norm of the selected array part - /// - /// Type of the norm - /// The optional operation mask - /// - public double Norm(NormTypes normType = NormTypes.L2, InputArrayRef mask = default) - { - return Cv2.Norm(this, normType, mask); - } - - /// - /// scales and shifts array elements so that either the specified norm (alpha) - /// or the minimum (alpha) and maximum (beta) array values get the specified values - /// - /// The norm value to normalize to or the lower range boundary - /// in the case of range normalization - /// The upper range boundary in the case of range normalization; - /// not used for norm normalization - /// The normalization type - /// When the parameter is negative, - /// the destination array will have the same type as src, - /// otherwise it will have the same number of channels as src and the depth =CV_MAT_DEPTH(rtype) - /// The optional operation mask - /// - public Mat Normalize(double alpha = 1, double beta = 0, - NormTypes normType = NormTypes.L2, int dtype = -1, InputArrayRef mask = default) - { - var dst = new Mat(); - Cv2.Normalize(this, dst, alpha, beta, normType, dtype, mask); - return dst; - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// Pointer to returned minimum value - /// Pointer to returned maximum value - public void MinMaxLoc(out double minVal, out double maxVal) - { - Cv2.MinMaxLoc(this, out minVal, out maxVal); - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// Pointer to returned minimum location - /// Pointer to returned maximum location - public void MinMaxLoc(out Point minLoc, out Point maxLoc) - { - Cv2.MinMaxLoc(this, out minLoc, out maxLoc); - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// Pointer to returned minimum value - /// Pointer to returned maximum value - /// Pointer to returned minimum location - /// Pointer to returned maximum location - /// The optional mask used to select a sub-array - public void MinMaxLoc(out double minVal, out double maxVal, - out Point minLoc, out Point maxLoc, InputArrayRef mask = default) - { - Cv2.MinMaxLoc(this, out minVal, out maxVal, out minLoc, out maxLoc, mask); - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// Pointer to returned minimum value - /// Pointer to returned maximum value - public void MinMaxIdx(out double minVal, out double maxVal) - { - Cv2.MinMaxIdx(this, out minVal, out maxVal); - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// - /// - public void MinMaxIdx(int[] minIdx, int[] maxIdx) - { - Cv2.MinMaxIdx(this, minIdx, maxIdx); - } - - /// - /// finds global minimum and maximum array elements and returns their values and their locations - /// - /// Pointer to returned minimum value - /// Pointer to returned maximum value - /// - /// - /// - public void MinMaxIdx(out double minVal, out double maxVal, - int[] minIdx, int[] maxIdx, InputArrayRef mask = default) - { - Cv2.MinMaxIdx(this, out minVal, out maxVal, minIdx, maxIdx, mask); - } - - /// - /// transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows - /// - /// The dimension index along which the matrix is reduced. - /// 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column - /// - /// When it is negative, the destination vector will have - /// the same type as the source matrix, otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), mtx.channels()) - /// - public Mat Reduce(ReduceDimension dim, ReduceTypes rtype, int dtype) - { - var dst = new Mat(); - Cv2.Reduce(this, dst, dim, rtype, dtype); - return dst; - } - - /// - /// Copies each plane of a multi-channel array to a dedicated array - /// - /// The number of arrays must match mtx.channels() . - /// The arrays themselves will be reallocated if needed - public Mat[] Split() - { - return Cv2.Split(this); - } - - /// - /// extracts a single channel from src (coi is 0-based index) - /// - /// - /// - public Mat ExtractChannel(int coi) - { - var dst = new Mat(); - Cv2.ExtractChannel(this, dst, coi); - return dst; - } - - /// - /// inserts a single channel to dst (coi is 0-based index) - /// - /// - /// - public void InsertChannel(InputOutputArrayRef dst, int coi) - { - Cv2.InsertChannel(this, dst, coi); - } - - /// - /// reverses the order of the rows, columns or both in a matrix - /// - /// Specifies how to flip the array: - /// 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, - /// and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas. - /// The destination array; will have the same size and same type as src - public Mat Flip(FlipMode flipCode) - { - var dst = new Mat(); - Cv2.Flip(this, dst, flipCode); - return dst; - } - - /// - /// replicates the input matrix the specified number of times in the horizontal and/or vertical direction - /// - /// How many times the src is repeated along the vertical axis - /// How many times the src is repeated along the horizontal axis - /// - public Mat Repeat(int ny, int nx) - { - var dst = new Mat(); - Cv2.Repeat(this, ny, nx, dst); - return dst; - } - - /// - /// Checks if array elements lie between the elements of two other arrays. - /// - /// inclusive lower boundary array or a scalar. - /// inclusive upper boundary array or a scalar. - /// The destination array, will have the same size as src and CV_8U type - public Mat InRange(InputArrayRef lowerb, InputArrayRef upperb) - { - var dst = new Mat(); - Cv2.InRange(this, lowerb, upperb, dst); - return dst; - } - - - /// - /// Checks if array elements lie between the elements of two other arrays. - /// - /// inclusive lower boundary array or a scalar. - /// inclusive upper boundary array or a scalar. - /// The destination array, will have the same size as src and CV_8U type - public Mat InRange(Scalar lowerb, Scalar upperb) - { - var dst = new Mat(); - Cv2.InRange(this, lowerb, upperb, dst); - return dst; - } - - /// - /// computes square root of each matrix element (dst = src**0.5) - /// - /// The destination array; will have the same size and the same type as src - public Mat Sqrt() - { - var dst = new Mat(); - Cv2.Sqrt(this, dst); - return dst; - } - - /// - /// raises the input matrix elements to the specified power (b = a**power) - /// - /// The exponent of power - /// The destination array; will have the same size and the same type as src - public Mat Pow(double power) - { - var dst = new Mat(); - Cv2.Pow(this, power, dst); - return dst; - } - - /// - /// computes exponent of each matrix element (dst = e**src) - /// - /// The destination array; will have the same size and same type as src - public Mat Exp() - { - var dst = new Mat(); - Cv2.Exp(this, dst); - return dst; - } - - /// - /// computes natural logarithm of absolute value of each matrix element: dst = log(abs(src)) - /// - /// The destination array; will have the same size and same type as src - public Mat Log() - { - var dst = new Mat(); - Cv2.Log(this, dst); - return dst; - } - - /// - /// checks that each matrix element is within the specified range. - /// - /// The flag indicating whether the functions quietly - /// return false when the array elements are out of range, - /// or they throw an exception. - /// - public bool CheckRange(bool quiet = true) - { - return Cv2.CheckRange(this, quiet); - } - - /// - /// checks that each matrix element is within the specified range. - /// - /// The flag indicating whether the functions quietly - /// return false when the array elements are out of range, - /// or they throw an exception. - /// The optional output parameter, where the position of - /// the first outlier is stored. - /// The inclusive lower boundary of valid values range - /// The exclusive upper boundary of valid values range - /// - public bool CheckRange(bool quiet, out Point pos, - double minVal = double.MinValue, double maxVal = double.MaxValue) - { - return Cv2.CheckRange(this, quiet, out pos, minVal, maxVal); - } - - /// - /// converts NaN's to the given number - /// - /// - public void PatchNaNs(double val = 0) - { - Cv2.PatchNaNs(this, val); - } - - /// - /// multiplies matrix by its transposition from the left or from the right - /// - /// Specifies the multiplication ordering; see the description below - /// The optional delta matrix, subtracted from src before the - /// multiplication. When the matrix is empty ( delta=Mat() ), it’s assumed to be - /// zero, i.e. nothing is subtracted, otherwise if it has the same size as src, - /// then it’s simply subtracted, otherwise it is "repeated" to cover the full src - /// and then subtracted. Type of the delta matrix, when it's not empty, must be the - /// same as the type of created destination matrix, see the rtype description - /// The optional scale factor for the matrix product - /// When it’s negative, the destination matrix will have the - /// same type as src . Otherwise, it will have type=CV_MAT_DEPTH(rtype), - /// which should be either CV_32F or CV_64F - public Mat MulTransposed(bool aTa, InputArrayRef delta = default, double scale = 1, int dtype = -1) - { - var dst = new Mat(); - Cv2.MulTransposed(this, dst, aTa, delta, scale, dtype); - return dst; - } - - /// - /// transposes the matrix - /// - /// The destination array of the same type as src - public Mat Transpose() - { - var dst = new Mat(); - Cv2.Transpose(this, dst); - return dst; - } - - /// - /// performs affine transformation of each element of multi-channel input matrix - /// - /// The transformation matrix - /// The destination array; will have the same size and depth as src and as many channels as mtx.rows - public Mat Transform(InputArrayRef m) - { - var dst = new Mat(); - Cv2.Transform(this, dst, m); - return dst; - } - - /// - /// performs perspective transformation of each element of multi-channel input matrix - /// - /// 3x3 or 4x4 transformation matrix - /// The destination array; it will have the same size and same type as src - public Mat PerspectiveTransform(InputArrayRef m) - { - var dst = new Mat(); - Cv2.PerspectiveTransform(this, dst, m); - return dst; - } - - /// - /// extends the symmetrical matrix from the lower half or from the upper half - /// - /// If true, the lower half is copied to the upper half, - /// otherwise the upper half is copied to the lower half - public void CompleteSymm(bool lowerToUpper = false) - { - Cv2.CompleteSymm(this, lowerToUpper); - } - - /// - /// initializes scaled identity matrix (not necessarily square). - /// - /// The value to assign to the diagonal elements - public void SetIdentity(Scalar? s = null) - { - Cv2.SetIdentity(this, s); - } - - /// - /// computes determinant of a square matrix. - /// The input matrix must have CV_32FC1 or CV_64FC1 type and square size. - /// - /// determinant of the specified matrix. - public double Determinant() - { - return Cv2.Determinant(this); - } - - /// - /// computes trace of a matrix - /// - /// - public Scalar Trace() - { - return Cv2.Trace(this); - } - - /// - /// sorts independently each matrix row or each matrix column - /// - /// The operation flags, a combination of the SortFlag values - /// The destination array of the same size and the same type as src - public Mat Sort(SortFlags flags) - { - var dst = new Mat(); - Cv2.Sort(this, dst, flags); - return dst; - } - - /// - /// sorts independently each matrix row or each matrix column - /// - /// The operation flags, a combination of SortFlag values - /// The destination integer array of the same size as src - public Mat SortIdx(SortFlags flags) - { - var dst = new Mat(); - Cv2.SortIdx(this, dst, flags); - return dst; - } - - /// - /// Performs a forward Discrete Fourier transform of 1D or 2D floating-point array. - /// - /// Transformation flags, a combination of the DftFlag2 values - /// When the parameter != 0, the function assumes that - /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) - /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, - /// thus the function can handle the rest of the rows more efficiently and - /// thus save some time. This technique is very useful for computing array cross-correlation - /// or convolution using DFT - /// The destination array, which size and type depends on the flags - public Mat Dft(DftFlags flags = 0, int nonzeroRows = 0) - { - var dst = new Mat(); - Cv2.Dft(this, dst, flags, nonzeroRows); - return dst; - } - - /// - /// Performs an inverse Discrete Fourier transform of 1D or 2D floating-point array. - /// - /// Transformation flags, a combination of the DftFlag2 values - /// When the parameter != 0, the function assumes that - /// only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) - /// or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, - /// thus the function can handle the rest of the rows more efficiently and - /// thus save some time. This technique is very useful for computing array cross-correlation - /// or convolution using DFT - /// The destination array, which size and type depends on the flags - public Mat Idft(DftFlags flags = 0, int nonzeroRows = 0) - { - var dst = new Mat(); - Cv2.Idft(this, dst, flags, nonzeroRows); - return dst; - } - - /// - /// performs forward or inverse 1D or 2D Discrete Cosine Transformation - /// - /// Transformation flags, a combination of DctFlag2 values - /// The destination array; will have the same size and same type as src - public Mat Dct(DctFlags flags = 0) - { - var dst = new Mat(); - Cv2.Dct(this, dst, flags); - return dst; - } - - /// - /// performs inverse 1D or 2D Discrete Cosine Transformation - /// - /// Transformation flags, a combination of DctFlag2 values - /// The destination array; will have the same size and same type as src - public Mat Idct(DctFlags flags = 0) - { - var dst = new Mat(); - Cv2.Idct(this, dst, flags); - return dst; - } - - /// - /// fills array with uniformly-distributed random numbers from the range [low, high) - /// - /// The inclusive lower boundary of the generated random numbers - /// The exclusive upper boundary of the generated random numbers - public void Randu(InputArrayRef low, InputArrayRef high) - { - Cv2.Randu(this, low, high); - } - - /// - /// fills array with uniformly-distributed random numbers from the range [low, high) - /// - /// The inclusive lower boundary of the generated random numbers - /// The exclusive upper boundary of the generated random numbers - public void Randu(Scalar low, Scalar high) - { - Cv2.Randu(this, low, high); - } - - /// - /// fills array with normally-distributed random numbers with the specified mean and the standard deviation - /// - /// The mean value (expectation) of the generated random numbers - /// The standard deviation of the generated random numbers - public void Randn(InputArrayRef mean, InputArrayRef stddev) - { - Cv2.Randn(this, mean, stddev); - } - - /// - /// fills array with normally-distributed random numbers with the specified mean and the standard deviation - /// - /// The mean value (expectation) of the generated random numbers - /// The standard deviation of the generated random numbers - public void Randn(Scalar mean, Scalar stddev) - { - Cv2.Randn(this, mean, stddev); - } - - /// - /// shuffles the input array elements - /// - /// The scale factor that determines the number of random swap operations. - /// The input/output numerical 1D array - public void RandShuffle(double iterFactor) - { - Cv2.RandShuffle(this, iterFactor); - } - - /// - /// shuffles the input array elements - /// - /// The scale factor that determines the number of random swap operations. - /// The optional random number generator used for shuffling. - /// If it is null, theRng() is used instead. - /// The input/output numerical 1D array - public void RandShuffle(double iterFactor, ref RNG rng) - { - Cv2.RandShuffle(this, iterFactor, ref rng); - } - - #region Drawing - - #region Line - - /// - /// Draws a line segment connecting two points - /// - /// First point's x-coordinate of the line segment. - /// First point's y-coordinate of the line segment. - /// Second point's x-coordinate of the line segment. - /// Second point's y-coordinate of the line segment. - /// Line color. - /// Line thickness. [By default this is 1] - /// Type of the line. [By default this is LineType.Link8] - /// Number of fractional bits in the point coordinates. [By default this is 0] - public void Line(int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Line(this, pt1X, pt1Y, pt2X, pt2Y, color, thickness, lineType, shift); - } - - /// - /// Draws a line segment connecting two points - /// - /// First point of the line segment. - /// Second point of the line segment. - /// Line color. - /// Line thickness. [By default this is 1] - /// Type of the line. [By default this is LineType.Link8] - /// Number of fractional bits in the point coordinates. [By default this is 0] - public void Line( - Point pt1, Point pt2, Scalar color, int thickness = 1, - LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Line(this, pt1, pt2, color, thickness, lineType, shift); - } - - #endregion - - #region Rectangle - - /// - /// Draws simple, thick or filled rectangle - /// - /// One of the rectangle vertices. - /// Opposite rectangle vertex. - /// Line color (RGB) or brightness (grayscale image). - /// Thickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1] - /// Type of the line, see cvLine description. [By default this is LineType.Link8] - /// Number of fractional bits in the point coordinates. [By default this is 0] - public void Rectangle( - Point pt1, Point pt2, Scalar color, int thickness = 1, - LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Rectangle(this, pt1, pt2, color, thickness, lineType, shift); - } - - /// - /// Draws simple, thick or filled rectangle - /// - /// Rectangle. - /// Line color (RGB) or brightness (grayscale image). - /// Thickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1] - /// Type of the line, see cvLine description. [By default this is LineType.Link8] - /// Number of fractional bits in the point coordinates. [By default this is 0] - public void Rectangle( - Rect rect, Scalar color, int thickness = 1, - LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Rectangle(this, rect, color, thickness, lineType, shift); - } - - #endregion - - #region Circle - - /// - /// Draws a circle - /// - /// X-coordinate of the center of the circle. - /// Y-coordinate of the center of the circle. - /// Radius of the circle. - /// Circle color. - /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] - /// Type of the circle boundary. [By default this is LineType.Link8] - /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public void Circle(int centerX, int centerY, int radius, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Circle(this, centerX, centerY, radius, color, thickness, lineType, shift); - } - - /// - /// Draws a circle - /// - /// Center of the circle. - /// Radius of the circle. - /// Circle color. - /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] - /// Type of the circle boundary. [By default this is LineType.Link8] - /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public void Circle(Point center, int radius, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Circle(this, center, radius, color, thickness, lineType, shift); - } - - #endregion - - #region Ellipse - - /// - /// Draws simple or thick elliptic arc or fills ellipse sector - /// - /// Center of the ellipse. - /// Length of the ellipse axes. - /// Rotation angle. - /// Starting angle of the elliptic arc. - /// Ending angle of the elliptic arc. - /// Ellipse color. - /// Thickness of the ellipse arc. [By default this is 1] - /// Type of the ellipse boundary. [By default this is LineType.Link8] - /// Number of fractional bits in the center coordinates and axes' values. [By default this is 0] - public void Ellipse( - Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Ellipse(this, center, axes, angle, startAngle, endAngle, color, thickness, lineType, shift); - } - - /// - /// Draws simple or thick elliptic arc or fills ellipse sector - /// - /// The enclosing box of the ellipse drawn - /// Ellipse color. - /// Thickness of the ellipse boundary. [By default this is 1] - /// Type of the ellipse boundary. [By default this is LineType.Link8] - public void Ellipse(RotatedRect box, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8) - { - Cv2.Ellipse(this, box, color, thickness, lineType); - } - - #endregion - - /// - /// Draws a marker on a predefined position in an image. - /// - /// The function cv::drawMarker draws a marker on a given position in the image.For the moment several - /// marker types are supported, see #MarkerTypes for more information. - /// - /// The point where the crosshair is positioned. - /// Line color. - /// The specific type of marker you want to use. - /// The length of the marker axis [default = 20 pixels] - /// Line thickness. - /// Type of the line. - public void DrawMarker( - Point position, Scalar color, - MarkerTypes markerType = MarkerTypes.Cross, int markerSize = 20, int thickness = 1, LineTypes lineType = LineTypes.Link8) - { - Cv2.DrawMarker(this, position, color, markerType, markerSize, thickness, lineType); - } - - #region FillConvexPoly - - /// - /// Fills a convex polygon. - /// - /// The polygon vertices - /// Polygon color - /// Type of the polygon boundaries - /// The number of fractional bits in the vertex coordinates - public void FillConvexPoly(IEnumerable pts, Scalar color, - LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.FillConvexPoly(this, pts, color, lineType, shift); - } - - #endregion - - #region FillPoly - - /// - /// Fills the area bounded by one or more polygons - /// - /// Array of polygons, each represented as an array of points - /// Polygon color - /// Type of the polygon boundaries - /// The number of fractional bits in the vertex coordinates - /// - public void FillPoly(IEnumerable> pts, Scalar color, - LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null) - { - Cv2.FillPoly(this, pts, color, lineType, shift, offset); - } - - #endregion - - #region Polylines - - /// - /// draws one or more polygonal curves - /// - /// - /// - /// - /// - /// - /// - public void Polylines(IEnumerable> pts, bool isClosed, Scalar color, - int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) - { - Cv2.Polylines(this, pts, isClosed, color, thickness, lineType, shift); - } - - #endregion - - #region PutText - - /// - /// renders text string in the image - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void PutText(string text, Point org, - HersheyFonts fontFace, double fontScale, Scalar color, - int thickness = 1, - LineTypes lineType = LineTypes.Link8, - bool bottomLeftOrigin = false) - { - Cv2.PutText(this, text, org, fontFace, fontScale, color, thickness, lineType, bottomLeftOrigin); - } - - #endregion - - #region ImEncode / ToBytes - - /// - /// Encodes an image into a memory buffer. - /// - /// Encodes an image into a memory buffer. - /// Format-specific parameters. - /// - public byte[] ImEncode(string ext = ".png", int[]? prms = null) - { - ThrowIfDisposed(); - Cv2.ImEncode(ext, this, out var buf, prms); - return buf; - } - - /// - /// Encodes an image into a memory buffer. - /// - /// Encodes an image into a memory buffer. - /// Format-specific parameters. - /// - public byte[] ImEncode(string ext = ".png", params ImageEncodingParam[] prms) - { - ThrowIfDisposed(); - Cv2.ImEncode(ext, this, out var buf, prms); - return buf; - } - - #endregion - - #region ImWrite / SaveImage - - /// - /// Saves an image to a specified file. - /// - /// - /// - /// - public bool ImWrite(string fileName, int[]? prms = null) - { - return Cv2.ImWrite(fileName, this, prms); - } - - /// - /// Saves an image to a specified file. - /// - /// - /// - /// - public bool ImWrite(string fileName, params ImageEncodingParam[] prms) - { - return Cv2.ImWrite(fileName, this, prms); - } - - /// - /// Saves an image to a specified file. - /// - /// - /// - /// - public bool SaveImage(string fileName, int[]? prms = null) - { - return Cv2.ImWrite(fileName, this, prms); - } - - /// - /// Saves an image to a specified file. - /// - /// - /// - /// - public bool SaveImage(string fileName, params ImageEncodingParam[] prms) - { - return Cv2.ImWrite(fileName, this, prms); - } - - #endregion - - #endregion - - #endregion - - #region imgproc - - /// - /// Forms a border around the image - /// - /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate - /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate - /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate - /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate - /// The border type - /// The border value if borderType == Constant - public Mat CopyMakeBorder(int top, int bottom, int left, int right, BorderTypes borderType, Scalar? value = null) - { - var dst = new Mat(); - Cv2.CopyMakeBorder(this, dst, top, bottom, left, right, borderType, value); - return dst; - } - - /// - /// Smoothes image using median filter. - /// The source image must have 1-, 3- or 4-channel and - /// its depth should be CV_8U , CV_16U or CV_32F. - /// - /// The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ... - /// The destination array; will have the same size and the same type as src. - public Mat MedianBlur(int ksize) - { - var dst = new Mat(); - Cv2.MedianBlur(this, dst, ksize); - return dst; - } - - /// - /// Blurs an image using a Gaussian filter. - /// The input image can have any number of channels, which are processed independently, - /// but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - /// - /// Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. - /// Or, they can be zero’s and then they are computed from sigma* . - /// Gaussian kernel standard deviation in X direction. - /// Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, - /// if both sigmas are zeros, they are computed from ksize.width and ksize.height, - /// respectively (see getGaussianKernel() for details); to fully control the result - /// regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. - /// pixel extrapolation method - public Mat GaussianBlur(Size ksize, double sigmaX, - double sigmaY = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.GaussianBlur(this, dst, ksize, sigmaX, sigmaY, borderType); - return dst; - } - - /// - /// Applies bilateral filter to the image - /// The source image must be a 8-bit or floating-point, 1-channel or 3-channel image. - /// - /// The diameter of each pixel neighborhood, that is used during filtering. - /// If it is non-positive, it's computed from sigmaSpace - /// Filter sigma in the color space. - /// Larger value of the parameter means that farther colors within the pixel neighborhood - /// will be mixed together, resulting in larger areas of semi-equal color - /// Filter sigma in the coordinate space. - /// Larger value of the parameter means that farther pixels will influence each other - /// (as long as their colors are close enough; see sigmaColor). Then d>0 , it specifies - /// the neighborhood size regardless of sigmaSpace, otherwise d is proportional to sigmaSpace - /// - /// The destination image; will have the same size and the same type as src - public Mat BilateralFilter(int d, double sigmaColor, double sigmaSpace, - BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.BilateralFilter(this, dst, d, sigmaColor, sigmaSpace, borderType); - return dst; - } - - /// - /// Smoothes image using box filter - /// - /// - /// The smoothing kernel size - /// The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center - /// Indicates, whether the kernel is normalized by its area or not - /// The border mode used to extrapolate pixels outside of the image - /// The destination image; will have the same size and the same type as src - public Mat BoxFilter(MatType ddepth, Size ksize, Point? anchor = null, - bool normalize = true, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.BoxFilter(this, dst, ddepth, ksize, anchor, normalize, borderType); - return dst; - } - - /// - /// Smoothes image using normalized box filter - /// - /// The smoothing kernel size - /// The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center - /// The border mode used to extrapolate pixels outside of the image - /// The destination image; will have the same size and the same type as src - public Mat Blur(Size ksize, Point? anchor = null, - BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.Blur(this, dst, ksize, anchor, borderType); - return dst; - } - - /// - /// Convolves an image with the kernel - /// - /// The desired depth of the destination image. If it is negative, it will be the same as src.depth() - /// Convolution kernel (or rather a correlation kernel), - /// a single-channel floating point matrix. If you want to apply different kernels to - /// different channels, split the image into separate color planes using split() and process them individually - /// The anchor of the kernel that indicates the relative position of - /// a filtered point within the kernel. The anchor should lie within the kernel. - /// The special default value (-1,-1) means that the anchor is at the kernel center - /// The optional value added to the filtered pixels before storing them in dst - /// The pixel extrapolation method - /// The destination image. It will have the same size and the same number of channels as src - public Mat Filter2D(MatType ddepth, InputArray kernel, Point? anchor = null, - double delta = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.Filter2D(this, dst, ddepth, kernel, anchor, delta, borderType); - return dst; - } - - /// - /// Applies separable linear filter to an image - /// - /// The destination image depth - /// The coefficients for filtering each row - /// The coefficients for filtering each column - /// The anchor position within the kernel; The default value (-1, 1) means that the anchor is at the kernel center - /// The value added to the filtered results before storing them - /// The pixel extrapolation method - /// The destination image; will have the same size and the same number of channels as src - public Mat SepFilter2D(MatType ddepth, InputArray kernelX, InputArray kernelY, - Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.SepFilter2D(this, dst, ddepth, kernelX, kernelY, anchor, delta, borderType); - return dst; - } - - /// - /// Calculates the first, second, third or mixed image derivatives using an extended Sobel operator - /// - /// The destination image depth - /// Order of the derivative x - /// Order of the derivative y - /// Size of the extended Sobel kernel, must be 1, 3, 5 or 7 - /// The optional scale factor for the computed derivative values (by default, no scaling is applied - /// The optional delta value, added to the results prior to storing them in dst - /// The pixel extrapolation method - /// The destination image; will have the same size and the same number of channels as src - public Mat Sobel(MatType ddepth, int xorder, int yorder, - int ksize = 3, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.Sobel(this, dst, ddepth, xorder, yorder, ksize, scale, delta, borderType); - return dst; - } - - /// - /// Calculates the first x- or y- image derivative using Scharr operator - /// - /// The destination image depth - /// Order of the derivative x - /// Order of the derivative y - /// The optional scale factor for the computed derivative values (by default, no scaling is applie - /// The optional delta value, added to the results prior to storing them in dst - /// The pixel extrapolation method - /// The destination image; will have the same size and the same number of channels as src - public Mat Scharr(MatType ddepth, int xorder, int yorder, - double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.Scharr(this, dst, ddepth, xorder, yorder, scale, delta, borderType); - return dst; - } - - /// - /// Calculates the Laplacian of an image - /// - /// The desired depth of the destination image - /// The aperture size used to compute the second-derivative filters - /// The optional scale factor for the computed Laplacian values (by default, no scaling is applied - /// The optional delta value, added to the results prior to storing them in dst - /// The pixel extrapolation method - /// Destination image; will have the same size and the same number of channels as src - public Mat Laplacian(MatType ddepth, - int ksize = 1, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.Laplacian(this, dst, ddepth, ksize, scale, delta, borderType); - return dst; - } - - /// - /// Finds edges in an image using Canny algorithm. - /// - /// The first threshold for the hysteresis procedure - /// The second threshold for the hysteresis procedure - /// Aperture size for the Sobel operator [By default this is ApertureSize.Size3] - /// Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false] - /// The output edge map. It will have the same size and the same type as image - // ReSharper disable once InconsistentNaming - public Mat Canny(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) - { - var dst = new Mat(); - Cv2.Canny(this, dst, threshold1, threshold2, apertureSize, L2gradient); - return dst; - } - - /// - /// computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix. - /// - /// - /// - /// - public Mat CornerEigenValsAndVecs(int blockSize, int ksize, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.CornerEigenValsAndVecs(this, dst, blockSize, ksize, borderType); - return dst; - } - - /// - /// computes another complex cornerness criteria at each pixel - /// - /// - /// - public Mat PreCornerDetect(int ksize, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.PreCornerDetect(this, dst, ksize, borderType); - return dst; - } - - /// - /// adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria - /// - /// Initial coordinates of the input corners and refined coordinates provided for output. - /// Half of the side length of the search window. - /// Half of the size of the dead region in the middle of the search zone - /// over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities - /// of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such a size. - /// Criteria for termination of the iterative process of corner refinement. - /// That is, the process of corner position refinement stops either after criteria.maxCount iterations - /// or when the corner position moves by less than criteria.epsilon on some iteration. - /// - public Point2f[] CornerSubPix(IEnumerable inputCorners, - Size winSize, Size zeroZone, TermCriteria criteria) - { - return Cv2.CornerSubPix(this, inputCorners, winSize, zeroZone, criteria); - } - - /// - /// Finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima. - /// Input matrix must be 8-bit or floating-point 32-bit, single-channel image. - /// - /// Maximum number of corners to return. If there are more corners than are found, - /// the strongest of them is returned. - /// Parameter characterizing the minimal accepted quality of image corners. - /// The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - /// or the Harris function response (see cornerHarris() ). The corners with the quality measure less than - /// the product are rejected. For example, if the best corner has the quality measure = 1500, and the qualityLevel=0.01, - /// then all the corners with the quality measure less than 15 are rejected. - /// Minimum possible Euclidean distance between the returned corners. - /// Optional region of interest. If the image is not empty - /// (it needs to have the type CV_8UC1 and the same size as image ), it specifies the region - /// in which the corners are detected. - /// Size of an average block for computing a derivative covariation matrix over each pixel neighborhood. - /// Parameter indicating whether to use a Harris detector - /// Free parameter of the Harris detector. - /// Output vector of detected corners. - public Point2f[] GoodFeaturesToTrack( - int maxCorners, double qualityLevel, double minDistance, - InputArray mask, int blockSize, bool useHarrisDetector, double k) - { - return Cv2.GoodFeaturesToTrack(this, maxCorners, qualityLevel, - minDistance, mask, blockSize, useHarrisDetector, k); - } - - /// - /// Finds lines in a binary image using standard Hough transform. - /// The input matrix must be 8-bit, single-channel, binary source image. - /// This image may be modified by the function. - /// - /// Distance resolution of the accumulator in pixels - /// Angle resolution of the accumulator in radians - /// The accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold ) - /// For the multi-scale Hough transform it is the divisor for the distance resolution rho. [By default this is 0] - /// For the multi-scale Hough transform it is the divisor for the distance resolution theta. [By default this is 0] - /// The output vector of lines. Each line is represented by a two-element vector (rho, theta) . - /// rho is the distance from the coordinate origin (0,0) (top-left corner of the image) and theta is the line rotation angle in radians - public LineSegmentPolar[] HoughLines(double rho, double theta, int threshold, - double srn = 0, double stn = 0) - { - return Cv2.HoughLines(this, rho, theta, threshold, srn, stn); - } - - /// - /// Finds lines segments in a binary image using probabilistic Hough transform. - /// - /// Distance resolution of the accumulator in pixels - /// Angle resolution of the accumulator in radians - /// The accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold ) - /// The minimum line length. Line segments shorter than that will be rejected. [By default this is 0] - /// The maximum allowed gap between points on the same line to link them. [By default this is 0] - /// The output lines. Each line is represented by a 4-element vector (x1, y1, x2, y2) - public LineSegmentPoint[] HoughLinesP(double rho, double theta, int threshold, - double minLineLength = 0, double maxLineGap = 0) - { - return Cv2.HoughLinesP(this, rho, theta, threshold, minLineLength, maxLineGap); - } - - /// - /// Finds circles in a grayscale image using a Hough transform. - /// The input matrix must be 8-bit, single-channel and grayscale. - /// - /// The available methods are HoughMethods.Gradient and HoughMethods.GradientAlt - /// The inverse ratio of the accumulator resolution to the image resolution. - /// Minimum distance between the centers of the detected circles. - /// The first method-specific parameter. [By default this is 100] - /// The second method-specific parameter. [By default this is 100] - /// Minimum circle radius. [By default this is 0] - /// Maximum circle radius. [By default this is 0] - /// The output vector found circles. Each vector is encoded as 3-element floating-point vector (x, y, radius) - public CircleSegment[] HoughCircles(HoughModes method, double dp, double minDist, - double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) - { - return Cv2.HoughCircles(this, method, dp, minDist, param1, param2, minRadius, maxRadius); - } - - /// - /// Dilates an image by using a specific structuring element. - /// - /// The structuring element used for dilation. If element=new Mat() , a 3x3 rectangular structuring element is used - /// Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center - /// The number of times dilation is applied. [By default this is 1] - /// The pixel extrapolation method. [By default this is BorderTypes.Constant] - /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] - /// The destination image. It will have the same size and the same type as src - public Mat Dilate(InputArray? element, Point? anchor = null, int iterations = 1, - BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.Dilate(this, dst, element, anchor, iterations, borderType, borderValue); - return dst; - } - - /// - /// Erodes an image by using a specific structuring element. - /// - /// The structuring element used for dilation. If element=new Mat(), a 3x3 rectangular structuring element is used - /// Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center - /// The number of times erosion is applied - /// The pixel extrapolation method - /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] - /// The destination image. It will have the same size and the same type as src - public Mat Erode(InputArray? element, Point? anchor = null, int iterations = 1, - BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.Erode(this, dst, element, anchor, iterations, borderType, borderValue); - return dst; - } - - /// - /// Performs advanced morphological transformations - /// - /// Type of morphological operation - /// Structuring element - /// Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center - /// Number of times erosion and dilation are applied. [By default this is 1] - /// The pixel extrapolation method. [By default this is BorderTypes.Constant] - /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] - /// Destination image. It will have the same size and the same type as src - public Mat MorphologyEx( - MorphTypes op, InputArray? element, - Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, - Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.MorphologyEx(this, dst, op, element, anchor, iterations, borderType, borderValue); - return dst; - } - - /// - /// Resizes an image. - /// - /// output image size; if it equals zero, it is computed as: - /// dsize = Size(round(fx*src.cols), round(fy*src.rows)) - /// Either dsize or both fx and fy must be non-zero. - /// scale factor along the horizontal axis; when it equals 0, - /// it is computed as: (double)dsize.width/src.cols - /// scale factor along the vertical axis; when it equals 0, - /// it is computed as: (double)dsize.height/src.rows - /// interpolation method - /// output image; it has the size dsize (when it is non-zero) or the size computed - /// from src.size(), fx, and fy; the type of dst is the same as of src. - public Mat Resize(Size dsize, double fx = 0, double fy = 0, - InterpolationFlags interpolation = InterpolationFlags.Linear) - { - var dst = new Mat(); - Cv2.Resize(this, dst, dsize, fx, fy, interpolation); - return dst; - } - - /// - /// Applies an affine transformation to an image. - /// - /// output image that has the size dsize and the same type as src. - /// 2x3 transformation matrix. - /// size of the output image. - /// combination of interpolation methods and the optional flag - /// WARP_INVERSE_MAP that means that M is the inverse transformation (dst -> src) . - /// pixel extrapolation method; when borderMode=BORDER_TRANSPARENT, - /// it means that the pixels in the destination image corresponding to the "outliers" - /// in the source image are not modified by the function. - /// value used in case of a constant border; by default, it is 0. - public Mat WarpAffine(InputArray m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, - BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.WarpAffine(this, dst, m, dsize, flags, borderMode, borderValue); - return dst; - } - - /// - /// Applies a perspective transformation to an image. - /// - /// 3x3 transformation matrix. - /// size of the output image. - /// combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) - /// and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation (dst -> src). - /// pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE). - /// value used in case of a constant border; by default, it equals 0. - /// output image that has the size dsize and the same type as src. - public Mat WarpPerspective(Mat m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, - BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.WarpPerspective(this, dst, m, dsize, flags, borderMode, borderValue); - return dst; - } - - /// - /// Applies a generic geometrical transformation to an image. - /// - /// The first map of either (x,y) points or just x values having the type CV_16SC2, CV_32FC1, or CV_32FC2. - /// The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if map1 is (x,y) points), respectively. - /// Interpolation method. The method INTER_AREA is not supported by this function. - /// Pixel extrapolation method. When borderMode=BORDER_TRANSPARENT, - /// it means that the pixels in the destination image that corresponds to the "outliers" in - /// the source image are not modified by the function. - /// Value used in case of a constant border. By default, it is 0. - /// Destination image. It has the same size as map1 and the same type as src - public Mat Remap(InputArray map1, InputArray map2, InterpolationFlags interpolation = InterpolationFlags.Linear, - BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) - { - var dst = new Mat(); - Cv2.Remap(this, dst, map1, map2, interpolation, borderMode, borderValue); - return dst; - } - - /// - /// Inverts an affine transformation. - /// - /// Output reverse affine transformation. - public Mat InvertAffineTransform() - { - var dst = new Mat(); - Cv2.InvertAffineTransform(this, dst); - return dst; - } - - /// - /// Retrieves a pixel rectangle from an image with sub-pixel accuracy. - /// - /// Size of the extracted patch. - /// Floating point coordinates of the center of the extracted rectangle - /// within the source image. The center must be inside the image. - /// Depth of the extracted pixels. By default, they have the same depth as src. - /// Extracted patch that has the size patchSize and the same number of channels as src . - public Mat GetRectSubPix(Size patchSize, Point2f center, int patchType = -1) - { - var dst = new Mat(); - Cv2.GetRectSubPix(this, patchSize, center, dst, patchType); - return dst; - } - - /// - /// Adds an image to the accumulator. - /// - /// Optional operation mask. - /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. - public Mat Accumulate(InputArray mask) - { - var dst = new Mat(); - Cv2.Accumulate(this, dst, mask); - return dst; - } - - /// - /// Adds the square of a source image to the accumulator. - /// - /// Optional operation mask. - /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. - public Mat AccumulateSquare(InputArray mask) - { - var dst = new Mat(); - Cv2.AccumulateSquare(this, dst, mask); - return dst; - } - - /// - /// Computes a Hanning window coefficients in two dimensions. - /// - /// The window size specifications - /// Created array type - public void CreateHanningWindow(Size winSize, MatType type) - { - Cv2.CreateHanningWindow(this, winSize, type); - } - - /// - /// Applies a fixed-level threshold to each array element. - /// The input matrix must be single-channel, 8-bit or 32-bit floating point. - /// - /// threshold value. - /// maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. - /// thresholding type (see the details below). - /// output array of the same size and type as src. - public Mat Threshold(double thresh, double maxval, ThresholdTypes type) - { - var dst = new Mat(); - Cv2.Threshold(this, dst, thresh, maxval, type); - return dst; - } - - /// - /// Applies an adaptive threshold to an array. - /// Source matrix must be 8-bit single-channel image. - /// - /// Non-zero value assigned to the pixels for which the condition is satisfied. See the details below. - /// Adaptive thresholding algorithm to use, ADAPTIVE_THRESH_MEAN_C or ADAPTIVE_THRESH_GAUSSIAN_C . - /// Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV . - /// Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. - /// Constant subtracted from the mean or weighted mean (see the details below). - /// Normally, it is positive but may be zero or negative as well. - /// Destination image of the same size and the same type as src. - public Mat AdaptiveThreshold(double maxValue, AdaptiveThresholdTypes adaptiveMethod, - ThresholdTypes thresholdType, int blockSize, double c) - { - var dst = new Mat(); - Cv2.AdaptiveThreshold(this, dst, maxValue, adaptiveMethod, - thresholdType, blockSize, c); - return dst; - } - - /// - /// Blurs an image and downsamples it. - /// - /// size of the output image; by default, it is computed as Size((src.cols+1)/2 - /// - /// - public Mat PyrDown(Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.PyrDown(this, dst, dstSize, borderType); - return dst; - } - - /// - /// Upsamples an image and then blurs it. - /// - /// size of the output image; by default, it is computed as Size(src.cols*2, (src.rows*2) - /// - /// - public Mat PyrUp(Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) - { - var dst = new Mat(); - Cv2.PyrUp(this, dst, dstSize, borderType); - return dst; - } - - /// - /// Upsamples an image and then blurs it. - /// - /// - /// - /// - public IEnumerable BuildPyramid(int maxlevel, BorderTypes borderType = BorderTypes.Default) - { - using var dst = new VectorOfMat(); - Cv2.BuildPyramid(this, dst, maxlevel, borderType); - return dst.ToArray(); - } - - /// - /// corrects lens distortion for the given camera matrix and distortion coefficients - /// - /// Input camera matrix - /// Input vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]]) of 4, 5, - /// or 8 elements. If the vector is null, the zero distortion coefficients are assumed. - /// Camera matrix of the distorted image. - /// By default, it is the same as cameraMatrix but you may additionally scale - /// and shift the result by using a different matrix. - /// Output (corrected) image that has the same size and type as src . - public Mat Undistort(InputArray cameraMatrix, InputArray distCoeffs, InputArray? newCameraMatrix = null) - { - var dst = new Mat(); - Cv2.Undistort(this, dst, cameraMatrix, distCoeffs, newCameraMatrix); - return dst; - } - - /// - /// returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true) - /// - /// Camera view image size in pixels. - /// Location of the principal point in the new camera matrix. - /// The parameter indicates whether this location should be at the image center or not. - /// the camera matrix that is either an exact copy of the input cameraMatrix - /// (when centerPrinicipalPoint=false), or the modified one (when centerPrincipalPoint=true). - public Mat GetDefaultNewCameraMatrix(Size? imgSize = null, bool centerPrincipalPoint = false) - { - return Cv2.GetDefaultNewCameraMatrix(this, imgSize, centerPrincipalPoint); - } - - /// - /// Computes the ideal point coordinates from the observed point coordinates. - /// Input matrix is an observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2). - /// - /// Camera matrix - /// Input vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]]) of 4, 5, or 8 elements. - /// If the vector is null, the zero distortion coefficients are assumed. - /// Rectification transformation in the object space (3x3 matrix). - /// R1 or R2 computed by stereoRectify() can be passed here. - /// If the matrix is empty, the identity transformation is used. - /// New camera matrix (3x3) or new projection matrix (3x4). - /// P1 or P2 computed by stereoRectify() can be passed here. If the matrix is empty, - /// the identity new camera matrix is used. - /// Output ideal point coordinates after undistortion and reverse perspective transformation. - /// If matrix P is identity or omitted, dst will contain normalized point coordinates. - public Mat UndistortPoints( - InputArray cameraMatrix, InputArray distCoeffs, - InputArray? r = null, InputArray? p = null) - { - var dst = new Mat(); - Cv2.UndistortPoints(this, dst, cameraMatrix, distCoeffs, r, p); - return dst; - } - - /// - /// Normalizes the grayscale image brightness and contrast by normalizing its histogram. - /// The source matrix is 8-bit single channel image. - /// - /// The destination image; will have the same size and the same type as src - public Mat EqualizeHist() - { - var dst = new Mat(); - Cv2.EqualizeHist(this, dst); - return dst; - } - - /// - /// Performs a marker-based image segmentation using the watershed algorithm. - /// Input matrix is 8-bit 3-channel image. - /// - /// Input/output 32-bit single-channel image (map) of markers. - /// It should have the same size as image. - public void Watershed(InputOutputArray markers) - { - Cv2.Watershed(this, markers); - } - - /// - /// Performs initial step of meanshift segmentation of an image. - /// The source matrix is 8-bit, 3-channel image. - /// - /// The spatial window radius. - /// The color window radius. - /// Maximum level of the pyramid for the segmentation. - /// Termination criteria: when to stop meanshift iterations. - /// The destination image of the same format and the same size as the source. - public Mat PyrMeanShiftFiltering(double sp, double sr, int maxLevel = 1, TermCriteria? termcrit = null) - { - var dst = new Mat(); - Cv2.PyrMeanShiftFiltering(this, dst, sp, sr, maxLevel, termcrit); - return dst; - } - - /// - /// Segments the image using GrabCut algorithm. - /// The input is 8-bit 3-channel image. - /// - /// Input/output 8-bit single-channel mask. - /// The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. - /// Its elements may have Cv2.GC_BGD / Cv2.GC_FGD / Cv2.GC_PR_BGD / Cv2.GC_PR_FGD - /// ROI containing a segmented object. The pixels outside of the ROI are - /// marked as "obvious background". The parameter is only used when mode==GC_INIT_WITH_RECT. - /// Temporary array for the background model. Do not modify it while you are processing the same image. - /// Temporary arrays for the foreground model. Do not modify it while you are processing the same image. - /// Number of iterations the algorithm should make before returning the result. - /// Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL . - /// Operation mode that could be one of GrabCutFlag value. - public void GrabCut(InputOutputArray mask, Rect rect, - InputOutputArray bgdModel, InputOutputArray fgdModel, - int iterCount, GrabCutModes mode) - { - Cv2.GrabCut(this, mask, rect, bgdModel, fgdModel, iterCount, mode); - } - - /// - /// Fills a connected component with the given color. - /// Input/output 1- or 3-channel, 8-bit, or floating-point image. - /// It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the - /// second variant of the function. See the details below. - /// - /// Starting point. - /// New value of the repainted domain pixels. - /// - public int FloodFill(Point seedPoint, Scalar newVal) - { - return Cv2.FloodFill(this, seedPoint, newVal); - } - - /// - /// Fills a connected component with the given color. - /// Input/output 1- or 3-channel, 8-bit, or floating-point image. - /// It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the - /// second variant of the function. See the details below. - /// - /// Starting point. - /// New value of the repainted domain pixels. - /// Optional output parameter set by the function to the - /// minimum bounding rectangle of the repainted domain. - /// Maximal lower brightness/color difference between the currently - /// observed pixel and one of its neighbors belonging to the component, or a seed pixel - /// being added to the component. - /// Maximal upper brightness/color difference between the currently - /// observed pixel and one of its neighbors belonging to the component, or a seed pixel - /// being added to the component. - /// Operation flags. Lower bits contain a connectivity value, - /// 4 (default) or 8, used within the function. Connectivity determines which - /// neighbors of a pixel are considered. - /// - public int FloodFill( - Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, - FloodFillFlags flags = FloodFillFlags.Link4) - { - return Cv2.FloodFill(this, seedPoint, newVal, out rect, - loDiff, upDiff, flags); - } - - /// - /// Fills a connected component with the given color. - /// Input/output 1- or 3-channel, 8-bit, or floating-point image. - /// It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the - /// second variant of the function. See the details below. - /// - /// (For the second function only) Operation mask that should be a single-channel 8-bit image, - /// 2 pixels wider and 2 pixels taller. The function uses and updates the mask, so you take responsibility of - /// initializing the mask content. Flood-filling cannot go across non-zero pixels in the mask. For example, - /// an edge detector output can be used as a mask to stop filling at edges. It is possible to use the same mask - /// in multiple calls to the function to make sure the filled area does not overlap. - /// Starting point. - /// New value of the repainted domain pixels. - /// - public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal) - { - return Cv2.FloodFill(this, mask, seedPoint, newVal); - } - - /// - /// Fills a connected component with the given color. - /// Input/output 1- or 3-channel, 8-bit, or floating-point image. - /// It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the - /// second variant of the function. See the details below. - /// - /// (For the second function only) Operation mask that should be a single-channel 8-bit image, - /// 2 pixels wider and 2 pixels taller. The function uses and updates the mask, so you take responsibility of - /// initializing the mask content. Flood-filling cannot go across non-zero pixels in the mask. For example, - /// an edge detector output can be used as a mask to stop filling at edges. It is possible to use the same mask - /// in multiple calls to the function to make sure the filled area does not overlap. - /// Starting point. - /// New value of the repainted domain pixels. - /// Optional output parameter set by the function to the - /// minimum bounding rectangle of the repainted domain. - /// Maximal lower brightness/color difference between the currently - /// observed pixel and one of its neighbors belonging to the component, or a seed pixel - /// being added to the component. - /// Maximal upper brightness/color difference between the currently - /// observed pixel and one of its neighbors belonging to the component, or a seed pixel - /// being added to the component. - /// Operation flags. Lower bits contain a connectivity value, - /// 4 (default) or 8, used within the function. Connectivity determines which - /// neighbors of a pixel are considered. - /// - public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal, - out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, - FloodFillFlags flags = FloodFillFlags.Link4) - { - return Cv2.FloodFill(this, mask, seedPoint, - newVal, out rect, loDiff, upDiff, flags); - } - - /// - /// Converts image from one color space to another - /// - /// The color space conversion code - /// The number of channels in the destination image; if the parameter is 0, the number of the channels will be derived automatically from src and the code - /// The destination image; will have the same size and the same depth as src - public Mat CvtColor(ColorConversionCodes code, int dstCn = 0) - { - var dst = new Mat(); - Cv2.CvtColor(this, dst, code, dstCn); - return dst; - } - - /// - /// Calculates all of the moments - /// up to the third order of a polygon or rasterized shape. - /// The input is a raster image (single-channel, 8-bit or floating-point 2D array). - /// - /// If it is true, then all the non-zero image pixels are treated as 1’s - /// - public Moments Moments(bool binaryImage = false) - { - return new Moments(this, binaryImage); - } - - /// - /// Computes the proximity map for the raster template and the image where the template is searched for - /// The input is Image where the search is running; should be 8-bit or 32-bit floating-point. - /// - /// Searched template; must be not greater than the source image and have the same data type - /// Specifies the comparison method - /// Mask of searched template. It must have the same datatype and size with templ. It is not set by default. - /// A map of comparison results; will be single-channel 32-bit floating-point. - /// If image is WxH and templ is wxh then result will be (W-w+1) x (H-h+1). - public Mat MatchTemplate(InputArray templ, TemplateMatchModes method, InputArray? mask = null) - { - var dst = new Mat(); - Cv2.MatchTemplate(this, templ, dst, method, mask); - return dst; - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// destination labeled image - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// The number of labels - public int ConnectedComponents(OutputArray labels, - PixelConnectivity connectivity = PixelConnectivity.Connectivity8) - { - return ConnectedComponents(labels, connectivity, MatType.CV_32S); - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// destination labeled image - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// output image label type. Currently CV_32S and CV_16U are supported. - /// The number of labels - public int ConnectedComponents(OutputArray labels, - PixelConnectivity connectivity, MatType ltype) - { - return Cv2.ConnectedComponents(this, labels, connectivity, ltype); - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// destination labeled rectangular array - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// The number of labels - public int ConnectedComponents(out int[,] labels, PixelConnectivity connectivity) - { - return Cv2.ConnectedComponents(this, out labels, connectivity); - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// destination labeled image - /// statistics output for each label, including the background label, - /// see below for available statistics. Statistics are accessed via stats(label, COLUMN) - /// where COLUMN is one of cv::ConnectedComponentsTypes - /// floating point centroid (x,y) output for each label, - /// including the background label - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// - public int ConnectedComponentsWithStats( - OutputArray labels, OutputArray stats, OutputArray centroids, - PixelConnectivity connectivity = PixelConnectivity.Connectivity8) - { - return ConnectedComponentsWithStats(labels, stats, centroids, connectivity, MatType.CV_32S); - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// destination labeled image - /// statistics output for each label, including the background label, - /// see below for available statistics. Statistics are accessed via stats(label, COLUMN) - /// where COLUMN is one of cv::ConnectedComponentsTypes - /// floating point centroid (x,y) output for each label, - /// including the background label - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// output image label type. Currently CV_32S and CV_16U are supported. - /// - public int ConnectedComponentsWithStats( - OutputArray labels, OutputArray stats, OutputArray centroids, - PixelConnectivity connectivity, MatType ltype) - { - return Cv2.ConnectedComponentsWithStats(this, labels, stats, centroids, connectivity, ltype); - } - - /// - /// computes the connected components labeled image of boolean image. - /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 - /// represents the background label. ltype specifies the output label image type, an important - /// consideration based on the total number of labels or alternatively the total number of - /// pixels in the source image. - /// - /// 8 or 4 for 8-way or 4-way connectivity respectively - /// - public ConnectedComponents ConnectedComponentsEx(PixelConnectivity connectivity = PixelConnectivity.Connectivity8) - { - return Cv2.ConnectedComponentsEx(this, connectivity); - } - - /// - /// Finds contours in a binary image. - /// The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. - /// Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours. - /// - /// Detected contours. Each contour is stored as a vector of points. - /// Optional output vector, containing information about the image topology. - /// It has as many elements as the number of contours. For each i-th contour contours[i], - /// the members of the elements hierarchy[i] are set to 0-based indices in contours of the next - /// and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. - /// If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - /// Contour retrieval mode - /// Contour approximation method - /// Optional offset by which every contour point is shifted. - /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public void FindContours(out Point[][] contours, out HierarchyIndex[] hierarchy, - RetrievalModes mode, ContourApproximationModes method, Point? offset = null) - { - Cv2.FindContours(this, out contours, out hierarchy, mode, method, offset); - } - - /// - /// Finds contours in a binary image. - /// The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. - /// Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours. - /// - /// Detected contours. Each contour is stored as a vector of points. - /// Optional output vector, containing information about the image topology. - /// It has as many elements as the number of contours. For each i-th contour contours[i], - /// the members of the elements hierarchy[i] are set to 0-based indices in contours of the next - /// and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. - /// If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - /// Contour retrieval mode - /// Contour approximation method - /// Optional offset by which every contour point is shifted. - /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public void FindContours(out Mat[] contours, OutputArray hierarchy, - RetrievalModes mode, ContourApproximationModes method, Point? offset = null) - { - Cv2.FindContours(this, out contours, hierarchy, mode, method, offset); - } - - /// - /// Finds contours in a binary image. - /// The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. - /// Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours. - /// - /// Contour retrieval mode - /// Contour approximation method - /// Optional offset by which every contour point is shifted. - /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - /// Detected contours. Each contour is stored as a vector of points. - public Point[][] FindContoursAsArray(RetrievalModes mode, ContourApproximationModes method, Point? offset = null) - { - return Cv2.FindContoursAsArray(this, mode, method, offset); - } - - /// - /// Finds contours in a binary image. - /// The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. - /// Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours. - /// - /// Contour retrieval mode - /// Contour approximation method - /// Optional offset by which every contour point is shifted. - /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - /// Detected contours. Each contour is stored as a vector of points. - public Mat[] FindContoursAsMat(RetrievalModes mode, ContourApproximationModes method, Point? offset = null) - { - return Cv2.FindContoursAsMat(this, mode, method, offset); - } - - /// - /// Draws contours in the image - /// - /// All the input contours. Each contour is stored as a point vector. - /// Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - /// Color of the contours. - /// Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), - /// the contour interiors are drawn. - /// Line connectivity. - /// Optional information about hierarchy. It is only needed if you want to draw only some of the contours - /// Maximal level for drawn contours. If it is 0, only the specified contour is drawn. - /// If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, - /// all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account - /// when there is hierarchy available. - /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) - public void DrawContours( - IEnumerable> contours, - int contourIdx, - Scalar color, - int thickness = 1, - LineTypes lineType = LineTypes.Link8, - IEnumerable? hierarchy = null, - int maxLevel = int.MaxValue, - Point? offset = null) - { - Cv2.DrawContours(this, contours, contourIdx, color, - thickness, lineType, hierarchy, maxLevel, offset); - } - - /// - /// Draws contours in the image - /// - /// All the input contours. Each contour is stored as a point vector. - /// Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - /// Color of the contours. - /// Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), - /// the contour interiors are drawn. - /// Line connectivity. - /// Optional information about hierarchy. It is only needed if you want to draw only some of the contours - /// Maximal level for drawn contours. If it is 0, only the specified contour is drawn. - /// If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, - /// all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account - /// when there is hierarchy available. - /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) - public void DrawContours( - IEnumerable contours, - int contourIdx, - Scalar color, - int thickness = 1, - LineTypes lineType = LineTypes.Link8, - Mat? hierarchy = null, - int maxLevel = int.MaxValue, - Point? offset = null) - { - Cv2.DrawContours(this, contours, contourIdx, color, - thickness, lineType, hierarchy, maxLevel, offset); - } - - /// - /// Approximates contour or a curve using Douglas-Peucker algorithm. - /// The input is the polygon or curve to approximate and - /// it must be 1 x N or N x 1 matrix of type CV_32SC2 or CV_32FC2. - /// - /// Specifies the approximation accuracy. - /// This is the maximum distance between the original curve and its approximation. - /// The result of the approximation; - /// The type should match the type of the input curve - /// The result of the approximation; - /// The type should match the type of the input curve - // ReSharper disable once InconsistentNaming - public Mat ApproxPolyDP(double epsilon, bool closed) - { - var dst = new Mat(); - Cv2.ApproxPolyDP(this, dst, epsilon, closed); - return dst; - } - - /// - /// Calculates a contour perimeter or a curve length. - /// The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. - /// - /// Indicates, whether the curve is closed or not - /// - public double ArcLength(bool closed) - { - return Cv2.ArcLength(this, closed); - } - - /// - /// Calculates the up-right bounding rectangle of a point set. - /// The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. - /// - /// Minimal up-right bounding rectangle for the specified point set. - public Rect BoundingRect() - { - return Cv2.BoundingRect(this); - } - - /// - /// Calculates the contour area. - /// The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. - /// - /// - /// - public double ContourArea(bool oriented = false) - { - return Cv2.ContourArea(this, oriented); - } - - /// - /// Finds the minimum area rotated rectangle enclosing a 2D point set. - /// The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. - /// - /// - public RotatedRect MinAreaRect() - { - return Cv2.MinAreaRect(this); - } - - /// - /// Finds the minimum area circle enclosing a 2D point set. - /// The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. - /// - /// The output center of the circle - /// The output radius of the circle - public void MinEnclosingCircle(out Point2f center, out float radius) - { - Cv2.MinEnclosingCircle(this, out center, out radius); - } - - /// - /// Computes convex hull for a set of 2D points. - /// - /// If true, the output convex hull will be oriented clockwise, - /// otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate - /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, - /// and y axis is oriented downwards. - /// - /// The output convex hull. It is either a vector of points that form the - /// hull (must have the same type as the input points), or a vector of 0-based point - /// indices of the hull points in the original array (since the set of convex hull - /// points is a subset of the original point set). - public Mat ConvexHull(bool clockwise = false, bool returnPoints = true) - { - var dst = new Mat(); - Cv2.ConvexHull(this, dst, clockwise, returnPoints); - return dst; - } - - /// - /// Computes convex hull for a set of 2D points. - /// - /// If true, the output convex hull will be oriented clockwise, - /// otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate - /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, - /// and y axis is oriented downwards. - /// The output convex hull. It is a vector of points that form the - /// hull (must have the same type as the input points). - public Point[] ConvexHullPoints(bool clockwise = false) - { - var dst = new Mat(); - Cv2.ConvexHull(this, dst, clockwise); - return dst.ToArray(); - } - - /// - /// Computes convex hull for a set of 2D points. - /// - /// If true, the output convex hull will be oriented clockwise, - /// otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate - /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, - /// and y axis is oriented downwards. - /// The output convex hull. It is a vector of points that form the - /// hull (must have the same type as the input points). - public Point2f[] ConvexHullFloatPoints(bool clockwise = false) - { - var dst = new Mat(); - Cv2.ConvexHull(this, dst, clockwise); - return dst.ToArray(); - } - - /// - /// Computes convex hull for a set of 2D points. - /// - /// If true, the output convex hull will be oriented clockwise, - /// otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate - /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, - /// and y axis is oriented downwards. - /// The output convex hull. It is a vector of 0-based point - /// indices of the hull points in the original array (since the set of convex hull - /// points is a subset of the original point set). - public int[] ConvexHullIndices(bool clockwise = false) - { - var dst = new Mat(); - Cv2.ConvexHull(this, dst, clockwise, false); - return dst.ToArray(); - } - - /// - /// Computes the contour convexity defects - /// - /// Convex hull obtained using convexHull() that - /// should contain indices of the contour points that make the hull. - /// The output vector of convexity defects. - /// Each convexity defect is represented as 4-element integer vector - /// (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), - /// where indices are 0-based indices in the original contour of the convexity defect beginning, - /// end and the farthest point, and fixpt_depth is fixed-point approximation - /// (with 8 fractional bits) of the distance between the farthest contour point and the hull. - /// That is, to get the floating-point value of the depth will be fixpt_depth/256.0. - public Mat ConvexityDefects(InputArray convexHull) - { - var dst = new Mat(); - Cv2.ConvexityDefects(this, convexHull, dst); - return dst; - } - - /// - /// Computes the contour convexity defects - /// - /// Convex hull obtained using convexHull() that - /// should contain indices of the contour points that make the hull. - /// The output vector of convexity defects. - /// Each convexity defect is represented as 4-element integer vector - /// (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), - /// where indices are 0-based indices in the original contour of the convexity defect beginning, - /// end and the farthest point, and fixpt_depth is fixed-point approximation - /// (with 8 fractional bits) of the distance between the farthest contour point and the hull. - /// That is, to get the floating-point value of the depth will be fixpt_depth/256.0. - public Vec4i[] ConvexityDefectsAsVec(InputArray convexHull) - { - var dst = new Mat(); - Cv2.ConvexityDefects(this, convexHull, dst); - return dst.ToArray(); - } - - /// - /// Returns true if the contour is convex. - /// Does not support contours with self-intersection - /// - /// - public bool IsContourConvex() - { - return Cv2.IsContourConvex(this); - } - - /// - /// Fits ellipse to the set of 2D points. - /// - /// - public RotatedRect FitEllipse() - { - return Cv2.FitEllipse(this); - } - - /// - /// Fits line to the set of 2D points using M-estimator algorithm. - /// The input is vector of 2D points. - /// - /// Distance used by the M-estimator - /// Numerical parameter ( C ) for some types of distances. - /// If it is 0, an optimal value is chosen. - /// Sufficient accuracy for the radius - /// (distance between the coordinate origin and the line). - /// Sufficient accuracy for the angle. - /// 0.01 would be a good default value for reps and aeps. - /// Output line parameters. - public Line2D FitLine2D(DistanceTypes distType, double param, double reps, double aeps) - { - var line = new Mat(); - Cv2.FitLine(this, line, distType, param, reps, aeps); - return new Line2D(line.ToArray()); - } - - /// - /// Fits line to the set of 3D points using M-estimator algorithm. - /// The input is vector of 3D points. - /// - /// Distance used by the M-estimator - /// Numerical parameter ( C ) for some types of distances. - /// If it is 0, an optimal value is chosen. - /// Sufficient accuracy for the radius - /// (distance between the coordinate origin and the line). - /// Sufficient accuracy for the angle. - /// 0.01 would be a good default value for reps and aeps. - /// Output line parameters. - public Line3D FitLine3D(DistanceTypes distType, double param, double reps, double aeps) - { - var line = new Mat(); - Cv2.FitLine(this, line, distType, param, reps, aeps); - return new Line3D(line.ToArray()); - } - - /// - /// Checks if the point is inside the contour. - /// Optionally computes the signed distance from the point to the contour boundary. - /// - /// Point tested against the contour. - /// If true, the function estimates the signed distance - /// from the point to the nearest contour edge. Otherwise, the function only checks - /// if the point is inside a contour or not. - /// Positive (inside), negative (outside), or zero (on an edge) value. - public double PointPolygonTest(Point2f pt, bool measureDist) - { - return Cv2.PointPolygonTest(this, pt, measureDist); - } - - /// - /// Computes the distance transform map - /// - /// - /// - public Mat DistanceTransform(DistanceTypes distanceType, DistanceTransformMasks maskSize) - { - var dst = new Mat(); - Cv2.DistanceTransform(this, dst, distanceType, maskSize); - return dst; - } - - #endregion -} diff --git a/test/OpenCvSharp.Tests.Windows/BitmapSourceConverterTest.cs b/test/OpenCvSharp.Tests.Windows/BitmapSourceConverterTest.cs index 79ea35634..c54d9fe8d 100644 --- a/test/OpenCvSharp.Tests.Windows/BitmapSourceConverterTest.cs +++ b/test/OpenCvSharp.Tests.Windows/BitmapSourceConverterTest.cs @@ -75,14 +75,14 @@ public void BitmapSourceSample() var whiteColor8 = new Scalar(255, 255, 255); using (var mat = new Mat(size, size, MatType.CV_8UC3, new Scalar(128, 128, 128))) { - mat.Rectangle(new Rect(15, 10, 100, 100), blueColor8, -1); - mat.PutText("B", new Point(50, 70), HersheyFonts.HersheyComplex, 1, whiteColor8); + Cv2.Rectangle(mat, new Rect(15, 10, 100, 100), blueColor8, -1); + Cv2.PutText(mat, "B", new Point(50, 70), HersheyFonts.HersheyComplex, 1, whiteColor8); - mat.Rectangle(new Rect(130, 10, 100, 100), greenColor8, -1); - mat.PutText("G", new Point(165, 70), HersheyFonts.HersheyComplex, 1, whiteColor8); + Cv2.Rectangle(mat, new Rect(130, 10, 100, 100), greenColor8, -1); + Cv2.PutText(mat, "G", new Point(165, 70), HersheyFonts.HersheyComplex, 1, whiteColor8); - mat.Rectangle(new Rect(75, 130, 100, 100), redColor8, -1); - mat.PutText("R", new Point(110, 190), HersheyFonts.HersheyComplex, 1, whiteColor8); + Cv2.Rectangle(mat, new Rect(75, 130, 100, 100), redColor8, -1); + Cv2.PutText(mat, "R", new Point(110, 190), HersheyFonts.HersheyComplex, 1, whiteColor8); bs8 = OpenCvSharp.WpfExtensions.BitmapSourceConverter.ToBitmapSource(mat); } @@ -93,14 +93,14 @@ public void BitmapSourceSample() var whiteColor16 = new Scalar(65535, 65535, 65535); using (var mat = new Mat(size, size, MatType.CV_16UC3, new Scalar(32767, 32767, 32767))) { - mat.Rectangle(new Rect(15, 10, 100, 100), blueColor16, -1); - mat.PutText("B", new Point(50, 70), HersheyFonts.HersheyComplex, 1, whiteColor16); + Cv2.Rectangle(mat, new Rect(15, 10, 100, 100), blueColor16, -1); + Cv2.PutText(mat, "B", new Point(50, 70), HersheyFonts.HersheyComplex, 1, whiteColor16); - mat.Rectangle(new Rect(130, 10, 100, 100), greenColor16, -1); - mat.PutText("G", new Point(165, 70), HersheyFonts.HersheyComplex, 1, whiteColor16); + Cv2.Rectangle(mat, new Rect(130, 10, 100, 100), greenColor16, -1); + Cv2.PutText(mat, "G", new Point(165, 70), HersheyFonts.HersheyComplex, 1, whiteColor16); - mat.Rectangle(new Rect(75, 130, 100, 100), redColor16, -1); - mat.PutText("R", new Point(110, 190), HersheyFonts.HersheyComplex, 1, whiteColor16); + Cv2.Rectangle(mat, new Rect(75, 130, 100, 100), redColor16, -1); + Cv2.PutText(mat, "R", new Point(110, 190), HersheyFonts.HersheyComplex, 1, whiteColor16); bs16 = OpenCvSharp.WpfExtensions.BitmapSourceConverter.ToBitmapSource(mat); } diff --git a/test/OpenCvSharp.Tests/aruco/ArucoTest.cs b/test/OpenCvSharp.Tests/aruco/ArucoTest.cs index 0e877fa0f..b14ce0a6b 100644 --- a/test/OpenCvSharp.Tests/aruco/ArucoTest.cs +++ b/test/OpenCvSharp.Tests/aruco/ArucoTest.cs @@ -225,7 +225,8 @@ public void ArucoDetector_Dispose() public void DrawDetectedMarker() { using var image = LoadImage("markers_6x6_250.png", ImreadModes.Grayscale); - using var outputImage = image.CvtColor(ColorConversionCodes.GRAY2RGB); + using var outputImage = new Mat(); + Cv2.CvtColor(image, outputImage, ColorConversionCodes.GRAY2RGB); using var dict = Cv2.Aruco.GetPredefinedDictionary(PredefinedDictionaryType.Dict6X6_250); using var detector = new ArucoDetector(dict); detector.DetectMarkers(image, out var corners, out var ids, out var rejectedImgPoints); @@ -423,7 +424,8 @@ public void DrawDetectedCornersCharuco() using var board = new CharucoBoard(5, 7, 0.04f, 0.02f, dict); using var boardImage = new Mat(); board.GenerateImage(new Size(600, 800), boardImage, 10, 1); - using var outputImage = boardImage.CvtColor(ColorConversionCodes.GRAY2RGB); + using var outputImage = new Mat(); + Cv2.CvtColor(boardImage, outputImage, ColorConversionCodes.GRAY2RGB); using var detector = new CharucoDetector(board); detector.DetectBoard(boardImage, out var charucoCorners, out var charucoIds, out _, out _); diff --git a/test/OpenCvSharp.Tests/core/MatExprParityTest.cs b/test/OpenCvSharp.Tests/core/MatExprParityTest.cs index eac8418d4..16f342b4e 100644 --- a/test/OpenCvSharp.Tests/core/MatExprParityTest.cs +++ b/test/OpenCvSharp.Tests/core/MatExprParityTest.cs @@ -388,7 +388,7 @@ public void Abs() { using var a = FloatNeg(); - using Mat actual = a.Abs(); + using Mat actual = Cv2.Abs(a).ToMat(); using var zeros = Mat.ZerosMat(3, 3, MatType.CV_32FC1); using var expected = new Mat(); Cv2.Absdiff(a, zeros, expected); diff --git a/test/OpenCvSharp.Tests/core/MatTest.cs b/test/OpenCvSharp.Tests/core/MatTest.cs index dae4567b5..2e6cea249 100644 --- a/test/OpenCvSharp.Tests/core/MatTest.cs +++ b/test/OpenCvSharp.Tests/core/MatTest.cs @@ -248,7 +248,8 @@ public void SetTo() { using var graySrc = LoadImage("mandrill.png", ImreadModes.Grayscale); using var resultImage = graySrc.Clone(); - using var mask = graySrc.InRange(100, 200); + using var mask = new Mat(); + Cv2.InRange(graySrc, new Scalar(100), new Scalar(200), mask); var ret = resultImage.SetTo(0, mask); ShowImagesWhenDebugMode(resultImage); Assert.True(ReferenceEquals(resultImage, ret)); @@ -1085,7 +1086,7 @@ public void GetSubMat() using var mat = new Mat(10, 10, MatType.CV_8UC1, Scalar.All(0)); var rect = new Rect(2, 2, 7, 5); - mat.Rectangle(rect, new Scalar(expectedValue), -1); + Cv2.Rectangle(mat, rect, new Scalar(expectedValue), -1); using var subMat = mat.SubMat(rect); Assert.Equal(rect.Width, subMat.Cols); @@ -1108,7 +1109,7 @@ public void GetSubMatByIndexer() using var mat = new Mat(10, 10, MatType.CV_8UC1, Scalar.All(0)); var rect = new Rect(2, 2, 7, 5); - mat.Rectangle(rect, new Scalar(expectedValue), -1); + Cv2.Rectangle(mat, rect, new Scalar(expectedValue), -1); using var subMat = mat[rect]; Assert.Equal(rect.Width, subMat.Cols); @@ -1198,7 +1199,8 @@ public void Issue349() using var mat1 = Mat.FromPixelData(8, 8, MatType.CV_32FC1, ptr); for (long i = 0; i < 1000000; i++) { - using var mat2 = mat1.Idct(); + using var mat2 = new Mat(); + Cv2.Idct(mat1, mat2); GC.KeepAlive(mat2); } @@ -1212,7 +1214,7 @@ public void Issue349() public void TestStreamWriting() { using var m = new Mat(new Size(87, 92), MatType.CV_8UC1); - m.Randn(Scalar.RandomColor(), new Scalar(7)); + Cv2.Randn(m, Scalar.RandomColor(), new Scalar(7)); using var stream = new System.IO.MemoryStream(); stream.Write([1, 2, 3, 4], 0, 4); diff --git a/test/OpenCvSharp.Tests/dnn/ModelTest.cs b/test/OpenCvSharp.Tests/dnn/ModelTest.cs index 7ee22a4ae..6098d95f0 100644 --- a/test/OpenCvSharp.Tests/dnn/ModelTest.cs +++ b/test/OpenCvSharp.Tests/dnn/ModelTest.cs @@ -56,7 +56,7 @@ public void ModelPredictReturnsProbabilities() using var strip = outputs[0].Reshape(1, (int)outputs[0].Total()); var minIdx = new[] { -1 }; var maxIdx = new[] { -1 }; - strip.MinMaxIdx(minIdx, maxIdx); + Cv2.MinMaxIdx(strip, minIdx, maxIdx); Assert.Equal(9, maxIdx[0]); } finally diff --git a/test/OpenCvSharp.Tests/dnn/TensorflowTest.cs b/test/OpenCvSharp.Tests/dnn/TensorflowTest.cs index 676a06085..53885539c 100644 --- a/test/OpenCvSharp.Tests/dnn/TensorflowTest.cs +++ b/test/OpenCvSharp.Tests/dnn/TensorflowTest.cs @@ -67,7 +67,7 @@ private static int GetResultClass(Mat prob) var minIdx = new[] {-1}; var maxIdx = new[] { -1 }; - strip.MinMaxIdx(minIdx,maxIdx); + Cv2.MinMaxIdx(strip, minIdx, maxIdx); return maxIdx[0]; } diff --git a/test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs b/test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs index 5909e2b9b..3eb6a4ec7 100644 --- a/test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs +++ b/test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs @@ -24,7 +24,8 @@ public void CreateAndDispose() public void TrainAndPredict() { using var image = LoadImage("lenna.png"); - using var grayImage = image.CvtColor(ColorConversionCodes.BGR2GRAY); + using var grayImage = new Mat(); + Cv2.CvtColor(image, grayImage, ColorConversionCodes.BGR2GRAY); using var model = LBPHFaceRecognizer.Create(); using var cascade = new CascadeClassifier("_data/text/haarcascade_frontalface_default.xml"); diff --git a/test/OpenCvSharp.Tests/img_hash/AverageHashTest.cs b/test/OpenCvSharp.Tests/img_hash/AverageHashTest.cs index d73295a63..c6dec9c25 100644 --- a/test/OpenCvSharp.Tests/img_hash/AverageHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/AverageHashTest.cs @@ -57,13 +57,14 @@ public void CompareDifferentImage() using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(256, 256); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). - Assert.Equal(264411, hash, tolerance: 1000); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). + Assert.Equal(264411, hash, tolerance: 1000); } } } diff --git a/test/OpenCvSharp.Tests/img_hash/BlockMeanHashTest.cs b/test/OpenCvSharp.Tests/img_hash/BlockMeanHashTest.cs index 93d746f23..7dcd34564 100644 --- a/test/OpenCvSharp.Tests/img_hash/BlockMeanHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/BlockMeanHashTest.cs @@ -86,13 +86,14 @@ public void CompareDifferentImage(BlockMeanHashMode mode) using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(256, 256); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). - Assert.Equal(264411, hash, tolerance: 1000); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). + Assert.Equal(264411, hash, tolerance: 1000); } } } diff --git a/test/OpenCvSharp.Tests/img_hash/ColorMomentHashTest.cs b/test/OpenCvSharp.Tests/img_hash/ColorMomentHashTest.cs index 356619b8f..40fef2802 100644 --- a/test/OpenCvSharp.Tests/img_hash/ColorMomentHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/ColorMomentHashTest.cs @@ -64,13 +64,14 @@ public void CompareDifferentImage() using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(256, 256); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). - Assert.Equal(236458999.828723, hash, tolerance: 500000); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). + Assert.Equal(236458999.828723, hash, tolerance: 500000); } } } diff --git a/test/OpenCvSharp.Tests/img_hash/MarrHildrethHashTest.cs b/test/OpenCvSharp.Tests/img_hash/MarrHildrethHashTest.cs index 34f5f8a8b..ec2f96263 100644 --- a/test/OpenCvSharp.Tests/img_hash/MarrHildrethHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/MarrHildrethHashTest.cs @@ -54,13 +54,14 @@ public void CompareDifferentImage() using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(256, 256); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). - Assert.Equal(264411, hash, tolerance: 1000); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). + Assert.Equal(264411, hash, tolerance: 1000); } } } diff --git a/test/OpenCvSharp.Tests/img_hash/PHashTest.cs b/test/OpenCvSharp.Tests/img_hash/PHashTest.cs index a8904a330..b39e3c7dc 100644 --- a/test/OpenCvSharp.Tests/img_hash/PHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/PHashTest.cs @@ -57,13 +57,14 @@ public void CompareDifferentImage() using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(256, 256); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). - Assert.Equal(264411, hash, tolerance: 1000); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + // Tolerance widened to absorb cross-platform floating-point variance (e.g. Linux ARM64). + Assert.Equal(264411, hash, tolerance: 1000); } } } diff --git a/test/OpenCvSharp.Tests/img_hash/RadialVarianceHashTest.cs b/test/OpenCvSharp.Tests/img_hash/RadialVarianceHashTest.cs index 86dc75480..93b8048c3 100644 --- a/test/OpenCvSharp.Tests/img_hash/RadialVarianceHashTest.cs +++ b/test/OpenCvSharp.Tests/img_hash/RadialVarianceHashTest.cs @@ -41,12 +41,13 @@ public void CompareSameImage() using (var img1 = LoadImage("lenna.png", ImreadModes.Grayscale)) { var size = new Size(40, 40); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img1.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - Assert.Equal(1, hash, 6); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img1, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + Assert.Equal(1, hash, 6); } } @@ -58,12 +59,13 @@ public void CompareDifferentImage() using (var img2 = LoadImage("building.jpg", ImreadModes.Grayscale)) { var size = new Size(40, 40); - using (var scaledImg1 = img1.Resize(size)) - using (var scaledImg2 = img2.Resize(size)) - { - double hash = model.Compare(scaledImg1, scaledImg2); - Assert.Equal(0.085777, hash, tolerance: 0.001); - } + using var scaledImg1 = new Mat(); + Cv2.Resize(img1, scaledImg1, size); + using var scaledImg2 = new Mat(); + Cv2.Resize(img2, scaledImg2, size); + + double hash = model.Compare(scaledImg1, scaledImg2); + Assert.Equal(0.085777, hash, tolerance: 0.001); } } } diff --git a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs index d0a675353..76d2f01c3 100644 --- a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs +++ b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs @@ -451,9 +451,9 @@ static Point[] ToPoints(IEnumerable enumerable) } using var img = new Mat(200, 200, MatType.CV_8UC3, new Scalar(0)); - img.Polylines([ToPoints(rr1.Points())], true, Scalar.Red); - img.Polylines([ToPoints(rr2.Points())], true, Scalar.Green); - img.Polylines([ToPoints(intersectingRegion)], true, Scalar.White); + Cv2.Polylines(img, [ToPoints(rr1.Points())], true, Scalar.Red); + Cv2.Polylines(img, [ToPoints(rr2.Points())], true, Scalar.Green); + Cv2.Polylines(img, [ToPoints(intersectingRegion)], true, Scalar.White); Window.ShowImages(img); } @@ -514,7 +514,7 @@ public void RectangleFilled() var color = Scalar.Red; using Mat img = Mat.Zeros(100, 100, MatType.CV_8UC3); - img.Rectangle(new Rect(10, 10, 80, 80), color, Cv2.FILLED/*-1*/); + Cv2.Rectangle(img, new Rect(10, 10, 80, 80), color, Cv2.FILLED/*-1*/); if (Debugger.IsAttached) { @@ -858,7 +858,8 @@ private static void ResizeCore(InterpolationFlags flags) where T : unmanaged { using var src = new Mat(10, 10); - using var dst = src.Resize(default, 0.5, 0.5, flags); + using var dst = new Mat(); + Cv2.Resize(src, dst, default, 0.5, 0.5, flags); Assert.Equal(new Size(5, 5), dst.Size()); } @@ -1393,7 +1394,8 @@ public void GoodFeaturesToTrack() public void GrabCut() { using var color = LoadImage("lenna.png", ImreadModes.Color); - using var img = color.Resize(new Size(64, 64)); + using var img = new Mat(); + Cv2.Resize(color, img, new Size(64, 64)); using var mask = new Mat(); using var bgdModel = new Mat(); using var fgdModel = new Mat(); @@ -1468,7 +1470,8 @@ public void MinAreaRect() public void PhaseCorrelate() { using var gray = LoadImage("lenna.png", ImreadModes.Grayscale); - using var small = gray.Resize(new Size(64, 64)); + using var small = new Mat(); + Cv2.Resize(gray, small, new Size(64, 64)); using var src = new Mat(); small.ConvertTo(src, MatType.CV_32F); using var window = new Mat(); @@ -1483,7 +1486,8 @@ public void PhaseCorrelate() public void Watershed() { using var color = LoadImage("lenna.png", ImreadModes.Color); - using var img = color.Resize(new Size(64, 64)); + using var img = new Mat(); + Cv2.Resize(color, img, new Size(64, 64)); using var markers = new Mat(img.Size(), MatType.CV_32SC1, Scalar.All(0)); markers.Set(8, 8, 1); markers.Set(56, 56, 2); diff --git a/test/OpenCvSharp.Tests/photo/PhotoTest.cs b/test/OpenCvSharp.Tests/photo/PhotoTest.cs index e4c9cacaf..fc9173828 100644 --- a/test/OpenCvSharp.Tests/photo/PhotoTest.cs +++ b/test/OpenCvSharp.Tests/photo/PhotoTest.cs @@ -12,7 +12,7 @@ public void Inpaint() using var dst = new Mat(); using var mask = new Mat(src.Size(), MatType.CV_8UC1, Scalar.All(0)); - mask.Rectangle(new Rect(65, 15, 130, 30), Scalar.All(255), -1); + Cv2.Rectangle(mask, new Rect(65, 15, 130, 30), Scalar.All(255), -1); Cv2.Inpaint(src, mask, dst, 2, InpaintTypes.Telea); @@ -101,7 +101,7 @@ public void ColorChange() { using var src = new Mat("_data/image/mandrill.png", ImreadModes.Color); using var mask = new Mat(src.Size(), MatType.CV_8UC1, Scalar.All(0)); - mask.Rectangle(new Rect(50, 50, 200, 200), Scalar.All(255), -1); + Cv2.Rectangle(mask, new Rect(50, 50, 200, 200), Scalar.All(255), -1); using var dst = new Mat(); Cv2.ColorChange(src, mask, dst, 1.5f, 0.5f, 1.0f); @@ -113,7 +113,7 @@ public void IlluminationChange() { using var src = new Mat("_data/image/mandrill.png", ImreadModes.Color); using var mask = new Mat(src.Size(), MatType.CV_8UC1, Scalar.All(0)); - mask.Rectangle(new Rect(50, 50, 200, 200), Scalar.All(255), -1); + Cv2.Rectangle(mask, new Rect(50, 50, 200, 200), Scalar.All(255), -1); using var dst = new Mat(); Cv2.IlluminationChange(src, mask, dst, 0.2f, 0.4f); @@ -125,7 +125,7 @@ public void TextureFlattening() { using var src = new Mat("_data/image/mandrill.png", ImreadModes.Color); using var mask = new Mat(src.Size(), MatType.CV_8UC1, Scalar.All(0)); - mask.Rectangle(new Rect(50, 50, 200, 200), Scalar.All(255), -1); + Cv2.Rectangle(mask, new Rect(50, 50, 200, 200), Scalar.All(255), -1); using var dst = new Mat(); Cv2.TextureFlattening(src, mask, dst, 30, 45, 3); diff --git a/test/OpenCvSharp.Tests/stitching/StitchingTest.cs b/test/OpenCvSharp.Tests/stitching/StitchingTest.cs index 07c92df30..ad496f281 100644 --- a/test/OpenCvSharp.Tests/stitching/StitchingTest.cs +++ b/test/OpenCvSharp.Tests/stitching/StitchingTest.cs @@ -50,10 +50,10 @@ private static Mat[] SelectStitchingImages(int width, int height, int count) int x2 = x1 + width; int y2 = y1 + height; - result.Line(new Point(x1, y1), new Point(x1, y2), new Scalar(0, 0, 255)); - result.Line(new Point(x1, y2), new Point(x2, y2), new Scalar(0, 0, 255)); - result.Line(new Point(x2, y2), new Point(x2, y1), new Scalar(0, 0, 255)); - result.Line(new Point(x2, y1), new Point(x1, y1), new Scalar(0, 0, 255)); + Cv2.Line(result, new Point(x1, y1), new Point(x1, y2), new Scalar(0, 0, 255)); + Cv2.Line(result, new Point(x1, y2), new Point(x2, y2), new Scalar(0, 0, 255)); + Cv2.Line(result, new Point(x2, y2), new Point(x2, y1), new Scalar(0, 0, 255)); + Cv2.Line(result, new Point(x2, y1), new Point(x1, y1), new Scalar(0, 0, 255)); Mat m = source[new Rect(x1, y1, width, height)]; mats.Add(m.Clone()); diff --git a/test/OpenCvSharp.Tests/text/TextDetectorTest.cs b/test/OpenCvSharp.Tests/text/TextDetectorTest.cs index ef5631948..929cd85dc 100644 --- a/test/OpenCvSharp.Tests/text/TextDetectorTest.cs +++ b/test/OpenCvSharp.Tests/text/TextDetectorTest.cs @@ -54,7 +54,7 @@ public void Detect() { foreach (var box in boxes) { - image.Rectangle(box, Scalar.Red, 2); + Cv2.Rectangle(image, box, Scalar.Red, 2); } Window.ShowImages(image); } diff --git a/test/OpenCvSharp.Tests/tracking/TrackerTestBase.cs b/test/OpenCvSharp.Tests/tracking/TrackerTestBase.cs index 46c880272..2c3a7881e 100644 --- a/test/OpenCvSharp.Tests/tracking/TrackerTestBase.cs +++ b/test/OpenCvSharp.Tests/tracking/TrackerTestBase.cs @@ -47,7 +47,8 @@ protected static void UpdateBase(Tracker tracker) if (Debugger.IsAttached) { Directory.CreateDirectory(path); - mat.Rectangle( + Cv2.Rectangle( + mat, new Point(bb.X, bb.Y), new Point(bb.X + bb.Width, bb.Y + bb.Height), new Scalar(0, 0, 255)); diff --git a/test/OpenCvSharp.Tests/video/KalmanTest.cs b/test/OpenCvSharp.Tests/video/KalmanTest.cs index 6357bef09..6b08471da 100644 --- a/test/OpenCvSharp.Tests/video/KalmanTest.cs +++ b/test/OpenCvSharp.Tests/video/KalmanTest.cs @@ -178,7 +178,7 @@ private static void IsDataEqual(Mat lhs, Mat rhs) { Assert.Equal(lhs.Size(), rhs.Size()); Assert.Equal(lhs.Type(), rhs.Type()); - Assert.Equal(lhs.Sum(), rhs.Sum()); + Assert.Equal(Cv2.Sum(lhs), Cv2.Sum(rhs)); using Mat diff = lhs - rhs; Assert.Equal(Scalar.Black, Cv2.Sum(diff)); diff --git a/test/OpenCvSharp.Tests/ximgproc/StructuredEdgeDetectionTest.cs b/test/OpenCvSharp.Tests/ximgproc/StructuredEdgeDetectionTest.cs index 47ea9ee57..8b72bdeab 100644 --- a/test/OpenCvSharp.Tests/ximgproc/StructuredEdgeDetectionTest.cs +++ b/test/OpenCvSharp.Tests/ximgproc/StructuredEdgeDetectionTest.cs @@ -82,7 +82,7 @@ public void GetBoundingBoxes() Assert.NotEmpty(boxes); foreach (var box in boxes) { - image.Rectangle(box, Scalar.Red, 2); + Cv2.Rectangle(image, box, Scalar.Red, 2); } ShowImagesWhenDebugMode(image32F, edges, orientation, edgesNms, image); //Window.ShowImages(image, edgesNms); diff --git a/test/OpenCvSharp.Tests/ximgproc/XimgProcTest.cs b/test/OpenCvSharp.Tests/ximgproc/XimgProcTest.cs index f1ffebe1e..9c0d538f1 100644 --- a/test/OpenCvSharp.Tests/ximgproc/XimgProcTest.cs +++ b/test/OpenCvSharp.Tests/ximgproc/XimgProcTest.cs @@ -103,10 +103,10 @@ public void ColorMatchTemplate() Assert.False(dst.Empty()); Assert.Equal(MatType.CV_64FC1, dst.Type()); - dst.MinMaxLoc(out var minVal, out var maxVal, out var minLoc, out var maxLoc); + Cv2.MinMaxLoc(dst, out var minVal, out var maxVal, out var minLoc, out var maxLoc); using var view = src.Clone(); - view.Rectangle(maxLoc, new Point(maxLoc.X + template.Width, maxLoc.Y + template.Height), Scalar.Red, 3); + Cv2.Rectangle(view, maxLoc, new Point(maxLoc.X + template.Width, maxLoc.Y + template.Height), Scalar.Red, 3); ShowImagesWhenDebugMode(view, template); } @@ -364,7 +364,7 @@ public void RLPaintAndCreateRLEImage() using var canvas = Mat.ZerosMat(10, 10, MatType.CV_8UC1); Cv2.XImgProc.RL.Paint(canvas, rle, Scalar.All(255)); - Assert.True(canvas.CountNonZero() > 0); + Assert.True(Cv2.CountNonZero(canvas) > 0); } // peilin.hpp From dec89b5362becdac24500fc3ed9926d433dc34aa Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 17:56:06 +0900 Subject: [PATCH 17/29] Migration: UMat.cs instance methods (CopyTo/ConvertTo/SetTo/Mul/Dot) to InputArrayRef/OutputArrayRef (issue #1976 step 5, part 12) --- src/OpenCvSharp/Modules/core/Mat/UMat.cs | 75 +++++++----------------- 1 file changed, 21 insertions(+), 54 deletions(-) diff --git a/src/OpenCvSharp/Modules/core/Mat/UMat.cs b/src/OpenCvSharp/Modules/core/Mat/UMat.cs index 3d681835e..70792999a 100644 --- a/src/OpenCvSharp/Modules/core/Mat/UMat.cs +++ b/src/OpenCvSharp/Modules/core/Mat/UMat.cs @@ -694,27 +694,15 @@ public UMat Clone(Rect roi) /// /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(OutputArray m, InputArray? mask = null) + public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - if (mask is null) - { - NativeMethods.HandleException( - NativeMethods.core_UMat_copyTo1(Handle, m.ToOutputProxy())); - } - else - { - NativeMethods.HandleException( - NativeMethods.core_UMat_copyTo2(Handle, m.ToOutputProxy(), mask.ToInputProxy())); - } + NativeMethods.HandleException( + NativeMethods.core_UMat_copyTo2(Handle, m.Proxy, mask.Proxy)); - m.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(m.Source); + GC.KeepAlive(mask.Source); } /// @@ -722,27 +710,18 @@ public void CopyTo(OutputArray m, InputArray? mask = null) /// /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(UMat m, InputArray? mask = null) + public void CopyTo(UMat m, InputArrayRef mask = default) { ThrowIfDisposed(); if (m is null) throw new ArgumentNullException(nameof(m)); m.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); - if (mask is null) - { - NativeMethods.HandleException( - NativeMethods.core_UMat_copyTo_toUMat1(Handle, m.CvPtr)); - } - else - { - NativeMethods.HandleException( - NativeMethods.core_UMat_copyTo_toUMat2(Handle, m.CvPtr, mask.ToInputProxy())); - } + NativeMethods.HandleException( + NativeMethods.core_UMat_copyTo_toUMat2(Handle, m.CvPtr, mask.Proxy)); GC.KeepAlive(m); - GC.KeepAlive(mask); + GC.KeepAlive(mask.Source); } /// @@ -753,17 +732,14 @@ public void CopyTo(UMat m, InputArray? mask = null) /// if rtype is negative, the output matrix will have the same type as the input. /// optional scale factor. /// optional delta added to the scaled values. - public void ConvertTo(OutputArray m, MatType rtype, double alpha = 1, double beta = 0) + public void ConvertTo(OutputArrayRef m, MatType rtype, double alpha = 1, double beta = 0) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_UMat_convertTo(Handle, m.ToOutputProxy(), rtype, alpha, beta)); + NativeMethods.core_UMat_convertTo(Handle, m.Proxy, rtype, alpha, beta)); - m.Fix(); + GC.KeepAlive(m.Source); } /// @@ -807,18 +783,15 @@ public UMat SetTo(Scalar value, UMat? mask = null) /// /// /// - public UMat SetTo(InputArray value, UMat? mask = null) + public UMat SetTo(InputArrayRef value, UMat? mask = null) { ThrowIfDisposed(); - if (value is null) - throw new ArgumentNullException(nameof(value)); - value.ThrowIfDisposed(); var maskPtr = Cv2.ToPtr(mask); NativeMethods.HandleException( - NativeMethods.core_UMat_setTo_InputArray(Handle, value.ToInputProxy(), maskPtr)); + NativeMethods.core_UMat_setTo_InputArray(Handle, value.Proxy, maskPtr)); - GC.KeepAlive(value); + GC.KeepAlive(value.Source); GC.KeepAlive(mask); return this; } @@ -897,17 +870,14 @@ public UMat Inv(DecompTypes method = DecompTypes.LU) /// /// /// - public UMat Mul(InputArray m, double scale = 1) + public UMat Mul(InputArrayRef m, double scale = 1) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_UMat_mul(Handle, m.ToInputProxy(), scale, out var ret)); + NativeMethods.core_UMat_mul(Handle, m.Proxy, scale, out var ret)); - GC.KeepAlive(m); + GC.KeepAlive(m.Source); var retVal = new UMat(ret); return retVal; } @@ -917,17 +887,14 @@ public UMat Mul(InputArray m, double scale = 1) /// /// another dot-product operand. /// - public double Dot(InputArray m) + public double Dot(InputArrayRef m) { ThrowIfDisposed(); - if (m is null) - throw new ArgumentNullException(nameof(m)); - m.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_UMat_dot(Handle, m.ToInputProxy(), out var ret)); + NativeMethods.core_UMat_dot(Handle, m.Proxy, out var ret)); - GC.KeepAlive(m); + GC.KeepAlive(m.Source); return ret; } From 98133776333d5644856e4dbf77d82914a584eed9 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 18:45:03 +0900 Subject: [PATCH 18/29] Migration: PCA.cs/SVD.cs/LDA.cs/RNG.cs to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 13) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the "core残り" batch alongside Mat.cs/UMat.cs (parts 11-12). --- src/OpenCvSharp/Modules/core/LDA.cs | 86 ++++++------------- src/OpenCvSharp/Modules/core/PCA.cs | 104 +++++++---------------- src/OpenCvSharp/Modules/core/RNG.cs | 27 ++---- src/OpenCvSharp/Modules/core/SVD.cs | 123 ++++++++-------------------- 4 files changed, 95 insertions(+), 245 deletions(-) diff --git a/src/OpenCvSharp/Modules/core/LDA.cs b/src/OpenCvSharp/Modules/core/LDA.cs index 3259a21d3..d6350c986 100644 --- a/src/OpenCvSharp/Modules/core/LDA.cs +++ b/src/OpenCvSharp/Modules/core/LDA.cs @@ -31,18 +31,12 @@ public LDA(int numComponents = 0) /// /// /// - public LDA(InputArray src, InputArray labels, int numComponents = 0) + public LDA(InputArrayRef src, InputArrayRef labels, int numComponents = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - src.ThrowIfDisposed(); - labels.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_LDA_new2(src.ToInputProxy(), labels.ToInputProxy(), numComponents, out var p)); - GC.KeepAlive(src); - GC.KeepAlive(labels); + NativeMethods.core_LDA_new2(src.Proxy, labels.Proxy, numComponents, out var p)); + GC.KeepAlive(src.Source); + GC.KeepAlive(labels.Source); InitSafeHandle(p); } @@ -139,21 +133,15 @@ public void Load(FileStorage node) /// /// /// - public void Compute(InputArray src, InputArray labels) + public void Compute(InputArrayRef src, InputArrayRef labels) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - src.ThrowIfDisposed(); - labels.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_LDA_compute(Handle, src.ToInputProxy(), labels.ToInputProxy())); + NativeMethods.core_LDA_compute(Handle, src.Proxy, labels.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(labels); + GC.KeepAlive(src.Source); + GC.KeepAlive(labels.Source); } /// @@ -162,17 +150,14 @@ public void Compute(InputArray src, InputArray labels) /// /// /// - public Mat Project(InputArray src) + public Mat Project(InputArrayRef src) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_LDA_project(Handle, src.ToInputProxy(), out var ret)); + NativeMethods.core_LDA_project(Handle, src.Proxy, out var ret)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); return new Mat(ret); } @@ -183,17 +168,14 @@ public Mat Project(InputArray src) /// /// /// - public Mat Reconstruct(InputArray src) + public Mat Reconstruct(InputArrayRef src) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_LDA_reconstruct(Handle, src.ToInputProxy(), out var ret)); + NativeMethods.core_LDA_reconstruct(Handle, src.Proxy, out var ret)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); return new Mat(ret); } @@ -205,24 +187,14 @@ public Mat Reconstruct(InputArray src) /// /// /// - public static Mat SubspaceProject(InputArray w, InputArray mean, InputArray src) + public static Mat SubspaceProject(InputArrayRef w, InputArrayRef mean, InputArrayRef src) { - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - w.ThrowIfDisposed(); - mean.ThrowIfDisposed(); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_LDA_subspaceProject(w.ToInputProxy(), mean.ToInputProxy(), src.ToInputProxy(), out var ret)); + NativeMethods.core_LDA_subspaceProject(w.Proxy, mean.Proxy, src.Proxy, out var ret)); - GC.KeepAlive(w); - GC.KeepAlive(mean); - GC.KeepAlive(src); + GC.KeepAlive(w.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(src.Source); return new Mat(ret); } @@ -234,24 +206,14 @@ public static Mat SubspaceProject(InputArray w, InputArray mean, InputArray src) /// /// /// - public static Mat SubspaceReconstruct(InputArray w, InputArray mean, InputArray src) + public static Mat SubspaceReconstruct(InputArrayRef w, InputArrayRef mean, InputArrayRef src) { - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - w.ThrowIfDisposed(); - mean.ThrowIfDisposed(); - src.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_LDA_subspaceReconstruct(w.ToInputProxy(), mean.ToInputProxy(), src.ToInputProxy(), out var ret)); + NativeMethods.core_LDA_subspaceReconstruct(w.Proxy, mean.Proxy, src.Proxy, out var ret)); - GC.KeepAlive(w); - GC.KeepAlive(mean); - GC.KeepAlive(src); + GC.KeepAlive(w.Source); + GC.KeepAlive(mean.Source); + GC.KeepAlive(src.Source); return new Mat(ret); } diff --git a/src/OpenCvSharp/Modules/core/PCA.cs b/src/OpenCvSharp/Modules/core/PCA.cs index 50b080e9c..30567f490 100644 --- a/src/OpenCvSharp/Modules/core/PCA.cs +++ b/src/OpenCvSharp/Modules/core/PCA.cs @@ -28,18 +28,12 @@ public PCA() /// optional mean value; if the matrix is empty (@c noArray()), the mean is computed from the data. /// operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) /// maximum number of components that PCA should retain; by default, all the components are retained. - public PCA(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) + public PCA(InputArrayRef data, InputArrayRef mean, Flags flags, int maxComponents = 0) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_new2(data.ToInputProxy(), mean.ToInputProxy(), (int)flags, maxComponents, out var p)); - GC.KeepAlive(data); - GC.KeepAlive(mean); + NativeMethods.core_PCA_new2(data.Proxy, mean.Proxy, (int)flags, maxComponents, out var p)); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); InitSafeHandle(p); } @@ -51,18 +45,12 @@ public PCA(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) /// operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. - public PCA(InputArray data, InputArray mean, Flags flags, double retainedVariance) + public PCA(InputArrayRef data, InputArrayRef mean, Flags flags, double retainedVariance) { - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_new3(data.ToInputProxy(), mean.ToInputProxy(), (int)flags, retainedVariance, out var p)); - GC.KeepAlive(data); - GC.KeepAlive(mean); + NativeMethods.core_PCA_new3(data.Proxy, mean.Proxy, (int)flags, retainedVariance, out var p)); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); InitSafeHandle(p); } @@ -136,19 +124,13 @@ public Mat Mean /// maximum number of components that PCA should retain; /// by default, all the components are retained. /// - public PCA Compute(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) + public PCA Compute(InputArrayRef data, InputArrayRef mean, Flags flags, int maxComponents = 0) { ThrowIfDisposed(); - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_operatorThis(Handle, data.ToInputProxy(), mean.ToInputProxy(), (int)flags, maxComponents)); - GC.KeepAlive(data); - GC.KeepAlive(mean); + NativeMethods.core_PCA_operatorThis(Handle, data.Proxy, mean.Proxy, (int)flags, maxComponents)); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); return this; } @@ -173,19 +155,13 @@ public PCA Compute(InputArray data, InputArray mean, Flags flags, int maxCompone /// Using this parameter will let the %PCA decided how many components to /// retain but it will always keep at least 2. /// - public PCA ComputeVar(InputArray data, InputArray mean, Flags flags, double retainedVariance) + public PCA ComputeVar(InputArrayRef data, InputArrayRef mean, Flags flags, double retainedVariance) { ThrowIfDisposed(); - if (data is null) - throw new ArgumentNullException(nameof(data)); - if (mean is null) - throw new ArgumentNullException(nameof(mean)); - data.ThrowIfDisposed(); - mean.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_computeVar(Handle, data.ToInputProxy(), mean.ToInputProxy(), (int)flags, retainedVariance)); - GC.KeepAlive(data); - GC.KeepAlive(mean); + NativeMethods.core_PCA_computeVar(Handle, data.Proxy, mean.Proxy, (int)flags, retainedVariance)); + GC.KeepAlive(data.Source); + GC.KeepAlive(mean.Source); return this; } @@ -205,15 +181,12 @@ public PCA ComputeVar(InputArray data, InputArray mean, Flags flags, double reta /// (vector dimensionality) and `vec.rows` is the number of vectors to /// project, and the same is true for the PCA::DATA_AS_COL case. /// - public Mat Project(InputArray vec) + public Mat Project(InputArrayRef vec) { ThrowIfDisposed(); - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - vec.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_project1(Handle, vec.ToInputProxy(), out var ret)); - GC.KeepAlive(vec); + NativeMethods.core_PCA_project1(Handle, vec.Proxy, out var ret)); + GC.KeepAlive(vec.Source); return Mat.FromNativePointer(ret); } @@ -229,20 +202,13 @@ public Mat Project(InputArray vec) /// means that `result.cols==vec.cols` and the number of rows match the /// number of principal components (for example, `maxComponents` parameter /// passed to the constructor). - public void Project(InputArray vec, OutputArray result) + public void Project(InputArrayRef vec, OutputArrayRef result) { ThrowIfDisposed(); - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - vec.ThrowIfDisposed(); - result.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_PCA_project2(Handle, vec.ToInputProxy(), result.ToOutputProxy())); - result.Fix(); - GC.KeepAlive(vec); - GC.KeepAlive(result); + NativeMethods.core_PCA_project2(Handle, vec.Proxy, result.Proxy)); + GC.KeepAlive(vec.Source); + GC.KeepAlive(result.Source); } /// @@ -258,15 +224,12 @@ public void Project(InputArray vec, OutputArray result) /// coordinates of the vectors in the principal component subspace, /// the layout and size are the same as of PCA::project output vectors. /// - public Mat BackProject(InputArray vec) + public Mat BackProject(InputArrayRef vec) { ThrowIfDisposed(); - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - vec.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_PCA_backProject1(Handle, vec.ToInputProxy(), out var ret)); - GC.KeepAlive(vec); + NativeMethods.core_PCA_backProject1(Handle, vec.Proxy, out var ret)); + GC.KeepAlive(vec.Source); return new Mat(ret); } @@ -284,20 +247,13 @@ public Mat BackProject(InputArray vec) /// the layout and size are the same as of PCA::project output vectors. /// reconstructed vectors; the layout and size are the same as /// of PCA::project input vectors. - public void BackProject(InputArray vec, OutputArray result) + public void BackProject(InputArrayRef vec, OutputArrayRef result) { ThrowIfDisposed(); - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - vec.ThrowIfDisposed(); - result.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_PCA_backProject2(Handle, vec.ToInputProxy(), result.ToOutputProxy())); - result.Fix(); - GC.KeepAlive(vec); - GC.KeepAlive(result); + NativeMethods.core_PCA_backProject2(Handle, vec.Proxy, result.Proxy)); + GC.KeepAlive(vec.Source); + GC.KeepAlive(result.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/RNG.cs b/src/OpenCvSharp/Modules/core/RNG.cs index 45bd7386f..436a1ea75 100644 --- a/src/OpenCvSharp/Modules/core/RNG.cs +++ b/src/OpenCvSharp/Modules/core/RNG.cs @@ -270,29 +270,18 @@ public double Uniform(double a, double b) /// theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely produce array mostly filled /// with 0's and 255's, since the range (0, 255) is significantly smaller than [-DBL_MAX, DBL_MAX). public void Fill( - InputOutputArray mat, - DistributionType distType, - InputArray a, - InputArray b, + InputOutputArrayRef mat, + DistributionType distType, + InputArrayRef a, + InputArrayRef b, bool saturateRange = false) { - if (mat is null) - throw new ArgumentNullException(nameof(mat)); - if (a is null) - throw new ArgumentNullException(nameof(a)); - if (b is null) - throw new ArgumentNullException(nameof(b)); - mat.ThrowIfNotReady(); - a.ThrowIfDisposed(); - b.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_RNG_fill(ref state, mat.ToInputOutputProxy(), (int) distType, a.ToInputProxy(), b.ToInputProxy(), saturateRange ? 1 : 0)); + NativeMethods.core_RNG_fill(ref state, mat.Proxy, (int) distType, a.Proxy, b.Proxy, saturateRange ? 1 : 0)); - mat.Fix(); - GC.KeepAlive(mat); - GC.KeepAlive(a); - GC.KeepAlive(b); + GC.KeepAlive(mat.Source); + GC.KeepAlive(a.Source); + GC.KeepAlive(b.Source); } /// diff --git a/src/OpenCvSharp/Modules/core/SVD.cs b/src/OpenCvSharp/Modules/core/SVD.cs index c6f351abf..ccce5d0fc 100644 --- a/src/OpenCvSharp/Modules/core/SVD.cs +++ b/src/OpenCvSharp/Modules/core/SVD.cs @@ -22,14 +22,11 @@ public SVD() /// /// /// - public SVD(InputArray src, Flags flags = 0) + public SVD(InputArrayRef src, Flags flags = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_SVD_new2(src.ToInputProxy(), (int)flags, out var p)); - GC.KeepAlive(src); + NativeMethods.core_SVD_new2(src.Proxy, (int)flags, out var p)); + GC.KeepAlive(src.Source); InitSafeHandle(p); } @@ -83,15 +80,12 @@ public Mat Vt() /// /// /// - public SVD Run(InputArray src, Flags flags = 0) + public SVD Run(InputArrayRef src, Flags flags = 0) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.core_SVD_operatorThis(Handle, src.ToInputProxy(), (int)flags)); - GC.KeepAlive(src); + NativeMethods.core_SVD_operatorThis(Handle, src.Proxy, (int)flags)); + GC.KeepAlive(src.Source); return this; } @@ -101,19 +95,13 @@ public SVD Run(InputArray src, Flags flags = 0) /// /// /// - public void BackSubst(InputArray rhs, OutputArray dst) + public void BackSubst(InputArrayRef rhs, OutputArrayRef dst) { ThrowIfDisposed(); - if (rhs is null) - throw new ArgumentNullException(nameof(rhs)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - rhs.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_SVD_backSubst(Handle, rhs.ToInputProxy(), dst.ToOutputProxy())); - GC.KeepAlive(rhs); - GC.KeepAlive(dst); + NativeMethods.core_SVD_backSubst(Handle, rhs.Proxy, dst.Proxy)); + GC.KeepAlive(rhs.Source); + GC.KeepAlive(dst.Source); } /// @@ -124,30 +112,15 @@ public void BackSubst(InputArray rhs, OutputArray dst) /// /// /// - public static void Compute(InputArray src, OutputArray w, - OutputArray u, OutputArray vt, Flags flags = 0) + public static void Compute(InputArrayRef src, OutputArrayRef w, + OutputArrayRef u, OutputArrayRef vt, Flags flags = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (u is null) - throw new ArgumentNullException(nameof(u)); - if (vt is null) - throw new ArgumentNullException(nameof(vt)); - src.ThrowIfDisposed(); - w.ThrowIfNotReady(); - u.ThrowIfNotReady(); - vt.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_SVD_static_compute1(src.ToInputProxy(), w.ToOutputProxy(), u.ToOutputProxy(), vt.ToOutputProxy(), (int)flags)); - w.Fix(); - u.Fix(); - vt.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(w); - GC.KeepAlive(u); - GC.KeepAlive(vt); + NativeMethods.core_SVD_static_compute1(src.Proxy, w.Proxy, u.Proxy, vt.Proxy, (int)flags)); + GC.KeepAlive(src.Source); + GC.KeepAlive(w.Source); + GC.KeepAlive(u.Source); + GC.KeepAlive(vt.Source); } /// @@ -156,19 +129,12 @@ public static void Compute(InputArray src, OutputArray w, /// /// /// - public static void Compute(InputArray src, OutputArray w, Flags flags = 0) + public static void Compute(InputArrayRef src, OutputArrayRef w, Flags flags = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (w is null) - throw new ArgumentNullException(nameof(w)); - src.ThrowIfDisposed(); - w.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_SVD_static_compute2(src.ToInputProxy(), w.ToOutputProxy(), (int)flags)); - w.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(w); + NativeMethods.core_SVD_static_compute2(src.Proxy, w.Proxy, (int)flags)); + GC.KeepAlive(src.Source); + GC.KeepAlive(w.Source); } /// @@ -179,32 +145,16 @@ public static void Compute(InputArray src, OutputArray w, Flags flags = 0) /// /// /// - public static void BackSubst(InputArray w, InputArray u, - InputArray vt, InputArray rhs, OutputArray dst) + public static void BackSubst(InputArrayRef w, InputArrayRef u, + InputArrayRef vt, InputArrayRef rhs, OutputArrayRef dst) { - if (w is null) - throw new ArgumentNullException(nameof(w)); - if (u is null) - throw new ArgumentNullException(nameof(u)); - if (vt is null) - throw new ArgumentNullException(nameof(vt)); - if (rhs is null) - throw new ArgumentNullException(nameof(rhs)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - w.ThrowIfDisposed(); - u.ThrowIfDisposed(); - vt.ThrowIfDisposed(); - rhs.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_SVD_static_backSubst(w.ToInputProxy(), u.ToInputProxy(), vt.ToInputProxy(), rhs.ToInputProxy(), dst.ToOutputProxy())); - dst.Fix(); - GC.KeepAlive(w); - GC.KeepAlive(u); - GC.KeepAlive(vt); - GC.KeepAlive(rhs); - GC.KeepAlive(dst); + NativeMethods.core_SVD_static_backSubst(w.Proxy, u.Proxy, vt.Proxy, rhs.Proxy, dst.Proxy)); + GC.KeepAlive(w.Source); + GC.KeepAlive(u.Source); + GC.KeepAlive(vt.Source); + GC.KeepAlive(rhs.Source); + GC.KeepAlive(dst.Source); } /// @@ -212,19 +162,12 @@ public static void BackSubst(InputArray w, InputArray u, /// /// /// - public static void SolveZ(InputArray src, OutputArray dst) + public static void SolveZ(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.core_SVD_static_solveZ(src.ToInputProxy(), dst.ToOutputProxy())); - dst.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + NativeMethods.core_SVD_static_solveZ(src.Proxy, dst.Proxy)); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// From d47b554bbe9d86839b6cfd1a8887ebc0a29832a4 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:05:30 +0900 Subject: [PATCH 19/29] Migration: Cv2_imgproc.cs (133 methods) + Moments.cs to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 14) Scripted the mechanical parts of this conversion (signature retyping, null-check/ThrowIfDisposed/ThrowIfNotReady/Fix() removal, ToXProxy()-> .Proxy, GC.KeepAlive(x)->GC.KeepAlive(x.Source)) since Cv2_imgproc.cs is the largest Cv2 static file; manually fixed the handful of cases the script couldn't infer: - CreateHanningWindow's dst is purely an output (native signature takes OutputArray, not InputOutputArray) despite the old class-based API exposing it as InputOutputArray via inheritance -- InputOutputArrayRef has no such inheritance, so the param is now OutputArrayRef. - Moments' InputArray constructor/helper migrated alongside its only caller (Cv2.Moments). - Call sites passing literal `null` for now non-nullable *Ref parameters (CalcHist mask, MorphologyEx element, EMD cost) updated to `default`. - ImgProcTest.Rectangle's InputOutputArray.Create(...) smoke coverage swapped for InputOutputArrayRef.Create(...). --- src/OpenCvSharp/Cv2/Cv2_imgproc.cs | 2077 +++++------------ src/OpenCvSharp/Modules/imgproc/Moments.cs | 11 +- test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs | 14 +- 3 files changed, 572 insertions(+), 1530 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_imgproc.cs b/src/OpenCvSharp/Cv2/Cv2_imgproc.cs index 1b9043f95..0202faec5 100644 --- a/src/OpenCvSharp/Cv2/Cv2_imgproc.cs +++ b/src/OpenCvSharp/Cv2/Cv2_imgproc.cs @@ -45,24 +45,15 @@ static partial class Cv2 /// and wish to preserve all the fractional bits, you may want to set normalize = false. /// Type of filter coefficients. It can be CV_32f or CV_64F. public static void GetDerivKernels( - OutputArray kx, OutputArray ky, int dx, int dy, int ksize, + OutputArrayRef kx, OutputArrayRef ky, int dx, int dy, int ksize, bool normalize = false, MatType? ktype = null) { - if (kx is null) - throw new ArgumentNullException(nameof(kx)); - if (ky is null) - throw new ArgumentNullException(nameof(ky)); - kx.ThrowIfNotReady(); - ky.ThrowIfNotReady(); - var ktype0 = ktype.GetValueOrDefault(MatType.CV_32F); NativeMethods.HandleException( NativeMethods.imgproc_getDerivKernels( - kx.ToOutputProxy(), ky.ToOutputProxy(), dx, dy, ksize, normalize ? 1 : 0, ktype0)); - GC.KeepAlive(kx); - GC.KeepAlive(ky); - kx.Fix(); - ky.Fix(); + kx.Proxy, ky.Proxy, dx, dy, ksize, normalize ? 1 : 0, ktype0)); + GC.KeepAlive(kx.Source); + GC.KeepAlive(ky.Source); } /// @@ -125,21 +116,13 @@ public static Mat GetStructuringElement(MorphShapes shape, Size ksize, Point anc /// For larger aperture sizes it can only be CV_8U /// The destination array; will have the same size and the same type as src /// The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ... - public static void MedianBlur(InputArray src, OutputArray dst, int ksize) + public static void MedianBlur(InputArrayRef src, OutputArrayRef dst, int ksize) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_medianBlur(src.ToInputProxy(), dst.ToOutputProxy(), ksize)); + NativeMethods.imgproc_medianBlur(src.Proxy, dst.Proxy, ksize)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -157,22 +140,14 @@ public static void MedianBlur(InputArray src, OutputArray dst, int ksize) /// regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. /// pixel extrapolation method /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, + public static void GaussianBlur(InputArrayRef src, OutputArrayRef dst, Size ksize, double sigmaX, double sigmaY = 0, BorderTypes borderType = BorderTypes.Default, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_GaussianBlur(src.ToInputProxy(), dst.ToOutputProxy(), ksize, sigmaX, sigmaY, borderType, (int)hint)); + NativeMethods.imgproc_GaussianBlur(src.Proxy, dst.Proxy, ksize, sigmaX, sigmaY, borderType, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -190,22 +165,14 @@ public static void GaussianBlur(InputArray src, OutputArray dst, Size ksize, dou /// (as long as their colors are close enough; see sigmaColor). Then d>0 , it specifies /// the neighborhood size regardless of sigmaSpace, otherwise d is proportional to sigmaSpace /// - public static void BilateralFilter(InputArray src, OutputArray dst, int d, double sigmaColor, + public static void BilateralFilter(InputArrayRef src, OutputArrayRef dst, int d, double sigmaColor, double sigmaSpace, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_bilateralFilter(src.ToInputProxy(), dst.ToOutputProxy(), d, sigmaColor, sigmaSpace, borderType)); + NativeMethods.imgproc_bilateralFilter(src.Proxy, dst.Proxy, d, sigmaColor, sigmaSpace, borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -219,24 +186,16 @@ public static void BilateralFilter(InputArray src, OutputArray dst, int d, doubl /// Indicates, whether the kernel is normalized by its area or not /// The border mode used to extrapolate pixels outside of the image public static void BoxFilter( - InputArray src, OutputArray dst, MatType ddepth, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, Size ksize, Point? anchor = null, bool normalize = true, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_boxFilter(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, ksize, anchor0, normalize ? 1 : 0, borderType)); + NativeMethods.imgproc_boxFilter(src.Proxy, dst.Proxy, ddepth, ksize, anchor0, normalize ? 1 : 0, borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -256,24 +215,16 @@ public static void BoxFilter( /// /// public static void SqrBoxFilter( - InputArray src, OutputArray dst, int ddepth, + InputArrayRef src, OutputArrayRef dst, int ddepth, Size ksize, Point? anchor = null, bool normalize = true, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_sqrBoxFilter(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, ksize, anchor0, normalize ? 1 : 0, borderType)); + NativeMethods.imgproc_sqrBoxFilter(src.Proxy, dst.Proxy, ddepth, ksize, anchor0, normalize ? 1 : 0, borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -285,23 +236,15 @@ public static void SqrBoxFilter( /// The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center /// The border mode used to extrapolate pixels outside of the image public static void Blur( - InputArray src, OutputArray dst, Size ksize, + InputArrayRef src, OutputArrayRef dst, Size ksize, Point? anchor = null, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_blur(src.ToInputProxy(), dst.ToOutputProxy(), ksize, anchor0, (int)borderType)); + NativeMethods.imgproc_blur(src.Proxy, dst.Proxy, ksize, anchor0, (int)borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -319,28 +262,17 @@ public static void Blur( /// The optional value added to the filtered pixels before storing them in dst /// The pixel extrapolation method public static void Filter2D( - InputArray src, OutputArray dst, MatType ddepth, - InputArray kernel, Point? anchor = null, double delta = 0, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, + InputArrayRef kernel, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (kernel is null) - throw new ArgumentNullException(nameof(kernel)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - kernel.ThrowIfDisposed(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_filter2D(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, kernel.ToInputProxy(), anchor0, delta, (int)borderType)); + NativeMethods.imgproc_filter2D(src.Proxy, dst.Proxy, ddepth, kernel.Proxy, anchor0, delta, (int)borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(kernel); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(kernel.Source); } /// @@ -350,28 +282,17 @@ public static void Filter2D( /// output image of the same size and the same number of channels as src. /// convolution kernel (or rather a correlation kernel), a single-channel floating point matrix. /// filtering parameters (anchor, border, depth, scale, shift). Null uses the defaults. - public static void Filter2D(InputArray src, OutputArray dst, InputArray kernel, Filter2DParams? @params = null) + public static void Filter2D(InputArrayRef src, OutputArrayRef dst, InputArrayRef kernel, Filter2DParams? @params = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (kernel is null) - throw new ArgumentNullException(nameof(kernel)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - kernel.ThrowIfDisposed(); - var p = @params ?? new Filter2DParams(); NativeMethods.HandleException( NativeMethods.imgproc_filter2Dp( - src.ToInputProxy(), dst.ToOutputProxy(), kernel.ToInputProxy(), + src.Proxy, dst.Proxy, kernel.Proxy, p.AnchorX, p.AnchorY, (int)p.BorderType, p.BorderValue, p.Ddepth, p.Scale, p.Shift)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(kernel); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(kernel.Source); } /// @@ -386,33 +307,19 @@ public static void Filter2D(InputArray src, OutputArray dst, InputArray kernel, /// The value added to the filtered results before storing them /// The pixel extrapolation method public static void SepFilter2D( - InputArray src, OutputArray dst, MatType ddepth, InputArray kernelX, InputArray kernelY, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, InputArrayRef kernelX, InputArrayRef kernelY, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (kernelX is null) - throw new ArgumentNullException(nameof(kernelX)); - if (kernelY is null) - throw new ArgumentNullException(nameof(kernelY)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - kernelX.ThrowIfDisposed(); - kernelY.ThrowIfDisposed(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_sepFilter2D(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, - kernelX.ToInputProxy(), kernelY.ToInputProxy(), anchor0, delta, (int) borderType)); + NativeMethods.imgproc_sepFilter2D(src.Proxy, dst.Proxy, ddepth, + kernelX.Proxy, kernelY.Proxy, anchor0, delta, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(kernelX); - GC.KeepAlive(kernelY); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(kernelX.Source); + GC.KeepAlive(kernelY.Source); } /// @@ -428,24 +335,16 @@ public static void SepFilter2D( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Sobel( - InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, int xorder, int yorder, int ksize = 3, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_Sobel(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, xorder, yorder, + NativeMethods.imgproc_Sobel(src.Proxy, dst.Proxy, ddepth, xorder, yorder, ksize, scale, delta, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -457,24 +356,12 @@ public static void Sobel( /// size of Sobel kernel. It must be 3. /// pixel extrapolation method public static void SpatialGradient( - InputArray src, OutputArray dx, OutputArray dy, int ksize = 3, BorderTypes borderType = BorderTypes.Default) + InputArrayRef src, OutputArrayRef dx, OutputArrayRef dy, int ksize = 3, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dx is null) - throw new ArgumentNullException(nameof(dx)); - if (dy is null) - throw new ArgumentNullException(nameof(dy)); - src.ThrowIfDisposed(); - dx.ThrowIfNotReady(); - dy.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_spatialGradient(src.ToInputProxy(), dx.ToOutputProxy(), dy.ToOutputProxy(), ksize, (int)borderType)); + NativeMethods.imgproc_spatialGradient(src.Proxy, dx.Proxy, dy.Proxy, ksize, (int)borderType)); - GC.KeepAlive(src); - dx.Fix(); - dy.Fix(); + GC.KeepAlive(src.Source); } /// @@ -489,23 +376,15 @@ public static void SpatialGradient( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Scharr( - InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, int xorder, int yorder, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_Scharr(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, xorder, yorder, + NativeMethods.imgproc_Scharr(src.Proxy, dst.Proxy, ddepth, xorder, yorder, scale, delta, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -519,23 +398,15 @@ public static void Scharr( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Laplacian( - InputArray src, OutputArray dst, MatType ddepth, + InputArrayRef src, OutputArrayRef dst, MatType ddepth, int ksize = 1, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_Laplacian(src.ToInputProxy(), dst.ToOutputProxy(), ddepth, ksize, scale, delta, (int) borderType)); + NativeMethods.imgproc_Laplacian(src.Proxy, dst.Proxy, ddepth, ksize, scale, delta, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -547,22 +418,14 @@ public static void Laplacian( /// The second threshold for the hysteresis procedure /// Aperture size for the Sobel operator [By default this is ApertureSize.Size3] /// Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false] - public static void Canny(InputArray src, OutputArray edges, + public static void Canny(InputArrayRef src, OutputArrayRef edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (edges is null) - throw new ArgumentNullException(nameof(edges)); - src.ThrowIfDisposed(); - edges.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_Canny1(src.ToInputProxy(), edges.ToOutputProxy(), threshold1, threshold2, apertureSize, L2gradient ? 1 : 0)); + NativeMethods.imgproc_Canny1(src.Proxy, edges.Proxy, threshold1, threshold2, apertureSize, L2gradient ? 1 : 0)); - GC.KeepAlive(src); - GC.KeepAlive(edges); - edges.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(edges.Source); } /// @@ -575,27 +438,16 @@ public static void Canny(InputArray src, OutputArray edges, /// second threshold for the hysteresis procedure. /// Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false] public static void Canny( - InputArray dx, InputArray dy, OutputArray edges, + InputArrayRef dx, InputArrayRef dy, OutputArrayRef edges, double threshold1, double threshold2, bool L2gradient = false) { - if (dx is null) - throw new ArgumentNullException(nameof(dx)); - if (dy is null) - throw new ArgumentNullException(nameof(dy)); - if (edges is null) - throw new ArgumentNullException(nameof(edges)); - dx.ThrowIfDisposed(); - dy.ThrowIfDisposed(); - edges.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_Canny2( - dx.ToInputProxy(), dy.ToInputProxy(), edges.ToOutputProxy(), threshold1, threshold2, L2gradient ? 1 : 0)); + dx.Proxy, dy.Proxy, edges.Proxy, threshold1, threshold2, L2gradient ? 1 : 0)); - GC.KeepAlive(dx); - GC.KeepAlive(dy); - edges.Fix(); + GC.KeepAlive(dx.Source); + GC.KeepAlive(dy.Source); } /// @@ -607,25 +459,17 @@ public static void Canny( /// Aperture parameter for the Sobel operator. /// Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. public static void CornerMinEigenVal( - InputArray src, - OutputArray dst, + InputArrayRef src, + OutputArrayRef dst, int blockSize, int ksize = 3, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_cornerMinEigenVal(src.ToInputProxy(), dst.ToOutputProxy(), blockSize, ksize, (int) borderType)); + NativeMethods.imgproc_cornerMinEigenVal(src.Proxy, dst.Proxy, blockSize, ksize, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -639,26 +483,18 @@ public static void CornerMinEigenVal( /// Harris detector free parameter. See the formula above. /// Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. public static void CornerHarris( - InputArray src, - OutputArray dst, + InputArrayRef src, + OutputArrayRef dst, int blockSize, int ksize, double k, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_cornerHarris(src.ToInputProxy(), dst.ToOutputProxy(), blockSize, ksize, k, (int)borderType)); + NativeMethods.imgproc_cornerHarris(src.Proxy, dst.Proxy, blockSize, ksize, k, (int)borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -670,22 +506,14 @@ public static void CornerHarris( /// /// public static void CornerEigenValsAndVecs( - InputArray src, OutputArray dst, int blockSize, int ksize, + InputArrayRef src, OutputArrayRef dst, int blockSize, int ksize, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_cornerEigenValsAndVecs(src.ToInputProxy(), dst.ToOutputProxy(), blockSize, ksize, (int) borderType)); + NativeMethods.imgproc_cornerEigenValsAndVecs(src.Proxy, dst.Proxy, blockSize, ksize, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -696,21 +524,13 @@ public static void CornerEigenValsAndVecs( /// /// public static void PreCornerDetect( - InputArray src, OutputArray dst, int ksize, BorderTypes borderType = BorderTypes.Default) + InputArrayRef src, OutputArrayRef dst, int ksize, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_preCornerDetect(src.ToInputProxy(), dst.ToOutputProxy(), ksize, (int) borderType)); + NativeMethods.imgproc_preCornerDetect(src.Proxy, dst.Proxy, ksize, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -726,14 +546,11 @@ public static void PreCornerDetect( /// That is, the process of corner position refinement stops either after criteria.maxCount iterations /// or when the corner position moves by less than criteria.epsilon on some iteration. /// - public static Point2f[] CornerSubPix(InputArray image, IEnumerable inputCorners, + public static Point2f[] CornerSubPix(InputArrayRef image, IEnumerable inputCorners, Size winSize, Size zeroZone, TermCriteria criteria) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (inputCorners is null) throw new ArgumentNullException(nameof(inputCorners)); - image.ThrowIfDisposed(); var inputCornersSrc = inputCorners.ToArray(); var inputCornersCopy = new Point2f[inputCornersSrc.Length]; @@ -741,8 +558,8 @@ public static Point2f[] CornerSubPix(InputArray image, IEnumerable inpu using var vector = new StdVector(inputCornersCopy); NativeMethods.HandleException( - NativeMethods.imgproc_cornerSubPix(image.ToInputProxy(), vector.CvPtr, winSize, zeroZone, criteria)); - GC.KeepAlive(image); + NativeMethods.imgproc_cornerSubPix(image.Proxy, vector.CvPtr, winSize, zeroZone, criteria)); + GC.KeepAlive(image.Source); return vector.ToArray(); } @@ -765,21 +582,17 @@ public static Point2f[] CornerSubPix(InputArray image, IEnumerable inpu /// Parameter indicating whether to use a Harris detector /// Free parameter of the Harris detector. /// Output vector of detected corners. - public static Point2f[] GoodFeaturesToTrack(InputArray src, + public static Point2f[] GoodFeaturesToTrack(InputArrayRef src, int maxCorners, double qualityLevel, double minDistance, - InputArray mask, int blockSize, bool useHarrisDetector, double k) + InputArrayRef mask, int blockSize, bool useHarrisDetector, double k) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); - using var vector = new StdVector(); - var maskPtr = mask?.ToInputProxy() ?? default; + var maskPtr = mask.Proxy; NativeMethods.HandleException( - NativeMethods.imgproc_goodFeaturesToTrack(src.ToInputProxy(), vector.CvPtr, maxCorners, qualityLevel, + NativeMethods.imgproc_goodFeaturesToTrack(src.Proxy, vector.CvPtr, maxCorners, qualityLevel, minDistance, maskPtr, blockSize, useHarrisDetector ? 1 : 0, k)); - GC.KeepAlive(src); - GC.KeepAlive(mask); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); return vector.ToArray(); } @@ -795,16 +608,13 @@ public static Point2f[] GoodFeaturesToTrack(InputArray src, /// The output vector of lines. Each line is represented by a two-element vector (rho, theta) . /// rho is the distance from the coordinate origin (0,0) (top-left corner of the image) and theta is the line rotation angle in radians public static LineSegmentPolar[] HoughLines( - InputArray image, double rho, double theta, int threshold, + InputArrayRef image, double rho, double theta, int threshold, double srn = 0, double stn = 0) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - using var vec = new StdVector(); NativeMethods.HandleException( - NativeMethods.imgproc_HoughLines(image.ToInputProxy(), vec.CvPtr, rho, theta, threshold, srn, stn)); - GC.KeepAlive(image); + NativeMethods.imgproc_HoughLines(image.Proxy, vec.CvPtr, rho, theta, threshold, srn, stn)); + GC.KeepAlive(image.Source); return vec.ToArray(); } @@ -819,16 +629,13 @@ public static LineSegmentPolar[] HoughLines( /// The maximum allowed gap between points on the same line to link them. [By default this is 0] /// The output lines. Each line is represented by a 4-element vector (x1, y1, x2, y2) public static LineSegmentPoint[] HoughLinesP( - InputArray image, double rho, double theta, int threshold, + InputArrayRef image, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); using var vec = new StdVector(); NativeMethods.HandleException( - NativeMethods.imgproc_HoughLinesP(image.ToInputProxy(), vec.CvPtr, rho, theta, threshold, minLineLength, maxLineGap)); - GC.KeepAlive(image); + NativeMethods.imgproc_HoughLinesP(image.Proxy, vec.CvPtr, rho, theta, threshold, minLineLength, maxLineGap)); + GC.KeepAlive(image.Source); return vec.ToArray(); } @@ -847,23 +654,15 @@ public static LineSegmentPoint[] HoughLinesP( /// Maximum angle value of the accumulator in radians. /// Angle resolution of the accumulator in radians. public static void HoughLinesPointSet( - InputArray point, OutputArray lines, int linesMax, int threshold, + InputArrayRef point, OutputArrayRef lines, int linesMax, int threshold, double minRho, double maxRho, double rhoStep, double minTheta, double maxTheta, double thetaStep) { - if (point is null) - throw new ArgumentNullException(nameof(point)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - point.ThrowIfDisposed(); - lines.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_HoughLinesPointSet( - point.ToInputProxy(), lines.ToOutputProxy(), linesMax, threshold, minRho, maxRho, rhoStep, minTheta, maxTheta, thetaStep)); + point.Proxy, lines.Proxy, linesMax, threshold, minRho, maxRho, rhoStep, minTheta, maxTheta, thetaStep)); - GC.KeepAlive(point); - lines.Fix(); + GC.KeepAlive(point.Source); } /// @@ -879,17 +678,14 @@ public static void HoughLinesPointSet( /// Maximum circle radius. [By default this is 0] /// The output vector found circles. Each vector is encoded as 3-element floating-point vector (x, y, radius) public static CircleSegment[] HoughCircles( - InputArray image, HoughModes method, double dp, double minDist, + InputArrayRef image, HoughModes method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); using var vec = new StdVector(); NativeMethods.HandleException( - NativeMethods.imgproc_HoughCircles(image.ToInputProxy(), vec.CvPtr, (int) method, dp, minDist, param1, + NativeMethods.imgproc_HoughCircles(image.Proxy, vec.CvPtr, (int) method, dp, minDist, param1, param2, minRadius, maxRadius)); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); return vec.ToArray(); } @@ -913,27 +709,19 @@ public static Scalar MorphologyDefaultBorderValue() /// The pixel extrapolation method. [By default this is BorderType.Constant] /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void Dilate( - InputArray src, OutputArray dst, InputArray? element, + InputArrayRef src, OutputArrayRef dst, InputArrayRef element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); var borderValue0 = borderValue.GetValueOrDefault(MorphologyDefaultBorderValue()); - var elementPtr = element?.ToInputProxy() ?? default; + var elementPtr = element.Proxy; NativeMethods.HandleException( - NativeMethods.imgproc_dilate(src.ToInputProxy(), dst.ToOutputProxy(), elementPtr, anchor0, iterations, (int) borderType, borderValue0)); + NativeMethods.imgproc_dilate(src.Proxy, dst.Proxy, elementPtr, anchor0, iterations, (int) borderType, borderValue0)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(element); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(element.Source); } /// @@ -947,27 +735,19 @@ public static void Dilate( /// The pixel extrapolation method /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void Erode( - InputArray src, OutputArray dst, InputArray? element, + InputArrayRef src, OutputArrayRef dst, InputArrayRef element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); var borderValue0 = borderValue.GetValueOrDefault(MorphologyDefaultBorderValue()); - var elementPtr = element?.ToInputProxy() ?? default; + var elementPtr = element.Proxy; NativeMethods.HandleException( - NativeMethods.imgproc_erode(src.ToInputProxy(), dst.ToOutputProxy(), elementPtr, anchor0, iterations, (int) borderType, borderValue0)); + NativeMethods.imgproc_erode(src.Proxy, dst.Proxy, elementPtr, anchor0, iterations, (int) borderType, borderValue0)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(element); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(element.Source); } /// @@ -982,29 +762,20 @@ public static void Erode( /// The pixel extrapolation method. [By default this is BorderType.Constant] /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void MorphologyEx( - InputArray src, OutputArray dst, MorphTypes op, InputArray? element, + InputArrayRef src, OutputArrayRef dst, MorphTypes op, InputArrayRef element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - element?.ThrowIfDisposed(); - var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); var borderValue0 = borderValue.GetValueOrDefault(MorphologyDefaultBorderValue()); - var elementPtr = element?.ToInputProxy() ?? default; + var elementPtr = element.Proxy; NativeMethods.HandleException( - NativeMethods.imgproc_morphologyEx(src.ToInputProxy(), dst.ToOutputProxy(), (int) op, elementPtr, anchor0, iterations, + NativeMethods.imgproc_morphologyEx(src.Proxy, dst.Proxy, (int) op, elementPtr, anchor0, iterations, (int) borderType, borderValue0)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(element); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(element.Source); } /// @@ -1021,22 +792,14 @@ public static void MorphologyEx( /// scale factor along the vertical axis; when it equals 0, /// it is computed as: (double)dsize.height/src.rows /// interpolation method - public static void Resize(InputArray src, OutputArray dst, Size dsize, + public static void Resize(InputArrayRef src, OutputArrayRef dst, Size dsize, double fx = 0, double fy = 0, InterpolationFlags interpolation = InterpolationFlags.Linear) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_resize(src.ToInputProxy(), dst.ToOutputProxy(), dsize, fx, fy, (int) interpolation)); + NativeMethods.imgproc_resize(src.Proxy, dst.Proxy, dsize, fx, fy, (int) interpolation)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1054,29 +817,18 @@ public static void Resize(InputArray src, OutputArray dst, Size dsize, /// value used in case of a constant border; by default, it is 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpAffine( - InputArray src, OutputArray dst, InputArray m, Size dsize, + InputArrayRef src, OutputArrayRef dst, InputArrayRef m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (m is null) - throw new ArgumentNullException(nameof(m)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - m.ThrowIfDisposed(); - var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); NativeMethods.HandleException( - NativeMethods.imgproc_warpAffine(src.ToInputProxy(), dst.ToOutputProxy(), m.ToInputProxy(), dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); + NativeMethods.imgproc_warpAffine(src.Proxy, dst.Proxy, m.Proxy, dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(m); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(m.Source); } /// @@ -1092,31 +844,20 @@ public static void WarpAffine( /// value used in case of a constant border; by default, it equals 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpPerspective( - InputArray src, OutputArray dst, InputArray m, Size dsize, + InputArrayRef src, OutputArrayRef dst, InputArrayRef m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (m is null) - throw new ArgumentNullException(nameof(m)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - m.ThrowIfDisposed(); - var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); NativeMethods.HandleException( NativeMethods.imgproc_warpPerspective_MisInputArray( - src.ToInputProxy(), dst.ToOutputProxy(), m.ToInputProxy(), dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); + src.Proxy, dst.Proxy, m.Proxy, dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(m); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(m.Source); } /// @@ -1132,20 +873,14 @@ public static void WarpPerspective( /// value used in case of a constant border; by default, it equals 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpPerspective( - InputArray src, OutputArray dst, float[,] m, Size dsize, + InputArrayRef src, OutputArrayRef dst, float[,] m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); if (m is null) throw new ArgumentNullException(nameof(m)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); var mRow = m.GetLength(0); @@ -1153,11 +888,10 @@ public static void WarpPerspective( var mSpan = MemoryMarshal.CreateReadOnlySpan(ref m[0, 0], m.Length); NativeMethods.HandleException( NativeMethods.imgproc_warpPerspective_MisArray( - src.ToInputProxy(), dst.ToOutputProxy(), mSpan, mRow, mCol, dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); + src.Proxy, dst.Proxy, mSpan, mRow, mCol, dsize, (int) flags, (int) borderMode, borderValue0, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1174,34 +908,20 @@ public static void WarpPerspective( /// Value used in case of a constant border. By default, it is 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void Remap( - InputArray src, OutputArray dst, InputArray map1, InputArray map2, + InputArrayRef src, OutputArrayRef dst, InputArrayRef map1, InputArrayRef map2, InterpolationFlags interpolation = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (map1 is null) - throw new ArgumentNullException(nameof(map1)); - if (map2 is null) - throw new ArgumentNullException(nameof(map2)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - map1.ThrowIfDisposed(); - map2.ThrowIfDisposed(); - var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); NativeMethods.HandleException( - NativeMethods.imgproc_remap(src.ToInputProxy(), dst.ToOutputProxy(), map1.ToInputProxy(), map2.ToInputProxy(), (int) interpolation, + NativeMethods.imgproc_remap(src.Proxy, dst.Proxy, map1.Proxy, map2.Proxy, (int) interpolation, (int) borderMode, borderValue0, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); - GC.KeepAlive(map1); - GC.KeepAlive(map2); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(map1.Source); + GC.KeepAlive(map2.Source); } /// @@ -1213,31 +933,16 @@ public static void Remap( /// The second output map. /// Type of the first output map that should be CV_16SC2 , CV_32FC1 , or CV_32FC2 . /// Flag indicating whether the fixed-point maps are used for the nearest-neighbor or for a more complex interpolation. - public static void ConvertMaps(InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, MatType dstmap1Type, bool nnInterpolation = false) - { - if (map1 is null) - throw new ArgumentNullException(nameof(map1)); - if (map2 is null) - throw new ArgumentNullException(nameof(map2)); - if (dstmap1 is null) - throw new ArgumentNullException(nameof(dstmap1)); - if (dstmap2 is null) - throw new ArgumentNullException(nameof(dstmap2)); - map1.ThrowIfDisposed(); - map2.ThrowIfDisposed(); - dstmap1.ThrowIfDisposed(); - dstmap2.ThrowIfDisposed(); - - NativeMethods.HandleException( - NativeMethods.imgproc_convertMaps(map1.ToInputProxy(), map2.ToInputProxy(), dstmap1.ToOutputProxy(), dstmap2.ToOutputProxy(), dstmap1Type, + public static void ConvertMaps(InputArrayRef map1, InputArrayRef map2, OutputArrayRef dstmap1, OutputArrayRef dstmap2, MatType dstmap1Type, bool nnInterpolation = false) + { + NativeMethods.HandleException( + NativeMethods.imgproc_convertMaps(map1.Proxy, map2.Proxy, dstmap1.Proxy, dstmap2.Proxy, dstmap1Type, nnInterpolation ? 1 : 0)); - GC.KeepAlive(map1); - GC.KeepAlive(map2); - GC.KeepAlive(dstmap1); - GC.KeepAlive(dstmap2); - dstmap1.Fix(); - dstmap2.Fix(); + GC.KeepAlive(map1.Source); + GC.KeepAlive(map2.Source); + GC.KeepAlive(dstmap1.Source); + GC.KeepAlive(dstmap2.Source); } /// @@ -1259,19 +964,12 @@ public static Mat GetRotationMatrix2D(Point2f center, double angle, double scale /// /// Original affine transformation. /// Output reverse affine transformation. - public static void InvertAffineTransform(InputArray m, OutputArray im) + public static void InvertAffineTransform(InputArrayRef m, OutputArrayRef im) { - if (m is null) - throw new ArgumentNullException(nameof(m)); - if (im is null) - throw new ArgumentNullException(nameof(im)); - m.ThrowIfDisposed(); - im.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.imgproc_invertAffineTransform(m.ToInputProxy(), im.ToOutputProxy())); - GC.KeepAlive(m); - GC.KeepAlive(im); - im.Fix(); + NativeMethods.imgproc_invertAffineTransform(m.Proxy, im.Proxy)); + GC.KeepAlive(m.Source); + GC.KeepAlive(im.Source); } /// @@ -1302,20 +1000,12 @@ public static Mat GetPerspectiveTransform(IEnumerable src, IEnumerable< /// Coordinates of quadrangle vertices in the source image. /// Coordinates of the corresponding quadrangle vertices in the destination image. /// - public static Mat GetPerspectiveTransform(InputArray src, InputArray dst) + public static Mat GetPerspectiveTransform(InputArrayRef src, InputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_getPerspectiveTransform2(src.ToInputProxy(), dst.ToInputProxy(), out var retMat)); - GC.KeepAlive(src); - GC.KeepAlive(dst); + NativeMethods.imgproc_getPerspectiveTransform2(src.Proxy, dst.Proxy, out var retMat)); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return new Mat(retMat); } @@ -1347,21 +1037,13 @@ public static Mat GetAffineTransform(IEnumerable src, IEnumerableCoordinates of triangle vertices in the source image. /// Coordinates of the corresponding triangle vertices in the destination image. /// - public static Mat GetAffineTransform(InputArray src, InputArray dst) + public static Mat GetAffineTransform(InputArrayRef src, InputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_getAffineTransform2(src.ToInputProxy(), dst.ToInputProxy(), out var retMat)); + NativeMethods.imgproc_getAffineTransform2(src.Proxy, dst.Proxy, out var retMat)); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return new Mat(retMat); } @@ -1374,22 +1056,14 @@ public static Mat GetAffineTransform(InputArray src, InputArray dst) /// within the source image. The center must be inside the image. /// Extracted patch that has the size patchSize and the same number of channels as src . /// Depth of the extracted pixels. By default, they have the same depth as src. - public static void GetRectSubPix(InputArray image, Size patchSize, Point2f center, - OutputArray patch, int patchType = -1) + public static void GetRectSubPix(InputArrayRef image, Size patchSize, Point2f center, + OutputArrayRef patch, int patchType = -1) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (patch is null) - throw new ArgumentNullException(nameof(patch)); - image.ThrowIfDisposed(); - patch.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_getRectSubPix(image.ToInputProxy(), patchSize, center, patch.ToOutputProxy(), patchType)); + NativeMethods.imgproc_getRectSubPix(image.Proxy, patchSize, center, patch.Proxy, patchType)); - GC.KeepAlive(image); - GC.KeepAlive(patch); - patch.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(patch.Source); } /// @@ -1408,23 +1082,15 @@ public static void GetRectSubPix(InputArray image, Size patchSize, Point2f cente /// interpolation methods. /// interpolation methods. public static void WarpPolar( - InputArray src, OutputArray dst, Size dsize, + InputArrayRef src, OutputArrayRef dst, Size dsize, Point2f center, double maxRadius, InterpolationFlags interpolationFlags, WarpPolarMode warpPolarMode) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - int flags = (int)interpolationFlags | (int)warpPolarMode; NativeMethods.HandleException( - NativeMethods.imgproc_warpPolar(src.ToInputProxy(), dst.ToOutputProxy(), dsize, center, maxRadius, flags)); + NativeMethods.imgproc_warpPolar(src.Proxy, dst.Proxy, dsize, center, maxRadius, flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1434,22 +1100,13 @@ public static void WarpPolar( /// /// /// - public static void Integral(InputArray src, OutputArray sum, MatType? sdepth = null) + public static void Integral(InputArrayRef src, OutputArrayRef sum, MatType? sdepth = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (sum is null) - throw new ArgumentNullException(nameof(sum)); - - src.ThrowIfDisposed(); - sum.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_integral1(src.ToInputProxy(), sum.ToOutputProxy(), sdepth?.Value ?? -1)); + NativeMethods.imgproc_integral1(src.Proxy, sum.Proxy, sdepth?.Value ?? -1)); - GC.KeepAlive(src); - GC.KeepAlive(sum); - sum.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(sum.Source); } /// @@ -1460,26 +1117,14 @@ public static void Integral(InputArray src, OutputArray sum, MatType? sdepth = n /// /// /// - public static void Integral(InputArray src, OutputArray sum, OutputArray sqsum, MatType? sdepth = null) + public static void Integral(InputArrayRef src, OutputArrayRef sum, OutputArrayRef sqsum, MatType? sdepth = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (sum is null) - throw new ArgumentNullException(nameof(sum)); - if (sqsum is null) - throw new ArgumentNullException(nameof(sqsum)); - src.ThrowIfDisposed(); - sum.ThrowIfNotReady(); - sqsum.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_integral2(src.ToInputProxy(), sum.ToOutputProxy(), sqsum.ToOutputProxy(), sdepth?.Value ?? -1)); + NativeMethods.imgproc_integral2(src.Proxy, sum.Proxy, sqsum.Proxy, sdepth?.Value ?? -1)); - GC.KeepAlive(src); - GC.KeepAlive(sum); - GC.KeepAlive(sqsum); - sum.Fix(); - sqsum.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(sum.Source); + GC.KeepAlive(sqsum.Source); } /// @@ -1493,32 +1138,16 @@ public static void Integral(InputArray src, OutputArray sum, OutputArray sqsum, /// desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or CV_64F. /// desired depth of the integral image of squared pixel values, CV_32F or CV_64F. public static void Integral( - InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, + InputArrayRef src, OutputArrayRef sum, OutputArrayRef sqsum, OutputArrayRef tilted, MatType? sdepth = null, MatType? sqdepth = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (sum is null) - throw new ArgumentNullException(nameof(sum)); - if (sqsum is null) - throw new ArgumentNullException(nameof(sqsum)); - if (tilted is null) - throw new ArgumentNullException(nameof(tilted)); - src.ThrowIfDisposed(); - sum.ThrowIfNotReady(); - sqsum.ThrowIfNotReady(); - tilted.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_integral3(src.ToInputProxy(), sum.ToOutputProxy(), sqsum.ToOutputProxy(), tilted.ToOutputProxy(), sdepth?.Value ?? -1, sqdepth?.Value ?? -1)); + NativeMethods.imgproc_integral3(src.Proxy, sum.Proxy, sqsum.Proxy, tilted.Proxy, sdepth?.Value ?? -1, sqdepth?.Value ?? -1)); - GC.KeepAlive(src); - GC.KeepAlive(sum); - GC.KeepAlive(sqsum); - GC.KeepAlive(tilted); - sum.Fix(); - sqsum.Fix(); - tilted.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(sum.Source); + GC.KeepAlive(sqsum.Source); + GC.KeepAlive(tilted.Source); } /// @@ -1527,22 +1156,14 @@ public static void Integral( /// Input image as 1- or 3-channel, 8-bit or 32-bit floating point. /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void Accumulate(InputArray src, InputOutputArray dst, InputArray mask) + public static void Accumulate(InputArrayRef src, InputOutputArrayRef dst, InputArrayRef mask) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_accumulate(src.ToInputProxy(), dst.ToInputOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.imgproc_accumulate(src.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1551,22 +1172,14 @@ public static void Accumulate(InputArray src, InputOutputArray dst, InputArray m /// Input image as 1- or 3-channel, 8-bit or 32-bit floating point. /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void AccumulateSquare(InputArray src, InputOutputArray dst, InputArray mask) + public static void AccumulateSquare(InputArrayRef src, InputOutputArrayRef dst, InputArrayRef mask) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_accumulateSquare(src.ToInputProxy(), dst.ToInputOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.imgproc_accumulateSquare(src.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1576,26 +1189,15 @@ public static void AccumulateSquare(InputArray src, InputOutputArray dst, InputA /// Second input image of the same type and the same size as src1 /// Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void AccumulateProduct(InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask) + public static void AccumulateProduct(InputArrayRef src1, InputArrayRef src2, InputOutputArrayRef dst, InputArrayRef mask) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_accumulateProduct(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToInputOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.imgproc_accumulateProduct(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1605,22 +1207,14 @@ public static void AccumulateProduct(InputArray src1, InputArray src2, InputOutp /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Weight of the input image. /// Optional operation mask. - public static void AccumulateWeighted(InputArray src, InputOutputArray dst, double alpha, InputArray mask) + public static void AccumulateWeighted(InputArrayRef src, InputOutputArrayRef dst, double alpha, InputArrayRef mask) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_accumulateWeighted(src.ToInputProxy(), dst.ToInputOutputProxy(), alpha, mask?.ToInputProxy() ?? default)); + NativeMethods.imgproc_accumulateWeighted(src.Proxy, dst.Proxy, alpha, mask.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -1637,25 +1231,15 @@ public static void AccumulateWeighted(InputArray src, InputOutputArray dst, doub /// Floating point array with windowing coefficients to reduce edge effects (optional). /// Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). /// detected phase shift(sub-pixel) between the two arrays. - public static Point2d PhaseCorrelate(InputArray src1, InputArray src2, - InputArray window, out double response) + public static Point2d PhaseCorrelate(InputArrayRef src1, InputArrayRef src2, + InputArrayRef window, out double response) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (window is null) - throw new ArgumentNullException(nameof(window)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - window.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_phaseCorrelate(src1.ToInputProxy(), src2.ToInputProxy(), window.ToInputProxy(), out response, out var ret)); + NativeMethods.imgproc_phaseCorrelate(src1.Proxy, src2.Proxy, window.Proxy, out response, out var ret)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(window); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(window.Source); return ret; } @@ -1665,17 +1249,12 @@ public static Point2d PhaseCorrelate(InputArray src1, InputArray src2, /// Destination array to place Hann coefficients in /// The window size specifications /// Created array type - public static void CreateHanningWindow(InputOutputArray dst, Size winSize, MatType type) + public static void CreateHanningWindow(OutputArrayRef dst, Size winSize, MatType type) { - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_createHanningWindow(dst.ToOutputProxy(), winSize, type)); + NativeMethods.imgproc_createHanningWindow(dst.Proxy, winSize, type)); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(dst.Source); } /// @@ -1687,21 +1266,13 @@ public static void CreateHanningWindow(InputOutputArray dst, Size winSize, MatTy /// maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. /// thresholding type (see the details below). /// the computed threshold value when type == OTSU - public static double Threshold(InputArray src, OutputArray dst, double thresh, double maxval, ThresholdTypes type) + public static double Threshold(InputArrayRef src, OutputArrayRef dst, double thresh, double maxval, ThresholdTypes type) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_threshold(src.ToInputProxy(), dst.ToOutputProxy(), thresh, maxval, (int)type, out var ret)); + NativeMethods.imgproc_threshold(src.Proxy, dst.Proxy, thresh, maxval, (int)type, out var ret)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return ret; } @@ -1716,22 +1287,14 @@ public static double Threshold(InputArray src, OutputArray dst, double thresh, d /// Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. /// Constant subtracted from the mean or weighted mean (see the details below). /// Normally, it is positive but may be zero or negative as well. - public static void AdaptiveThreshold(InputArray src, OutputArray dst, + public static void AdaptiveThreshold(InputArrayRef src, OutputArrayRef dst, double maxValue, AdaptiveThresholdTypes adaptiveMethod, ThresholdTypes thresholdType, int blockSize, double c) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_adaptiveThreshold(src.ToInputProxy(), dst.ToOutputProxy(), maxValue, (int) adaptiveMethod, (int)thresholdType, blockSize, c)); + NativeMethods.imgproc_adaptiveThreshold(src.Proxy, dst.Proxy, maxValue, (int) adaptiveMethod, (int)thresholdType, blockSize, c)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1741,23 +1304,15 @@ public static void AdaptiveThreshold(InputArray src, OutputArray dst, /// output image; it has the specified size and the same type as src. /// size of the output image; by default, it is computed as Size((src.cols+1)/2 /// - public static void PyrDown(InputArray src, OutputArray dst, + public static void PyrDown(InputArrayRef src, OutputArrayRef dst, Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var dstSize0 = dstSize.GetValueOrDefault(new Size()); NativeMethods.HandleException( - NativeMethods.imgproc_pyrDown(src.ToInputProxy(), dst.ToOutputProxy(), dstSize0, (int) borderType)); + NativeMethods.imgproc_pyrDown(src.Proxy, dst.Proxy, dstSize0, (int) borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1767,19 +1322,16 @@ public static void PyrDown(InputArray src, OutputArray dst, /// /// /// - public static void BuildPyramid(InputArray src, VectorOfMat dst,int maxlevel, + public static void BuildPyramid(InputArrayRef src, VectorOfMat dst,int maxlevel, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); if (dst is null) throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); dst.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.imgproc_buildPyramid(src.ToInputProxy(), dst.CvPtr, maxlevel,(int)borderType)); + NativeMethods.imgproc_buildPyramid(src.Proxy, dst.CvPtr, maxlevel,(int)borderType)); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); GC.KeepAlive(dst); } @@ -1790,23 +1342,15 @@ public static void BuildPyramid(InputArray src, VectorOfMat dst,int maxlevel, /// output image. It has the specified size and the same type as src. /// size of the output image; by default, it is computed as Size(src.cols*2, (src.rows*2) /// - public static void PyrUp(InputArray src, OutputArray dst, + public static void PyrUp(InputArrayRef src, OutputArrayRef dst, Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var dstSize0 = dstSize.GetValueOrDefault(new Size()); NativeMethods.HandleException( - NativeMethods.imgproc_pyrUp(src.ToInputProxy(), dst.ToOutputProxy(), dstSize0, (int)borderType)); + NativeMethods.imgproc_pyrUp(src.Proxy, dst.Proxy, dstSize0, (int)borderType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1822,8 +1366,8 @@ public static void PyrUp(InputArray src, OutputArray dst, /// /// public static void CalcHist(Mat[] images, - int[] channels, InputArray? mask, - OutputArray hist, int dims, int[] histSize, + int[] channels, InputArrayRef mask, + OutputArrayRef hist, int dims, int[] histSize, Rangef[] ranges, bool uniform = true, bool accumulate = false) { if (ranges is null) @@ -1846,34 +1390,30 @@ public static void CalcHist(Mat[] images, /// /// public static void CalcHist(Mat[] images, - int[] channels, InputArray? mask, - OutputArray hist, int dims, int[] histSize, + int[] channels, InputArrayRef mask, + OutputArrayRef hist, int dims, int[] histSize, float[][] ranges, bool uniform = true, bool accumulate = false) { if (images is null) throw new ArgumentNullException(nameof(images)); if (channels is null) throw new ArgumentNullException(nameof(channels)); - if (hist is null) - throw new ArgumentNullException(nameof(hist)); if (histSize is null) throw new ArgumentNullException(nameof(histSize)); if (ranges is null) throw new ArgumentNullException(nameof(ranges)); - hist.ThrowIfNotReady(); var imagesPtr = images.Select(x => x.CvPtr).ToArray(); using (var rangesPtr = new ArrayAddress2(ranges)) { NativeMethods.HandleException( NativeMethods.imgproc_calcHist( - imagesPtr, images.Length, channels, mask?.ToInputProxy() ?? default, hist.ToOutputProxy(), + imagesPtr, images.Length, channels, mask.Proxy, hist.Proxy, dims, histSize, rangesPtr.GetPointer(), uniform ? 1 : 0, accumulate ? 1 : 0)); } GC.KeepAlive(images); - GC.KeepAlive(mask); - GC.KeepAlive(hist); - hist.Fix(); + GC.KeepAlive(mask.Source); + GC.KeepAlive(hist.Source); } /// @@ -1886,34 +1426,27 @@ public static void CalcHist(Mat[] images, /// /// public static void CalcBackProject(Mat[] images, - int[] channels, InputArray hist, OutputArray backProject, + int[] channels, InputArrayRef hist, OutputArrayRef backProject, Rangef[] ranges, bool uniform = true) { if (images is null) throw new ArgumentNullException(nameof(images)); if (channels is null) throw new ArgumentNullException(nameof(channels)); - if (hist is null) - throw new ArgumentNullException(nameof(hist)); - if (backProject is null) - throw new ArgumentNullException(nameof(backProject)); if (ranges is null) throw new ArgumentNullException(nameof(ranges)); - hist.ThrowIfDisposed(); - backProject.ThrowIfNotReady(); var imagesPtr =images.Select(x => x.CvPtr).ToArray(); var rangesFloat = ranges.Select(r => new [] {r.Start, r.End}).ToArray(); using (var rangesPtr = new ArrayAddress2(rangesFloat)) { NativeMethods.HandleException( - NativeMethods.imgproc_calcBackProject(imagesPtr, images.Length, channels, hist.ToInputProxy(), - backProject.ToOutputProxy(), rangesPtr.GetPointer(), uniform ? 1 : 0)); + NativeMethods.imgproc_calcBackProject(imagesPtr, images.Length, channels, hist.Proxy, + backProject.Proxy, rangesPtr.GetPointer(), uniform ? 1 : 0)); } GC.KeepAlive(images); - GC.KeepAlive(hist); - GC.KeepAlive(backProject); - backProject.Fix(); + GC.KeepAlive(hist.Source); + GC.KeepAlive(backProject.Source); } /// @@ -1923,20 +1456,13 @@ public static void CalcBackProject(Mat[] images, /// The second compared histogram of the same size as h1 /// The comparison method /// - public static double CompareHist(InputArray h1, InputArray h2, HistCompMethods method) + public static double CompareHist(InputArrayRef h1, InputArrayRef h2, HistCompMethods method) { - if (h1 is null) - throw new ArgumentNullException(nameof(h1)); - if (h2 is null) - throw new ArgumentNullException(nameof(h2)); - h1.ThrowIfDisposed(); - h2.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_compareHist(h1.ToInputProxy(), h2.ToInputProxy(), (int)method, out var ret)); + NativeMethods.imgproc_compareHist(h1.Proxy, h2.Proxy, (int)method, out var ret)); - GC.KeepAlive(h1); - GC.KeepAlive(h2); + GC.KeepAlive(h1.Source); + GC.KeepAlive(h2.Source); return ret; } @@ -1945,21 +1471,13 @@ public static double CompareHist(InputArray h1, InputArray h2, HistCompMethods m /// /// The source 8-bit single channel image /// The destination image; will have the same size and the same type as src - public static void EqualizeHist(InputArray src, OutputArray dst) + public static void EqualizeHist(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_equalizeHist(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.imgproc_equalizeHist(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1993,9 +1511,9 @@ public static CLAHE CreateCLAHE(double clipLimit = 40.0, Size? tileGridSize = nu /// to either signature1 or signature2. The weights must be non-negative and have at least one non-zero value. /// Used metric. /// - public static float EMD(InputArray signature1, InputArray signature2, DistanceTypes distType) + public static float EMD(InputArrayRef signature1, InputArrayRef signature2, DistanceTypes distType) { - return EMD(signature1, signature2, distType, null, out _); + return EMD(signature1, signature2, distType, default, out _); } /// @@ -2020,8 +1538,8 @@ public static float EMD(InputArray signature1, InputArray signature2, DistanceTy /// User-defined size1 x size2 cost matrix. Also, if a cost matrix /// is used, lower boundary lowerBound cannot be calculated because it needs a metric function. /// - public static float EMD(InputArray signature1, InputArray signature2, - DistanceTypes distType, InputArray? cost) + public static float EMD(InputArrayRef signature1, InputArrayRef signature2, + DistanceTypes distType, InputArrayRef cost) { return EMD(signature1, signature2, distType, cost, out _); } @@ -2058,26 +1576,18 @@ public static float EMD(InputArray signature1, InputArray signature2, /// Resultant size1 x size2 flow matrix: flow[i,j] is a flow from i-th point of signature1 /// to j-th point of signature2. /// - public static float EMD(InputArray signature1, InputArray signature2, - DistanceTypes distType, InputArray? cost, out float lowerBound, OutputArray? flow = null) + public static float EMD(InputArrayRef signature1, InputArrayRef signature2, + DistanceTypes distType, InputArrayRef cost, out float lowerBound, OutputArrayRef flow = default) { - if (signature1 is null) - throw new ArgumentNullException(nameof(signature1)); - if (signature2 is null) - throw new ArgumentNullException(nameof(signature2)); - signature1.ThrowIfDisposed(); - signature2.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.imgproc_EMD( - signature1.ToInputProxy(), signature2.ToInputProxy(), (int) distType, cost?.ToInputProxy() ?? default, - out lowerBound, flow?.ToOutputProxy() ?? default, out var ret)); - - GC.KeepAlive(signature1); - GC.KeepAlive(signature2); - GC.KeepAlive(cost); - GC.KeepAlive(flow); - flow?.Fix(); + signature1.Proxy, signature2.Proxy, (int) distType, cost.Proxy, + out lowerBound, flow.Proxy, out var ret)); + + GC.KeepAlive(signature1.Source); + GC.KeepAlive(signature2.Source); + GC.KeepAlive(cost.Source); + GC.KeepAlive(flow.Source); return ret; } @@ -2087,21 +1597,13 @@ public static float EMD(InputArray signature1, InputArray signature2, /// Input 8-bit 3-channel image. /// Input/output 32-bit single-channel image (map) of markers. /// It should have the same size as image. - public static void Watershed(InputArray image, InputOutputArray markers) + public static void Watershed(InputArrayRef image, InputOutputArrayRef markers) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (markers is null) - throw new ArgumentNullException(nameof(markers)); - image.ThrowIfDisposed(); - markers.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_watershed(image.ToInputProxy(), markers.ToInputOutputProxy())); + NativeMethods.imgproc_watershed(image.Proxy, markers.Proxy)); - GC.KeepAlive(image); - GC.KeepAlive(markers); - markers.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(markers.Source); } /// @@ -2113,24 +1615,16 @@ public static void Watershed(InputArray image, InputOutputArray markers) /// The color window radius. /// Maximum level of the pyramid for the segmentation. /// Termination criteria: when to stop meanshift iterations. - public static void PyrMeanShiftFiltering(InputArray src, OutputArray dst, + public static void PyrMeanShiftFiltering(InputArrayRef src, OutputArrayRef dst, double sp, double sr, int maxLevel = 1, TermCriteria? termcrit = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - var termcrit0 = termcrit.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 5, 1)); NativeMethods.HandleException( - NativeMethods.imgproc_pyrMeanShiftFiltering(src.ToInputProxy(), dst.ToOutputProxy(), sp, sr, maxLevel, termcrit0)); + NativeMethods.imgproc_pyrMeanShiftFiltering(src.Proxy, dst.Proxy, sp, sr, maxLevel, termcrit0)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2147,35 +1641,19 @@ public static void PyrMeanShiftFiltering(InputArray src, OutputArray dst, /// Number of iterations the algorithm should make before returning the result. /// Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL . /// Operation mode that could be one of GrabCutFlag value. - public static void GrabCut(InputArray img, InputOutputArray mask, Rect rect, - InputOutputArray bgdModel, InputOutputArray fgdModel, + public static void GrabCut(InputArrayRef img, InputOutputArrayRef mask, Rect rect, + InputOutputArrayRef bgdModel, InputOutputArrayRef fgdModel, int iterCount, GrabCutModes mode) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - if (bgdModel is null) - throw new ArgumentNullException(nameof(bgdModel)); - if (fgdModel is null) - throw new ArgumentNullException(nameof(fgdModel)); - img.ThrowIfDisposed(); - mask.ThrowIfNotReady(); - bgdModel.ThrowIfNotReady(); - fgdModel.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_grabCut( - img.ToInputProxy(), mask.ToInputOutputProxy(), rect, - bgdModel.ToInputOutputProxy(), fgdModel.ToInputOutputProxy(), iterCount, (int) mode)); + img.Proxy, mask.Proxy, rect, + bgdModel.Proxy, fgdModel.Proxy, iterCount, (int) mode)); - GC.KeepAlive(img); - GC.KeepAlive(mask); - GC.KeepAlive(bgdModel); - GC.KeepAlive(fgdModel); - mask.Fix(); - bgdModel.Fix(); - fgdModel.Fix(); + GC.KeepAlive(img.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(bgdModel.Source); + GC.KeepAlive(fgdModel.Source); } /// @@ -2191,32 +1669,20 @@ public static void GrabCut(InputArray img, InputOutputArray mask, Rect rect, /// #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, /// the parameter is forced to 3 because a 3x3 mask gives the same result as 5x5 or any larger aperture. /// Type of the label array to build - public static void DistanceTransformWithLabels(InputArray src, - OutputArray dst, - OutputArray labels, + public static void DistanceTransformWithLabels(InputArrayRef src, + OutputArrayRef dst, + OutputArrayRef labels, DistanceTypes distanceType, DistanceTransformMasks maskSize, DistanceTransformLabelTypes labelType = DistanceTransformLabelTypes.CComp) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - labels.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_distanceTransformWithLabels( - src.ToInputProxy(), dst.ToOutputProxy(), labels.ToOutputProxy(), (int) distanceType, (int) maskSize, (int) labelType)); + src.Proxy, dst.Proxy, labels.Proxy, (int) distanceType, (int) maskSize, (int) labelType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(labels); - dst.Fix(); - labels.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(labels.Source); } /// @@ -2231,25 +1697,17 @@ public static void DistanceTransformWithLabels(InputArray src, /// the same result as 5x5 or any larger aperture. /// Type of output image. It can be MatType.CV_8U or MatType.CV_32F. /// Type CV_8U can be used only for the first variant of the function and distanceType == #DIST_L1. - public static void DistanceTransform(InputArray src, - OutputArray dst, + public static void DistanceTransform(InputArrayRef src, + OutputArrayRef dst, DistanceTypes distanceType, DistanceTransformMasks maskSize, int dstType = MatType.CV_32S) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_distanceTransform(src.ToInputProxy(), dst.ToOutputProxy(), (int) distanceType, (int) maskSize, dstType)); + NativeMethods.imgproc_distanceTransform(src.Proxy, dst.Proxy, (int) distanceType, (int) maskSize, dstType)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2261,7 +1719,7 @@ public static void DistanceTransform(InputArray src, /// Starting point. /// New value of the repainted domain pixels. /// - public static int FloodFill(InputOutputArray image, Point seedPoint, Scalar newVal) + public static int FloodFill(InputOutputArrayRef image, Point seedPoint, Scalar newVal) { return FloodFill(image, seedPoint, newVal, out _); } @@ -2287,14 +1745,11 @@ public static int FloodFill(InputOutputArray image, Point seedPoint, Scalar newV /// neighbors of a pixel are considered. Using FloodFillFlags.MaskOnly will /// fill in the mask using the grey value 255 (white). /// - public static int FloodFill(InputOutputArray image, + public static int FloodFill(InputOutputArrayRef image, Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); var loDiff0 = loDiff.GetValueOrDefault(new Scalar()); var upDiff0 = upDiff.GetValueOrDefault(new Scalar()); @@ -2305,11 +1760,10 @@ public static int FloodFill(InputOutputArray image, NativeMethods.HandleException( NativeMethods.imgproc_floodFill1( - image.ToInputOutputProxy(), seedPoint, newVal, out rect, + image.Proxy, seedPoint, newVal, out rect, loDiff0, upDiff0, (int)flags, out var ret)); - GC.KeepAlive(image); - image.Fix(); + GC.KeepAlive(image.Source); return ret; } @@ -2327,7 +1781,7 @@ public static int FloodFill(InputOutputArray image, /// Starting point. /// New value of the repainted domain pixels. /// - public static int FloodFill(InputOutputArray image, InputOutputArray mask, + public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, Point seedPoint, Scalar newVal) { return FloodFill(image, mask, seedPoint, newVal, out _); @@ -2359,17 +1813,11 @@ public static int FloodFill(InputOutputArray image, InputOutputArray mask, /// neighbors of a pixel are considered. Using FloodFillFlags.MaskOnly will /// fill in the mask using the grey value 255 (white). /// - public static int FloodFill(InputOutputArray image, InputOutputArray mask, + public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - image.ThrowIfNotReady(); - mask.ThrowIfNotReady(); var loDiff0 = loDiff.GetValueOrDefault(new Scalar()); var upDiff0 = upDiff.GetValueOrDefault(new Scalar()); @@ -2380,13 +1828,11 @@ public static int FloodFill(InputOutputArray image, InputOutputArray mask, NativeMethods.HandleException( NativeMethods.imgproc_floodFill2( - image.ToInputOutputProxy(), mask.ToInputOutputProxy(), seedPoint, + image.Proxy, mask.Proxy, seedPoint, newVal, out rect, loDiff0, upDiff0, (int)flags, out var ret)); - GC.KeepAlive(image); - GC.KeepAlive(mask); - image.Fix(); - mask.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); return ret; } @@ -2399,33 +1845,16 @@ public static int FloodFill(InputOutputArray image, InputOutputArray mask, /// It has a type of CV_32FC1 and the same size with src1. /// It has a type of CV_32FC1 and the same size with src1. /// It is created if it does not have the same size and type with src1. - public static void BlendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, - OutputArray dst) - { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (weights1 is null) - throw new ArgumentNullException(nameof(weights1)); - if (weights2 is null) - throw new ArgumentNullException(nameof(weights2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - weights1.ThrowIfDisposed(); - weights2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - + public static void BlendLinear(InputArrayRef src1, InputArrayRef src2, InputArrayRef weights1, InputArrayRef weights2, + OutputArrayRef dst) + { NativeMethods.HandleException( - NativeMethods.imgproc_blendLinear(src1.ToInputProxy(), src2.ToInputProxy(), weights1.ToInputProxy(), weights2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.imgproc_blendLinear(src1.Proxy, src2.Proxy, weights1.Proxy, weights2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(weights1); - GC.KeepAlive(weights2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(weights1.Source); + GC.KeepAlive(weights2.Source); } /// @@ -2436,22 +1865,14 @@ public static void BlendLinear(InputArray src1, InputArray src2, InputArray weig /// The color space conversion code /// The number of channels in the destination image; if the parameter is 0, the number of the channels will be derived automatically from src and the code /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void CvtColor(InputArray src, OutputArray dst, ColorConversionCodes code, int dstCn = 0, + public static void CvtColor(InputArrayRef src, OutputArrayRef dst, ColorConversionCodes code, int dstCn = 0, AlgorithmHint hint = AlgorithmHint.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_cvtColor(src.ToInputProxy(), dst.ToOutputProxy(), (int) code, dstCn, (int)hint)); + NativeMethods.imgproc_cvtColor(src.Proxy, dst.Proxy, (int) code, dstCn, (int)hint)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2471,26 +1892,15 @@ public static void CvtColor(InputArray src, OutputArray dst, ColorConversionCode /// - #COLOR_YUV2BGRA_NV21 /// - #COLOR_YUV2RGBA_NV21 /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void CvtColorTwoPlane(InputArray src1, InputArray src2, OutputArray dst, ColorConversionCodes code, + public static void CvtColorTwoPlane(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, ColorConversionCodes code, AlgorithmHint hint = AlgorithmHint.Default) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_cvtColorTwoPlane(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy(), (int)code, (int)hint)); + NativeMethods.imgproc_cvtColorTwoPlane(src1.Proxy, src2.Proxy, dst.Proxy, (int)code, (int)hint)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); + GC.KeepAlive(dst.Source); } /// @@ -2521,21 +1931,13 @@ public static void CvtColorTwoPlane(InputArray src1, InputArray src2, OutputArra /// /// # COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA /// - public static void Demosaicing(InputArray src, OutputArray dst, ColorConversionCodes code, int dstCn = 0) + public static void Demosaicing(InputArrayRef src, OutputArrayRef dst, ColorConversionCodes code, int dstCn = 0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_demosaicing(src.ToInputProxy(), dst.ToOutputProxy(), (int)code, dstCn)); + NativeMethods.imgproc_demosaicing(src.Proxy, dst.Proxy, (int)code, dstCn)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -2546,7 +1948,7 @@ public static void Demosaicing(InputArray src, OutputArray dst, ColorConversionC /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - public static Moments Moments(InputArray array, bool binaryImage = false) + public static Moments Moments(InputArrayRef array, bool binaryImage = false) { return new (array, binaryImage); } @@ -2609,31 +2011,19 @@ public static Moments Moments(IEnumerable array, bool binaryImage = fal /// Specifies the comparison method /// Mask of searched template. It must have the same datatype and size with templ. It is not set by default. public static void MatchTemplate( - InputArray image, - InputArray templ, - OutputArray result, + InputArrayRef image, + InputArrayRef templ, + OutputArrayRef result, TemplateMatchModes method, - InputArray? mask = null) + InputArrayRef mask = default) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (templ is null) - throw new ArgumentNullException(nameof(templ)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - image.ThrowIfDisposed(); - templ.ThrowIfDisposed(); - result.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_matchTemplate(image.ToInputProxy(), templ.ToInputProxy(), result.ToOutputProxy(), (int) method, mask?.ToInputProxy() ?? default)); + NativeMethods.imgproc_matchTemplate(image.Proxy, templ.Proxy, result.Proxy, (int) method, mask.Proxy)); - GC.KeepAlive(image); - GC.KeepAlive(templ); - GC.KeepAlive(result); - result.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(image.Source); + GC.KeepAlive(templ.Source); + GC.KeepAlive(result.Source); + GC.KeepAlive(mask.Source); } /// @@ -2655,22 +2045,14 @@ public static void MatchTemplate( /// connected components algorithm type. /// public static int ConnectedComponentsWithAlgorithm( - InputArray image, OutputArray labels, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) + InputArrayRef image, OutputArrayRef labels, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - image.ThrowIfDisposed(); - labels.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_connectedComponentsWithAlgorithm( - image.ToInputProxy(), labels.ToOutputProxy(), (int)connectivity, ltype, (int)ccltype, out var ret)); + image.Proxy, labels.Proxy, (int)connectivity, ltype, (int)ccltype, out var ret)); - GC.KeepAlive(image); - GC.KeepAlive(labels); - labels.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(labels.Source); return ret; } @@ -2685,7 +2067,7 @@ public static int ConnectedComponentsWithAlgorithm( /// destination labeled image /// 8 or 4 for 8-way or 4-way connectivity respectively /// The number of labels - public static int ConnectedComponents(InputArray image, OutputArray labels, + public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) { return ConnectedComponents(image, labels, connectivity, MatType.CV_32S); @@ -2703,23 +2085,16 @@ public static int ConnectedComponents(InputArray image, OutputArray labels, /// 8 or 4 for 8-way or 4-way connectivity respectively /// output image label type. Currently CV_32S and CV_16U are supported. /// The number of labels - public static int ConnectedComponents(InputArray image, OutputArray labels, + public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels, PixelConnectivity connectivity, MatType ltype) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - image.ThrowIfDisposed(); - labels.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.imgproc_connectedComponents( - image.ToInputProxy(), labels.ToOutputProxy(), (int)connectivity, ltype, out var ret)); + image.Proxy, labels.Proxy, (int)connectivity, ltype, out var ret)); - GC.KeepAlive(image); - GC.KeepAlive(labels); - labels.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(labels.Source); return ret; } @@ -2734,7 +2109,7 @@ public static int ConnectedComponents(InputArray image, OutputArray labels, /// destination labeled rectangular array /// 8 or 4 for 8-way or 4-way connectivity respectively /// The number of labels - public static int ConnectedComponents(InputArray image, out int[,] labels, PixelConnectivity connectivity) + public static int ConnectedComponents(InputArrayRef image, out int[,] labels, PixelConnectivity connectivity) { using var labelsMat = new Mat(); var result = ConnectedComponents(image, labelsMat, connectivity, MatType.CV_32S); @@ -2765,38 +2140,22 @@ public static int ConnectedComponents(InputArray image, out int[,] labels, Pixel /// connected components algorithm type. /// public static int ConnectedComponentsWithStatsWithAlgorithm( - InputArray image, - OutputArray labels, - OutputArray stats, - OutputArray centroids, + InputArrayRef image, + OutputArrayRef labels, + OutputArrayRef stats, + OutputArrayRef centroids, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - if (stats is null) - throw new ArgumentNullException(nameof(stats)); - if (centroids is null) - throw new ArgumentNullException(nameof(centroids)); - image.ThrowIfDisposed(); - labels.ThrowIfNotReady(); - stats.ThrowIfNotReady(); - centroids.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_connectedComponentsWithStatsWithAlgorithm( - image.ToInputProxy(), labels.ToOutputProxy(), stats.ToOutputProxy(), centroids.ToOutputProxy(), (int)connectivity, ltype, (int)ccltype, out var ret)); - - GC.KeepAlive(image); - GC.KeepAlive(labels); - GC.KeepAlive(stats); - GC.KeepAlive(centroids); - labels.Fix(); - stats.Fix(); - centroids.Fix(); + image.Proxy, labels.Proxy, stats.Proxy, centroids.Proxy, (int)connectivity, ltype, (int)ccltype, out var ret)); + + GC.KeepAlive(image.Source); + GC.KeepAlive(labels.Source); + GC.KeepAlive(stats.Source); + GC.KeepAlive(centroids.Source); return ret; } @@ -2817,8 +2176,8 @@ public static int ConnectedComponentsWithStatsWithAlgorithm( /// 8 or 4 for 8-way or 4-way connectivity respectively /// public static int ConnectedComponentsWithStats( - InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, + InputArrayRef image, OutputArrayRef labels, + OutputArrayRef stats, OutputArrayRef centroids, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) { return ConnectedComponentsWithStats(image, labels, stats, centroids, connectivity, MatType.CV_32S); @@ -2842,35 +2201,19 @@ public static int ConnectedComponentsWithStats( /// output image label type. Currently CV_32S and CV_16U are supported. /// public static int ConnectedComponentsWithStats( - InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, + InputArrayRef image, OutputArrayRef labels, + OutputArrayRef stats, OutputArrayRef centroids, PixelConnectivity connectivity, MatType ltype) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (labels is null) - throw new ArgumentNullException(nameof(labels)); - if (stats is null) - throw new ArgumentNullException(nameof(stats)); - if (centroids is null) - throw new ArgumentNullException(nameof(centroids)); - image.ThrowIfDisposed(); - labels.ThrowIfNotReady(); - stats.ThrowIfNotReady(); - centroids.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_connectedComponentsWithStats( - image.ToInputProxy(), labels.ToOutputProxy(), stats.ToOutputProxy(), centroids.ToOutputProxy(), (int) connectivity, ltype, out var ret)); - - GC.KeepAlive(image); - GC.KeepAlive(labels); - GC.KeepAlive(stats); - GC.KeepAlive(centroids); - labels.Fix(); - stats.Fix(); - centroids.Fix(); + image.Proxy, labels.Proxy, stats.Proxy, centroids.Proxy, (int) connectivity, ltype, out var ret)); + + GC.KeepAlive(image.Source); + GC.KeepAlive(labels.Source); + GC.KeepAlive(stats.Source); + GC.KeepAlive(centroids.Source); return ret; } @@ -2886,7 +2229,7 @@ public static int ConnectedComponentsWithStats( /// /// public static ConnectedComponents ConnectedComponentsEx( - InputArray image, + InputArrayRef image, PixelConnectivity connectivity = PixelConnectivity.Connectivity8, ConnectedComponentsAlgorithmsTypes ccltype = ConnectedComponentsAlgorithmsTypes.Default) { @@ -2932,25 +2275,21 @@ public static ConnectedComponents ConnectedComponentsEx( /// Contour approximation method /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public static void FindContours(InputArray image, out Point[][] contours, + public static void FindContours(InputArrayRef image, out Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - var offset0 = offset.GetValueOrDefault(new Point()); using var contoursVec = new VectorOfVectorPoint(); using var hierarchyVec = new StdVector(); NativeMethods.HandleException( NativeMethods.imgproc_findContours1_vector( - image.ToInputProxy(), contoursVec.CvPtr, hierarchyVec.CvPtr, (int) mode, (int) method, offset0)); + image.Proxy, contoursVec.CvPtr, hierarchyVec.CvPtr, (int) mode, (int) method, offset0)); contours = contoursVec.ToArray(); var hierarchyOrg = hierarchyVec.ToArray(); hierarchy = hierarchyOrg.Select(HierarchyIndex.FromVec4i).ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -2969,26 +2308,18 @@ public static void FindContours(InputArray image, out Point[][] contours, /// Contour approximation method /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public static void FindContours(InputArray image, out Mat[] contours, - OutputArray hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + public static void FindContours(InputArrayRef image, out Mat[] contours, + OutputArrayRef hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (hierarchy is null) - throw new ArgumentNullException(nameof(hierarchy)); - image.ThrowIfDisposed(); - hierarchy.ThrowIfNotReady(); - var offset0 = offset.GetValueOrDefault(new Point()); using var contoursVec = new VectorOfMat(); NativeMethods.HandleException( - NativeMethods.imgproc_findContours1_OutputArray(image.ToInputProxy(), contoursVec.CvPtr, hierarchy.ToOutputProxy(), (int) mode, (int) method, offset0)); + NativeMethods.imgproc_findContours1_OutputArray(image.Proxy, contoursVec.CvPtr, hierarchy.Proxy, (int) mode, (int) method, offset0)); contours = contoursVec.ToArray(); - hierarchy.Fix(); - GC.KeepAlive(image); - GC.KeepAlive(hierarchy); + GC.KeepAlive(image.Source); + GC.KeepAlive(hierarchy.Source); } /// @@ -3002,45 +2333,37 @@ public static void FindContours(InputArray image, out Mat[] contours, /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. /// Detected contours. Each contour is stored as a vector of points. - public static Point[][] FindContoursAsArray(InputArray image, + public static Point[][] FindContoursAsArray(InputArrayRef image, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - var offset0 = offset.GetValueOrDefault(new Point()); using var contoursVec = new VectorOfVectorPoint(); NativeMethods.HandleException( - NativeMethods.imgproc_findContours2_vector(image.ToInputProxy(), contoursVec.CvPtr, (int) mode, (int) method, offset0)); - GC.KeepAlive(image); + NativeMethods.imgproc_findContours2_vector(image.Proxy, contoursVec.CvPtr, (int) mode, (int) method, offset0)); + GC.KeepAlive(image.Source); return contoursVec.ToArray(); } /// /// Finds contours in a binary image using the link-runs algorithm (OpenCV 5). This is an - /// alternative to + /// alternative to /// with reduced memory consumption; it always uses the equivalent of RETR_CCOMP retrieval. /// /// Source, an 8-bit single-channel binary image. /// Detected contours. Each contour is stored as a vector of points. /// Output vector containing information about the image topology /// (next/previous/first-child/parent indices for each contour). - public static void FindContoursLinkRuns(InputArray image, out Point[][] contours, out HierarchyIndex[] hierarchy) + public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] contours, out HierarchyIndex[] hierarchy) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var contoursVec = new VectorOfVectorPoint(); using var hierarchyVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.imgproc_findContoursLinkRuns1(image.ToInputProxy(), contoursVec.CvPtr, hierarchyVec.CvPtr)); + NativeMethods.imgproc_findContoursLinkRuns1(image.Proxy, contoursVec.CvPtr, hierarchyVec.CvPtr)); contours = contoursVec.ToArray(); hierarchy = hierarchyVec.ToArray().Select(HierarchyIndex.FromVec4i).ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -3048,18 +2371,14 @@ public static void FindContoursLinkRuns(InputArray image, out Point[][] contours /// /// Source, an 8-bit single-channel binary image. /// Detected contours. Each contour is stored as a vector of points. - public static void FindContoursLinkRuns(InputArray image, out Point[][] contours) + public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] contours) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var contoursVec = new VectorOfVectorPoint(); NativeMethods.HandleException( - NativeMethods.imgproc_findContoursLinkRuns2(image.ToInputProxy(), contoursVec.CvPtr)); + NativeMethods.imgproc_findContoursLinkRuns2(image.Proxy, contoursVec.CvPtr)); contours = contoursVec.ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -3073,18 +2392,14 @@ public static void FindContoursLinkRuns(InputArray image, out Point[][] contours /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. /// Detected contours. Each contour is stored as a vector of points. - public static Mat[] FindContoursAsMat(InputArray image, + public static Mat[] FindContoursAsMat(InputArrayRef image, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - var offset0 = offset.GetValueOrDefault(new Point()); using var contoursVec = new VectorOfMat(); NativeMethods.HandleException( - NativeMethods.imgproc_findContours2_OutputArray(image.ToInputProxy(), contoursVec.CvPtr, (int)mode, (int)method, offset0)); - GC.KeepAlive(image); + NativeMethods.imgproc_findContours2_OutputArray(image.Proxy, contoursVec.CvPtr, (int)mode, (int)method, offset0)); + GC.KeepAlive(image.Source); return contoursVec.ToArray>(); } @@ -3100,21 +2415,13 @@ public static Mat[] FindContoursAsMat(InputArray image, /// This is the maximum distance between the original curve and its approximation. /// The result of the approximation; /// The type should match the type of the input curve - public static void ApproxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed) + public static void ApproxPolyDP(InputArrayRef curve, OutputArrayRef approxCurve, double epsilon, bool closed) { - if (curve is null) - throw new ArgumentNullException(nameof(curve)); - if (approxCurve is null) - throw new ArgumentNullException(nameof(approxCurve)); - curve.ThrowIfDisposed(); - approxCurve.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_approxPolyDP_InputArray(curve.ToInputProxy(), approxCurve.ToOutputProxy(), epsilon, closed ? 1 : 0)); + NativeMethods.imgproc_approxPolyDP_InputArray(curve.Proxy, approxCurve.Proxy, epsilon, closed ? 1 : 0)); - GC.KeepAlive(curve); - GC.KeepAlive(approxCurve); - approxCurve.Fix(); + GC.KeepAlive(curve.Source); + GC.KeepAlive(approxCurve.Source); } /// @@ -3169,15 +2476,11 @@ public static Point2f[] ApproxPolyDP(IEnumerable curve, double epsilon, /// The input vector of 2D points, represented by CV_32SC2 or CV_32FC2 matrix. /// Indicates, whether the curve is closed or not. /// - public static double ArcLength(InputArray curve, bool closed) + public static double ArcLength(InputArrayRef curve, bool closed) { - if (curve is null) - throw new ArgumentNullException(nameof(curve)); - curve.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_arcLength_InputArray(curve.ToInputProxy(), closed ? 1 : 0, out var ret)); - GC.KeepAlive(curve); + NativeMethods.imgproc_arcLength_InputArray(curve.Proxy, closed ? 1 : 0, out var ret)); + GC.KeepAlive(curve.Source); return ret; } @@ -3220,15 +2523,11 @@ public static double ArcLength(IEnumerable curve, bool closed) /// /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// Minimal up-right bounding rectangle for the specified point set. - public static Rect BoundingRect(InputArray curve) + public static Rect BoundingRect(InputArrayRef curve) { - if (curve is null) - throw new ArgumentNullException(nameof(curve)); - curve.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_boundingRect_InputArray(curve.ToInputProxy(), out var ret)); - GC.KeepAlive(curve); + NativeMethods.imgproc_boundingRect_InputArray(curve.Proxy, out var ret)); + GC.KeepAlive(curve.Source); return ret; } @@ -3270,15 +2569,11 @@ public static Rect BoundingRect(IEnumerable curve) /// The contour vertices, represented by CV_32SC2 or CV_32FC2 matrix /// /// - public static double ContourArea(InputArray contour, bool oriented = false) + public static double ContourArea(InputArrayRef contour, bool oriented = false) { - if (contour is null) - throw new ArgumentNullException(nameof(contour)); - contour.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_contourArea_InputArray(contour.ToInputProxy(), oriented ? 1 : 0, out var ret)); - GC.KeepAlive(contour); + NativeMethods.imgproc_contourArea_InputArray(contour.Proxy, oriented ? 1 : 0, out var ret)); + GC.KeepAlive(contour.Source); return ret; } @@ -3321,15 +2616,11 @@ public static double ContourArea(IEnumerable contour, bool oriented = f /// /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// - public static RotatedRect MinAreaRect(InputArray points) + public static RotatedRect MinAreaRect(InputArrayRef points) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_minAreaRect_InputArray(points.ToInputProxy(), out var ret)); - GC.KeepAlive(points); + NativeMethods.imgproc_minAreaRect_InputArray(points.Proxy, out var ret)); + GC.KeepAlive(points.Source); return ret; } @@ -3375,15 +2666,10 @@ public static RotatedRect MinAreaRect(IEnumerable points) /// The input rotated rectangle. It may be the output of /// The output array of four vertices of rectangles. /// - public static void BoxPoints(RotatedRect box, OutputArray points) + public static void BoxPoints(RotatedRect box, OutputArrayRef points) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_boxPoints_OutputArray(box, points.ToOutputProxy())); - points.Fix(); + NativeMethods.imgproc_boxPoints_OutputArray(box, points.Proxy)); } /// @@ -3409,14 +2695,11 @@ public static Point2f[] BoxPoints(RotatedRect box) /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// The output center of the circle /// The output radius of the circle - public static void MinEnclosingCircle(InputArray points, out Point2f center, out float radius) + public static void MinEnclosingCircle(InputArrayRef points, out Point2f center, out float radius) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.imgproc_minEnclosingCircle_InputArray(points.ToInputProxy(), out center, out radius)); - GC.KeepAlive(points); + NativeMethods.imgproc_minEnclosingCircle_InputArray(points.Proxy, out center, out radius)); + GC.KeepAlive(points.Source); } /// @@ -3455,20 +2738,12 @@ public static void MinEnclosingCircle(IEnumerable points, out Point2f c /// Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector or Mat /// Output vector of three 2D points defining the vertices of the triangle. The depth /// Triangle area - public static double MinEnclosingTriangle(InputArray points, OutputArray triangle) + public static double MinEnclosingTriangle(InputArrayRef points, OutputArrayRef triangle) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (triangle is null) - throw new ArgumentNullException(nameof(triangle)); - points.ThrowIfDisposed(); - triangle.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_minEnclosingTriangle_InputOutputArray(points.ToInputProxy(), triangle.ToOutputProxy(), out var ret)); + NativeMethods.imgproc_minEnclosingTriangle_InputOutputArray(points.Proxy, triangle.Proxy, out var ret)); - GC.KeepAlive(points); - triangle.Fix(); + GC.KeepAlive(points.Source); return ret; } @@ -3524,18 +2799,13 @@ public static double MinEnclosingTriangle(IEnumerable points, out Point /// Comparison method /// Method-specific parameter (not supported now) /// - public static double MatchShapes(InputArray contour1, InputArray contour2, ShapeMatchModes method, double parameter = 0) + public static double MatchShapes(InputArrayRef contour1, InputArrayRef contour2, ShapeMatchModes method, double parameter = 0) { - if (contour1 is null) - throw new ArgumentNullException(nameof(contour1)); - if (contour2 is null) - throw new ArgumentNullException(nameof(contour2)); - NativeMethods.HandleException( - NativeMethods.imgproc_matchShapes_InputArray(contour1.ToInputProxy(), contour2.ToInputProxy(), (int)method, parameter, out var ret)); + NativeMethods.imgproc_matchShapes_InputArray(contour1.Proxy, contour2.Proxy, (int)method, parameter, out var ret)); - GC.KeepAlive(contour1); - GC.KeepAlive(contour2); + GC.KeepAlive(contour1.Source); + GC.KeepAlive(contour2.Source); return ret; } @@ -3578,21 +2848,13 @@ public static double MatchShapes(IEnumerable contour1, IEnumerable /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, /// and y axis is oriented downwards. /// - public static void ConvexHull(InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true) + public static void ConvexHull(InputArrayRef points, OutputArrayRef hull, bool clockwise = false, bool returnPoints = true) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (hull is null) - throw new ArgumentNullException(nameof(hull)); - points.ThrowIfDisposed(); - hull.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_convexHull_InputArray(points.ToInputProxy(), hull.ToOutputProxy(), clockwise ? 1 : 0, returnPoints ? 1 : 0)); + NativeMethods.imgproc_convexHull_InputArray(points.Proxy, hull.Proxy, clockwise ? 1 : 0, returnPoints ? 1 : 0)); - GC.KeepAlive(points); - GC.KeepAlive(hull); - hull.Fix(); + GC.KeepAlive(points.Source); + GC.KeepAlive(hull.Source); } /// @@ -3703,25 +2965,14 @@ public static int[] ConvexHullIndices(IEnumerable points, bool clockwis /// (with 8 fractional bits) of the distance between the farthest contour point and the hull. /// That is, to get the floating-point value of the depth will be fixpt_depth/256.0. /// - public static void ConvexityDefects(InputArray contour, InputArray convexHull, OutputArray convexityDefects) + public static void ConvexityDefects(InputArrayRef contour, InputArrayRef convexHull, OutputArrayRef convexityDefects) { - if (contour is null) - throw new ArgumentNullException(nameof(contour)); - if (convexHull is null) - throw new ArgumentNullException(nameof(convexHull)); - if (convexityDefects is null) - throw new ArgumentNullException(nameof(convexityDefects)); - contour.ThrowIfDisposed(); - convexHull.ThrowIfDisposed(); - convexityDefects.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_convexityDefects_InputArray(contour.ToInputProxy(), convexHull.ToInputProxy(), convexityDefects.ToOutputProxy())); + NativeMethods.imgproc_convexityDefects_InputArray(contour.Proxy, convexHull.Proxy, convexityDefects.Proxy)); - GC.KeepAlive(contour); - GC.KeepAlive(convexHull); - GC.KeepAlive(convexityDefects); - convexityDefects.Fix(); + GC.KeepAlive(contour.Source); + GC.KeepAlive(convexHull.Source); + GC.KeepAlive(convexityDefects.Source); } /// @@ -3791,16 +3042,12 @@ public static Vec4i[] ConvexityDefects(IEnumerable contour, IEnumerable /// /// Input vector of 2D points /// - public static bool IsContourConvex(InputArray contour) + public static bool IsContourConvex(InputArrayRef contour) { - if (contour is null) - throw new ArgumentNullException(nameof(contour)); - contour.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_isContourConvex_InputArray(contour.ToInputProxy(), out var ret)); + NativeMethods.imgproc_isContourConvex_InputArray(contour.Proxy, out var ret)); - GC.KeepAlive(contour); + GC.KeepAlive(contour.Source); return ret != 0; } @@ -3846,26 +3093,15 @@ public static bool IsContourConvex(IEnumerable contour) /// /// /// - public static float IntersectConvexConvex(InputArray p1, InputArray p2, OutputArray p12, bool handleNested = true) + public static float IntersectConvexConvex(InputArrayRef p1, InputArrayRef p2, OutputArrayRef p12, bool handleNested = true) { - if (p1 is null) - throw new ArgumentNullException(nameof(p1)); - if (p2 is null) - throw new ArgumentNullException(nameof(p2)); - if (p12 is null) - throw new ArgumentNullException(nameof(p12)); - p1.ThrowIfDisposed(); - p2.ThrowIfDisposed(); - p12.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_intersectConvexConvex_InputArray( - p1.ToInputProxy(), p2.ToInputProxy(), p12.ToOutputProxy(), handleNested ? 1 : 0, out var ret)); + p1.Proxy, p2.Proxy, p12.Proxy, handleNested ? 1 : 0, out var ret)); - GC.KeepAlive(p1); - GC.KeepAlive(p2); - GC.KeepAlive(p12); - p12.Fix(); + GC.KeepAlive(p1.Source); + GC.KeepAlive(p2.Source); + GC.KeepAlive(p12.Source); return ret; } @@ -3931,16 +3167,12 @@ public static float IntersectConvexConvex(IEnumerable p1, IEnumerable

/// Input 2D point set /// - public static RotatedRect FitEllipse(InputArray points) + public static RotatedRect FitEllipse(InputArrayRef points) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_fitEllipse_InputArray(points.ToInputProxy(), out var ret)); + NativeMethods.imgproc_fitEllipse_InputArray(points.Proxy, out var ret)); - GC.KeepAlive(points); + GC.KeepAlive(points.Source); return ret; } @@ -3985,16 +3217,12 @@ public static RotatedRect FitEllipse(IEnumerable points) ///

/// Input 2D point set /// - public static RotatedRect FitEllipseAMS(InputArray points) + public static RotatedRect FitEllipseAMS(InputArrayRef points) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_fitEllipseAMS_InputArray(points.ToInputProxy(), out var ret)); + NativeMethods.imgproc_fitEllipseAMS_InputArray(points.Proxy, out var ret)); - GC.KeepAlive(points); + GC.KeepAlive(points.Source); return ret; } @@ -4047,16 +3275,12 @@ public static RotatedRect FitEllipseAMS(IEnumerable points) ///
/// Input 2D point set /// - public static RotatedRect FitEllipseDirect(InputArray points) + public static RotatedRect FitEllipseDirect(InputArrayRef points) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - points.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_fitEllipseDirect_InputArray(points.ToInputProxy(), out var ret)); + NativeMethods.imgproc_fitEllipseDirect_InputArray(points.Proxy, out var ret)); - GC.KeepAlive(points); + GC.KeepAlive(points.Source); return ret; } @@ -4118,23 +3342,15 @@ public static RotatedRect FitEllipseDirect(IEnumerable points) /// (distance between the coordinate origin and the line). /// Sufficient accuracy for the angle. /// 0.01 would be a good default value for reps and aeps. - public static void FitLine(InputArray points, OutputArray line, DistanceTypes distType, + public static void FitLine(InputArrayRef points, OutputArrayRef line, DistanceTypes distType, double param, double reps, double aeps) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (line is null) - throw new ArgumentNullException(nameof(line)); - points.ThrowIfDisposed(); - line.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_fitLine_InputArray( - points.ToInputProxy(), line.ToOutputProxy(), (int) distType, param, reps, aeps)); + points.Proxy, line.Proxy, (int) distType, param, reps, aeps)); - GC.KeepAlive(points); - GC.KeepAlive(line); - line.Fix(); + GC.KeepAlive(points.Source); + GC.KeepAlive(line.Source); } /// @@ -4244,15 +3460,12 @@ public static Line3D FitLine(IEnumerable points, DistanceTypes distType /// /// /// - public static double PointPolygonTest(InputArray contour, Point2f pt, bool measureDist) + public static double PointPolygonTest(InputArrayRef contour, Point2f pt, bool measureDist) { - if (contour is null) - throw new ArgumentNullException(nameof(contour)); - contour.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.imgproc_pointPolygonTest_InputArray( - contour.ToInputProxy(), pt, measureDist ? 1 : 0, out var ret)); - GC.KeepAlive(contour); + contour.Proxy, pt, measureDist ? 1 : 0, out var ret)); + GC.KeepAlive(contour.Source); return ret; } @@ -4310,18 +3523,13 @@ public static double PointPolygonTest(IEnumerable contour, Point2f pt, /// Stored as std::vector<cv::Point2f> or cv::Mat as Mx1 of type CV_32FC2. /// public static RectanglesIntersectTypes RotatedRectangleIntersection( - RotatedRect rect1, RotatedRect rect2, OutputArray intersectingRegion) + RotatedRect rect1, RotatedRect rect2, OutputArrayRef intersectingRegion) { - if (intersectingRegion is null) - throw new ArgumentNullException(nameof(intersectingRegion)); - intersectingRegion.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_rotatedRectangleIntersection_OutputArray( - rect1, rect2, intersectingRegion.ToOutputProxy(), out var ret)); + rect1, rect2, intersectingRegion.Proxy, out var ret)); - GC.KeepAlive(intersectingRegion); - intersectingRegion.Fix(); + GC.KeepAlive(intersectingRegion.Source); return (RectanglesIntersectTypes)ret; } @@ -4357,21 +3565,13 @@ public static RectanglesIntersectTypes RotatedRectangleIntersection( /// The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. /// The result is the colormapped source image. Note: Mat::create is called on dst. /// colormap The colormap to apply - public static void ApplyColorMap(InputArray src, OutputArray dst, ColormapTypes colormap) + public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, ColormapTypes colormap) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_applyColorMap1(src.ToInputProxy(), dst.ToOutputProxy(), (int) colormap)); + NativeMethods.imgproc_applyColorMap1(src.Proxy, dst.Proxy, (int) colormap)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -4380,24 +3580,13 @@ public static void ApplyColorMap(InputArray src, OutputArray dst, ColormapTypes /// The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. /// The result is the colormapped source image. Note: Mat::create is called on dst. /// The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 - public static void ApplyColorMap(InputArray src, OutputArray dst, InputArray userColor) + public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, InputArrayRef userColor) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (userColor is null) - throw new ArgumentNullException(nameof(userColor)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - userColor.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_applyColorMap2(src.ToInputProxy(), dst.ToOutputProxy(), userColor.ToInputProxy())); + NativeMethods.imgproc_applyColorMap2(src.Proxy, dst.Proxy, userColor.Proxy)); - GC.KeepAlive(src); - dst.Fix(); - GC.KeepAlive(userColor); + GC.KeepAlive(src.Source); + GC.KeepAlive(userColor.Source); } #region Drawing @@ -4414,7 +3603,7 @@ public static void ApplyColorMap(InputArray src, OutputArray dst, InputArray use /// Line thickness. [By default this is 1] /// Type of the line. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] - public static void Line(InputOutputArray img, int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, + public static void Line(InputOutputArrayRef img, int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { Line(img, new Point(pt1X, pt1Y), new Point(pt2X, pt2Y), color, thickness, lineType, shift); @@ -4431,18 +3620,13 @@ public static void Line(InputOutputArray img, int pt1X, int pt1Y, int pt2X, int /// Type of the line. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Line( - InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, + InputOutputArrayRef img, Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.imgproc_line(img.ToInputOutputProxy(), pt1, pt2, color, thickness, (int) lineType, shift)); + NativeMethods.imgproc_line(img.Proxy, pt1, pt2, color, thickness, (int) lineType, shift)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -4459,7 +3643,7 @@ public static void Line( /// Number of fractional bits in the point coordinates. /// The length of the arrow tip in relation to the arrow length public static void ArrowedLine( - InputOutputArray img, + InputOutputArrayRef img, Point pt1, Point pt2, Scalar color, int thickness = 1, @@ -4467,16 +3651,11 @@ public static void ArrowedLine( int shift = 0, double tipLength = 0.1) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_arrowedLine( - img.ToInputOutputProxy(), pt1, pt2, color, thickness, (int) lineType, shift, tipLength)); + img.Proxy, pt1, pt2, color, thickness, (int) lineType, shift, tipLength)); - GC.KeepAlive(img); - img.Fix(); + GC.KeepAlive(img.Source); } /// @@ -4490,18 +3669,14 @@ public static void ArrowedLine( /// Type of the line, see cvLine description. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Rectangle( - InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, + InputOutputArrayRef img, Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - NativeMethods.HandleException( NativeMethods.imgproc_rectangle_InputOutputArray_Point( - img.ToInputOutputProxy(), pt1, pt2, color, thickness, (int) lineType, shift)); + img.Proxy, pt1, pt2, color, thickness, (int) lineType, shift)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -4515,17 +3690,13 @@ public static void Rectangle( /// Type of the line, see cvLine description. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Rectangle( - InputOutputArray img, Rect rect, Scalar color, int thickness = 1, + InputOutputArrayRef img, Rect rect, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - NativeMethods.HandleException( NativeMethods.imgproc_rectangle_InputOutputArray_Rect( - img.ToInputOutputProxy(), rect, color, thickness, (int) lineType, shift)); - img.Fix(); - GC.KeepAlive(img); + img.Proxy, rect, color, thickness, (int) lineType, shift)); + GC.KeepAlive(img.Source); } /// @@ -4583,7 +3754,7 @@ public static void Rectangle( /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] /// Type of the circle boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public static void Circle(InputOutputArray img, int centerX, int centerY, int radius, Scalar color, + public static void Circle(InputOutputArrayRef img, int centerX, int centerY, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { Circle(img, new Point(centerX, centerY), radius, color, thickness, lineType, shift); @@ -4599,17 +3770,12 @@ public static void Circle(InputOutputArray img, int centerX, int centerY, int ra /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] /// Type of the circle boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public static void Circle(InputOutputArray img, Point center, int radius, Scalar color, + public static void Circle(InputOutputArrayRef img, Point center, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_circle(img.ToInputOutputProxy(), center, radius, color, thickness, (int) lineType, shift)); - img.Fix(); - GC.KeepAlive(img); + NativeMethods.imgproc_circle(img.Proxy, center, radius, color, thickness, (int) lineType, shift)); + GC.KeepAlive(img.Source); } /// @@ -4626,19 +3792,14 @@ public static void Circle(InputOutputArray img, Point center, int radius, Scalar /// Type of the ellipse boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and axes' values. [By default this is 0] public static void Ellipse( - InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, + InputOutputArrayRef img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_ellipse1( - img.ToInputOutputProxy(), center, axes, angle, startAngle, endAngle, color, thickness, (int) lineType, shift)); + img.Proxy, center, axes, angle, startAngle, endAngle, color, thickness, (int) lineType, shift)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -4649,17 +3810,12 @@ public static void Ellipse( /// Ellipse color. /// Thickness of the ellipse boundary. [By default this is 1] /// Type of the ellipse boundary. [By default this is LineType.Link8] - public static void Ellipse(InputOutputArray img, RotatedRect box, Scalar color, + public static void Ellipse(InputOutputArrayRef img, RotatedRect box, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_ellipse2(img.ToInputOutputProxy(), box, color, thickness, (int) lineType)); - img.Fix(); - GC.KeepAlive(img); + NativeMethods.imgproc_ellipse2(img.Proxy, box, color, thickness, (int) lineType)); + GC.KeepAlive(img.Source); } /// @@ -4676,19 +3832,14 @@ public static void Ellipse(InputOutputArray img, RotatedRect box, Scalar color, /// Line thickness. /// Type of the line. public static void DrawMarker( - InputOutputArray img, Point position, Scalar color, + InputOutputArrayRef img, Point position, Scalar color, MarkerTypes markerType = MarkerTypes.Cross, int markerSize = 20, int thickness = 1, LineTypes lineType = LineTypes.Link8) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.imgproc_drawMarker( - img.ToInputOutputProxy(), position, color, (int)markerType, markerSize, thickness, (int)lineType)); + img.Proxy, position, color, (int)markerType, markerSize, thickness, (int)lineType)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -4721,21 +3872,15 @@ public static void FillConvexPoly(Mat img, IEnumerable pts, Scalar color, /// Polygon color /// Type of the polygon boundaries /// The number of fractional bits in the vertex coordinates - public static void FillConvexPoly(InputOutputArray img, InputArray pts, Scalar color, + public static void FillConvexPoly(InputOutputArrayRef img, InputArrayRef pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (pts is null) - throw new ArgumentNullException(nameof(pts)); - img.ThrowIfDisposed(); - pts.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.imgproc_fillConvexPoly_InputOutputArray( - img.ToInputOutputProxy(), pts.ToInputProxy(), color, (int) lineType, shift)); - GC.KeepAlive(img); - GC.KeepAlive(pts); + img.Proxy, pts.Proxy, color, (int) lineType, shift)); + GC.KeepAlive(img.Source); + GC.KeepAlive(pts.Source); } /// @@ -4753,8 +3898,6 @@ public static void FillPoly( { if (img is null) throw new ArgumentNullException(nameof(img)); - if (pts is null) - throw new ArgumentNullException(nameof(pts)); img.ThrowIfDisposed(); var offset0 = offset.GetValueOrDefault(new Point()); @@ -4789,23 +3932,16 @@ public static void FillPoly( /// The number of fractional bits in the vertex coordinates /// public static void FillPoly( - InputOutputArray img, InputArray pts, Scalar color, + InputOutputArrayRef img, InputArrayRef pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (pts is null) - throw new ArgumentNullException(nameof(pts)); - img.ThrowIfDisposed(); - pts.ThrowIfDisposed(); var offset0 = offset.GetValueOrDefault(new Point()); NativeMethods.HandleException( NativeMethods.imgproc_fillPoly_InputOutputArray( - img.ToInputOutputProxy(), pts.ToInputProxy(), color, (int) lineType, shift, offset0)); - GC.KeepAlive(img); - GC.KeepAlive(pts); - img.Fix(); + img.Proxy, pts.Proxy, color, (int) lineType, shift, offset0)); + GC.KeepAlive(img.Source); + GC.KeepAlive(pts.Source); } /// @@ -4829,8 +3965,6 @@ public static void Polylines( { if (img is null) throw new ArgumentNullException(nameof(img)); - if (pts is null) - throw new ArgumentNullException(nameof(pts)); img.ThrowIfDisposed(); var ptsList = new List(); @@ -4863,22 +3997,14 @@ public static void Polylines( /// /// public static void Polylines( - InputOutputArray img, InputArray pts, bool isClosed, Scalar color, + InputOutputArrayRef img, InputArrayRef pts, bool isClosed, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (pts is null) - throw new ArgumentNullException(nameof(pts)); - img.ThrowIfDisposed(); - pts.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.imgproc_polylines_InputOutputArray( - img.ToInputOutputProxy(), pts.ToInputProxy(), isClosed ? 1 : 0, color, thickness, (int) lineType, shift)); - GC.KeepAlive(img); - img.Fix(); - GC.KeepAlive(pts); + img.Proxy, pts.Proxy, isClosed ? 1 : 0, color, thickness, (int) lineType, shift)); + GC.KeepAlive(img.Source); + GC.KeepAlive(pts.Source); } /// @@ -4898,7 +4024,7 @@ public static void Polylines( /// when there is hierarchy available. /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) public static void DrawContours( - InputOutputArray image, + InputOutputArrayRef image, IEnumerable> contours, int contourIdx, Scalar color, @@ -4908,11 +4034,8 @@ public static void DrawContours( int maxLevel = int.MaxValue, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (contours is null) throw new ArgumentNullException(nameof(contours)); - image.ThrowIfNotReady(); var offset0 = offset.GetValueOrDefault(new Point()); var contoursArray = contours.Select(c => c.ToArray()).ToArray(); @@ -4923,7 +4046,7 @@ public static void DrawContours( { NativeMethods.HandleException( NativeMethods.imgproc_drawContours_vector( - image.ToInputOutputProxy(), contoursPtr.GetPointer(), contoursArray.Length, contourSize2, + image.Proxy, contoursPtr.GetPointer(), contoursArray.Length, contourSize2, contourIdx, color, thickness, (int) lineType, IntPtr.Zero, 0, maxLevel, offset0)); } else @@ -4931,12 +4054,11 @@ public static void DrawContours( var hierarchyVecs = hierarchy.Select(hi => hi.ToVec4i()).ToArray(); NativeMethods.HandleException( NativeMethods.imgproc_drawContours_vector( - image.ToInputOutputProxy(), contoursPtr.GetPointer(), contoursArray.Length, contourSize2, + image.Proxy, contoursPtr.GetPointer(), contoursArray.Length, contourSize2, contourIdx, color, thickness, (int) lineType, hierarchyVecs, hierarchyVecs.Length, maxLevel, offset0)); } } - GC.KeepAlive(image); - image.Fix(); + GC.KeepAlive(image.Source); } /// @@ -4956,33 +4078,29 @@ public static void DrawContours( /// when there is hierarchy available. /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) public static void DrawContours( - InputOutputArray image, + InputOutputArrayRef image, IEnumerable contours, int contourIdx, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, - InputArray? hierarchy = null, + InputArrayRef hierarchy = default, int maxLevel = int.MaxValue, Point? offset = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (contours is null) throw new ArgumentNullException(nameof(contours)); - image.ThrowIfNotReady(); var offset0 = offset.GetValueOrDefault(new Point()); var contoursPtr = contours.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( NativeMethods.imgproc_drawContours_InputArray( - image.ToInputOutputProxy(), contoursPtr, contoursPtr.Length, - contourIdx, color, thickness, (int) lineType, hierarchy?.ToInputProxy() ?? default, maxLevel, offset0)); - image.Fix(); - GC.KeepAlive(image); + image.Proxy, contoursPtr, contoursPtr.Length, + contourIdx, color, thickness, (int) lineType, hierarchy.Proxy, maxLevel, offset0)); + GC.KeepAlive(image.Source); GC.KeepAlive(contours); - GC.KeepAlive(hierarchy); + GC.KeepAlive(hierarchy.Source); } /// @@ -5068,22 +4186,18 @@ public static Point2d[] Ellipse2Poly(Point2d center, Size2d axes, int angle, /// Line type. See #LineTypes /// When true, the image data origin is at the bottom-left corner. /// Otherwise, it is at the top-left corner. - public static void PutText(InputOutputArray img, string text, Point org, + public static void PutText(InputOutputArrayRef img, string text, Point org, HersheyFonts fontFace, double fontScale, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, bool bottomLeftOrigin = false) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (string.IsNullOrEmpty(text)) throw new ArgumentNullException(text); - img.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.imgproc_putText(img.ToInputOutputProxy(), text, org, (int) fontFace, fontScale, color, + NativeMethods.imgproc_putText(img.Proxy, text, org, (int) fontFace, fontScale, color, thickness, (int) lineType, bottomLeftOrigin ? 1 : 0)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -5135,25 +4249,21 @@ public static double GetFontScaleFromHeight(HersheyFonts fontFace, int pixelHeig /// Optional text wrapping range. Null uses the default behavior. /// The coordinates in pixels from where the text can be continued. public static Point PutText( - InputOutputArray img, string text, Point org, Scalar color, FontFace fontFace, int size, + InputOutputArrayRef img, string text, Point org, Scalar color, FontFace fontFace, int size, int weight = 0, PutTextFlags flags = PutTextFlags.AlignLeft, Range? wrap = null) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (text is null) throw new ArgumentNullException(nameof(text)); if (fontFace is null) throw new ArgumentNullException(nameof(fontFace)); - img.ThrowIfDisposed(); fontFace.ThrowIfDisposed(); var w = wrap ?? new Range(0, 0); NativeMethods.HandleException( NativeMethods.imgproc_putText_FontFace( - img.ToInputOutputProxy(), text, org, color, fontFace.CvPtr, size, weight, (int)flags, w.Start, w.End, out var ret)); + img.Proxy, text, org, color, fontFace.CvPtr, size, weight, (int)flags, w.Start, w.End, out var ret)); - img.Fix(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); GC.KeepAlive(fontFace); return ret; } @@ -5207,34 +4317,18 @@ public static Rect GetTextSize( /// This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. /// OX is drawn in red, OY in green and OZ in blue. public static void DrawFrameAxes( - InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, - InputArray rvec, InputArray tvec, float length, int thickness = 3) - { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - image.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - rvec.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - + InputOutputArrayRef image, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, + InputArrayRef rvec, InputArrayRef tvec, float length, int thickness = 3) + { NativeMethods.HandleException( NativeMethods.imgproc_drawFrameAxes( - image.ToInputOutputProxy(), cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), rvec.ToInputProxy(), tvec.ToInputProxy(), length, thickness)); + image.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, rvec.Proxy, tvec.Proxy, length, thickness)); - GC.KeepAlive(image); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(rvec); - GC.KeepAlive(tvec); + GC.KeepAlive(image.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(rvec.Source); + GC.KeepAlive(tvec.Source); } /// @@ -5248,31 +4342,20 @@ public static void DrawFrameAxes( /// Camera matrix of the distorted image. /// By default, it is the same as cameraMatrix but you may additionally scale /// and shift the result by using a different matrix. - public static void Undistort(InputArray src, OutputArray dst, - InputArray cameraMatrix, - InputArray distCoeffs, - InputArray? newCameraMatrix = null) + public static void Undistort(InputArrayRef src, OutputArrayRef dst, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + InputArrayRef newCameraMatrix = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgproc_undistort(src.ToInputProxy(), dst.ToOutputProxy(), cameraMatrix.ToInputProxy(), - distCoeffs?.ToInputProxy() ?? default, newCameraMatrix?.ToInputProxy() ?? default)); + NativeMethods.imgproc_undistort(src.Proxy, dst.Proxy, cameraMatrix.Proxy, + distCoeffs.Proxy, newCameraMatrix.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(newCameraMatrix); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(newCameraMatrix.Source); } /// @@ -5287,41 +4370,20 @@ public static void Undistort(InputArray src, OutputArray dst, /// /// public static void InitUndistortRectifyMap( - InputArray cameraMatrix, InputArray distCoeffs, - InputArray r, InputArray newCameraMatrix, - Size size, MatType m1Type, OutputArray map1, OutputArray map2) - { - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (newCameraMatrix is null) - throw new ArgumentNullException(nameof(newCameraMatrix)); - if (map1 is null) - throw new ArgumentNullException(nameof(map1)); - if (map2 is null) - throw new ArgumentNullException(nameof(map2)); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - r.ThrowIfDisposed(); - newCameraMatrix.ThrowIfDisposed(); - map1.ThrowIfNotReady(); - map2.ThrowIfNotReady(); - + InputArrayRef cameraMatrix, InputArrayRef distCoeffs, + InputArrayRef r, InputArrayRef newCameraMatrix, + Size size, MatType m1Type, OutputArrayRef map1, OutputArrayRef map2) + { NativeMethods.HandleException( NativeMethods.imgproc_initUndistortRectifyMap( - cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), r.ToInputProxy(), newCameraMatrix.ToInputProxy(), size, m1Type, map1.ToOutputProxy(), map2.ToOutputProxy())); + cameraMatrix.Proxy, distCoeffs.Proxy, r.Proxy, newCameraMatrix.Proxy, size, m1Type, map1.Proxy, map2.Proxy)); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(r); - GC.KeepAlive(newCameraMatrix); - GC.KeepAlive(map1); - GC.KeepAlive(map2); - map1.Fix(); - map2.Fix(); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(newCameraMatrix.Source); + GC.KeepAlive(map1.Source); + GC.KeepAlive(map2.Source); } /// @@ -5338,35 +4400,20 @@ public static void InitUndistortRectifyMap( /// /// public static float InitWideAngleProjMap( - InputArray cameraMatrix, InputArray distCoeffs, + InputArrayRef cameraMatrix, InputArrayRef distCoeffs, Size imageSize, int destImageWidth, MatType m1Type, - OutputArray map1, OutputArray map2, + OutputArrayRef map1, OutputArrayRef map2, ProjectionType projType, double alpha = 0) { - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (map1 is null) - throw new ArgumentNullException(nameof(map1)); - if (map2 is null) - throw new ArgumentNullException(nameof(map2)); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - map1.ThrowIfNotReady(); - map2.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_initWideAngleProjMap( - cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), imageSize, - destImageWidth, m1Type, map1.ToOutputProxy(), map2.ToOutputProxy(), (int) projType, alpha, out var ret)); - - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(map1); - GC.KeepAlive(map2); - map1.Fix(); - map2.Fix(); + cameraMatrix.Proxy, distCoeffs.Proxy, imageSize, + destImageWidth, m1Type, map1.Proxy, map2.Proxy, (int) projType, alpha, out var ret)); + + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(map1.Source); + GC.KeepAlive(map2.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/imgproc/Moments.cs b/src/OpenCvSharp/Modules/imgproc/Moments.cs index 4ebc23b46..3a3cbc212 100644 --- a/src/OpenCvSharp/Modules/imgproc/Moments.cs +++ b/src/OpenCvSharp/Modules/imgproc/Moments.cs @@ -65,11 +65,8 @@ public Moments(double m00, double m10, double m01, double m20, double m11, /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - public Moments(InputArray array, bool binaryImage = false) + public Moments(InputArrayRef array, bool binaryImage = false) { - if (array is null) - throw new ArgumentNullException(nameof(array)); - array.ThrowIfDisposed(); InitializeFromInputArray(array, binaryImage); } @@ -147,11 +144,11 @@ public Moments(IEnumerable array, bool binaryImage = false) /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - private void InitializeFromInputArray(InputArray array, bool binaryImage) + private void InitializeFromInputArray(InputArrayRef array, bool binaryImage) { NativeMethods.HandleException( - NativeMethods.imgproc_moments(array.ToInputProxy(), binaryImage ? 1 : 0, out var m)); - GC.KeepAlive(array); + NativeMethods.imgproc_moments(array.Proxy, binaryImage ? 1 : 0, out var m)); + GC.KeepAlive(array.Source); Initialize(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03); } diff --git a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs index 76d2f01c3..efea40b5d 100644 --- a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs +++ b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs @@ -26,7 +26,7 @@ public void MorphologyExDilate() using var src = new Mat(100, 100, MatType.CV_8UC1, Scalar.All(255)); using var dst = new Mat(); Cv2.Rectangle(src, new Rect(30, 30, 40, 40), Scalar.Black, 1); - Cv2.MorphologyEx(src, dst, MorphTypes.Dilate, null); + Cv2.MorphologyEx(src, dst, MorphTypes.Dilate, default); ShowImagesWhenDebugMode(src, dst); @@ -39,7 +39,7 @@ public void MorphologyExErode() using var src = Mat.ZerosMat(100, 100, MatType.CV_8UC1); using var dst = new Mat(); Cv2.Rectangle(src, new Rect(30, 30, 40, 40), Scalar.White, 1); - Cv2.MorphologyEx(src, dst, MorphTypes.Erode, null); + Cv2.MorphologyEx(src, dst, MorphTypes.Erode, default); ShowImagesWhenDebugMode(src, dst); @@ -468,13 +468,11 @@ public void Rectangle() using Mat img2 = img1.Clone(); using Mat img3 = img1.Clone(); using Mat img4 = img1.Clone(); - using InputOutputArray ioa3 = InputOutputArray.Create(img3); - using InputOutputArray ioa4 = InputOutputArray.Create(img4); Cv2.Rectangle(img1, new Rect(10, 10, 80, 80), color, 1); Cv2.Rectangle(img2, new Point(10, 10), new Point(89, 89), color, 1); - Cv2.Rectangle(ioa3, new Rect(10, 10, 80, 80), color, 1); - Cv2.Rectangle(ioa4, new Point(10, 10), new Point(89, 89), color, 1); + Cv2.Rectangle(InputOutputArrayRef.Create(img3), new Rect(10, 10, 80, 80), color, 1); + Cv2.Rectangle(InputOutputArrayRef.Create(img4), new Point(10, 10), new Point(89, 89), color, 1); ShowImagesWhenDebugMode(img1, img2); @@ -653,7 +651,7 @@ public void CalcHist() Cv2.CalcHist( images: [src], channels: [0], - mask: null, + mask: default, hist: hist, dims: 1, histSize: [256], @@ -1223,7 +1221,7 @@ public void CalcBackProject() using var src = LoadImage("lenna.png", ImreadModes.Grayscale); using var hist = new Mat(); var ranges = new[] { new Rangef(0, 256) }; - Cv2.CalcHist(new[] { src }, SingleChannelIndex, null, hist, 1, GrayscaleHistSize, ranges); + Cv2.CalcHist(new[] { src }, SingleChannelIndex, default, hist, 1, GrayscaleHistSize, ranges); using var backProject = new Mat(); Cv2.CalcBackProject(new[] { src }, SingleChannelIndex, hist, backProject, ranges); From ac862af665dc8cced2e6c1540f46706fe1d85621 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:15:58 +0900 Subject: [PATCH 20/29] Migration: Cv2_geometry.cs (42 methods) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 15) Scripted via migrate_step5.py (same tool used for Cv2_imgproc.cs). Only manual fixup needed: the two convenience Rodrigues(double[]/double[,]) overloads built explicit old-class InputArray.Create(...)/ OutputArray.Create(...) wrappers around their Mats before delegating to Rodrigues(InputArrayRef, OutputArrayRef, OutputArrayRef) -- simplified to pass the Mats directly, since Mat converts implicitly to the *Ref types. --- src/OpenCvSharp/Cv2/Cv2_geometry.cs | 1146 ++++++++------------------- 1 file changed, 320 insertions(+), 826 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_geometry.cs b/src/OpenCvSharp/Cv2/Cv2_geometry.cs index a0cc192c0..d1051a31e 100644 --- a/src/OpenCvSharp/Cv2/Cv2_geometry.cs +++ b/src/OpenCvSharp/Cv2/Cv2_geometry.cs @@ -19,23 +19,14 @@ static partial class Cv2 /// Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). /// Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. /// Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial derivatives of the output array components with respect to the input array components. - public static void Rodrigues(InputArray src, OutputArray dst, OutputArray? jacobian = null) + public static void Rodrigues(InputArrayRef src, OutputArrayRef dst, OutputArrayRef jacobian = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.geometry_Rodrigues(src.ToInputProxy(), dst.ToOutputProxy(), jacobian?.ToOutputProxy() ?? default)); + NativeMethods.geometry_Rodrigues(src.Proxy, dst.Proxy, jacobian.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(jacobian); - dst.Fix(); - jacobian?.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(jacobian.Source); } /// @@ -54,10 +45,7 @@ public static void Rodrigues(double[] vector, out double[,] matrix, out double[, using var vectorM = Mat.FromPixelData(3, 1, MatType.CV_64FC1, vector); using var matrixM = new Mat(); using var jacobianM = new Mat(); - using var vectorInputArray = InputArray.Create(vectorM); - using var matrixOutputArray = OutputArray.Create(matrixM); - using var jacobianOutputArray = OutputArray.Create(jacobianM); - Rodrigues(vectorInputArray, matrixOutputArray, jacobianOutputArray); + Rodrigues(vectorM, matrixM, jacobianM); matrix = matrixM.ToRectangularArray(); jacobian = jacobianM.ToRectangularArray(); } @@ -78,10 +66,7 @@ public static void Rodrigues(double[,] matrix, out double[] vector, out double[, using var matrixM = Mat.FromPixelData(3, 3, MatType.CV_64FC1, matrix); using var vectorM = new Mat(); using var jacobianM = new Mat(); - using var matrixOutputArray = InputArray.Create(matrixM); - using var vectorInputArray = OutputArray.Create(vectorM); - using var jacobianOutputArray = OutputArray.Create(jacobianM); - Rodrigues(matrixOutputArray, vectorInputArray, jacobianOutputArray); + Rodrigues(matrixM, vectorM, jacobianM); vector = vectorM.ToArray(); jacobian = jacobianM.ToRectangularArray(); } @@ -98,31 +83,23 @@ public static void Rodrigues(double[,] matrix, out double[] vector, out double[, /// Confidence level, between 0 and 1. /// public static Mat FindHomography( - InputArray srcPoints, - InputArray dstPoints, + InputArrayRef srcPoints, + InputArrayRef dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, - OutputArray? mask = null, + OutputArrayRef mask = default, int maxIters = 2000, double confidence = 0.995) { - if (srcPoints is null) - throw new ArgumentNullException(nameof(srcPoints)); - if (dstPoints is null) - throw new ArgumentNullException(nameof(dstPoints)); - srcPoints.ThrowIfDisposed(); - dstPoints.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_findHomography_InputArray( - srcPoints.ToInputProxy(), dstPoints.ToInputProxy(), (int)method, - ransacReprojThreshold, mask?.ToOutputProxy() ?? default, maxIters, confidence, + srcPoints.Proxy, dstPoints.Proxy, (int)method, + ransacReprojThreshold, mask.Proxy, maxIters, confidence, out var ret)); - GC.KeepAlive(srcPoints); - GC.KeepAlive(dstPoints); - GC.KeepAlive(mask); - mask?.Fix(); + GC.KeepAlive(srcPoints.Source); + GC.KeepAlive(dstPoints.Source); + GC.KeepAlive(mask.Source); return new Mat(ret); } @@ -143,7 +120,7 @@ public static Mat FindHomography( IEnumerable dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, - OutputArray? mask = null, + OutputArrayRef mask = default, int maxIters = 2000, double confidence = 0.995) { @@ -159,11 +136,10 @@ public static Mat FindHomography( NativeMethods.geometry_findHomography_vector( srcPointsArray, srcPointsArray.Length, dstPointsArray, dstPointsArray.Length, - (int)method, ransacReprojThreshold, mask?.ToOutputProxy() ?? default, maxIters, confidence, + (int)method, ransacReprojThreshold, mask.Proxy, maxIters, confidence, out var ret)); - GC.KeepAlive(mask); - mask?.Fix(); + GC.KeepAlive(mask.Source); return new Mat(ret); } @@ -177,31 +153,20 @@ public static Mat FindHomography( /// /// public static Mat FindHomography( - InputArray srcPoints, - InputArray dstPoints, - OutputArray mask, + InputArrayRef srcPoints, + InputArrayRef dstPoints, + OutputArrayRef mask, UsacParams? @params) { - if (srcPoints is null) - throw new ArgumentNullException(nameof(srcPoints)); - if (dstPoints is null) - throw new ArgumentNullException(nameof(dstPoints)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - srcPoints.ThrowIfDisposed(); - dstPoints.ThrowIfDisposed(); - mask.ThrowIfNotReady(); - var p = (@params ?? new UsacParams()).ToNativeStruct(); NativeMethods.HandleException( NativeMethods.geometry_findHomography_UsacParams( - srcPoints.ToInputProxy(), dstPoints.ToInputProxy(), mask.ToOutputProxy(), ref p, + srcPoints.Proxy, dstPoints.Proxy, mask.Proxy, ref p, out var ret)); - GC.KeepAlive(srcPoints); - GC.KeepAlive(dstPoints); - GC.KeepAlive(mask); - mask.Fix(); + GC.KeepAlive(srcPoints.Source); + GC.KeepAlive(dstPoints.Source); + GC.KeepAlive(mask.Source); return new Mat(ret); } @@ -215,30 +180,17 @@ public static Mat FindHomography( /// Optional output 3x3 rotation matrix around y-axis. /// Optional output 3x3 rotation matrix around z-axis. /// - public static Vec3d RQDecomp3x3(InputArray src, OutputArray mtxR, OutputArray mtxQ, - OutputArray? qx = null, OutputArray? qy = null, OutputArray? qz = null) + public static Vec3d RQDecomp3x3(InputArrayRef src, OutputArrayRef mtxR, OutputArrayRef mtxQ, + OutputArrayRef qx = default, OutputArrayRef qy = default, OutputArrayRef qz = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (mtxR is null) - throw new ArgumentNullException(nameof(mtxR)); - if (mtxQ is null) - throw new ArgumentNullException(nameof(mtxQ)); - src.ThrowIfDisposed(); - mtxR.ThrowIfNotReady(); - mtxQ.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_RQDecomp3x3_InputArray( - src.ToInputProxy(), mtxR.ToOutputProxy(), mtxQ.ToOutputProxy(), - qx?.ToOutputProxy() ?? default, qy?.ToOutputProxy() ?? default, qz?.ToOutputProxy() ?? default, out var ret)); - - GC.KeepAlive(src); - GC.KeepAlive(mtxR); - GC.KeepAlive(mtxQ); - qx?.Fix(); - qy?.Fix(); - qz?.Fix(); + src.Proxy, mtxR.Proxy, mtxQ.Proxy, + qx.Proxy, qy.Proxy, qz.Proxy, out var ret)); + + GC.KeepAlive(src.Source); + GC.KeepAlive(mtxR.Source); + GC.KeepAlive(mtxQ.Source); return ret; } @@ -302,49 +254,29 @@ public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] /// Optional 3x3 rotation matrix around z-axis. /// ptional three-element vector containing three Euler angles of rotation in degrees. public static void DecomposeProjectionMatrix( - InputArray projMatrix, - OutputArray cameraMatrix, - OutputArray rotMatrix, - OutputArray transVect, - OutputArray? rotMatrixX = null, - OutputArray? rotMatrixY = null, - OutputArray? rotMatrixZ = null, - OutputArray? eulerAngles = null) + InputArrayRef projMatrix, + OutputArrayRef cameraMatrix, + OutputArrayRef rotMatrix, + OutputArrayRef transVect, + OutputArrayRef rotMatrixX = default, + OutputArrayRef rotMatrixY = default, + OutputArrayRef rotMatrixZ = default, + OutputArrayRef eulerAngles = default) { - if (projMatrix is null) - throw new ArgumentNullException(nameof(projMatrix)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (rotMatrix is null) - throw new ArgumentNullException(nameof(rotMatrix)); - if (transVect is null) - throw new ArgumentNullException(nameof(transVect)); - projMatrix.ThrowIfDisposed(); - cameraMatrix.ThrowIfNotReady(); - rotMatrix.ThrowIfNotReady(); - transVect.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_decomposeProjectionMatrix_InputArray( - projMatrix.ToInputProxy(), cameraMatrix.ToOutputProxy(), rotMatrix.ToOutputProxy(), transVect.ToOutputProxy(), - rotMatrixX?.ToOutputProxy() ?? default, rotMatrixY?.ToOutputProxy() ?? default, rotMatrixZ?.ToOutputProxy() ?? default, eulerAngles?.ToOutputProxy() ?? default)); + projMatrix.Proxy, cameraMatrix.Proxy, rotMatrix.Proxy, transVect.Proxy, + rotMatrixX.Proxy, rotMatrixY.Proxy, rotMatrixZ.Proxy, eulerAngles.Proxy)); - GC.KeepAlive(projMatrix); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(rotMatrix); - GC.KeepAlive(transVect); - GC.KeepAlive(rotMatrixX); - GC.KeepAlive(rotMatrixY); - GC.KeepAlive(rotMatrixZ); - GC.KeepAlive(eulerAngles); + GC.KeepAlive(projMatrix.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(rotMatrix.Source); + GC.KeepAlive(transVect.Source); + GC.KeepAlive(rotMatrixX.Source); + GC.KeepAlive(rotMatrixY.Source); + GC.KeepAlive(rotMatrixZ.Source); + GC.KeepAlive(eulerAngles.Source); - cameraMatrix.Fix(); - rotMatrix.Fix(); - transVect.Fix(); - rotMatrixX?.Fix(); - rotMatrixY?.Fix(); - rotMatrixZ?.Fix(); - eulerAngles?.Fix(); } /// @@ -423,27 +355,13 @@ public static void DecomposeProjectionMatrix(double[,] projMatrix, /// First output derivative matrix d(A*B)/dA of size A.rows*B.cols X A.rows*A.cols . /// Second output derivative matrix d(A*B)/dB of size A.rows*B.cols X B.rows*B.cols . public static void MatMulDeriv( - InputArray a, InputArray b, - OutputArray dABdA, OutputArray dABdB) - { - if (a is null) - throw new ArgumentNullException(nameof(a)); - if (b is null) - throw new ArgumentNullException(nameof(b)); - if (dABdA is null) - throw new ArgumentNullException(nameof(dABdA)); - if (dABdB is null) - throw new ArgumentNullException(nameof(dABdB)); - a.ThrowIfDisposed(); - b.ThrowIfDisposed(); - dABdA.ThrowIfNotReady(); - dABdB.ThrowIfNotReady(); + InputArrayRef a, InputArrayRef b, + OutputArrayRef dABdA, OutputArrayRef dABdB) + { NativeMethods.HandleException( - NativeMethods.geometry_matMulDeriv(a.ToInputProxy(), b.ToInputProxy(), dABdA.ToOutputProxy(), dABdB.ToOutputProxy())); - GC.KeepAlive(a); - GC.KeepAlive(b); - dABdA.Fix(); - dABdB.Fix(); + NativeMethods.geometry_matMulDeriv(a.Proxy, b.Proxy, dABdA.Proxy, dABdB.Proxy)); + GC.KeepAlive(a.Source); + GC.KeepAlive(b.Source); } /// @@ -464,53 +382,34 @@ public static void MatMulDeriv( /// Optional output derivatives of rvec3 or tvec3 with regard to rvec1, rvec2, tvec1 and tvec2, respectively. /// Optional output derivatives of rvec3 or tvec3 with regard to rvec1, rvec2, tvec1 and tvec2, respectively. public static void ComposeRT( - InputArray rvec1, InputArray tvec1, - InputArray rvec2, InputArray tvec2, - OutputArray rvec3, OutputArray tvec3, - OutputArray? dr3dr1 = null, OutputArray? dr3dt1 = null, - OutputArray? dr3dr2 = null, OutputArray? dr3dt2 = null, - OutputArray? dt3dr1 = null, OutputArray? dt3dt1 = null, - OutputArray? dt3dr2 = null, OutputArray? dt3dt2 = null) + InputArrayRef rvec1, InputArrayRef tvec1, + InputArrayRef rvec2, InputArrayRef tvec2, + OutputArrayRef rvec3, OutputArrayRef tvec3, + OutputArrayRef dr3dr1 = default, OutputArrayRef dr3dt1 = default, + OutputArrayRef dr3dr2 = default, OutputArrayRef dr3dt2 = default, + OutputArrayRef dt3dr1 = default, OutputArrayRef dt3dt1 = default, + OutputArrayRef dt3dr2 = default, OutputArrayRef dt3dt2 = default) { - if (rvec1 is null) - throw new ArgumentNullException(nameof(rvec1)); - if (tvec1 is null) - throw new ArgumentNullException(nameof(tvec1)); - if (rvec2 is null) - throw new ArgumentNullException(nameof(rvec2)); - if (tvec2 is null) - throw new ArgumentNullException(nameof(tvec2)); - if (rvec3 is null) - throw new ArgumentNullException(nameof(rvec3)); - if (tvec3 is null) - throw new ArgumentNullException(nameof(tvec3)); - rvec1.ThrowIfDisposed(); - tvec1.ThrowIfDisposed(); - rvec2.ThrowIfDisposed(); - tvec2.ThrowIfDisposed(); - rvec3.ThrowIfNotReady(); - tvec3.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_composeRT_InputArray( - rvec1.ToInputProxy(), tvec1.ToInputProxy(), rvec2.ToInputProxy(), tvec2.ToInputProxy(), rvec3.ToOutputProxy(), tvec3.ToOutputProxy(), - dr3dr1?.ToOutputProxy() ?? default, dr3dt1?.ToOutputProxy() ?? default, dr3dr2?.ToOutputProxy() ?? default, dr3dt2?.ToOutputProxy() ?? default, - dt3dr1?.ToOutputProxy() ?? default, dt3dt1?.ToOutputProxy() ?? default, dt3dr2?.ToOutputProxy() ?? default, dt3dt2?.ToOutputProxy() ?? default)); - - GC.KeepAlive(rvec1); - GC.KeepAlive(tvec1); - GC.KeepAlive(rvec2); - GC.KeepAlive(tvec2); - GC.KeepAlive(rvec3); - GC.KeepAlive(tvec3); - GC.KeepAlive(dr3dr1); - GC.KeepAlive(dr3dt1); - GC.KeepAlive(dr3dr2); - GC.KeepAlive(dr3dt2); - GC.KeepAlive(dt3dr1); - GC.KeepAlive(dt3dt1); - GC.KeepAlive(dt3dr2); - GC.KeepAlive(dt3dt2); + rvec1.Proxy, tvec1.Proxy, rvec2.Proxy, tvec2.Proxy, rvec3.Proxy, tvec3.Proxy, + dr3dr1.Proxy, dr3dt1.Proxy, dr3dr2.Proxy, dr3dt2.Proxy, + dt3dr1.Proxy, dt3dt1.Proxy, dt3dr2.Proxy, dt3dt2.Proxy)); + + GC.KeepAlive(rvec1.Source); + GC.KeepAlive(tvec1.Source); + GC.KeepAlive(rvec2.Source); + GC.KeepAlive(tvec2.Source); + GC.KeepAlive(rvec3.Source); + GC.KeepAlive(tvec3.Source); + GC.KeepAlive(dr3dr1.Source); + GC.KeepAlive(dr3dt1.Source); + GC.KeepAlive(dr3dr2.Source); + GC.KeepAlive(dr3dt2.Source); + GC.KeepAlive(dt3dr1.Source); + GC.KeepAlive(dt3dt1.Source); + GC.KeepAlive(dt3dr2.Source); + GC.KeepAlive(dt3dt2.Source); } /// @@ -624,44 +523,28 @@ public static void ComposeRT(double[] rvec1, double[] tvec1, /// If the parameter is not 0, the function assumes that the aspect ratio (fx/fy) /// is fixed and correspondingly adjusts the jacobian matrix. public static void ProjectPoints( - InputArray objectPoints, - InputArray rvec, - InputArray tvec, - InputArray cameraMatrix, - InputArray distCoeffs, - OutputArray imagePoints, - OutputArray? jacobian = null, + InputArrayRef objectPoints, + InputArrayRef rvec, + InputArrayRef tvec, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + OutputArrayRef imagePoints, + OutputArrayRef jacobian = default, double aspectRatio = 0) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - objectPoints.ThrowIfDisposed(); - rvec.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - imagePoints.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_projectPoints_InputArray( - objectPoints.ToInputProxy(), - rvec.ToInputProxy(), tvec.ToInputProxy(), cameraMatrix.ToInputProxy(), distCoeffs?.ToInputProxy() ?? default, - imagePoints.ToOutputProxy(), jacobian?.ToOutputProxy() ?? default, aspectRatio)); + objectPoints.Proxy, + rvec.Proxy, tvec.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, + imagePoints.Proxy, jacobian.Proxy, aspectRatio)); - GC.KeepAlive(objectPoints); - GC.KeepAlive(rvec); - GC.KeepAlive(tvec); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(imagePoints); - GC.KeepAlive(jacobian); + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(rvec.Source); + GC.KeepAlive(tvec.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(jacobian.Source); } /// @@ -747,43 +630,22 @@ public static void ProjectPoints( /// the rotation and translation vectors, respectively, and further optimizes them. /// Method for solving a PnP problem: public static void SolvePnP( - InputArray objectPoints, - InputArray imagePoints, - InputArray cameraMatrix, - InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, + InputArrayRef objectPoints, + InputArrayRef imagePoints, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + OutputArrayRef rvec, OutputArrayRef tvec, bool useExtrinsicGuess = false, SolvePnPMethod flags = SolvePnPMethod.Iterative) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - objectPoints.ThrowIfDisposed(); - imagePoints.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - rvec.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - NativeMethods.HandleException(NativeMethods.geometry_solvePnP_InputArray( - objectPoints.ToInputProxy(), imagePoints.ToInputProxy(), cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), - rvec.ToOutputProxy(), tvec.ToOutputProxy(), useExtrinsicGuess ? 1 : 0, (int) flags)); + objectPoints.Proxy, imagePoints.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, + rvec.Proxy, tvec.Proxy, useExtrinsicGuess ? 1 : 0, (int) flags)); - rvec.Fix(); - tvec.Fix(); - GC.KeepAlive(objectPoints); - GC.KeepAlive(imagePoints); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); } /// @@ -868,51 +730,29 @@ public static void SolvePnP( /// Output vector that contains indices of inliers in objectPoints and imagePoints . /// Method for solving a PnP problem public static void SolvePnPRansac( - InputArray objectPoints, - InputArray imagePoints, - InputArray cameraMatrix, - InputArray distCoeffs, - OutputArray? rvec, - OutputArray? tvec, + InputArrayRef objectPoints, + InputArrayRef imagePoints, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + OutputArrayRef rvec, + OutputArrayRef tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0f, double confidence = 0.99, - OutputArray? inliers = null, + OutputArrayRef inliers = default, SolvePnPMethod flags = SolvePnPMethod.Iterative) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - objectPoints.ThrowIfDisposed(); - imagePoints.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - rvec.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_solvePnPRansac_InputArray( - objectPoints.ToInputProxy(), imagePoints.ToInputProxy(), cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), - rvec.ToOutputProxy(), tvec.ToOutputProxy(), useExtrinsicGuess ? 1 : 0, iterationsCount, - reprojectionError, confidence, inliers?.ToOutputProxy() ?? default, (int) flags)); + objectPoints.Proxy, imagePoints.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, + rvec.Proxy, tvec.Proxy, useExtrinsicGuess ? 1 : 0, iterationsCount, + reprojectionError, confidence, inliers.Proxy, (int) flags)); - GC.KeepAlive(objectPoints); - GC.KeepAlive(imagePoints); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - rvec.Fix(); - tvec.Fix(); - inliers?.Fix(); + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); } /// @@ -1020,20 +860,16 @@ public static void SolvePnPRansac( /// Principal point in pixels. /// fy / fx public static void CalibrationMatrixValues( - InputArray cameraMatrix, Size imageSize, + InputArrayRef cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, out double fovx, out double fovy, out double focalLength, out Point2d principalPoint, out double aspectRatio) { - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_calibrationMatrixValues_InputArray( - cameraMatrix.ToInputProxy(), imageSize, apertureWidth, apertureHeight, + cameraMatrix.Proxy, imageSize, apertureWidth, apertureHeight, out fovx, out fovy, out focalLength, out principalPoint, out aspectRatio)); - GC.KeepAlive(cameraMatrix); + GC.KeepAlive(cameraMatrix.Source); } /// @@ -1088,24 +924,20 @@ public static void CalibrationMatrixValues( /// subset of the source image (determined by alpha) to the corrected image. /// optimal new camera matrix public static Mat GetOptimalNewCameraMatrix( - InputArray cameraMatrix, - InputArray? distCoeffs, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, Size imageSize, double alpha, Size newImgSize, out Rect validPixROI, bool centerPrincipalPoint = false) { - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_getOptimalNewCameraMatrix_InputArray( - cameraMatrix.ToInputProxy(), distCoeffs?.ToInputProxy() ?? default, imageSize, alpha, newImgSize, + cameraMatrix.Proxy, distCoeffs.Proxy, imageSize, alpha, newImgSize, out validPixROI, centerPrincipalPoint ? 1 : 0, out var ret)); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); return new Mat(ret); } @@ -1158,21 +990,13 @@ public static Mat GetOptimalNewCameraMatrix( /// /// Input vector of N-dimensional points. /// Output vector of N+1-dimensional points. - public static void ConvertPointsToHomogeneous(InputArray src, OutputArray dst) + public static void ConvertPointsToHomogeneous(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.geometry_convertPointsToHomogeneous_InputArray(src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.geometry_convertPointsToHomogeneous_InputArray(src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1216,18 +1040,11 @@ public static Vec4f[] ConvertPointsToHomogeneous(IEnumerable src) /// /// Input vector of N-dimensional points. /// Output vector of N-1-dimensional points. - public static void ConvertPointsFromHomogeneous(InputArray src, OutputArray dst) + public static void ConvertPointsFromHomogeneous(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.geometry_convertPointsFromHomogeneous_InputArray(src.ToInputProxy(), dst.ToOutputProxy())); - GC.KeepAlive(src); - dst.Fix(); + NativeMethods.geometry_convertPointsFromHomogeneous_InputArray(src.Proxy, dst.Proxy)); + GC.KeepAlive(src.Source); } /// @@ -1271,18 +1088,11 @@ public static Vec3f[] ConvertPointsFromHomogeneous(IEnumerable src) /// /// Input array or vector of 2D, 3D, or 4D points. /// Output vector of 2D, 3D, or 4D points. - public static void ConvertPointsHomogeneous(InputArray src, OutputArray dst) + public static void ConvertPointsHomogeneous(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.geometry_convertPointsHomogeneous(src.ToInputProxy(), dst.ToOutputProxy())); - GC.KeepAlive(src); - dst.Fix(); + NativeMethods.geometry_convertPointsHomogeneous(src.Proxy, dst.Proxy)); + GC.KeepAlive(src.Source); } /// @@ -1302,25 +1112,17 @@ public static void ConvertPointsHomogeneous(InputArray src, OutputArray dst) /// to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. For other methods, it is set to all 1’s. /// fundamental matrix public static Mat FindFundamentalMat( - InputArray points1, InputArray points2, + InputArrayRef points1, InputArrayRef points2, FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArray? mask = null) + OutputArrayRef mask = default) { - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_findFundamentalMat_InputArray( - points1.ToInputProxy(), points2.ToInputProxy(), (int) method, - param1, param2, mask?.ToOutputProxy() ?? default, out var ret)); - mask?.Fix(); - GC.KeepAlive(points1); - GC.KeepAlive(points2); + points1.Proxy, points2.Proxy, (int) method, + param1, param2, mask.Proxy, out var ret)); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); return new Mat(ret); } @@ -1347,7 +1149,7 @@ public static Mat FindFundamentalMat( FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArray? mask = null) + OutputArrayRef mask = default) { if (points1 is null) throw new ArgumentNullException(nameof(points1)); @@ -1361,8 +1163,7 @@ public static Mat FindFundamentalMat( NativeMethods.geometry_findFundamentalMat_arrayF32( points1Array, points1Array.Length, points2Array, points2Array.Length, (int) method, - param1, param2, mask?.ToOutputProxy() ?? default, out var ret)); - mask?.Fix(); + param1, param2, mask.Proxy, out var ret)); return new Mat(ret); } @@ -1389,7 +1190,7 @@ public static Mat FindFundamentalMat( FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArray? mask = null) + OutputArrayRef mask = default) { if (points1 is null) throw new ArgumentNullException(nameof(points1)); @@ -1403,8 +1204,7 @@ public static Mat FindFundamentalMat( NativeMethods.geometry_findFundamentalMat_arrayF64( points1Array, points1Array.Length, points2Array, points2Array.Length, (int) method, - param1, param2, mask?.ToOutputProxy() ?? default, out var ret)); - mask?.Fix(); + param1, param2, mask.Proxy, out var ret)); return new Mat(ret); } @@ -1417,27 +1217,16 @@ public static Mat FindFundamentalMat( /// Output array of N elements; every element marks an inlier (1) or outlier (0). /// USAC parameters. Null uses the defaults. /// The estimated fundamental matrix. - public static Mat FindFundamentalMat(InputArray points1, InputArray points2, OutputArray mask, UsacParams? @params) + public static Mat FindFundamentalMat(InputArrayRef points1, InputArrayRef points2, OutputArrayRef mask, UsacParams? @params) { - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - mask.ThrowIfNotReady(); - var p = (@params ?? new UsacParams()).ToNativeStruct(); NativeMethods.HandleException( NativeMethods.geometry_findFundamentalMat_UsacParams( - points1.ToInputProxy(), points2.ToInputProxy(), mask.ToOutputProxy(), ref p, out var ret)); + points1.Proxy, points2.Proxy, mask.Proxy, ref p, out var ret)); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - GC.KeepAlive(mask); - mask.Fix(); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); + GC.KeepAlive(mask.Source); return new Mat(ret); } @@ -1449,28 +1238,17 @@ public static Mat FindFundamentalMat(InputArray points1, InputArray points2, Out /// Fundamental matrix that can be estimated using findFundamentalMat() or stereoRectify() . /// Output vector of the epipolar lines corresponding to the points in the other image. /// Each line ax + by + c=0 is encoded by 3 numbers (a, b, c) . - public static void ComputeCorrespondEpilines(InputArray points, + public static void ComputeCorrespondEpilines(InputArrayRef points, int whichImage, - InputArray F, - OutputArray lines) + InputArrayRef F, + OutputArrayRef lines) { - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (F is null) - throw new ArgumentNullException(nameof(F)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - points.ThrowIfDisposed(); - F.ThrowIfDisposed(); - lines.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_computeCorrespondEpilines_InputArray( - points.ToInputProxy(), whichImage, F.ToInputProxy(), lines.ToOutputProxy())); + points.Proxy, whichImage, F.Proxy, lines.Proxy)); - GC.KeepAlive(F); - GC.KeepAlive(points); - lines.Fix(); + GC.KeepAlive(F.Source); + GC.KeepAlive(points.Source); } /// @@ -1555,36 +1333,19 @@ public static Point3f[] ComputeCorrespondEpilines(IEnumerable points, /// it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. /// 4xN array of reconstructed points in homogeneous coordinates. public static void TriangulatePoints( - InputArray projMatr1, InputArray projMatr2, - InputArray projPoints1, InputArray projPoints2, - OutputArray points4D) + InputArrayRef projMatr1, InputArrayRef projMatr2, + InputArrayRef projPoints1, InputArrayRef projPoints2, + OutputArrayRef points4D) { - if (projMatr1 is null) - throw new ArgumentNullException(nameof(projMatr1)); - if (projMatr2 is null) - throw new ArgumentNullException(nameof(projMatr2)); - if (projPoints1 is null) - throw new ArgumentNullException(nameof(projPoints1)); - if (projPoints2 is null) - throw new ArgumentNullException(nameof(projPoints2)); - if (points4D is null) - throw new ArgumentNullException(nameof(points4D)); - projMatr1.ThrowIfDisposed(); - projMatr2.ThrowIfDisposed(); - projPoints1.ThrowIfDisposed(); - projPoints2.ThrowIfDisposed(); - points4D.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_triangulatePoints_InputArray( - projMatr1.ToInputProxy(), projMatr2.ToInputProxy(), - projPoints1.ToInputProxy(), projPoints2.ToInputProxy(), points4D.ToOutputProxy())); + projMatr1.Proxy, projMatr2.Proxy, + projPoints1.Proxy, projPoints2.Proxy, points4D.Proxy)); - GC.KeepAlive(projMatr1); - GC.KeepAlive(projMatr2); - GC.KeepAlive(projPoints1); - GC.KeepAlive(projPoints2); - points4D.Fix(); + GC.KeepAlive(projMatr1.Source); + GC.KeepAlive(projMatr2.Source); + GC.KeepAlive(projPoints1.Source); + GC.KeepAlive(projPoints2.Source); } @@ -1648,35 +1409,17 @@ public static Vec4d[] TriangulatePoints( /// The optimized points1. /// The optimized points2. public static void CorrectMatches( - InputArray F, InputArray points1, InputArray points2, - OutputArray newPoints1, OutputArray newPoints2) + InputArrayRef F, InputArrayRef points1, InputArrayRef points2, + OutputArrayRef newPoints1, OutputArrayRef newPoints2) { - if (F is null) - throw new ArgumentNullException(nameof(F)); - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (newPoints1 is null) - throw new ArgumentNullException(nameof(newPoints1)); - if (newPoints2 is null) - throw new ArgumentNullException(nameof(newPoints2)); - F.ThrowIfDisposed(); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - newPoints1.ThrowIfNotReady(); - newPoints2.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_correctMatches_InputArray( - F.ToInputProxy(), points1.ToInputProxy(), points2.ToInputProxy(), - newPoints1.ToOutputProxy(), newPoints2.ToOutputProxy())); + F.Proxy, points1.Proxy, points2.Proxy, + newPoints1.Proxy, newPoints2.Proxy)); - GC.KeepAlive(F); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - newPoints1.Fix(); - newPoints2.Fix(); + GC.KeepAlive(F.Source); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); } /// @@ -1736,41 +1479,19 @@ public static void CorrectMatches( /// This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible pose hypotheses by doing cheirality check. /// The cheirality check basically means that the triangulated 3D points should have positive depth. public static int RecoverPose( - InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, - OutputArray R, OutputArray t, - InputOutputArray? mask = null) + InputArrayRef E, InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, + OutputArrayRef R, OutputArrayRef t, + InputOutputArrayRef mask = default) { - if (E is null) - throw new ArgumentNullException(nameof(E)); - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (R is null) - throw new ArgumentNullException(nameof(R)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - E.ThrowIfDisposed(); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - R.ThrowIfNotReady(); - t.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray1( - E.ToInputProxy(), points1.ToInputProxy(), points2.ToInputProxy(), cameraMatrix.ToInputProxy(), - R.ToOutputProxy(), t.ToOutputProxy(), mask?.ToInputOutputProxy() ?? default, out var ret)); + E.Proxy, points1.Proxy, points2.Proxy, cameraMatrix.Proxy, + R.Proxy, t.Proxy, mask.Proxy, out var ret)); - GC.KeepAlive(E); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - GC.KeepAlive(cameraMatrix); - R.Fix(); - t.Fix(); - mask?.Fix(); + GC.KeepAlive(E.Source); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); + GC.KeepAlive(cameraMatrix.Source); return ret; } @@ -1792,38 +1513,19 @@ public static int RecoverPose( /// This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible pose hypotheses by doing cheirality check. /// The cheirality check basically means that the triangulated 3D points should have positive depth. public static int RecoverPose( - InputArray E, InputArray points1, InputArray points2, - OutputArray R, OutputArray t, double focal, Point2d pp, - InputOutputArray? mask = null) + InputArrayRef E, InputArrayRef points1, InputArrayRef points2, + OutputArrayRef R, OutputArrayRef t, double focal, Point2d pp, + InputOutputArrayRef mask = default) { - if (E is null) - throw new ArgumentNullException(nameof(E)); - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (R is null) - throw new ArgumentNullException(nameof(R)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - E.ThrowIfDisposed(); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - R.ThrowIfNotReady(); - t.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray2( - E.ToInputProxy(), points1.ToInputProxy(), points2.ToInputProxy(), - R.ToOutputProxy(), t.ToOutputProxy(), focal, pp, mask?.ToInputOutputProxy() ?? default, out var ret)); + E.Proxy, points1.Proxy, points2.Proxy, + R.Proxy, t.Proxy, focal, pp, mask.Proxy, out var ret)); - GC.KeepAlive(E); - GC.KeepAlive(points1); - GC.KeepAlive(points2); + GC.KeepAlive(E.Source); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); GC.KeepAlive(pp); - R.Fix(); - t.Fix(); - mask?.Fix(); return ret; } @@ -1846,42 +1548,19 @@ public static int RecoverPose( /// The cheirality check basically means that the triangulated 3D points should have positive depth. /// 3d points which were reconstructed by triangulation. public static int RecoverPose( - InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, - OutputArray R, OutputArray t, double distanceTresh, - InputOutputArray? mask = null, OutputArray? triangulatedPoints = null) + InputArrayRef E, InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, + OutputArrayRef R, OutputArrayRef t, double distanceTresh, + InputOutputArrayRef mask = default, OutputArrayRef triangulatedPoints = default) { - if (E is null) - throw new ArgumentNullException(nameof(E)); - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (R is null) - throw new ArgumentNullException(nameof(R)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - E.ThrowIfDisposed(); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - R.ThrowIfNotReady(); - t.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray3( - E.ToInputProxy(), points1.ToInputProxy(), points2.ToInputProxy(), cameraMatrix.ToInputProxy(), - R.ToOutputProxy(), t.ToOutputProxy(), distanceTresh, mask?.ToInputOutputProxy() ?? default, triangulatedPoints?.ToOutputProxy() ?? default, out var ret)); - - GC.KeepAlive(E); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - GC.KeepAlive(cameraMatrix); - R.Fix(); - t.Fix(); - mask?.Fix(); - triangulatedPoints?.Fix(); + E.Proxy, points1.Proxy, points2.Proxy, cameraMatrix.Proxy, + R.Proxy, t.Proxy, distanceTresh, mask.Proxy, triangulatedPoints.Proxy, out var ret)); + + GC.KeepAlive(E.Source); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); + GC.KeepAlive(cameraMatrix.Source); return ret; } @@ -1904,30 +1583,19 @@ public static int RecoverPose( /// Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. /// essential matrix public static Mat FindEssentialMat( - InputArray points1, InputArray points2, InputArray cameraMatrix, + InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, - OutputArray? mask = null) + OutputArrayRef mask = default) { - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_findEssentialMat_InputArray1( - points1.ToInputProxy(), points2.ToInputProxy(), cameraMatrix.ToInputProxy(), - (int) method, prob, threshold, mask?.ToOutputProxy() ?? default, out var ret)); + points1.Proxy, points2.Proxy, cameraMatrix.Proxy, + (int) method, prob, threshold, mask.Proxy, out var ret)); - mask?.Fix(); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - GC.KeepAlive(cameraMatrix); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); + GC.KeepAlive(cameraMatrix.Source); return new Mat(ret); } @@ -1950,26 +1618,18 @@ public static Mat FindEssentialMat( /// Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. /// essential matrix public static Mat FindEssentialMat( - InputArray points1, InputArray points2, double focal, Point2d pp, + InputArrayRef points1, InputArrayRef points2, double focal, Point2d pp, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, - OutputArray? mask = null) + OutputArrayRef mask = default) { - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_findEssentialMat_InputArray2( - points1.ToInputProxy(), points2.ToInputProxy(), focal, pp, - (int) method, prob, threshold, mask?.ToOutputProxy() ?? default, out var ret)); + points1.Proxy, points2.Proxy, focal, pp, + (int) method, prob, threshold, mask.Proxy, out var ret)); - mask?.Fix(); - GC.KeepAlive(points1); - GC.KeepAlive(points2); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); return new Mat(ret); } @@ -1985,31 +1645,16 @@ public static Mat FindEssentialMat( /// Anything between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation significantly. /// Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. /// - public static int EstimateAffine3D(InputArray src, InputArray dst, - OutputArray outVal, OutputArray inliers, + public static int EstimateAffine3D(InputArrayRef src, InputArrayRef dst, + OutputArrayRef outVal, OutputArrayRef inliers, double ransacThreshold = 3, double confidence = 0.99) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (outVal is null) - throw new ArgumentNullException(nameof(outVal)); - if (inliers is null) - throw new ArgumentNullException(nameof(inliers)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - outVal.ThrowIfNotReady(); - inliers.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_estimateAffine3D( - src.ToInputProxy(), dst.ToInputProxy(), outVal.ToOutputProxy(), inliers.ToOutputProxy(), ransacThreshold, confidence, out var ret)); + src.Proxy, dst.Proxy, outVal.Proxy, inliers.Proxy, ransacThreshold, confidence, out var ret)); - outVal.Fix(); - inliers.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return ret; } @@ -2021,23 +1666,13 @@ public static int EstimateAffine3D(InputArray src, InputArray dst, /// F fundamental matrix /// The computed Sampson distance. /// https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp#L1109 - public static double SampsonDistance(InputArray pt1, InputArray pt2, InputArray f) + public static double SampsonDistance(InputArrayRef pt1, InputArrayRef pt2, InputArrayRef f) { - if (pt1 is null) - throw new ArgumentNullException(nameof(pt1)); - if (pt2 is null) - throw new ArgumentNullException(nameof(pt2)); - if (f is null) - throw new ArgumentNullException(nameof(f)); - pt1.ThrowIfDisposed(); - pt2.ThrowIfDisposed(); - f.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.geometry_sampsonDistance_InputArray(pt1.ToInputProxy(), pt2.ToInputProxy(), f.ToInputProxy(), out var ret)); + NativeMethods.geometry_sampsonDistance_InputArray(pt1.Proxy, pt2.Proxy, f.Proxy, out var ret)); - GC.KeepAlive(pt1); - GC.KeepAlive(pt2); + GC.KeepAlive(pt1.Source); + GC.KeepAlive(pt2.Source); return ret; } @@ -2085,27 +1720,19 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// Passing 0 will disable refining, so the output matrix will be output of robust method. /// Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation could not be estimated. public static Mat? EstimateAffine2D( - InputArray from, InputArray to, OutputArray? inliers = null, + InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 10) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - inliers?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_estimateAffine2D( - from.ToInputProxy(), to.ToInputProxy(), inliers?.ToOutputProxy() ?? default, + from.Proxy, to.Proxy, inliers.Proxy, (int) method, ransacReprojThreshold, maxIters, confidence, refineIters, out var matPtr)); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(inliers); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(inliers.Source); return (matPtr == IntPtr.Zero) ? null : new Mat(matPtr); } @@ -2125,27 +1752,19 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// /// Output 2D affine transformation (4 degrees of freedom) matrix 2x3 or empty matrix if transformation could not be estimated. public static Mat? EstimateAffinePartial2D( - InputArray from, InputArray to, OutputArray? inliers = null, + InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 10) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - inliers?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_estimateAffinePartial2D( - from.ToInputProxy(), to.ToInputProxy(), inliers?.ToOutputProxy() ?? default, + from.Proxy, to.Proxy, inliers.Proxy, (int) method, ransacReprojThreshold, maxIters, confidence, refineIters, out var matPtr)); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(inliers); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(inliers.Source); return (matPtr == IntPtr.Zero) ? null : new Mat(matPtr); } @@ -2160,34 +1779,26 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// Array of plane normal matrices. /// public static int DecomposeHomographyMat( - InputArray h, - InputArray k, + InputArrayRef h, + InputArrayRef k, out Mat[] rotations, out Mat[] translations, out Mat[] normals) { - if (h is null) - throw new ArgumentNullException(nameof(h)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - - h.ThrowIfDisposed(); - k.ThrowIfDisposed(); - using var rotationsVec = new VectorOfMat(); using var translationsVec = new VectorOfMat(); using var normalsVec = new VectorOfMat(); NativeMethods.HandleException( NativeMethods.geometry_decomposeHomographyMat( - h.ToInputProxy(), k.ToInputProxy(), rotationsVec.CvPtr, translationsVec.CvPtr, normalsVec.CvPtr, out var ret)); + h.Proxy, k.Proxy, rotationsVec.CvPtr, translationsVec.CvPtr, normalsVec.CvPtr, out var ret)); rotations = rotationsVec.ToArray(); translations = translationsVec.ToArray(); normals = normalsVec.ToArray(); - GC.KeepAlive(h); - GC.KeepAlive(k); + GC.KeepAlive(h.Source); + GC.KeepAlive(k.Source); GC.KeepAlive(rotations); GC.KeepAlive(translations); GC.KeepAlive(normals); @@ -2207,39 +1818,29 @@ public static int DecomposeHomographyMat( public static void FilterHomographyDecompByVisibleRefpoints( IEnumerable rotations, IEnumerable normals, - InputArray beforePoints, - InputArray afterPoints, - OutputArray possibleSolutions, - InputArray? pointsMask = null) + InputArrayRef beforePoints, + InputArrayRef afterPoints, + OutputArrayRef possibleSolutions, + InputArrayRef pointsMask = default) { if (rotations is null) throw new ArgumentNullException(nameof(rotations)); if (normals is null) throw new ArgumentNullException(nameof(normals)); - if (beforePoints is null) - throw new ArgumentNullException(nameof(beforePoints)); - if (afterPoints is null) - throw new ArgumentNullException(nameof(afterPoints)); - if (possibleSolutions is null) - throw new ArgumentNullException(nameof(possibleSolutions)); - beforePoints.ThrowIfDisposed(); - afterPoints.ThrowIfDisposed(); - possibleSolutions.ThrowIfNotReady(); - pointsMask?.ThrowIfDisposed(); using var rotationsVec = new VectorOfMat(rotations); using var normalsVec = new VectorOfMat(normals); NativeMethods.HandleException( NativeMethods.geometry_filterHomographyDecompByVisibleRefpoints( - rotationsVec.CvPtr, normalsVec.CvPtr, beforePoints.ToInputProxy(), afterPoints.ToInputProxy(), - possibleSolutions.ToOutputProxy(), pointsMask?.ToInputProxy() ?? default)); + rotationsVec.CvPtr, normalsVec.CvPtr, beforePoints.Proxy, afterPoints.Proxy, + possibleSolutions.Proxy, pointsMask.Proxy)); GC.KeepAlive(rotations); GC.KeepAlive(normals); - GC.KeepAlive(beforePoints); - GC.KeepAlive(afterPoints); - GC.KeepAlive(possibleSolutions); - GC.KeepAlive(pointsMask); + GC.KeepAlive(beforePoints.Source); + GC.KeepAlive(afterPoints.Source); + GC.KeepAlive(possibleSolutions.Source); + GC.KeepAlive(pointsMask.Source); } /// @@ -2252,17 +1853,14 @@ public static void FilterHomographyDecompByVisibleRefpoints( /// the camera matrix that is either an exact copy of the input cameraMatrix /// (when centerPrinicipalPoint=false), or the modified one (when centerPrincipalPoint=true). public static Mat GetDefaultNewCameraMatrix( - InputArray cameraMatrix, Size? imgSize = null, bool centerPrincipalPoint = false) + InputArrayRef cameraMatrix, Size? imgSize = null, bool centerPrincipalPoint = false) { - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - cameraMatrix.ThrowIfDisposed(); var imgSize0 = imgSize.GetValueOrDefault(new Size()); NativeMethods.HandleException( NativeMethods.geometry_getDefaultNewCameraMatrix( - cameraMatrix.ToInputProxy(), imgSize0, centerPrincipalPoint ? 1 : 0, out var matPtr)); - GC.KeepAlive(cameraMatrix); + cameraMatrix.Proxy, imgSize0, centerPrincipalPoint ? 1 : 0, out var matPtr)); + GC.KeepAlive(cameraMatrix.Source); return new Mat(matPtr); } @@ -2282,35 +1880,24 @@ public static Mat GetDefaultNewCameraMatrix( /// P1 or P2 computed by stereoRectify() can be passed here. If the matrix is empty, /// the identity new camera matrix is used. public static void UndistortPoints( - InputArray src, - OutputArray dst, - InputArray cameraMatrix, - InputArray distCoeffs, - InputArray? r = null, - InputArray? p = null) + InputArrayRef src, + OutputArrayRef dst, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + InputArrayRef r = default, + InputArrayRef p = default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_undistortPoints( - src.ToInputProxy(), dst.ToOutputProxy(), cameraMatrix.ToInputProxy(), - distCoeffs?.ToInputProxy() ?? default, r?.ToInputProxy() ?? default, p?.ToInputProxy() ?? default)); + src.Proxy, dst.Proxy, cameraMatrix.Proxy, + distCoeffs.Proxy, r.Proxy, p.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(r); - GC.KeepAlive(p); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(p.Source); } /// @@ -2330,36 +1917,25 @@ public static void UndistortPoints( /// the identity new camera matrix is used. /// public static void UndistortPointsIter( - InputArray src, - OutputArray dst, - InputArray cameraMatrix, - InputArray distCoeffs, - InputArray? r = null, - InputArray? p = null, + InputArrayRef src, + OutputArrayRef dst, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, + InputArrayRef r = default, + InputArrayRef p = default, TermCriteria? termCriteria = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - cameraMatrix.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.geometry_undistortPointsIter( - src.ToInputProxy(), dst.ToOutputProxy(), cameraMatrix.ToInputProxy(), - distCoeffs?.ToInputProxy() ?? default, r?.ToInputProxy() ?? default, p?.ToInputProxy() ?? default, termCriteria.GetValueOrDefault())); + src.Proxy, dst.Proxy, cameraMatrix.Proxy, + distCoeffs.Proxy, r.Proxy, p.Proxy, termCriteria.GetValueOrDefault())); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(r); - GC.KeepAlive(p); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(p.Source); } /// @@ -2374,42 +1950,21 @@ public static void UndistortPointsIter( /// Input/Output translation vector. Input values are used as the initial solution. /// Criteria when to stop the Levenberg-Marquardt iterative algorithm. public static void SolvePnPRefineLM( - InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, TermCriteria? criteria = null) + InputArrayRef objectPoints, InputArrayRef imagePoints, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, + InputOutputArrayRef rvec, InputOutputArrayRef tvec, TermCriteria? criteria = null) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - objectPoints.ThrowIfDisposed(); - imagePoints.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - rvec.ThrowIfNotReady(); - tvec.ThrowIfNotReady(); - var c = criteria ?? new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 20, 1.1920929e-07); NativeMethods.HandleException( NativeMethods.geometry_solvePnPRefineLM( - objectPoints.ToInputProxy(), imagePoints.ToInputProxy(), cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), - rvec.ToInputOutputProxy(), tvec.ToInputOutputProxy(), c)); + objectPoints.Proxy, imagePoints.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, + rvec.Proxy, tvec.Proxy, c)); - rvec.Fix(); - tvec.Fix(); - GC.KeepAlive(objectPoints); - GC.KeepAlive(imagePoints); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(rvec); - GC.KeepAlive(tvec); + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(rvec.Source); + GC.KeepAlive(tvec.Source); } /// @@ -2425,42 +1980,21 @@ public static void SolvePnPRefineLM( /// Criteria when to stop the iterative algorithm. /// Gain for the virtual visual servoing control law. public static void SolvePnPRefineVVS( - InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, TermCriteria? criteria = null, double vvsLambda = 1) + InputArrayRef objectPoints, InputArrayRef imagePoints, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, + InputOutputArrayRef rvec, InputOutputArrayRef tvec, TermCriteria? criteria = null, double vvsLambda = 1) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - objectPoints.ThrowIfDisposed(); - imagePoints.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - distCoeffs.ThrowIfDisposed(); - rvec.ThrowIfNotReady(); - tvec.ThrowIfNotReady(); - var c = criteria ?? new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 20, 1.1920929e-07); NativeMethods.HandleException( NativeMethods.geometry_solvePnPRefineVVS( - objectPoints.ToInputProxy(), imagePoints.ToInputProxy(), cameraMatrix.ToInputProxy(), distCoeffs.ToInputProxy(), - rvec.ToInputOutputProxy(), tvec.ToInputOutputProxy(), c, vvsLambda)); + objectPoints.Proxy, imagePoints.Proxy, cameraMatrix.Proxy, distCoeffs.Proxy, + rvec.Proxy, tvec.Proxy, c, vvsLambda)); - rvec.Fix(); - tvec.Fix(); - GC.KeepAlive(objectPoints); - GC.KeepAlive(imagePoints); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); - GC.KeepAlive(rvec); - GC.KeepAlive(tvec); + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); + GC.KeepAlive(rvec.Source); + GC.KeepAlive(tvec.Source); } /// @@ -2470,31 +2004,15 @@ public static void SolvePnPRefineVVS( /// One possible rotation matrix. /// Another possible rotation matrix. /// One possible translation (up to scale). - public static void DecomposeEssentialMat(InputArray e, OutputArray r1, OutputArray r2, OutputArray t) - { - if (e is null) - throw new ArgumentNullException(nameof(e)); - if (r1 is null) - throw new ArgumentNullException(nameof(r1)); - if (r2 is null) - throw new ArgumentNullException(nameof(r2)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - e.ThrowIfDisposed(); - r1.ThrowIfNotReady(); - r2.ThrowIfNotReady(); - t.ThrowIfNotReady(); - + public static void DecomposeEssentialMat(InputArrayRef e, OutputArrayRef r1, OutputArrayRef r2, OutputArrayRef t) + { NativeMethods.HandleException( - NativeMethods.geometry_decomposeEssentialMat(e.ToInputProxy(), r1.ToOutputProxy(), r2.ToOutputProxy(), t.ToOutputProxy())); + NativeMethods.geometry_decomposeEssentialMat(e.Proxy, r1.Proxy, r2.Proxy, t.Proxy)); - r1.Fix(); - r2.Fix(); - t.Fix(); - GC.KeepAlive(e); - GC.KeepAlive(r1); - GC.KeepAlive(r2); - GC.KeepAlive(t); + GC.KeepAlive(e.Source); + GC.KeepAlive(r1.Source); + GC.KeepAlive(r2.Source); + GC.KeepAlive(t.Source); } /// @@ -2508,30 +2026,15 @@ public static void DecomposeEssentialMat(InputArray e, OutputArray r1, OutputArr /// Confidence level, between 0 and 1. /// True if a translation was found. public static bool EstimateTranslation3D( - InputArray src, InputArray dst, OutputArray outVal, OutputArray inliers, + InputArrayRef src, InputArrayRef dst, OutputArrayRef outVal, OutputArrayRef inliers, double ransacThreshold = 3, double confidence = 0.99) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (outVal is null) - throw new ArgumentNullException(nameof(outVal)); - if (inliers is null) - throw new ArgumentNullException(nameof(inliers)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - outVal.ThrowIfNotReady(); - inliers.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_estimateTranslation3D( - src.ToInputProxy(), dst.ToInputProxy(), outVal.ToOutputProxy(), inliers.ToOutputProxy(), ransacThreshold, confidence, out var ret)); + src.Proxy, dst.Proxy, outVal.Proxy, inliers.Proxy, ransacThreshold, confidence, out var ret)); - outVal.Fix(); - inliers.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); return ret != 0; } @@ -2548,27 +2051,18 @@ public static bool EstimateTranslation3D( /// Maximum number of iterations of refining algorithm (Levenberg-Marquardt). /// The estimated 2D translation vector. public static Vec2d EstimateTranslation2D( - InputArray from, InputArray to, OutputArray? inliers = null, + InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 0) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - inliers?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.geometry_estimateTranslation2D( - from.ToInputProxy(), to.ToInputProxy(), inliers?.ToOutputProxy() ?? default, + from.Proxy, to.Proxy, inliers.Proxy, (int)method, ransacReprojThreshold, maxIters, confidence, refineIters, out var ret)); - inliers?.Fix(); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(inliers); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(inliers.Source); return ret; } } From 03e241ae455ca0ad5b2005d28cff01209df7937c Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:20:32 +0900 Subject: [PATCH 21/29] Migration: Cv2_calib.cs (11 methods) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 16) Scripted via migrate_step5.py; no manual fixups needed this time. --- src/OpenCvSharp/Cv2/Cv2_calib.cs | 267 ++++++++----------------------- 1 file changed, 70 insertions(+), 197 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_calib.cs b/src/OpenCvSharp/Cv2/Cv2_calib.cs index e49a7d343..eca927022 100644 --- a/src/OpenCvSharp/Cv2/Cv2_calib.cs +++ b/src/OpenCvSharp/Cv2/Cv2_calib.cs @@ -84,23 +84,15 @@ public static Mat InitCameraMatrix2D( /// The function returns true if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). /// Otherwise, if the function fails to find all the corners or reorder them, it returns false. public static bool FindChessboardCorners( - InputArray image, + InputArrayRef image, Size patternSize, - OutputArray corners, + OutputArrayRef corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (corners is null) - throw new ArgumentNullException(nameof(corners)); - image.ThrowIfDisposed(); - corners.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_findChessboardCorners_InputArray( - image.ToInputProxy(), patternSize, corners.ToOutputProxy(), (int) flags, out var ret)); - GC.KeepAlive(image); - corners.Fix(); + image.Proxy, patternSize, corners.Proxy, (int) flags, out var ret)); + GC.KeepAlive(image.Source); return ret != 0; } /// @@ -114,20 +106,16 @@ public static bool FindChessboardCorners( /// The function returns true if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). /// Otherwise, if the function fails to find all the corners or reorder them, it returns false. public static bool FindChessboardCorners( - InputArray image, + InputArrayRef image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var cornersVec = new StdVector(); NativeMethods.HandleException( NativeMethods.calib_findChessboardCorners_vector( - image.ToInputProxy(), patternSize, cornersVec.CvPtr, (int) flags, out var ret)); - GC.KeepAlive(image); + image.Proxy, patternSize, cornersVec.CvPtr, (int) flags, out var ret)); + GC.KeepAlive(image.Source); corners = cornersVec.ToArray(); return ret != 0; } @@ -142,26 +130,18 @@ public static bool FindChessboardCorners( /// feature detector that finds blobs like dark circles on light background. /// public static bool FindCirclesGrid( - InputArray image, + InputArrayRef image, Size patternSize, - OutputArray centers, + OutputArrayRef centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, FeatureDetector? blobDetector = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (centers is null) - throw new ArgumentNullException(nameof(centers)); - image.ThrowIfDisposed(); - centers.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_findCirclesGrid_InputArray( - image.ToInputProxy(), patternSize, centers.ToOutputProxy(), (int) flags, ToPtr(blobDetector), out var ret)); - GC.KeepAlive(image); - GC.KeepAlive(centers); + image.Proxy, patternSize, centers.Proxy, (int) flags, ToPtr(blobDetector), out var ret)); + GC.KeepAlive(image.Source); + GC.KeepAlive(centers.Source); GC.KeepAlive(blobDetector); - centers.Fix(); return ret != 0; } @@ -175,21 +155,17 @@ public static bool FindCirclesGrid( /// feature detector that finds blobs like dark circles on light background. /// public static bool FindCirclesGrid( - InputArray image, + InputArrayRef image, Size patternSize, out Point2f[] centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, FeatureDetector? blobDetector = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var centersVec = new StdVector(); NativeMethods.HandleException( NativeMethods.calib_findCirclesGrid_vector( - image.ToInputProxy(), patternSize, centersVec.CvPtr, (int) flags, ToPtr(blobDetector), out var ret)); - GC.KeepAlive(image); + image.Proxy, patternSize, centersVec.CvPtr, (int) flags, ToPtr(blobDetector), out var ret)); + GC.KeepAlive(image.Source); GC.KeepAlive(blobDetector); centers = centersVec.ToArray(); return ret != 0; @@ -223,8 +199,8 @@ public static double CalibrateCamera( IEnumerable objectPoints, IEnumerable imagePoints, Size imageSize, - InputOutputArray cameraMatrix, - InputOutputArray distCoeffs, + InputOutputArrayRef cameraMatrix, + InputOutputArrayRef distCoeffs, out Mat[] rvecs, out Mat[] tvecs, CalibrationFlags flags = CalibrationFlags.None, @@ -234,12 +210,6 @@ public static double CalibrateCamera( throw new ArgumentNullException(nameof(objectPoints)); if (imagePoints is null) throw new ArgumentNullException(nameof(imagePoints)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - if (distCoeffs is null) - throw new ArgumentNullException(nameof(distCoeffs)); - cameraMatrix.ThrowIfNotReady(); - distCoeffs.ThrowIfNotReady(); var criteria0 = criteria.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 30, Double.Epsilon)); @@ -253,17 +223,15 @@ public static double CalibrateCamera( NativeMethods.calib_calibrateCamera_InputArray( objectPointsPtrs, objectPointsPtrs.Length, imagePointsPtrs, objectPointsPtrs.Length, - imageSize, cameraMatrix.ToInputOutputProxy(), distCoeffs.ToInputOutputProxy(), + imageSize, cameraMatrix.Proxy, distCoeffs.Proxy, rvecsVec.CvPtr, tvecsVec.CvPtr, (int) flags, criteria0, out var ret)); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); GC.KeepAlive(objectPoints); GC.KeepAlive(imagePoints); rvecs = rvecsVec.ToArray(); tvecs = tvecsVec.ToArray(); - cameraMatrix.Fix(); - distCoeffs.Fix(); return ret; } @@ -362,10 +330,10 @@ public static double CalibrateCamera( public static double RegisterCameras( IEnumerable objectPoints1, IEnumerable objectPoints2, IEnumerable imagePoints1, IEnumerable imagePoints2, - InputArray cameraMatrix1, InputArray distCoeffs1, CameraModel cameraModel1, - InputArray cameraMatrix2, InputArray distCoeffs2, CameraModel cameraModel2, - InputOutputArray r, InputOutputArray t, OutputArray e, OutputArray f, - OutputArray perViewErrors, int flags = 0, TermCriteria? criteria = null) + InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, CameraModel cameraModel1, + InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, CameraModel cameraModel2, + InputOutputArrayRef r, InputOutputArrayRef t, OutputArrayRef e, OutputArrayRef f, + OutputArrayRef perViewErrors, int flags = 0, TermCriteria? criteria = null) { if (objectPoints1 is null) throw new ArgumentNullException(nameof(objectPoints1)); @@ -375,33 +343,6 @@ public static double RegisterCameras( throw new ArgumentNullException(nameof(imagePoints1)); if (imagePoints2 is null) throw new ArgumentNullException(nameof(imagePoints2)); - if (cameraMatrix1 is null) - throw new ArgumentNullException(nameof(cameraMatrix1)); - if (distCoeffs1 is null) - throw new ArgumentNullException(nameof(distCoeffs1)); - if (cameraMatrix2 is null) - throw new ArgumentNullException(nameof(cameraMatrix2)); - if (distCoeffs2 is null) - throw new ArgumentNullException(nameof(distCoeffs2)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - if (e is null) - throw new ArgumentNullException(nameof(e)); - if (f is null) - throw new ArgumentNullException(nameof(f)); - if (perViewErrors is null) - throw new ArgumentNullException(nameof(perViewErrors)); - cameraMatrix1.ThrowIfDisposed(); - distCoeffs1.ThrowIfDisposed(); - cameraMatrix2.ThrowIfDisposed(); - distCoeffs2.ThrowIfDisposed(); - r.ThrowIfNotReady(); - t.ThrowIfNotReady(); - e.ThrowIfNotReady(); - f.ThrowIfNotReady(); - perViewErrors.ThrowIfNotReady(); var criteria0 = criteria.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, 1e-6)); @@ -413,19 +354,14 @@ public static double RegisterCameras( NativeMethods.HandleException( NativeMethods.calib_registerCameras( op1, op1.Length, op2, op2.Length, ip1, ip1.Length, ip2, ip2.Length, - cameraMatrix1.ToInputProxy(), distCoeffs1.ToInputProxy(), (int)cameraModel1, - cameraMatrix2.ToInputProxy(), distCoeffs2.ToInputProxy(), (int)cameraModel2, - r.ToInputOutputProxy(), t.ToInputOutputProxy(), e.ToOutputProxy(), f.ToOutputProxy(), perViewErrors.ToOutputProxy(), flags, criteria0, out var ret)); - - r.Fix(); - t.Fix(); - e.Fix(); - f.Fix(); - perViewErrors.Fix(); - GC.KeepAlive(cameraMatrix1); - GC.KeepAlive(distCoeffs1); - GC.KeepAlive(cameraMatrix2); - GC.KeepAlive(distCoeffs2); + cameraMatrix1.Proxy, distCoeffs1.Proxy, (int)cameraModel1, + cameraMatrix2.Proxy, distCoeffs2.Proxy, (int)cameraModel2, + r.Proxy, t.Proxy, e.Proxy, f.Proxy, perViewErrors.Proxy, flags, criteria0, out var ret)); + + GC.KeepAlive(cameraMatrix1.Source); + GC.KeepAlive(distCoeffs1.Source); + GC.KeepAlive(cameraMatrix2.Source); + GC.KeepAlive(distCoeffs2.Source); GC.KeepAlive(objectPoints1); GC.KeepAlive(objectPoints2); GC.KeepAlive(imagePoints1); @@ -461,10 +397,10 @@ public static double CalibrateMultiview( IEnumerable objPoints, IReadOnlyList> imagePoints, IEnumerable imageSize, - InputArray detectionMask, - InputArray models, + InputArrayRef detectionMask, + InputArrayRef models, out Mat[] ks, out Mat[] distortions, out Mat[] rs, out Mat[] ts, - InputArray? flagsForIntrinsics = null, + InputArrayRef flagsForIntrinsics = default, int flags = 0, TermCriteria? criteria = null) { @@ -474,13 +410,6 @@ public static double CalibrateMultiview( throw new ArgumentNullException(nameof(imagePoints)); if (imageSize is null) throw new ArgumentNullException(nameof(imageSize)); - if (detectionMask is null) - throw new ArgumentNullException(nameof(detectionMask)); - if (models is null) - throw new ArgumentNullException(nameof(models)); - detectionMask.ThrowIfDisposed(); - models.ThrowIfDisposed(); - flagsForIntrinsics?.ThrowIfDisposed(); var criteria0 = criteria.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, double.Epsilon)); @@ -509,9 +438,9 @@ public static double CalibrateMultiview( objPointsPtrs, objPointsPtrs.Length, flatImagePoints.ToArray(), framesPerCamera.Length, framesPerCamera, imageSizeArray, imageSizeArray.Length, - detectionMask.ToInputProxy(), models.ToInputProxy(), + detectionMask.Proxy, models.Proxy, ksVec.CvPtr, distVec.CvPtr, rsVec.CvPtr, tsVec.CvPtr, - flagsForIntrinsics?.ToInputProxy() ?? default, flags, criteria0, out var ret)); + flagsForIntrinsics.Proxy, flags, criteria0, out var ret)); ks = ksVec.ToArray(); distortions = distVec.ToArray(); @@ -520,9 +449,9 @@ public static double CalibrateMultiview( GC.KeepAlive(objPoints); GC.KeepAlive(imagePoints); - GC.KeepAlive(detectionMask); - GC.KeepAlive(models); - GC.KeepAlive(flagsForIntrinsics); + GC.KeepAlive(detectionMask.Source); + GC.KeepAlive(models.Source); + GC.KeepAlive(flagsForIntrinsics.Source); return ret; } @@ -549,10 +478,10 @@ public static double StereoCalibrate( IReadOnlyList objectPoints, IReadOnlyList imagePoints1, IReadOnlyList imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, OutputArray R, - OutputArray T, OutputArray E, OutputArray F, + InputOutputArrayRef cameraMatrix1, InputOutputArrayRef distCoeffs1, + InputOutputArrayRef cameraMatrix2, InputOutputArrayRef distCoeffs2, + Size imageSize, OutputArrayRef R, + OutputArrayRef T, OutputArrayRef E, OutputArrayRef F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { @@ -562,30 +491,6 @@ public static double StereoCalibrate( throw new ArgumentNullException(nameof(imagePoints1)); if (imagePoints2 is null) throw new ArgumentNullException(nameof(imagePoints2)); - if (cameraMatrix1 is null) - throw new ArgumentNullException(nameof(cameraMatrix1)); - if (distCoeffs1 is null) - throw new ArgumentNullException(nameof(distCoeffs1)); - if (cameraMatrix2 is null) - throw new ArgumentNullException(nameof(cameraMatrix2)); - if (distCoeffs2 is null) - throw new ArgumentNullException(nameof(distCoeffs2)); - if (R is null) - throw new ArgumentNullException(nameof(R)); - if (T is null) - throw new ArgumentNullException(nameof(T)); - if (E is null) - throw new ArgumentNullException(nameof(E)); - if (F is null) - throw new ArgumentNullException(nameof(F)); - cameraMatrix1.ThrowIfDisposed(); - distCoeffs1.ThrowIfDisposed(); - cameraMatrix2.ThrowIfDisposed(); - distCoeffs2.ThrowIfDisposed(); - cameraMatrix1.ThrowIfNotReady(); - cameraMatrix2.ThrowIfNotReady(); - distCoeffs1.ThrowIfNotReady(); - distCoeffs2.ThrowIfNotReady(); var opPtrs = objectPoints.Select(x => x.CvPtr).ToArray(); var ip1Ptrs = imagePoints1.Select(x => x.CvPtr).ToArray(); @@ -598,30 +503,22 @@ public static double StereoCalibrate( NativeMethods.calib_stereoCalibrate_InputArray( opPtrs, opPtrs.Length, ip1Ptrs, ip1Ptrs.Length, ip2Ptrs, ip2Ptrs.Length, - cameraMatrix1.ToInputOutputProxy(), distCoeffs1.ToInputOutputProxy(), - cameraMatrix2.ToInputOutputProxy(), distCoeffs2.ToInputOutputProxy(), - imageSize, R.ToOutputProxy(), T.ToOutputProxy(), E.ToOutputProxy(), F.ToOutputProxy(), + cameraMatrix1.Proxy, distCoeffs1.Proxy, + cameraMatrix2.Proxy, distCoeffs2.Proxy, + imageSize, R.Proxy, T.Proxy, E.Proxy, F.Proxy, (int) flags, criteria0, out var ret)); - GC.KeepAlive(cameraMatrix1); - GC.KeepAlive(distCoeffs1); - GC.KeepAlive(cameraMatrix2); - GC.KeepAlive(distCoeffs2); - GC.KeepAlive(R); - GC.KeepAlive(T); - GC.KeepAlive(E); - GC.KeepAlive(F); + GC.KeepAlive(cameraMatrix1.Source); + GC.KeepAlive(distCoeffs1.Source); + GC.KeepAlive(cameraMatrix2.Source); + GC.KeepAlive(distCoeffs2.Source); + GC.KeepAlive(R.Source); + GC.KeepAlive(T.Source); + GC.KeepAlive(E.Source); + GC.KeepAlive(F.Source); GC.KeepAlive(objectPoints); GC.KeepAlive(imagePoints1); GC.KeepAlive(imagePoints2); - cameraMatrix1.Fix(); - distCoeffs1.Fix(); - cameraMatrix2.Fix(); - distCoeffs2.Fix(); - R.Fix(); - T.Fix(); - E.Fix(); - F.Fix(); return ret; } @@ -651,8 +548,8 @@ public static double StereoCalibrate( IEnumerable> imagePoints2, double[,] cameraMatrix1, double[] distCoeffs1, double[,] cameraMatrix2, double[] distCoeffs2, - Size imageSize, OutputArray R, - OutputArray T, OutputArray E, OutputArray F, + Size imageSize, OutputArrayRef R, + OutputArrayRef T, OutputArrayRef E, OutputArrayRef F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { @@ -689,12 +586,12 @@ public static double StereoCalibrate( ip2.GetPointer(), ip2.GetDim1Length(), ip2.GetDim2Lengths(), cameraMatrix1Ptr, distCoeffs1, distCoeffs1.Length, cameraMatrix2Ptr, distCoeffs2, distCoeffs2.Length, - imageSize, R?.ToOutputProxy() ?? default, T?.ToOutputProxy() ?? default, E?.ToOutputProxy() ?? default, F?.ToOutputProxy() ?? default, + imageSize, R.Proxy, T.Proxy, E.Proxy, F.Proxy, (int) flags, criteria0, out var ret)); - GC.KeepAlive(R); - GC.KeepAlive(T); - GC.KeepAlive(E); - GC.KeepAlive(F); + GC.KeepAlive(R.Source); + GC.KeepAlive(T.Source); + GC.KeepAlive(E.Source); + GC.KeepAlive(F.Source); return ret; } } @@ -740,8 +637,8 @@ public static void CalibrateHandEye( IEnumerable t_gripper2base, IEnumerable R_target2cam, IEnumerable t_target2cam, - OutputArray R_cam2gripper, - OutputArray t_cam2gripper, + OutputArrayRef R_cam2gripper, + OutputArrayRef t_cam2gripper, HandEyeCalibrationMethod method = HandEyeCalibrationMethod.TSAI) { if (R_gripper2base is null) @@ -752,12 +649,6 @@ public static void CalibrateHandEye( throw new ArgumentNullException(nameof(R_target2cam)); if (t_target2cam is null) throw new ArgumentNullException(nameof(t_target2cam)); - if (R_cam2gripper is null) - throw new ArgumentNullException(nameof(R_cam2gripper)); - if (t_cam2gripper is null) - throw new ArgumentNullException(nameof(t_cam2gripper)); - R_cam2gripper.ThrowIfNotReady(); - t_cam2gripper.ThrowIfNotReady(); var R_gripper2baseArray = R_gripper2base as Mat[] ?? R_gripper2base.ToArray(); var t_gripper2baseArray = t_gripper2base as Mat[] ?? t_gripper2base.ToArray(); @@ -782,14 +673,12 @@ public static void CalibrateHandEye( t_gripper2basePtrArray, t_gripper2basePtrArray.Length, R_target2camPtrArray, R_target2camPtrArray.Length, t_target2camPtrArray, t_target2camPtrArray.Length, - R_cam2gripper.ToOutputProxy(), t_cam2gripper.ToOutputProxy(), (int)method)); + R_cam2gripper.Proxy, t_cam2gripper.Proxy, (int)method)); GC.KeepAlive(R_gripper2base); GC.KeepAlive(t_gripper2base); GC.KeepAlive(R_target2cam); GC.KeepAlive(t_target2cam); - R_cam2gripper.Fix(); - t_cam2gripper.Fix(); foreach (var mat in R_gripper2baseArray) GC.KeepAlive(mat); foreach (var mat in t_gripper2baseArray) GC.KeepAlive(mat); @@ -830,10 +719,10 @@ public static void CalibrateRobotWorldHandEye( IEnumerable t_world2cam, IEnumerable R_base2gripper, IEnumerable t_base2gripper, - OutputArray R_base2world, - OutputArray t_base2world, - OutputArray R_gripper2cam, - OutputArray t_gripper2cam, + OutputArrayRef R_base2world, + OutputArrayRef t_base2world, + OutputArrayRef R_gripper2cam, + OutputArrayRef t_gripper2cam, RobotWorldHandEyeCalibrationMethod method = RobotWorldHandEyeCalibrationMethod.SHAH) { if (R_world2cam is null) @@ -844,18 +733,6 @@ public static void CalibrateRobotWorldHandEye( throw new ArgumentNullException(nameof(R_base2gripper)); if (t_base2gripper is null) throw new ArgumentNullException(nameof(t_base2gripper)); - if (R_base2world is null) - throw new ArgumentNullException(nameof(R_base2world)); - if (t_base2world is null) - throw new ArgumentNullException(nameof(t_base2world)); - if (R_gripper2cam is null) - throw new ArgumentNullException(nameof(R_gripper2cam)); - if (t_gripper2cam is null) - throw new ArgumentNullException(nameof(t_gripper2cam)); - R_base2world.ThrowIfNotReady(); - t_base2world.ThrowIfNotReady(); - R_gripper2cam.ThrowIfNotReady(); - t_gripper2cam.ThrowIfNotReady(); var R_world2camArray = R_world2cam as Mat[] ?? R_world2cam.ToArray(); var t_world2camArray = t_world2cam as Mat[] ?? t_world2cam.ToArray(); var R_base2gripperArray = R_base2gripper as Mat[] ?? R_base2gripper.ToArray(); @@ -879,13 +756,9 @@ public static void CalibrateRobotWorldHandEye( t_world2camPtrArray, t_world2camPtrArray.Length, R_base2gripperPtrArray, R_base2gripperPtrArray.Length, t_base2gripperPtrArray, t_base2gripperPtrArray.Length, - R_base2world.ToOutputProxy(), t_base2world.ToOutputProxy(), R_gripper2cam.ToOutputProxy(), t_gripper2cam.ToOutputProxy(), + R_base2world.Proxy, t_base2world.Proxy, R_gripper2cam.Proxy, t_gripper2cam.Proxy, (int)method)); - R_base2world.Fix(); - t_base2world.Fix(); - R_gripper2cam.Fix(); - t_gripper2cam.Fix(); foreach (var mat in R_world2camArray) GC.KeepAlive(mat); foreach (var mat in t_world2camArray) GC.KeepAlive(mat); foreach (var mat in R_base2gripperArray) GC.KeepAlive(mat); From f4d37a6f90199d78b197f2d38407ca3b9d914932 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:23:39 +0900 Subject: [PATCH 22/29] Migration: Cv2_video.cs (10 methods) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 17) Scripted via migrate_step5.py; fixed one null-literal call site (FindTransformECC's inputMask) to use default. --- src/OpenCvSharp/Cv2/Cv2_video.cs | 193 +++++------------- .../video/VideoTrackingTest.cs | 2 +- 2 files changed, 53 insertions(+), 142 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_video.cs b/src/OpenCvSharp/Cv2/Cv2_video.cs index fad7eb1cc..45b644b70 100644 --- a/src/OpenCvSharp/Cv2/Cv2_video.cs +++ b/src/OpenCvSharp/Cv2/Cv2_video.cs @@ -14,15 +14,11 @@ static partial class Cv2 /// Stop criteria for the underlying MeanShift() . /// public static RotatedRect CamShift( - InputArray probImage, ref Rect window, TermCriteria criteria) + InputArrayRef probImage, ref Rect window, TermCriteria criteria) { - if (probImage is null) - throw new ArgumentNullException(nameof(probImage)); - probImage.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.video_CamShift(probImage.ToInputProxy(), ref window, criteria, out var ret)); - GC.KeepAlive(probImage); + NativeMethods.video_CamShift(probImage.Proxy, ref window, criteria, out var ret)); + GC.KeepAlive(probImage.Source); return ret; } @@ -34,15 +30,11 @@ public static RotatedRect CamShift( /// Stop criteria for the iterative search algorithm. /// Number of iterations CAMSHIFT took to converge. public static int MeanShift( - InputArray probImage, ref Rect window, TermCriteria criteria) + InputArrayRef probImage, ref Rect window, TermCriteria criteria) { - if (probImage is null) - throw new ArgumentNullException(nameof(probImage)); - probImage.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.video_meanShift(probImage.ToInputProxy(), ref window, criteria, out var ret)); - GC.KeepAlive(probImage); + NativeMethods.video_meanShift(probImage.Proxy, ref window, criteria, out var ret)); + GC.KeepAlive(probImage.Source); return ret; } @@ -64,24 +56,16 @@ public static int MeanShift( /// You can pass false to force data copying. /// number of levels in constructed pyramid. Can be less than maxLevel. public static int BuildOpticalFlowPyramid( - InputArray img, OutputArray pyramid, + InputArrayRef img, OutputArrayRef pyramid, Size winSize, int maxLevel, bool withDerivatives = true, BorderTypes pyrBorder = BorderTypes.Reflect101, BorderTypes derivBorder = BorderTypes.Constant, bool tryReuseInputImage = true) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (pyramid is null) - throw new ArgumentNullException(nameof(pyramid)); - img.ThrowIfDisposed(); - pyramid.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.video_buildOpticalFlowPyramid1(img.ToInputProxy(), pyramid.ToOutputProxy(), winSize, maxLevel, withDerivatives ? 1 : 0, (int) pyrBorder, (int) derivBorder, tryReuseInputImage ? 1 : 0, out var ret)); - pyramid.Fix(); - GC.KeepAlive(img); + NativeMethods.video_buildOpticalFlowPyramid1(img.Proxy, pyramid.Proxy, winSize, maxLevel, withDerivatives ? 1 : 0, (int) pyrBorder, (int) derivBorder, tryReuseInputImage ? 1 : 0, out var ret)); + GC.KeepAlive(img.Source); return ret; } @@ -103,21 +87,17 @@ public static int BuildOpticalFlowPyramid( /// You can pass false to force data copying. /// number of levels in constructed pyramid. Can be less than maxLevel. public static int BuildOpticalFlowPyramid( - InputArray img, out Mat[] pyramid, + InputArrayRef img, out Mat[] pyramid, Size winSize, int maxLevel, bool withDerivatives = true, BorderTypes pyrBorder = BorderTypes.Reflect101, BorderTypes derivBorder = BorderTypes.Constant, bool tryReuseInputImage = true) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - using var pyramidVec = new VectorOfMat(); NativeMethods.HandleException( - NativeMethods.video_buildOpticalFlowPyramid2(img.ToInputProxy(), pyramidVec.CvPtr, winSize, maxLevel, withDerivatives ? 1 : 0, (int) pyrBorder, (int) derivBorder, tryReuseInputImage ? 1 : 0, out var ret)); - GC.KeepAlive(img); + NativeMethods.video_buildOpticalFlowPyramid2(img.Proxy, pyramidVec.CvPtr, winSize, maxLevel, withDerivatives ? 1 : 0, (int) pyrBorder, (int) derivBorder, tryReuseInputImage ? 1 : 0, out var ret)); + GC.KeepAlive(img.Source); pyramid = pyramidVec.ToArray(); return ret; } @@ -137,46 +117,24 @@ public static int BuildOpticalFlowPyramid( /// /// public static void CalcOpticalFlowPyrLK( - InputArray prevImg, InputArray nextImg, - InputArray prevPts, InputOutputArray nextPts, - OutputArray status, OutputArray err, + InputArrayRef prevImg, InputArrayRef nextImg, + InputArrayRef prevPts, InputOutputArrayRef nextPts, + OutputArrayRef status, OutputArrayRef err, Size? winSize = null, int maxLevel = 3, TermCriteria? criteria = null, OpticalFlowFlags flags = OpticalFlowFlags.None, double minEigThreshold = 1e-4) { - if (prevImg is null) - throw new ArgumentNullException(nameof(prevImg)); - if (nextImg is null) - throw new ArgumentNullException(nameof(nextImg)); - if (prevPts is null) - throw new ArgumentNullException(nameof(prevPts)); - if (nextPts is null) - throw new ArgumentNullException(nameof(nextPts)); - if (status is null) - throw new ArgumentNullException(nameof(status)); - if (err is null) - throw new ArgumentNullException(nameof(err)); - prevImg.ThrowIfDisposed(); - nextImg.ThrowIfDisposed(); - prevPts.ThrowIfDisposed(); - nextPts.ThrowIfNotReady(); - status.ThrowIfNotReady(); - err.ThrowIfNotReady(); - var winSize0 = winSize.GetValueOrDefault(new Size(21, 21)); var criteria0 = criteria.GetValueOrDefault( TermCriteria.Both(30, 0.01)); NativeMethods.HandleException( - NativeMethods.video_calcOpticalFlowPyrLK_InputArray(prevImg.ToInputProxy(), nextImg.ToInputProxy(), prevPts.ToInputProxy(), nextPts.ToInputOutputProxy(), status.ToOutputProxy(), err.ToOutputProxy(), winSize0, maxLevel, criteria0, (int) flags, minEigThreshold)); - GC.KeepAlive(prevImg); - GC.KeepAlive(nextImg); - GC.KeepAlive(prevPts); - nextPts.Fix(); - status.Fix(); - err.Fix(); + NativeMethods.video_calcOpticalFlowPyrLK_InputArray(prevImg.Proxy, nextImg.Proxy, prevPts.Proxy, nextPts.Proxy, status.Proxy, err.Proxy, winSize0, maxLevel, criteria0, (int) flags, minEigThreshold)); + GC.KeepAlive(prevImg.Source); + GC.KeepAlive(nextImg.Source); + GC.KeepAlive(prevPts.Source); } /// /// computes sparse optical flow using multi-scale Lucas-Kanade algorithm @@ -193,8 +151,8 @@ public static void CalcOpticalFlowPyrLK( /// /// public static void CalcOpticalFlowPyrLK( - InputArray prevImg, - InputArray nextImg, + InputArrayRef prevImg, + InputArrayRef nextImg, Point2f[] prevPts, ref Point2f[] nextPts, out byte[] status, @@ -205,16 +163,10 @@ public static void CalcOpticalFlowPyrLK( OpticalFlowFlags flags = OpticalFlowFlags.None, double minEigThreshold = 1e-4) { - if (prevImg is null) - throw new ArgumentNullException(nameof(prevImg)); - if (nextImg is null) - throw new ArgumentNullException(nameof(nextImg)); if (prevPts is null) throw new ArgumentNullException(nameof(prevPts)); if (nextPts is null) throw new ArgumentNullException(nameof(nextPts)); - prevImg.ThrowIfDisposed(); - nextImg.ThrowIfDisposed(); var winSize0 = winSize.GetValueOrDefault(new Size(21, 21)); var criteria0 = criteria.GetValueOrDefault( @@ -224,9 +176,9 @@ public static void CalcOpticalFlowPyrLK( using var statusVec = new StdVector(); using var errVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.video_calcOpticalFlowPyrLK_vector(prevImg.ToInputProxy(), nextImg.ToInputProxy(), prevPts, prevPts.Length, nextPtsVec.CvPtr, statusVec.CvPtr, errVec.CvPtr, winSize0, maxLevel, criteria0, (int) flags, minEigThreshold)); - GC.KeepAlive(prevImg); - GC.KeepAlive(nextImg); + NativeMethods.video_calcOpticalFlowPyrLK_vector(prevImg.Proxy, nextImg.Proxy, prevPts, prevPts.Length, nextPtsVec.CvPtr, statusVec.CvPtr, errVec.CvPtr, winSize0, maxLevel, criteria0, (int) flags, minEigThreshold)); + GC.KeepAlive(prevImg.Source); + GC.KeepAlive(nextImg.Source); nextPts = nextPtsVec.ToArray(); status = statusVec.ToArray(); err = errVec.ToArray(); @@ -252,25 +204,14 @@ public static void CalcOpticalFlowPyrLK( /// a basis for the polynomial expansion; for polyN=5, you can set polySigma=1.1, /// for polyN=7, a good value would be polySigma=1.5. /// operation flags that can be a combination of OPTFLOW_USE_INITIAL_FLOW and/or OPTFLOW_FARNEBACK_GAUSSIAN - public static void CalcOpticalFlowFarneback(InputArray prev, InputArray next, - InputOutputArray flow, double pyrScale, int levels, int winsize, + public static void CalcOpticalFlowFarneback(InputArrayRef prev, InputArrayRef next, + InputOutputArrayRef flow, double pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, OpticalFlowFlags flags) { - if (prev is null) - throw new ArgumentNullException(nameof(prev)); - if (next is null) - throw new ArgumentNullException(nameof(next)); - if (flow is null) - throw new ArgumentNullException(nameof(flow)); - prev.ThrowIfDisposed(); - next.ThrowIfDisposed(); - flow.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.video_calcOpticalFlowFarneback(prev.ToInputProxy(), next.ToInputProxy(), flow.ToInputOutputProxy(), pyrScale, levels, winsize, iterations, polyN, polySigma, (int) flags)); - GC.KeepAlive(prev); - GC.KeepAlive(next); - flow.Fix(); + NativeMethods.video_calcOpticalFlowFarneback(prev.Proxy, next.Proxy, flow.Proxy, pyrScale, levels, winsize, iterations, polyN, polySigma, (int) flags)); + GC.KeepAlive(prev.Source); + GC.KeepAlive(next.Source); } /// @@ -280,22 +221,14 @@ public static void CalcOpticalFlowFarneback(InputArray prev, InputArray next, /// single-channel input image to be warped to provide an image similar to templateImage, same type as templateImage. /// An optional mask to indicate valid values of inputImage. /// - public static double ComputeECC(InputArray templateImage, InputArray inputImage, InputArray? inputMask = null) + public static double ComputeECC(InputArrayRef templateImage, InputArrayRef inputImage, InputArrayRef inputMask = default) { - if (templateImage is null) - throw new ArgumentNullException(nameof(templateImage)); - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - templateImage.ThrowIfDisposed(); - inputImage.ThrowIfDisposed(); - inputMask?.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.video_computeECC(templateImage.ToInputProxy(), inputImage.ToInputProxy(), inputMask?.ToInputProxy() ?? default, out var ret)); + NativeMethods.video_computeECC(templateImage.Proxy, inputImage.Proxy, inputMask.Proxy, out var ret)); - GC.KeepAlive(templateImage); - GC.KeepAlive(inputImage); - GC.KeepAlive(inputMask); + GC.KeepAlive(templateImage.Source); + GC.KeepAlive(inputImage.Source); + GC.KeepAlive(inputMask.Source); return ret; } @@ -315,32 +248,21 @@ public static double ComputeECC(InputArray templateImage, InputArray inputImage, /// An optional value indicating size of gaussian blur filter; (DEFAULT: 5) /// public static double FindTransformECC( - InputArray templateImage, - InputArray inputImage, - InputOutputArray warpMatrix, + InputArrayRef templateImage, + InputArrayRef inputImage, + InputOutputArrayRef warpMatrix, MotionTypes motionType, TermCriteria criteria, - InputArray? inputMask = null, + InputArrayRef inputMask = default, int gaussFiltSize = 5) { - if (templateImage is null) - throw new ArgumentNullException(nameof(templateImage)); - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - if (warpMatrix is null) - throw new ArgumentNullException(nameof(warpMatrix)); - templateImage.ThrowIfDisposed(); - inputImage.ThrowIfDisposed(); - warpMatrix.ThrowIfDisposed(); - inputMask?.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.video_findTransformECC1(templateImage.ToInputProxy(), inputImage.ToInputProxy(), warpMatrix.ToInputOutputProxy(), (int)motionType, criteria, inputMask?.ToInputProxy() ?? default, gaussFiltSize, out var ret)); + NativeMethods.video_findTransformECC1(templateImage.Proxy, inputImage.Proxy, warpMatrix.Proxy, (int)motionType, criteria, inputMask.Proxy, gaussFiltSize, out var ret)); - GC.KeepAlive(templateImage); - GC.KeepAlive(inputImage); - GC.KeepAlive(warpMatrix); - GC.KeepAlive(inputMask); + GC.KeepAlive(templateImage.Source); + GC.KeepAlive(inputImage.Source); + GC.KeepAlive(warpMatrix.Source); + GC.KeepAlive(inputMask.Source); return ret; } @@ -359,33 +281,22 @@ public static double FindTransformECC( /// An optional mask to indicate valid values of inputImage. /// public static double FindTransformECC( - InputArray templateImage, - InputArray inputImage, - InputOutputArray warpMatrix, + InputArrayRef templateImage, + InputArrayRef inputImage, + InputOutputArrayRef warpMatrix, MotionTypes motionType = MotionTypes.Affine, TermCriteria? criteria = null, - InputArray? inputMask = null) + InputArrayRef inputMask = default) { - if (templateImage is null) - throw new ArgumentNullException(nameof(templateImage)); - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - if (warpMatrix is null) - throw new ArgumentNullException(nameof(warpMatrix)); - templateImage.ThrowIfDisposed(); - inputImage.ThrowIfDisposed(); - warpMatrix.ThrowIfDisposed(); - inputMask?.ThrowIfDisposed(); - var criteriaValue = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 50, 0.001)); NativeMethods.HandleException( - NativeMethods.video_findTransformECC2(templateImage.ToInputProxy(), inputImage.ToInputProxy(), warpMatrix.ToInputOutputProxy(), (int)motionType, criteriaValue, inputMask?.ToInputProxy() ?? default, out var ret)); + NativeMethods.video_findTransformECC2(templateImage.Proxy, inputImage.Proxy, warpMatrix.Proxy, (int)motionType, criteriaValue, inputMask.Proxy, out var ret)); - GC.KeepAlive(templateImage); - GC.KeepAlive(inputImage); - GC.KeepAlive(warpMatrix); - GC.KeepAlive(inputMask); + GC.KeepAlive(templateImage.Source); + GC.KeepAlive(inputImage.Source); + GC.KeepAlive(warpMatrix.Source); + GC.KeepAlive(inputMask.Source); return ret; } } diff --git a/test/OpenCvSharp.Tests/video/VideoTrackingTest.cs b/test/OpenCvSharp.Tests/video/VideoTrackingTest.cs index 2f69dc535..9b79c3ae3 100644 --- a/test/OpenCvSharp.Tests/video/VideoTrackingTest.cs +++ b/test/OpenCvSharp.Tests/video/VideoTrackingTest.cs @@ -100,7 +100,7 @@ public void FindTransformECC() Cv2.Rectangle(a, new Rect(16, 16, 28, 28), Scalar.All(255), -1); using var warp = Mat.FromPixelData(2, 3, MatType.CV_32FC1, new float[] { 1, 0, 0, 0, 1, 0 }); var cc = Cv2.FindTransformECC(a, a, warp, MotionTypes.Translation, - new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 50, 1e-4), null, 5); + new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 50, 1e-4), default, 5); Assert.True(cc > 0.9); // identical inputs -> near-perfect alignment } From 2398612a491b2fb2b83f2304f99c11b6c8522a56 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:25:49 +0900 Subject: [PATCH 23/29] Migration: Cv2_objdetect.cs (7 methods) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 18) Scripted via migrate_step5.py; no manual fixups needed. --- src/OpenCvSharp/Cv2/Cv2_objdetect.cs | 82 ++++++++-------------------- 1 file changed, 22 insertions(+), 60 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_objdetect.cs b/src/OpenCvSharp/Cv2/Cv2_objdetect.cs index 6a6f1c008..3d0bb5331 100644 --- a/src/OpenCvSharp/Cv2/Cv2_objdetect.cs +++ b/src/OpenCvSharp/Cv2/Cv2_objdetect.cs @@ -143,15 +143,11 @@ private static void ClearAndAddRange(ICollection list, IEnumerable valu /// /// /// - public static bool CheckChessboard(InputArray img, Size size) + public static bool CheckChessboard(InputArrayRef img, Size size) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.objdetect_checkChessboard(img.ToInputProxy(), size, out var ret)); - GC.KeepAlive(img); + NativeMethods.objdetect_checkChessboard(img.Proxy, size, out var ret)); + GC.KeepAlive(img.Source); return ret != 0; } @@ -165,21 +161,14 @@ public static bool CheckChessboard(InputArray img, Size size) /// flags Various operation flags that can be zero or a combination of the ChessboardFlags values. /// public static bool FindChessboardCornersSB( - InputArray image, Size patternSize, OutputArray corners, ChessboardFlags flags = 0) + InputArrayRef image, Size patternSize, OutputArrayRef corners, ChessboardFlags flags = 0) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (corners is null) - throw new ArgumentNullException(nameof(corners)); - image.ThrowIfDisposed(); - corners.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.objdetect_findChessboardCornersSB_OutputArray( - image.ToInputProxy(), patternSize, corners.ToOutputProxy(), (int) flags, out var ret)); + image.Proxy, patternSize, corners.Proxy, (int) flags, out var ret)); - GC.KeepAlive(image); - GC.KeepAlive(corners); + GC.KeepAlive(image.Source); + GC.KeepAlive(corners.Source); return ret != 0; } @@ -193,19 +182,15 @@ public static bool FindChessboardCornersSB( /// flags Various operation flags that can be zero or a combination of the ChessboardFlags values. /// public static bool FindChessboardCornersSB( - InputArray image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = 0) + InputArrayRef image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = 0) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var cornersVec = new StdVector(); NativeMethods.HandleException( NativeMethods.objdetect_findChessboardCornersSB_vector( - image.ToInputProxy(), patternSize, cornersVec.CvPtr, (int) flags, out var ret)); + image.Proxy, patternSize, cornersVec.CvPtr, (int) flags, out var ret)); corners = cornersVec.ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); return ret != 0; } @@ -216,20 +201,12 @@ public static bool FindChessboardCornersSB( /// /// /// - public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size regionSize) + public static bool Find4QuadCornerSubpix(InputArrayRef img, InputOutputArrayRef corners, Size regionSize) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (corners is null) - throw new ArgumentNullException(nameof(corners)); - img.ThrowIfDisposed(); - corners.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.objdetect_find4QuadCornerSubpix_InputArray( - img.ToInputProxy(), corners.ToInputOutputProxy(), regionSize, out var ret)); - GC.KeepAlive(img); - corners.Fix(); + img.Proxy, corners.Proxy, regionSize, out var ret)); + GC.KeepAlive(img.Source); return ret != 0; } /// @@ -239,19 +216,16 @@ public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corner /// /// /// - public static bool Find4QuadCornerSubpix(InputArray img, Point2f[] corners, Size regionSize) + public static bool Find4QuadCornerSubpix(InputArrayRef img, Point2f[] corners, Size regionSize) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (corners is null) throw new ArgumentNullException(nameof(corners)); - img.ThrowIfDisposed(); using var cornersVec = new StdVector(corners); NativeMethods.HandleException( NativeMethods.objdetect_find4QuadCornerSubpix_vector( - img.ToInputProxy(), cornersVec.CvPtr, regionSize, out var ret)); - GC.KeepAlive(img); + img.Proxy, cornersVec.CvPtr, regionSize, out var ret)); + GC.KeepAlive(img.Source); var newCorners = cornersVec.ToArray(); for (var i = 0; i < corners.Length; i++) @@ -269,21 +243,13 @@ public static bool Find4QuadCornerSubpix(InputArray img, Point2f[] corners, Size /// Number of inner corners per a chessboard row and column (patternSize = cv::Size(points_per_row,points_per_column)). /// Array of detected corners, the output of findChessboardCorners. /// Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here. - public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, - InputArray corners, bool patternWasFound) + public static void DrawChessboardCorners(InputOutputArrayRef image, Size patternSize, + InputArrayRef corners, bool patternWasFound) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (corners is null) - throw new ArgumentNullException(nameof(corners)); - image.ThrowIfNotReady(); - corners.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.objdetect_drawChessboardCorners_InputArray( - image.ToInputOutputProxy(), patternSize, corners.ToInputProxy(), patternWasFound ? 1 : 0)); - GC.KeepAlive(corners); - image.Fix(); + image.Proxy, patternSize, corners.Proxy, patternWasFound ? 1 : 0)); + GC.KeepAlive(corners.Source); } /// @@ -294,20 +260,16 @@ public static void DrawChessboardCorners(InputOutputArray image, Size patternSiz /// Array of detected corners, the output of findChessboardCorners. /// Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here. [SuppressMessage("Maintainability", "CA1508: Avoid dead conditional code")] - public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, + public static void DrawChessboardCorners(InputOutputArrayRef image, Size patternSize, IEnumerable corners, bool patternWasFound) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (corners is null) throw new ArgumentNullException(nameof(corners)); - image.ThrowIfNotReady(); var cornersArray = corners as Point2f[] ?? corners.ToArray(); NativeMethods.HandleException( NativeMethods.objdetect_drawChessboardCorners_array( - image.ToInputOutputProxy(), patternSize, cornersArray, cornersArray.Length, + image.Proxy, patternSize, cornersArray, cornersArray.Length, patternWasFound ? 1 : 0)); - image.Fix(); } } From d908bd4e2370874728e4fb23ca2369b165c5c2b9 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:28:13 +0900 Subject: [PATCH 24/29] Migration: Cv2_stereo.cs (7 methods) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 19) Scripted via migrate_step5.py; no manual fixups needed. Completes the Cv2 static-file batch that followed the ArrayProxy ABI migration's module order (core/imgproc/geometry/calib/video/objdetect/stereo). --- src/OpenCvSharp/Cv2/Cv2_stereo.cs | 303 ++++++++---------------------- 1 file changed, 82 insertions(+), 221 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_stereo.cs b/src/OpenCvSharp/Cv2/Cv2_stereo.cs index cbb16989c..28b96ba4d 100644 --- a/src/OpenCvSharp/Cv2/Cv2_stereo.cs +++ b/src/OpenCvSharp/Cv2/Cv2_stereo.cs @@ -38,12 +38,12 @@ static partial class Cv2 /// in the rectified images (no source image pixels are lost). Obviously, any intermediate value yields an intermediate result between those two extreme cases. /// New image resolution after rectification. The same size should be passed to initUndistortRectifyMap(). When (0,0) is passed (default), it is set to the original imageSize . /// Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion. - public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - Size imageSize, InputArray R, InputArray T, - OutputArray R1, OutputArray R2, - OutputArray P1, OutputArray P2, - OutputArray Q, + public static void StereoRectify(InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, + InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, + Size imageSize, InputArrayRef R, InputArrayRef T, + OutputArrayRef R1, OutputArrayRef R2, + OutputArrayRef P1, OutputArrayRef P2, + OutputArrayRef Q, StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, double alpha = -1, Size? newImageSize = null) { @@ -82,74 +82,35 @@ public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs /// Otherwise, they are likely to be smaller. /// Optional output rectangles inside the rectified images where all the pixels are valid. If alpha=0 , the ROIs cover the whole images. /// Otherwise, they are likely to be smaller. - public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - Size imageSize, InputArray R, InputArray T, - OutputArray R1, OutputArray R2, - OutputArray P1, OutputArray P2, - OutputArray Q, StereoRectificationFlags flags, + public static void StereoRectify(InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, + InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, + Size imageSize, InputArrayRef R, InputArrayRef T, + OutputArrayRef R1, OutputArrayRef R2, + OutputArrayRef P1, OutputArrayRef P2, + OutputArrayRef Q, StereoRectificationFlags flags, double alpha, Size newImageSize, out Rect validPixROI1, out Rect validPixROI2) { - if (cameraMatrix1 is null) - throw new ArgumentNullException(nameof(cameraMatrix1)); - if (distCoeffs1 is null) - throw new ArgumentNullException(nameof(distCoeffs1)); - if (cameraMatrix2 is null) - throw new ArgumentNullException(nameof(cameraMatrix2)); - if (distCoeffs2 is null) - throw new ArgumentNullException(nameof(distCoeffs2)); - if (R is null) - throw new ArgumentNullException(nameof(R)); - if (T is null) - throw new ArgumentNullException(nameof(T)); - if (R1 is null) - throw new ArgumentNullException(nameof(R1)); - if (R2 is null) - throw new ArgumentNullException(nameof(R2)); - if (P1 is null) - throw new ArgumentNullException(nameof(P1)); - if (P2 is null) - throw new ArgumentNullException(nameof(P2)); - if (Q is null) - throw new ArgumentNullException(nameof(Q)); - cameraMatrix1.ThrowIfDisposed(); - distCoeffs1.ThrowIfDisposed(); - cameraMatrix2.ThrowIfDisposed(); - distCoeffs2.ThrowIfDisposed(); - R.ThrowIfDisposed(); - T.ThrowIfDisposed(); - R1.ThrowIfNotReady(); - R2.ThrowIfNotReady(); - P1.ThrowIfNotReady(); - P2.ThrowIfNotReady(); - Q.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.stereo_stereoRectify_InputArray( - cameraMatrix1.ToInputProxy(), distCoeffs1.ToInputProxy(), - cameraMatrix2.ToInputProxy(), distCoeffs2.ToInputProxy(), - imageSize, R.ToInputProxy(), T.ToInputProxy(), - R1.ToOutputProxy(), R2.ToOutputProxy(), P1.ToOutputProxy(), P2.ToOutputProxy(), Q.ToOutputProxy(), + cameraMatrix1.Proxy, distCoeffs1.Proxy, + cameraMatrix2.Proxy, distCoeffs2.Proxy, + imageSize, R.Proxy, T.Proxy, + R1.Proxy, R2.Proxy, P1.Proxy, P2.Proxy, Q.Proxy, (int) flags, alpha, newImageSize, out validPixROI1, out validPixROI2)); - GC.KeepAlive(cameraMatrix1); - GC.KeepAlive(distCoeffs1); - GC.KeepAlive(cameraMatrix2); - GC.KeepAlive(distCoeffs2); - GC.KeepAlive(R); - GC.KeepAlive(T); - GC.KeepAlive(R1); - GC.KeepAlive(R2); - GC.KeepAlive(P1); - GC.KeepAlive(P2); - GC.KeepAlive(Q); + GC.KeepAlive(cameraMatrix1.Source); + GC.KeepAlive(distCoeffs1.Source); + GC.KeepAlive(cameraMatrix2.Source); + GC.KeepAlive(distCoeffs2.Source); + GC.KeepAlive(R.Source); + GC.KeepAlive(T.Source); + GC.KeepAlive(R1.Source); + GC.KeepAlive(R2.Source); + GC.KeepAlive(P1.Source); + GC.KeepAlive(P2.Source); + GC.KeepAlive(Q.Source); - R1.Fix(); - R2.Fix(); - P1.Fix(); - P2.Fix(); - Q.Fix(); } /// @@ -290,38 +251,20 @@ public static void StereoRectify(double[,] cameraMatrix1, double[] distCoeffs1, /// with the epipolar geometry (that is, the points for which |points2[i]^T * F * points1[i]| > threshold ) /// are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. /// - public static bool StereoRectifyUncalibrated(InputArray points1, InputArray points2, - InputArray F, Size imgSize, - OutputArray H1, OutputArray H2, + public static bool StereoRectifyUncalibrated(InputArrayRef points1, InputArrayRef points2, + InputArrayRef F, Size imgSize, + OutputArrayRef H1, OutputArrayRef H2, double threshold = 5) { - if (points1 is null) - throw new ArgumentNullException(nameof(points1)); - if (points2 is null) - throw new ArgumentNullException(nameof(points2)); - if (F is null) - throw new ArgumentNullException(nameof(F)); - if (H1 is null) - throw new ArgumentNullException(nameof(H1)); - if (H2 is null) - throw new ArgumentNullException(nameof(H2)); - points1.ThrowIfDisposed(); - points2.ThrowIfDisposed(); - F.ThrowIfDisposed(); - H1.ThrowIfNotReady(); - H2.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.stereo_stereoRectifyUncalibrated_InputArray( - points1.ToInputProxy(), points2.ToInputProxy(), F.ToInputProxy(), imgSize, H1.ToOutputProxy(), H2.ToOutputProxy(), threshold, out var ret)); + points1.Proxy, points2.Proxy, F.Proxy, imgSize, H1.Proxy, H2.Proxy, threshold, out var ret)); - GC.KeepAlive(points1); - GC.KeepAlive(points2); - GC.KeepAlive(F); - GC.KeepAlive(H1); - GC.KeepAlive(H2); - H1.Fix(); - H2.Fix(); + GC.KeepAlive(points1.Source); + GC.KeepAlive(points2.Source); + GC.KeepAlive(F.Source); + GC.KeepAlive(H1.Source); + GC.KeepAlive(H2.Source); return ret != 0; } @@ -410,111 +353,53 @@ public static bool StereoRectifyUncalibrated( /// /// public static float Rectify3Collinear( - InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - InputArray cameraMatrix3, InputArray distCoeffs3, + InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, + InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, + InputArrayRef cameraMatrix3, InputArrayRef distCoeffs3, IReadOnlyList imgpt1, IReadOnlyList imgpt3, - Size imageSize, InputArray R12, InputArray T12, - InputArray R13, InputArray T13, - OutputArray R1, OutputArray R2, OutputArray R3, - OutputArray P1, OutputArray P2, OutputArray P3, - OutputArray Q, double alpha, Size newImgSize, + Size imageSize, InputArrayRef R12, InputArrayRef T12, + InputArrayRef R13, InputArrayRef T13, + OutputArrayRef R1, OutputArrayRef R2, OutputArrayRef R3, + OutputArrayRef P1, OutputArrayRef P2, OutputArrayRef P3, + OutputArrayRef Q, double alpha, Size newImgSize, out Rect roi1, out Rect roi2, StereoRectificationFlags flags) { - if (cameraMatrix1 is null) - throw new ArgumentNullException(nameof(cameraMatrix1)); - if (distCoeffs1 is null) - throw new ArgumentNullException(nameof(distCoeffs1)); - if (cameraMatrix2 is null) - throw new ArgumentNullException(nameof(cameraMatrix2)); - if (distCoeffs2 is null) - throw new ArgumentNullException(nameof(distCoeffs2)); - if (cameraMatrix3 is null) - throw new ArgumentNullException(nameof(cameraMatrix3)); - if (distCoeffs3 is null) - throw new ArgumentNullException(nameof(distCoeffs3)); if (imgpt1 is null) throw new ArgumentNullException(nameof(imgpt1)); if (imgpt3 is null) throw new ArgumentNullException(nameof(imgpt3)); - if (R12 is null) - throw new ArgumentNullException(nameof(R12)); - if (T12 is null) - throw new ArgumentNullException(nameof(T12)); - if (R13 is null) - throw new ArgumentNullException(nameof(R13)); - if (T13 is null) - throw new ArgumentNullException(nameof(T13)); - if (R1 is null) - throw new ArgumentNullException(nameof(R1)); - if (R2 is null) - throw new ArgumentNullException(nameof(R2)); - if (R3 is null) - throw new ArgumentNullException(nameof(R3)); - if (P1 is null) - throw new ArgumentNullException(nameof(P1)); - if (P2 is null) - throw new ArgumentNullException(nameof(P2)); - if (P3 is null) - throw new ArgumentNullException(nameof(P3)); - if (Q is null) - throw new ArgumentNullException(nameof(Q)); - cameraMatrix1.ThrowIfDisposed(); - distCoeffs1.ThrowIfDisposed(); - cameraMatrix2.ThrowIfDisposed(); - distCoeffs2.ThrowIfDisposed(); - cameraMatrix3.ThrowIfDisposed(); - distCoeffs3.ThrowIfDisposed(); - R12.ThrowIfDisposed(); - T12.ThrowIfDisposed(); - R13.ThrowIfDisposed(); - T13.ThrowIfDisposed(); - R1.ThrowIfNotReady(); - R2.ThrowIfNotReady(); - R3.ThrowIfNotReady(); - P1.ThrowIfNotReady(); - P2.ThrowIfNotReady(); - P3.ThrowIfNotReady(); - Q.ThrowIfNotReady(); var imgpt1Ptrs = imgpt1.Select(x => x.CvPtr).ToArray(); var imgpt3Ptrs = imgpt3.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( NativeMethods.stereo_rectify3Collinear_InputArray( - cameraMatrix1.ToInputProxy(), distCoeffs1.ToInputProxy(), - cameraMatrix2.ToInputProxy(), distCoeffs2.ToInputProxy(), - cameraMatrix3.ToInputProxy(), distCoeffs3.ToInputProxy(), + cameraMatrix1.Proxy, distCoeffs1.Proxy, + cameraMatrix2.Proxy, distCoeffs2.Proxy, + cameraMatrix3.Proxy, distCoeffs3.Proxy, imgpt1Ptrs, imgpt1Ptrs.Length, imgpt3Ptrs, imgpt3Ptrs.Length, - imageSize, R12.ToInputProxy(), T12.ToInputProxy(), R13.ToInputProxy(), T13.ToInputProxy(), - R1.ToOutputProxy(), R2.ToOutputProxy(), R3.ToOutputProxy(), P1.ToOutputProxy(), P2.ToOutputProxy(), P3.ToOutputProxy(), - Q.ToOutputProxy(), alpha, newImgSize, out roi1, out roi2, (int) flags, out var ret)); + imageSize, R12.Proxy, T12.Proxy, R13.Proxy, T13.Proxy, + R1.Proxy, R2.Proxy, R3.Proxy, P1.Proxy, P2.Proxy, P3.Proxy, + Q.Proxy, alpha, newImgSize, out roi1, out roi2, (int) flags, out var ret)); - GC.KeepAlive(cameraMatrix1); - GC.KeepAlive(distCoeffs1); - GC.KeepAlive(cameraMatrix2); - GC.KeepAlive(distCoeffs2); - GC.KeepAlive(cameraMatrix3); - GC.KeepAlive(distCoeffs3); + GC.KeepAlive(cameraMatrix1.Source); + GC.KeepAlive(distCoeffs1.Source); + GC.KeepAlive(cameraMatrix2.Source); + GC.KeepAlive(distCoeffs2.Source); + GC.KeepAlive(cameraMatrix3.Source); + GC.KeepAlive(distCoeffs3.Source); GC.KeepAlive(imgpt1); GC.KeepAlive(imgpt3); - GC.KeepAlive(R12); - GC.KeepAlive(T12); - GC.KeepAlive(R13); - GC.KeepAlive(T13); - GC.KeepAlive(R1); - GC.KeepAlive(R2); - GC.KeepAlive(R3); - GC.KeepAlive(P1); - GC.KeepAlive(P2); - GC.KeepAlive(P3); - GC.KeepAlive(Q); - R1.Fix(); - R2.Fix(); - R3.Fix(); - P1.Fix(); - P2.Fix(); - P3.Fix(); - Q.Fix(); + GC.KeepAlive(R12.Source); + GC.KeepAlive(T12.Source); + GC.KeepAlive(R13.Source); + GC.KeepAlive(T13.Source); + GC.KeepAlive(R1.Source); + GC.KeepAlive(R2.Source); + GC.KeepAlive(R3.Source); + GC.KeepAlive(P1.Source); + GC.KeepAlive(P2.Source); + GC.KeepAlive(P3.Source); + GC.KeepAlive(Q.Source); return ret; } @@ -528,18 +413,13 @@ public static float Rectify3Collinear( /// Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point disparity map, where disparity values /// are multiplied by 16, this scale factor should be taken into account when specifying this parameter value. /// The optional temporary buffer to avoid memory allocation within the function. - public static void FilterSpeckles(InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff, - InputOutputArray? buf = null) + public static void FilterSpeckles(InputOutputArrayRef img, double newVal, int maxSpeckleSize, double maxDiff, + InputOutputArrayRef buf = default) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.stereo_filterSpeckles(img.ToInputOutputProxy(), newVal, maxSpeckleSize, maxDiff, buf?.ToInputOutputProxy() ?? default)); - GC.KeepAlive(img); - GC.KeepAlive(buf); - img.Fix(); + NativeMethods.stereo_filterSpeckles(img.Proxy, newVal, maxSpeckleSize, maxDiff, buf.Proxy)); + GC.KeepAlive(img.Source); + GC.KeepAlive(buf.Source); } /// @@ -568,23 +448,15 @@ public static Rect GetValidDisparityROI(Rect roi1, Rect roi2, /// /// /// - public static void ValidateDisparity(InputOutputArray disparity, InputArray cost, + public static void ValidateDisparity(InputOutputArrayRef disparity, InputArrayRef cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1) { - if (disparity is null) - throw new ArgumentNullException(nameof(disparity)); - if (cost is null) - throw new ArgumentNullException(nameof(cost)); - disparity.ThrowIfNotReady(); - cost.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.stereo_validateDisparity( - disparity.ToInputOutputProxy(), cost.ToInputProxy(), minDisparity, numberOfDisparities, disp12MaxDisp)); + disparity.Proxy, cost.Proxy, minDisparity, numberOfDisparities, disp12MaxDisp)); - disparity.Fix(); - GC.KeepAlive(disparity); - GC.KeepAlive(cost); + GC.KeepAlive(disparity.Source); + GC.KeepAlive(cost.Source); } /// @@ -599,27 +471,16 @@ public static void ValidateDisparity(InputOutputArray disparity, InputArray cost /// transformed to 3D points with a very large Z value (currently set to 10000). /// he optional output array depth. If it is -1, the output image will have CV_32F depth. /// ddepth can also be set to CV_16S, CV_32S or CV_32F. - public static void ReprojectImageTo3D(InputArray disparity, - OutputArray _3dImage, InputArray Q, + public static void ReprojectImageTo3D(InputArrayRef disparity, + OutputArrayRef _3dImage, InputArrayRef Q, bool handleMissingValues = false, int ddepth = -1) { - if (disparity is null) - throw new ArgumentNullException(nameof(disparity)); - if (_3dImage is null) - throw new ArgumentNullException(nameof(_3dImage)); - if (Q is null) - throw new ArgumentNullException(nameof(Q)); - disparity.ThrowIfDisposed(); - _3dImage.ThrowIfNotReady(); - Q.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.stereo_reprojectImageTo3D( - disparity.ToInputProxy(), _3dImage.ToOutputProxy(), Q.ToInputProxy(), handleMissingValues ? 1 : 0, ddepth)); + disparity.Proxy, _3dImage.Proxy, Q.Proxy, handleMissingValues ? 1 : 0, ddepth)); - _3dImage.Fix(); - GC.KeepAlive(disparity); - GC.KeepAlive(_3dImage); - GC.KeepAlive(Q); + GC.KeepAlive(disparity.Source); + GC.KeepAlive(_3dImage.Source); + GC.KeepAlive(Q.Source); } } From c87ebc83c30f9b4d562e659cee00aeceac42d557 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:54:13 +0900 Subject: [PATCH 25/29] Migration: remaining Modules/ classes (110 files) to InputArrayRef/OutputArrayRef/InputOutputArrayRef (issue #1976 step 5, part 20) Covers every remaining class-based InputArray/OutputArray/ InputOutputArray consumer in src/OpenCvSharp/Modules and the nested Cv2. facades (Aruco/Dnn/OptFlow/Detail/Text/XImgProc/XPhoto/Shape), completing issue #1976 Step 5's type migration across the whole library. Scripted via a generalized migrate_step5_v2.py that extends the Cv2 static-file script to instance methods and constructors (any access modifier, not just `public static`), since these files are mostly classes with instance members rather than Cv2 facade statics. Fixed two script bugs found along the way: - Missing \b word boundaries let e.g. "sum" match inside "sqsum". - The block-vs-expression-body scan treated any "=>" as an expression- bodied method terminator, including lambdas inside a constructor's `: base(..., x => ...)` initializer -- now tracks paren depth so only top-level terminators count. Manual fixups beyond the script: - FaceDetectorYN.Detect: replaced explicit `new InputArray(image)`/ `new OutputArray(faces)` wrapping with direct Mat-to-*Ref conversion (no owning wrapper needed anymore). - CharucoDetector: the cameraMatrix/distCoeffs "both null or both non-null" validation used `is null`, which doesn't apply to non- nullable ref structs -- rewritten to check Proxy.Kind against ArrayProxyKind.None. - A handful of leftover `if(x is null)` checks (no space after `if`, which the removal regex didn't match) caused CS0037 "null to non- nullable value type" -- removed. - XML doc references to old signatures updated to match the new *Ref parameter types. --- src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs | 356 +++-------- src/OpenCvSharp/Cv2/Cv2_features.cs | 46 +- src/OpenCvSharp/Cv2/Cv2_highgui.cs | 28 +- src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs | 21 +- src/OpenCvSharp/Cv2/Cv2_photo.cs | 224 ++----- src/OpenCvSharp/Cv2/Cv2_ptcloud.cs | 228 ++----- .../Modules/aruco/ArucoDetector.cs | 8 +- src/OpenCvSharp/Modules/aruco/CharucoBoard.cs | 17 +- .../Modules/aruco/CharucoDetector.cs | 34 +- src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs | 36 +- src/OpenCvSharp/Modules/aruco/Dictionary.cs | 14 +- .../Modules/barcode/BarcodeDetector.cs | 10 +- .../Modules/dnn/ClassificationModel.cs | 9 +- src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs | 9 +- src/OpenCvSharp/Modules/dnn/DetectionModel.cs | 9 +- .../Modules/dnn/Image2BlobParams.cs | 2 +- src/OpenCvSharp/Modules/dnn/KeypointsModel.cs | 9 +- src/OpenCvSharp/Modules/dnn/Model.cs | 9 +- .../Modules/dnn/SegmentationModel.cs | 13 +- .../Modules/dnn/TextDetectionModel.cs | 18 +- .../Modules/dnn/TextRecognitionModel.cs | 9 +- .../Modules/dnn_superres/DnnSuperResImpl.cs | 19 +- .../face/FaceRecognizer/FaceRecognizer.cs | 18 +- .../Modules/face/Facemark/Facemark.cs | 14 +- src/OpenCvSharp/Modules/features/ANNIndex.cs | 26 +- src/OpenCvSharp/Modules/features/Feature2D.cs | 44 +- .../Modules/features/LightGlueMatcher.cs | 14 +- src/OpenCvSharp/Modules/features/MSER.cs | 9 +- src/OpenCvSharp/Modules/flann/Index.cs | 8 +- .../Modules/img_hash/AverageHash.cs | 2 +- .../Modules/img_hash/BlockMeanHash.cs | 2 +- .../Modules/img_hash/ColorMomentHash.cs | 2 +- .../Modules/img_hash/ImgHashBase.cs | 31 +- .../Modules/img_hash/MarrHildrethHash.cs | 2 +- src/OpenCvSharp/Modules/img_hash/PHash.cs | 2 +- .../Modules/img_hash/RadialVarianceHash.cs | 2 +- src/OpenCvSharp/Modules/imgproc/CLAHE.cs | 15 +- .../Modules/imgproc/Enum/PutTextFlags.cs | 2 +- .../Modules/imgproc/Filter2DParams.cs | 2 +- src/OpenCvSharp/Modules/imgproc/FontFace.cs | 2 +- .../Modules/imgproc/GeneralizedHough.cs | 80 +-- .../Modules/imgproc/IntelligentScissorsMB.cs | 24 +- .../Modules/imgproc/LineSegmentDetector.cs | 77 +-- src/OpenCvSharp/Modules/ml/ANN_MLP.cs | 8 +- src/OpenCvSharp/Modules/ml/EM.cs | 147 ++--- src/OpenCvSharp/Modules/ml/KNearest.cs | 27 +- .../Modules/ml/LogisticRegression.cs | 13 +- .../Modules/ml/NormalBayesClassifier.cs | 24 +- src/OpenCvSharp/Modules/ml/SVM.cs | 17 +- src/OpenCvSharp/Modules/ml/StatModel.cs | 29 +- .../Modules/objdetect/FaceDetectorYN.cs | 6 +- .../Modules/objdetect/QRCodeDetector.cs | 61 +- .../Modules/optflow/Cv2.OptFlow.cs | 146 ++--- src/OpenCvSharp/Modules/photo/CalibrateCRF.cs | 10 +- .../Modules/photo/MergeExposures.cs | 14 +- src/OpenCvSharp/Modules/photo/MergeMertens.cs | 9 +- src/OpenCvSharp/Modules/photo/Tonemap.cs | 15 +- src/OpenCvSharp/Modules/ptcloud/Odometry.cs | 54 +- .../Modules/ptcloud/OdometryFrame.cs | 79 +-- .../Modules/ptcloud/OdometrySettings.cs | 51 +- .../Modules/ptcloud/RgbdNormals.cs | 37 +- src/OpenCvSharp/Modules/ptcloud/Volume.cs | 177 ++---- .../Modules/ptcloud/VolumeSettings.cs | 76 +-- .../saliency/MotionSaliencyBinWangApr2014.cs | 13 +- .../Modules/saliency/ObjectnessBING.cs | 9 +- .../saliency/StaticSaliencyFineGrained.cs | 26 +- .../StaticSaliencySpectralResidual.cs | 26 +- src/OpenCvSharp/Modules/shape/Cv2.Shape.cs | 15 +- .../Modules/shape/HistogramCostExtractor.cs | 18 +- .../shape/ShapeContextDistanceExtractor.cs | 30 +- .../Modules/shape/ShapeDistanceExtractor.cs | 14 +- .../Modules/shape/ShapeTransformer.cs | 44 +- .../Modules/stereo/StereoMatcher.cs | 19 +- .../Modules/stitching/Cv2.Detail.cs | 13 +- src/OpenCvSharp/Modules/stitching/Stitcher.cs | 107 +--- .../Modules/superres/DenseOpticalFlowExt.cs | 25 +- .../Modules/superres/FrameSource.cs | 10 +- .../Modules/superres/SuperResolution.cs | 12 +- src/OpenCvSharp/Modules/text/Cv2.Text.cs | 18 +- src/OpenCvSharp/Modules/text/TextDetector.cs | 10 +- .../Modules/text/TextDetectorCNN.cs | 10 +- .../Modules/tracking/TrackerCSRT.cs | 10 +- .../Modules/video/BackgroundSubtractor.cs | 27 +- .../Modules/videoio/VideoCapture.cs | 24 +- .../Modules/videoio/VideoWriter.cs | 9 +- .../Modules/wechat_qrcode/WeChatQRCode.cs | 20 +- .../xfeatures2d/BOWImgDescriptorExtractor.cs | 26 +- .../Modules/ximgproc/Cv2.XImgProc.cs | 581 ++++-------------- src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs | 14 +- .../Modules/ximgproc/EdgeDrawing.cs | 43 +- .../EdgeFilter/AdaptiveManifoldFilter.cs | 16 +- .../Modules/ximgproc/EdgeFilter/DTFilter.cs | 23 +- .../EdgeFilter/FastBilateralSolverFilter.cs | 28 +- .../EdgeFilter/FastGlobalSmootherFilter.cs | 23 +- .../ximgproc/EdgeFilter/GuidedFilter.cs | 23 +- .../Modules/ximgproc/FastLineDetector.cs | 46 +- .../Modules/ximgproc/RidgeDetectionFilter.cs | 8 +- .../Segmentation/GraphSegmentation.cs | 14 +- .../SelectiveSearchSegmentation.cs | 18 +- .../SelectiveSearchSegmentationStrategy.cs | 19 +- ...ctiveSearchSegmentationStrategyMultiple.cs | 19 +- .../ximgproc/StructuredEdgeDetection.cs | 58 +- .../ximgproc/Superpixel/SuperpixelLSC.cs | 26 +- .../ximgproc/Superpixel/SuperpixelSEEDS.cs | 25 +- .../ximgproc/Superpixel/SuperpixelSLIC.cs | 26 +- src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs | 70 +-- src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs | 16 +- .../Modules/xphoto/LearningBasedWB.cs | 32 +- src/OpenCvSharp/Modules/xphoto/SimpleWB.cs | 16 +- .../Modules/xphoto/WhiteBalancer.cs | 2 +- 110 files changed, 1128 insertions(+), 3059 deletions(-) diff --git a/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs b/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs index 7327ac91e..80ed66070 100644 --- a/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs +++ b/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs @@ -34,43 +34,24 @@ public static class FishEye /// rotation vector, translation vector, and the skew.In the old interface different components of /// the jacobian are returned via different output parameters. public static void ProjectPoints( - InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, - InputArray k, InputArray d, double alpha = 0, OutputArray? jacobian = null) + InputArrayRef objectPoints, OutputArrayRef imagePoints, InputArrayRef rvec, InputArrayRef tvec, + InputArrayRef k, InputArrayRef d, double alpha = 0, OutputArrayRef jacobian = default) { - if (objectPoints is null) - throw new ArgumentNullException(nameof(objectPoints)); - if (imagePoints is null) - throw new ArgumentNullException(nameof(imagePoints)); - if (rvec is null) - throw new ArgumentNullException(nameof(rvec)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - objectPoints.ThrowIfDisposed(); - rvec.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - jacobian?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_projectPoints2( - objectPoints.ToInputProxy(), - imagePoints.ToOutputProxy(), - rvec.ToInputProxy(), tvec.ToInputProxy(), - k.ToInputProxy(), d.ToInputProxy(), - alpha, jacobian?.ToOutputProxy() ?? default)); - - GC.KeepAlive(objectPoints); - GC.KeepAlive(rvec); - GC.KeepAlive(tvec); - GC.KeepAlive(k); - GC.KeepAlive(d); - GC.KeepAlive(imagePoints); - GC.KeepAlive(jacobian); + objectPoints.Proxy, + imagePoints.Proxy, + rvec.Proxy, tvec.Proxy, + k.Proxy, d.Proxy, + alpha, jacobian.Proxy)); + + GC.KeepAlive(objectPoints.Source); + GC.KeepAlive(rvec.Source); + GC.KeepAlive(tvec.Source); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); + GC.KeepAlive(imagePoints.Source); + GC.KeepAlive(jacobian.Source); } /// @@ -83,29 +64,16 @@ public static void ProjectPoints( /// Input vector of distortion coefficients /// The skew coefficient. public static void DistortPoints( - InputArray undistorted, OutputArray distorted, InputArray k, InputArray d, double alpha = 0) + InputArrayRef undistorted, OutputArrayRef distorted, InputArrayRef k, InputArrayRef d, double alpha = 0) { - if (undistorted is null) - throw new ArgumentNullException(nameof(undistorted)); - if (distorted is null) - throw new ArgumentNullException(nameof(distorted)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - undistorted.ThrowIfDisposed(); - distorted.ThrowIfNotReady(); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_distortPoints( - undistorted.ToInputProxy(), distorted.ToOutputProxy(), k.ToInputProxy(), d.ToInputProxy(), alpha)); + undistorted.Proxy, distorted.Proxy, k.Proxy, d.Proxy, alpha)); - GC.KeepAlive(undistorted); - GC.KeepAlive(distorted); - GC.KeepAlive(k); - GC.KeepAlive(d); + GC.KeepAlive(undistorted.Source); + GC.KeepAlive(distorted.Source); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); } /// @@ -121,34 +89,17 @@ public static void DistortPoints( /// Input vector of distortion coefficients. /// The skew coefficient. public static void DistortPoints( - InputArray undistorted, OutputArray distorted, InputArray kundistorted, InputArray k, InputArray d, double alpha = 0) + InputArrayRef undistorted, OutputArrayRef distorted, InputArrayRef kundistorted, InputArrayRef k, InputArrayRef d, double alpha = 0) { - if (undistorted is null) - throw new ArgumentNullException(nameof(undistorted)); - if (distorted is null) - throw new ArgumentNullException(nameof(distorted)); - if (kundistorted is null) - throw new ArgumentNullException(nameof(kundistorted)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - undistorted.ThrowIfDisposed(); - distorted.ThrowIfNotReady(); - kundistorted.ThrowIfDisposed(); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_distortPoints2( - undistorted.ToInputProxy(), distorted.ToOutputProxy(), kundistorted.ToInputProxy(), k.ToInputProxy(), d.ToInputProxy(), alpha)); + undistorted.Proxy, distorted.Proxy, kundistorted.Proxy, k.Proxy, d.Proxy, alpha)); - distorted.Fix(); - GC.KeepAlive(undistorted); - GC.KeepAlive(distorted); - GC.KeepAlive(kundistorted); - GC.KeepAlive(k); - GC.KeepAlive(d); + GC.KeepAlive(undistorted.Source); + GC.KeepAlive(distorted.Source); + GC.KeepAlive(kundistorted.Source); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); } /// @@ -163,34 +114,19 @@ public static void DistortPoints( /// New camera matrix (3x3) or new projection matrix (3x4) // ReSharper disable once MemberHidesStaticFromOuterClass public static void UndistortPoints( - InputArray distorted, OutputArray undistorted, - InputArray k, InputArray d, InputArray? r = null, InputArray? p = null) + InputArrayRef distorted, OutputArrayRef undistorted, + InputArrayRef k, InputArrayRef d, InputArrayRef r = default, InputArrayRef p = default) { - if (distorted is null) - throw new ArgumentNullException(nameof(distorted)); - if (undistorted is null) - throw new ArgumentNullException(nameof(undistorted)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - distorted.ThrowIfDisposed(); - undistorted.ThrowIfNotReady(); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - r?.ThrowIfDisposed(); - p?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_undistortPoints( - distorted.ToInputProxy(), undistorted.ToOutputProxy(), k.ToInputProxy(), d.ToInputProxy(), r?.ToInputProxy() ?? default, p?.ToInputProxy() ?? default)); - - GC.KeepAlive(distorted); - GC.KeepAlive(undistorted); - GC.KeepAlive(k); - GC.KeepAlive(d); - GC.KeepAlive(r); - GC.KeepAlive(p); + distorted.Proxy, undistorted.Proxy, k.Proxy, d.Proxy, r.Proxy, p.Proxy)); + + GC.KeepAlive(distorted.Source); + GC.KeepAlive(undistorted.Source); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(p.Source); } /// @@ -206,38 +142,19 @@ public static void UndistortPoints( /// The first output map. /// The second output map. public static void InitUndistortRectifyMap( - InputArray k, InputArray d, InputArray r, InputArray p, - Size size, int m1type, OutputArray map1, OutputArray map2) + InputArrayRef k, InputArrayRef d, InputArrayRef r, InputArrayRef p, + Size size, int m1type, OutputArrayRef map1, OutputArrayRef map2) { - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (p is null) - throw new ArgumentNullException(nameof(p)); - if (map1 is null) - throw new ArgumentNullException(nameof(map1)); - if (map2 is null) - throw new ArgumentNullException(nameof(map2)); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - r.ThrowIfDisposed(); - p.ThrowIfDisposed(); - map1.ThrowIfNotReady(); - map2.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_initUndistortRectifyMap( - k.ToInputProxy(), d.ToInputProxy(), r.ToInputProxy(), p.ToInputProxy(), size, m1type, map1.ToOutputProxy(), map2.ToOutputProxy())); + k.Proxy, d.Proxy, r.Proxy, p.Proxy, size, m1type, map1.Proxy, map2.Proxy)); - GC.KeepAlive(k); - GC.KeepAlive(d); - GC.KeepAlive(r); - GC.KeepAlive(p); - GC.KeepAlive(map1); - GC.KeepAlive(map2); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(p.Source); + GC.KeepAlive(map1.Source); + GC.KeepAlive(map2.Source); } /// @@ -251,32 +168,18 @@ public static void InitUndistortRectifyMap( /// may additionally scale and shift the result by using a different matrix. /// public static void UndistortImage( - InputArray distorted, OutputArray undistorted, - InputArray k, InputArray d, InputArray? knew = null, Size newSize = default) + InputArrayRef distorted, OutputArrayRef undistorted, + InputArrayRef k, InputArrayRef d, InputArrayRef knew = default, Size newSize = default) { - if (distorted is null) - throw new ArgumentNullException(nameof(distorted)); - if (undistorted is null) - throw new ArgumentNullException(nameof(undistorted)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - distorted.ThrowIfDisposed(); - undistorted.ThrowIfNotReady(); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - knew?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_undistortImage( - distorted.ToInputProxy(), undistorted.ToOutputProxy(), k.ToInputProxy(), d.ToInputProxy(), knew?.ToInputProxy() ?? default, newSize)); + distorted.Proxy, undistorted.Proxy, k.Proxy, d.Proxy, knew.Proxy, newSize)); - GC.KeepAlive(distorted); - GC.KeepAlive(undistorted); - GC.KeepAlive(k); - GC.KeepAlive(d); - GC.KeepAlive(knew); + GC.KeepAlive(distorted.Source); + GC.KeepAlive(undistorted.Source); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); + GC.KeepAlive(knew.Source); } /// @@ -293,30 +196,17 @@ public static void UndistortImage( /// /// Divisor for new focal length. public static void EstimateNewCameraMatrixForUndistortRectify( - InputArray k, InputArray d, Size imageSize, InputArray r, - OutputArray p, double balance = 0.0, Size newSize = default, double fovScale = 1.0) + InputArrayRef k, InputArrayRef d, Size imageSize, InputArrayRef r, + OutputArrayRef p, double balance = 0.0, Size newSize = default, double fovScale = 1.0) { - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (p is null) - throw new ArgumentNullException(nameof(p)); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); - r.ThrowIfDisposed(); - p.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_estimateNewCameraMatrixForUndistortRectify( - k.ToInputProxy(), d.ToInputProxy(), imageSize, r.ToInputProxy(), p.ToOutputProxy(), balance, newSize, fovScale)); + k.Proxy, d.Proxy, imageSize, r.Proxy, p.Proxy, balance, newSize, fovScale)); - GC.KeepAlive(k); - GC.KeepAlive(d); - GC.KeepAlive(r); - GC.KeepAlive(p); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(p.Source); } /// @@ -340,7 +230,7 @@ public static void EstimateNewCameraMatrixForUndistortRectify( /// public static double Calibrate( IEnumerable objectPoints, IEnumerable imagePoints, - Size imageSize, InputOutputArray k, InputOutputArray d, + Size imageSize, InputOutputArrayRef k, InputOutputArrayRef d, out IEnumerable rvecs, out IEnumerable tvecs, FishEyeCalibrationFlags flags = 0, TermCriteria? criteria = null) { @@ -348,12 +238,6 @@ public static double Calibrate( throw new ArgumentNullException(nameof(objectPoints)); if (imagePoints is null) throw new ArgumentNullException(nameof(imagePoints)); - if (k is null) - throw new ArgumentNullException(nameof(k)); - if (d is null) - throw new ArgumentNullException(nameof(d)); - k.ThrowIfDisposed(); - d.ThrowIfDisposed(); var criteriaVal = criteria.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, double.Epsilon)); @@ -365,15 +249,15 @@ public static double Calibrate( NativeMethods.HandleException( NativeMethods.calib_fisheye_calibrate( objectPointsVec.CvPtr, imagePointsVec.CvPtr, imageSize, - k.ToInputOutputProxy(), d.ToInputOutputProxy(), rvecsVec.CvPtr, tvecsVec.CvPtr, (int) flags, criteriaVal, out var result)); + k.Proxy, d.Proxy, rvecsVec.CvPtr, tvecsVec.CvPtr, (int) flags, criteriaVal, out var result)); rvecs = rvecsVec.ToArray(); tvecs = tvecsVec.ToArray(); GC.KeepAlive(objectPoints); GC.KeepAlive(imagePoints); - GC.KeepAlive(k); - GC.KeepAlive(d); + GC.KeepAlive(k.Source); + GC.KeepAlive(d.Source); return result; } @@ -406,62 +290,28 @@ public static double Calibrate( /// length.Balance is in range of[0, 1]. /// Divisor for new focal length. public static void StereoRectify( - InputArray k1, InputArray d1, InputArray k2, InputArray d2, - Size imageSize, InputArray r, InputArray tvec, OutputArray r1, OutputArray r2, - OutputArray p1, OutputArray p2, OutputArray q, FishEyeCalibrationFlags flags, Size newImageSize = default, + InputArrayRef k1, InputArrayRef d1, InputArrayRef k2, InputArrayRef d2, + Size imageSize, InputArrayRef r, InputArrayRef tvec, OutputArrayRef r1, OutputArrayRef r2, + OutputArrayRef p1, OutputArrayRef p2, OutputArrayRef q, FishEyeCalibrationFlags flags, Size newImageSize = default, double balance = 0.0, double fovScale = 1.0) { - if (k1 is null) - throw new ArgumentNullException(nameof(k1)); - if (d1 is null) - throw new ArgumentNullException(nameof(d1)); - if (k2 is null) - throw new ArgumentNullException(nameof(k2)); - if (d2 is null) - throw new ArgumentNullException(nameof(d2)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (tvec is null) - throw new ArgumentNullException(nameof(tvec)); - if (r1 is null) - throw new ArgumentNullException(nameof(r1)); - if (r2 is null) - throw new ArgumentNullException(nameof(r2)); - if (p1 is null) - throw new ArgumentNullException(nameof(p1)); - if (p2 is null) - throw new ArgumentNullException(nameof(p2)); - if (q is null) - throw new ArgumentNullException(nameof(q)); - k1.ThrowIfDisposed(); - d1.ThrowIfDisposed(); - k2.ThrowIfDisposed(); - d2.ThrowIfDisposed(); - r.ThrowIfDisposed(); - tvec.ThrowIfDisposed(); - r1.ThrowIfNotReady(); - r2.ThrowIfNotReady(); - p1.ThrowIfNotReady(); - p2.ThrowIfNotReady(); - q.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.calib_fisheye_stereoRectify( - k1.ToInputProxy(), d1.ToInputProxy(), k2.ToInputProxy(), d2.ToInputProxy(), - imageSize, r.ToInputProxy(), tvec.ToInputProxy(), r1.ToOutputProxy(), r2.ToOutputProxy(), - p1.ToOutputProxy(), p2.ToOutputProxy(), q.ToOutputProxy(), (int) flags, newImageSize, balance, fovScale)); - - GC.KeepAlive(k1); - GC.KeepAlive(d1); - GC.KeepAlive(k2); - GC.KeepAlive(d2); - GC.KeepAlive(r); - GC.KeepAlive(tvec); - GC.KeepAlive(r1); - GC.KeepAlive(r2); - GC.KeepAlive(p1); - GC.KeepAlive(p2); - GC.KeepAlive(q); + k1.Proxy, d1.Proxy, k2.Proxy, d2.Proxy, + imageSize, r.Proxy, tvec.Proxy, r1.Proxy, r2.Proxy, + p1.Proxy, p2.Proxy, q.Proxy, (int) flags, newImageSize, balance, fovScale)); + + GC.KeepAlive(k1.Source); + GC.KeepAlive(d1.Source); + GC.KeepAlive(k2.Source); + GC.KeepAlive(d2.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(tvec.Source); + GC.KeepAlive(r1.Source); + GC.KeepAlive(r2.Source); + GC.KeepAlive(p1.Source); + GC.KeepAlive(p2.Source); + GC.KeepAlive(q.Source); } /// @@ -485,8 +335,8 @@ public static void StereoRectify( /// public static double StereoCalibrate( IEnumerable objectPoints, IEnumerable imagePoints1, IEnumerable imagePoints2, - InputOutputArray k1, InputOutputArray d1, InputOutputArray k2, InputOutputArray d2, Size imageSize, - OutputArray r, OutputArray t, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.FixIntrinsic, + InputOutputArrayRef k1, InputOutputArrayRef d1, InputOutputArrayRef k2, InputOutputArrayRef d2, Size imageSize, + OutputArrayRef r, OutputArrayRef t, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { if (objectPoints is null) @@ -495,24 +345,6 @@ public static double StereoCalibrate( throw new ArgumentNullException(nameof(imagePoints1)); if (imagePoints2 is null) throw new ArgumentNullException(nameof(imagePoints2)); - if (k1 is null) - throw new ArgumentNullException(nameof(k1)); - if (d1 is null) - throw new ArgumentNullException(nameof(d1)); - if (k2 is null) - throw new ArgumentNullException(nameof(k2)); - if (d2 is null) - throw new ArgumentNullException(nameof(d2)); - if (r is null) - throw new ArgumentNullException(nameof(r)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - k1.ThrowIfNotReady(); - d1.ThrowIfNotReady(); - k2.ThrowIfNotReady(); - d2.ThrowIfNotReady(); - r.ThrowIfNotReady(); - t.ThrowIfNotReady(); var criteriaVal = criteria.GetValueOrDefault( new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 100, double.Epsilon)); @@ -523,18 +355,18 @@ public static double StereoCalibrate( NativeMethods.HandleException( NativeMethods.calib_fisheye_stereoCalibrate( objectPointsVec.CvPtr, imagePoints1Vec.CvPtr, imagePoints2Vec.CvPtr, - k1.ToInputOutputProxy(), d1.ToInputOutputProxy(), k2.ToInputOutputProxy(), d2.ToInputOutputProxy(), imageSize, - r.ToOutputProxy(), t.ToOutputProxy(), (int) flags, criteriaVal, out var result)); + k1.Proxy, d1.Proxy, k2.Proxy, d2.Proxy, imageSize, + r.Proxy, t.Proxy, (int) flags, criteriaVal, out var result)); GC.KeepAlive(objectPoints); GC.KeepAlive(imagePoints1); GC.KeepAlive(imagePoints2); - GC.KeepAlive(k1); - GC.KeepAlive(d1); - GC.KeepAlive(k2); - GC.KeepAlive(d2); - GC.KeepAlive(r); - GC.KeepAlive(t); + GC.KeepAlive(k1.Source); + GC.KeepAlive(d1.Source); + GC.KeepAlive(k2.Source); + GC.KeepAlive(d2.Source); + GC.KeepAlive(r.Source); + GC.KeepAlive(t.Source); return result; } diff --git a/src/OpenCvSharp/Cv2/Cv2_features.cs b/src/OpenCvSharp/Cv2/Cv2_features.cs index 88a6fcc1c..2cb6c7fdd 100644 --- a/src/OpenCvSharp/Cv2/Cv2_features.cs +++ b/src/OpenCvSharp/Cv2/Cv2_features.cs @@ -19,16 +19,12 @@ static partial class Cv2 /// if true, non-maximum suppression is applied to /// detected corners (keypoints). /// keypoints detected on the image. - public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupression = true) + public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSupression = true) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var kp = new StdVector(); NativeMethods.HandleException( - NativeMethods.features_FAST1(image.ToInputProxy(), kp.CvPtr, threshold, nonmaxSupression ? 1 : 0)); - GC.KeepAlive(image); + NativeMethods.features_FAST1(image.Proxy, kp.CvPtr, threshold, nonmaxSupression ? 1 : 0)); + GC.KeepAlive(image.Source); return kp.ToArray(); } @@ -42,16 +38,12 @@ public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupres /// detected corners (keypoints). /// one of the three neighborhoods as defined in the paper /// keypoints detected on the image. - public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupression, FASTType type) + public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSupression, FASTType type) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var kp = new StdVector(); NativeMethods.HandleException( - NativeMethods.features_FAST2(image.ToInputProxy(), kp.CvPtr, threshold, nonmaxSupression ? 1 : 0, (int)type)); - GC.KeepAlive(image); + NativeMethods.features_FAST2(image.Proxy, kp.CvPtr, threshold, nonmaxSupression ? 1 : 0, (int)type)); + GC.KeepAlive(image.Source); return kp.ToArray(); } @@ -65,16 +57,12 @@ public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupres /// detected corners (keypoints). /// one of the four neighborhoods as defined in the paper /// keypoints detected on the image. - public static KeyPoint[] AGAST(InputArray image, int threshold, bool nonmaxSuppression, AgastFeatureDetector.DetectorType type) + public static KeyPoint[] AGAST(InputArrayRef image, int threshold, bool nonmaxSuppression, AgastFeatureDetector.DetectorType type) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using var vector = new StdVector(); NativeMethods.HandleException( - NativeMethods.xfeatures2d_AGAST(image.ToInputProxy(), vector.CvPtr, threshold, nonmaxSuppression ? 1 : 0, (int) type)); - GC.KeepAlive(image); + NativeMethods.xfeatures2d_AGAST(image.Proxy, vector.CvPtr, threshold, nonmaxSuppression ? 1 : 0, (int) type)); + GC.KeepAlive(image.Source); return vector.ToArray(); } @@ -87,28 +75,22 @@ public static KeyPoint[] AGAST(InputArray image, int threshold, bool nonmaxSuppr /// Color of keypoints. /// Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags. public static void DrawKeypoints( - InputArray image, + InputArrayRef image, IEnumerable keypoints, - InputOutputArray outImage, + InputOutputArrayRef outImage, Scalar? color = null, DrawMatchesFlags flags = DrawMatchesFlags.Default) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (outImage is null) - throw new ArgumentNullException(nameof(outImage)); if (keypoints is null) throw new ArgumentNullException(nameof(keypoints)); - image.ThrowIfDisposed(); - outImage.ThrowIfDisposed(); var keypointsArray = keypoints.CastOrToArray(); var color0 = color.GetValueOrDefault(Scalar.All(-1)); NativeMethods.HandleException( - NativeMethods.features_drawKeypoints(image.ToInputProxy(), keypointsArray, keypointsArray.Length, outImage.ToInputOutputProxy(), color0, (int)flags)); + NativeMethods.features_drawKeypoints(image.Proxy, keypointsArray, keypointsArray.Length, outImage.Proxy, color0, (int)flags)); - GC.KeepAlive(image); - GC.KeepAlive(outImage); + GC.KeepAlive(image.Source); + GC.KeepAlive(outImage.Source); } /// diff --git a/src/OpenCvSharp/Cv2/Cv2_highgui.cs b/src/OpenCvSharp/Cv2/Cv2_highgui.cs index df5a61d10..a31e58d4f 100644 --- a/src/OpenCvSharp/Cv2/Cv2_highgui.cs +++ b/src/OpenCvSharp/Cv2/Cv2_highgui.cs @@ -302,18 +302,15 @@ public static int GetMouseWheelDelta(MouseEventFlags flags) /// selection rectangle will correspond to the initial mouse position. /// selected ROI or empty rect if selection canceled. // ReSharper disable once InconsistentNaming - public static Rect SelectROI(string windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false) + public static Rect SelectROI(string windowName, InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) { if (string.IsNullOrEmpty(windowName)) throw new ArgumentNullException(nameof(windowName)); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.highgui_selectROI1(windowName, img.ToInputProxy(), showCrosshair ? 1 : 0, fromCenter ? 1 : 0, out var ret)); + NativeMethods.highgui_selectROI1(windowName, img.Proxy, showCrosshair ? 1 : 0, fromCenter ? 1 : 0, out var ret)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return ret; } @@ -328,16 +325,12 @@ public static Rect SelectROI(string windowName, InputArray img, bool showCrossha /// selection rectangle will correspond to the initial mouse position. /// selected ROI or empty rect if selection canceled. // ReSharper disable once InconsistentNaming - public static Rect SelectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false) + public static Rect SelectROI(InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.highgui_selectROI2(img.ToInputProxy(), showCrosshair ? 1 : 0, fromCenter ? 1 : 0, out var ret)); + NativeMethods.highgui_selectROI2(img.Proxy, showCrosshair ? 1 : 0, fromCenter ? 1 : 0, out var ret)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return ret; } @@ -354,19 +347,16 @@ public static Rect SelectROI(InputArray img, bool showCrosshair = true, bool fro /// selection rectangle will correspond to the initial mouse position. /// selected ROIs. // ReSharper disable once InconsistentNaming - public static Rect[] SelectROIs(string windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false) + public static Rect[] SelectROIs(string windowName, InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) { if (string.IsNullOrEmpty(windowName)) throw new ArgumentNullException(nameof(windowName)); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); using var boundingBoxesVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.highgui_selectROIs(windowName, img.ToInputProxy(), boundingBoxesVec.CvPtr, showCrosshair ? 1 : 0, fromCenter ? 1 : 0)); + NativeMethods.highgui_selectROIs(windowName, img.Proxy, boundingBoxesVec.CvPtr, showCrosshair ? 1 : 0, fromCenter ? 1 : 0)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return boundingBoxesVec.ToArray(); } diff --git a/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs b/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs index 8cafe93c8..b83506e84 100644 --- a/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs +++ b/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs @@ -155,15 +155,11 @@ public static Mat ImDecode(Mat buf, ImreadModes flags) /// The input array of vector of bytes. /// The same flags as in imread /// - public static Mat ImDecode(InputArray buf, ImreadModes flags) + public static Mat ImDecode(InputArrayRef buf, ImreadModes flags) { - if (buf is null) - throw new ArgumentNullException(nameof(buf)); - buf.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.imgcodecs_imdecode_InputArray(buf.ToInputProxy(), (int) flags, out var ret)); - GC.KeepAlive(buf); + NativeMethods.imgcodecs_imdecode_InputArray(buf.Proxy, (int) flags, out var ret)); + GC.KeepAlive(buf.Source); return new Mat(ret); } @@ -211,19 +207,16 @@ public static Mat ImDecode(ReadOnlySpan span, ImreadModes flags) /// The image to be written /// Output buffer resized to fit the compressed image. /// Format-specific parameters. - public static bool ImEncode(string ext, InputArray img, out byte[] buf, int[]? prms = null) + public static bool ImEncode(string ext, InputArrayRef img, out byte[] buf, int[]? prms = null) { if (string.IsNullOrEmpty(ext)) throw new ArgumentNullException(nameof(ext)); - if (img is null) - throw new ArgumentNullException(nameof(img)); prms ??= []; - img.ThrowIfDisposed(); using var bufVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.imgcodecs_imencode_vector(ext, img.ToInputProxy(), bufVec.CvPtr, prms, prms.Length, out var ret)); - GC.KeepAlive(img); + NativeMethods.imgcodecs_imencode_vector(ext, img.Proxy, bufVec.CvPtr, prms, prms.Length, out var ret)); + GC.KeepAlive(img.Source); buf = bufVec.ToArray(); return ret != 0; } @@ -235,7 +228,7 @@ public static bool ImEncode(string ext, InputArray img, out byte[] buf, int[]? p /// The image to be written /// Output buffer resized to fit the compressed image. /// Format-specific parameters. - public static void ImEncode(string ext, InputArray img, out byte[] buf, params ImageEncodingParam[] prms) + public static void ImEncode(string ext, InputArrayRef img, out byte[] buf, params ImageEncodingParam[] prms) { if (prms is null) throw new ArgumentNullException(nameof(prms)); diff --git a/src/OpenCvSharp/Cv2/Cv2_photo.cs b/src/OpenCvSharp/Cv2/Cv2_photo.cs index 678812a13..3a4349efa 100644 --- a/src/OpenCvSharp/Cv2/Cv2_photo.cs +++ b/src/OpenCvSharp/Cv2/Cv2_photo.cs @@ -12,25 +12,14 @@ static partial class Cv2 /// Output image with the same size and type as src. /// Radius of a circular neighborhood of each point inpainted that is considered by the algorithm. /// Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA - public static void Inpaint(InputArray src, InputArray inpaintMask, - OutputArray dst, double inpaintRadius, InpaintTypes flags) + public static void Inpaint(InputArrayRef src, InputArrayRef inpaintMask, + OutputArrayRef dst, double inpaintRadius, InpaintTypes flags) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (inpaintMask is null) - throw new ArgumentNullException(nameof(inpaintMask)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - inpaintMask.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.photo_inpaint(src.ToInputProxy(), inpaintMask.ToInputProxy(), dst.ToOutputProxy(), inpaintRadius, (int)flags)); + NativeMethods.photo_inpaint(src.Proxy, inpaintMask.Proxy, dst.Proxy, inpaintRadius, (int)flags)); - dst.Fix(); - GC.KeepAlive(src); - GC.KeepAlive(inpaintMask); + GC.KeepAlive(src.Source); + GC.KeepAlive(inpaintMask.Source); } /// @@ -47,21 +36,13 @@ public static void Inpaint(InputArray src, InputArray inpaintMask, /// /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels - public static void FastNlMeansDenoising(InputArray src, OutputArray dst, float h = 3, + public static void FastNlMeansDenoising(InputArrayRef src, OutputArrayRef dst, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.photo_fastNlMeansDenoising(src.ToInputProxy(), dst.ToOutputProxy(), h, templateWindowSize, searchWindowSize)); + NativeMethods.photo_fastNlMeansDenoising(src.Proxy, dst.Proxy, h, templateWindowSize, searchWindowSize)); - dst.Fix(); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); } /// @@ -78,22 +59,14 @@ public static void FastNlMeansDenoising(InputArray src, OutputArray dst, float h /// /// Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. /// Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels - public static void FastNlMeansDenoisingColored(InputArray src, OutputArray dst, + public static void FastNlMeansDenoisingColored(InputArrayRef src, OutputArrayRef dst, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.photo_fastNlMeansDenoisingColored(src.ToInputProxy(), dst.ToOutputProxy(), h, hColor, templateWindowSize, searchWindowSize)); + NativeMethods.photo_fastNlMeansDenoisingColored(src.Proxy, dst.Proxy, h, hColor, templateWindowSize, searchWindowSize)); - dst.Fix(); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); } /// @@ -112,25 +85,21 @@ public static void FastNlMeansDenoisingColored(InputArray src, OutputArray dst, /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels public static void FastNlMeansDenoisingMulti( - IEnumerable srcImgs, OutputArray dst, + IEnumerable srcImgs, OutputArrayRef dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) { if (srcImgs is null) throw new ArgumentNullException(nameof(srcImgs)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); var srcImgPtrs = srcImgs.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( NativeMethods.photo_fastNlMeansDenoisingMulti( - srcImgPtrs, srcImgPtrs.Length, dst.ToOutputProxy(), + srcImgPtrs, srcImgPtrs.Length, dst.Proxy, imgToDenoiseIndex, temporalWindowSize, h, templateWindowSize, searchWindowSize)); - dst.Fix(); GC.KeepAlive(srcImgs); } @@ -150,23 +119,19 @@ public static void FastNlMeansDenoisingMulti( /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels public static void FastNlMeansDenoisingColoredMulti( - IEnumerable srcImgs, OutputArray dst, + IEnumerable srcImgs, OutputArrayRef dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) { if (srcImgs is null) throw new ArgumentNullException(nameof(srcImgs)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); var srcImgPtrs = srcImgs.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( NativeMethods.photo_fastNlMeansDenoisingColoredMulti( - srcImgPtrs, srcImgPtrs.Length, dst.ToOutputProxy(), imgToDenoiseIndex, + srcImgPtrs, srcImgPtrs.Length, dst.Proxy, imgToDenoiseIndex, temporalWindowSize, h, hColor, templateWindowSize, searchWindowSize)); - dst.Fix(); GC.KeepAlive(srcImgs); } @@ -212,24 +177,12 @@ public static void DenoiseTVL1( /// Output 8-bit 1-channel image. /// Output 8-bit 3-channel image. public static void Decolor( - InputArray src, OutputArray grayscale, OutputArray colorBoost) + InputArrayRef src, OutputArrayRef grayscale, OutputArrayRef colorBoost) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (grayscale is null) - throw new ArgumentNullException(nameof(grayscale)); - if (colorBoost is null) - throw new ArgumentNullException(nameof(colorBoost)); - src.ThrowIfDisposed(); - grayscale.ThrowIfNotReady(); - colorBoost.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.photo_decolor(src.ToInputProxy(), grayscale.ToOutputProxy(), colorBoost.ToOutputProxy())); + NativeMethods.photo_decolor(src.Proxy, grayscale.Proxy, colorBoost.Proxy)); - GC.KeepAlive(src); - grayscale.Fix(); - colorBoost.Fix(); + GC.KeepAlive(src.Source); } /// @@ -247,28 +200,16 @@ public static void Decolor( /// Output image with the same size and type as dst. /// Cloning method public static void SeamlessClone( - InputArray src, InputArray dst, InputArray? mask, Point p, - OutputArray blend, SeamlessCloneFlags flags) + InputArrayRef src, InputArrayRef dst, InputArrayRef mask, Point p, + OutputArrayRef blend, SeamlessCloneFlags flags) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - if (blend is null) - throw new ArgumentNullException(nameof(blend)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); - blend.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.photo_seamlessClone( - src.ToInputProxy(), dst.ToInputProxy(), mask?.ToInputProxy() ?? default, p, blend.ToOutputProxy(), (int) flags)); + src.Proxy, dst.Proxy, mask.Proxy, p, blend.Proxy, (int) flags)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - GC.KeepAlive(mask); - blend.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } /// @@ -282,24 +223,15 @@ public static void SeamlessClone( /// G-channel multiply factor. /// B-channel multiply factor. public static void ColorChange( - InputArray src, InputArray? mask, OutputArray dst, + InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, float redMul = 1.0f, float greenMul = 1.0f, float blueMul = 1.0f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.photo_colorChange( - src.ToInputProxy(), mask?.ToInputProxy() ?? default, dst.ToOutputProxy(), redMul, greenMul, blueMul)); + src.Proxy, mask.Proxy, dst.Proxy, redMul, greenMul, blueMul)); - GC.KeepAlive(src); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// @@ -316,25 +248,15 @@ public static void ColorChange( /// This is useful to highlight under-exposed foreground objects or to reduce specular reflections. /// public static void IlluminationChange( - InputArray src, InputArray? mask, OutputArray dst, + InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, float alpha = 0.2f, float beta = 0.4f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.photo_illuminationChange( - src.ToInputProxy(), mask?.ToInputProxy() ?? default, dst.ToOutputProxy(), alpha, beta)); + src.Proxy, mask.Proxy, dst.Proxy, alpha, beta)); - GC.KeepAlive(src); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// @@ -349,26 +271,16 @@ public static void IlluminationChange( /// Value > 100. /// The size of the Sobel kernel to be used. public static void TextureFlattening( - InputArray src, InputArray? mask, OutputArray dst, + InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, float lowThreshold = 30, float highThreshold = 45, int kernelSize = 3) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.photo_textureFlattening( - src.ToInputProxy(), mask?.ToInputProxy() ?? default, dst.ToOutputProxy(), lowThreshold, highThreshold, kernelSize)); + src.Proxy, mask.Proxy, dst.Proxy, lowThreshold, highThreshold, kernelSize)); - GC.KeepAlive(src); - GC.KeepAlive(mask); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(mask.Source); } /// @@ -381,24 +293,15 @@ public static void TextureFlattening( /// Range between 0 to 200. /// Range between 0 to 1. public static void EdgePreservingFilter( - InputArray src, OutputArray dst, + InputArrayRef src, OutputArrayRef dst, EdgePreservingMethods flags = EdgePreservingMethods.RecursFilter, float sigmaS = 60, float sigmaR = 0.4f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.photo_edgePreservingFilter( - src.ToInputProxy(), dst.ToOutputProxy(), (int) flags, sigmaS, sigmaR)); + src.Proxy, dst.Proxy, (int) flags, sigmaS, sigmaR)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -409,23 +312,14 @@ public static void EdgePreservingFilter( /// Range between 0 to 200. /// Range between 0 to 1. public static void DetailEnhance( - InputArray src, OutputArray dst, + InputArrayRef src, OutputArrayRef dst, float sigmaS = 10, float sigmaR = 0.15f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.photo_detailEnhance( - src.ToInputProxy(), dst.ToOutputProxy(), sigmaS, sigmaR)); + src.Proxy, dst.Proxy, sigmaS, sigmaR)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -438,27 +332,14 @@ public static void DetailEnhance( /// Range between 0 to 1. /// Range between 0 to 0.1. public static void PencilSketch( - InputArray src, OutputArray dst1, OutputArray dst2, + InputArrayRef src, OutputArrayRef dst1, OutputArrayRef dst2, float sigmaS = 60, float sigmaR = 0.07f, float shadeFactor = 0.02f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst1 is null) - throw new ArgumentNullException(nameof(dst1)); - if (dst2 is null) - throw new ArgumentNullException(nameof(dst2)); - - src.ThrowIfDisposed(); - dst1.ThrowIfNotReady(); - dst2.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.photo_pencilSketch( - src.ToInputProxy(), dst1.ToOutputProxy(), dst2.ToOutputProxy(), sigmaS, sigmaR, shadeFactor)); + src.Proxy, dst1.Proxy, dst2.Proxy, sigmaS, sigmaR, shadeFactor)); - GC.KeepAlive(src); - dst1.Fix(); - dst2.Fix(); + GC.KeepAlive(src.Source); } /// @@ -472,22 +353,13 @@ public static void PencilSketch( /// Range between 0 to 200. /// Range between 0 to 1. public static void Stylization( - InputArray src, OutputArray dst, + InputArrayRef src, OutputArrayRef dst, float sigmaS = 60, float sigmaR = 0.45f) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.photo_stylization( - src.ToInputProxy(), dst.ToOutputProxy(), sigmaS, sigmaR)); + src.Proxy, dst.Proxy, sigmaS, sigmaR)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } } diff --git a/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs b/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs index f8c37d43a..e73d2807b 100644 --- a/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs +++ b/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs @@ -20,41 +20,21 @@ static partial class Cv2 /// the result of transforming the depth into the external camera. /// whether or not the depth is dilated to avoid holes and occlusion errors (optional). public static void RegisterDepth( - InputArray unregisteredCameraMatrix, InputArray registeredCameraMatrix, InputArray registeredDistCoeffs, - InputArray Rt, InputArray unregisteredDepth, Size outputImagePlaneSize, - OutputArray registeredDepth, bool depthDilation = false) + InputArrayRef unregisteredCameraMatrix, InputArrayRef registeredCameraMatrix, InputArrayRef registeredDistCoeffs, + InputArrayRef Rt, InputArrayRef unregisteredDepth, Size outputImagePlaneSize, + OutputArrayRef registeredDepth, bool depthDilation = false) { - if (unregisteredCameraMatrix is null) - throw new ArgumentNullException(nameof(unregisteredCameraMatrix)); - if (registeredCameraMatrix is null) - throw new ArgumentNullException(nameof(registeredCameraMatrix)); - if (registeredDistCoeffs is null) - throw new ArgumentNullException(nameof(registeredDistCoeffs)); - if (Rt is null) - throw new ArgumentNullException(nameof(Rt)); - if (unregisteredDepth is null) - throw new ArgumentNullException(nameof(unregisteredDepth)); - if (registeredDepth is null) - throw new ArgumentNullException(nameof(registeredDepth)); - unregisteredCameraMatrix.ThrowIfDisposed(); - registeredCameraMatrix.ThrowIfDisposed(); - registeredDistCoeffs.ThrowIfDisposed(); - Rt.ThrowIfDisposed(); - unregisteredDepth.ThrowIfDisposed(); - registeredDepth.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ptcloud_registerDepth( - unregisteredCameraMatrix.ToInputProxy(), registeredCameraMatrix.ToInputProxy(), registeredDistCoeffs.ToInputProxy(), - Rt.ToInputProxy(), unregisteredDepth.ToInputProxy(), outputImagePlaneSize, - registeredDepth.ToOutputProxy(), depthDilation ? 1 : 0)); - - registeredDepth.Fix(); - GC.KeepAlive(unregisteredCameraMatrix); - GC.KeepAlive(registeredCameraMatrix); - GC.KeepAlive(registeredDistCoeffs); - GC.KeepAlive(Rt); - GC.KeepAlive(unregisteredDepth); + unregisteredCameraMatrix.Proxy, registeredCameraMatrix.Proxy, registeredDistCoeffs.Proxy, + Rt.Proxy, unregisteredDepth.Proxy, outputImagePlaneSize, + registeredDepth.Proxy, depthDilation ? 1 : 0)); + + GC.KeepAlive(unregisteredCameraMatrix.Source); + GC.KeepAlive(registeredCameraMatrix.Source); + GC.KeepAlive(registeredDistCoeffs.Source); + GC.KeepAlive(Rt.Source); + GC.KeepAlive(unregisteredDepth.Source); } /// @@ -64,28 +44,14 @@ public static void RegisterDepth( /// the calibration matrix. /// the list of xy coordinates. /// the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). - public static void DepthTo3dSparse(InputArray depth, InputArray inK, InputArray inPoints, OutputArray points3d) + public static void DepthTo3dSparse(InputArrayRef depth, InputArrayRef inK, InputArrayRef inPoints, OutputArrayRef points3d) { - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - if (inK is null) - throw new ArgumentNullException(nameof(inK)); - if (inPoints is null) - throw new ArgumentNullException(nameof(inPoints)); - if (points3d is null) - throw new ArgumentNullException(nameof(points3d)); - depth.ThrowIfDisposed(); - inK.ThrowIfDisposed(); - inPoints.ThrowIfDisposed(); - points3d.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ptcloud_depthTo3dSparse(depth.ToInputProxy(), inK.ToInputProxy(), inPoints.ToInputProxy(), points3d.ToOutputProxy())); + NativeMethods.ptcloud_depthTo3dSparse(depth.Proxy, inK.Proxy, inPoints.Proxy, points3d.Proxy)); - points3d.Fix(); - GC.KeepAlive(depth); - GC.KeepAlive(inK); - GC.KeepAlive(inPoints); + GC.KeepAlive(depth.Source); + GC.KeepAlive(inK.Source); + GC.KeepAlive(inPoints.Source); } /// @@ -95,26 +61,14 @@ public static void DepthTo3dSparse(InputArray depth, InputArray inK, InputArray /// the calibration matrix. /// the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). /// the mask of the points to consider (can be empty). - public static void DepthTo3d(InputArray depth, InputArray K, OutputArray points3d, InputArray? mask = null) + public static void DepthTo3d(InputArrayRef depth, InputArrayRef K, OutputArrayRef points3d, InputArrayRef mask = default) { - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - if (K is null) - throw new ArgumentNullException(nameof(K)); - if (points3d is null) - throw new ArgumentNullException(nameof(points3d)); - depth.ThrowIfDisposed(); - K.ThrowIfDisposed(); - points3d.ThrowIfNotReady(); - mask?.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.ptcloud_depthTo3d(depth.ToInputProxy(), K.ToInputProxy(), points3d.ToOutputProxy(), mask?.ToInputProxy() ?? default)); + NativeMethods.ptcloud_depthTo3d(depth.Proxy, K.Proxy, points3d.Proxy, mask.Proxy)); - points3d.Fix(); - GC.KeepAlive(depth); - GC.KeepAlive(K); - GC.KeepAlive(mask); + GC.KeepAlive(depth.Source); + GC.KeepAlive(K.Source); + GC.KeepAlive(mask.Source); } /// @@ -125,20 +79,12 @@ public static void DepthTo3d(InputArray depth, InputArray K, OutputArray points3 /// the desired output depth (CV_32F or CV_64F). /// the rescaled float depth image. /// factor by which depth is converted to distance (by default = 1000.0 for Kinect sensor). - public static void RescaleDepth(InputArray src, int type, OutputArray dst, double depthFactor = 1000.0) + public static void RescaleDepth(InputArrayRef src, int type, OutputArrayRef dst, double depthFactor = 1000.0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ptcloud_rescaleDepth(src.ToInputProxy(), type, dst.ToOutputProxy(), depthFactor)); + NativeMethods.ptcloud_rescaleDepth(src.Proxy, type, dst.Proxy, depthFactor)); - dst.Fix(); - GC.KeepAlive(src); + GC.KeepAlive(src.Source); } /// @@ -154,37 +100,19 @@ public static void RescaleDepth(InputArray src, int type, OutputArray dst, doubl /// The warped RGB image (optional). /// The mask of valid pixels in warped image (optional). public static void WarpFrame( - InputArray depth, InputArray? image, InputArray? mask, InputArray Rt, InputArray cameraMatrix, - OutputArray? warpedDepth = null, OutputArray? warpedImage = null, OutputArray? warpedMask = null) + InputArrayRef depth, InputArrayRef image, InputArrayRef mask, InputArrayRef Rt, InputArrayRef cameraMatrix, + OutputArrayRef warpedDepth = default, OutputArrayRef warpedImage = default, OutputArrayRef warpedMask = default) { - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - if (Rt is null) - throw new ArgumentNullException(nameof(Rt)); - if (cameraMatrix is null) - throw new ArgumentNullException(nameof(cameraMatrix)); - depth.ThrowIfDisposed(); - image?.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); - Rt.ThrowIfDisposed(); - cameraMatrix.ThrowIfDisposed(); - warpedDepth?.ThrowIfNotReady(); - warpedImage?.ThrowIfNotReady(); - warpedMask?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ptcloud_warpFrame( - depth.ToInputProxy(), image?.ToInputProxy() ?? default, mask?.ToInputProxy() ?? default, Rt.ToInputProxy(), cameraMatrix.ToInputProxy(), - warpedDepth?.ToOutputProxy() ?? default, warpedImage?.ToOutputProxy() ?? default, warpedMask?.ToOutputProxy() ?? default)); - - warpedDepth?.Fix(); - warpedImage?.Fix(); - warpedMask?.Fix(); - GC.KeepAlive(depth); - GC.KeepAlive(image); - GC.KeepAlive(mask); - GC.KeepAlive(Rt); - GC.KeepAlive(cameraMatrix); + depth.Proxy, image.Proxy, mask.Proxy, Rt.Proxy, cameraMatrix.Proxy, + warpedDepth.Proxy, warpedImage.Proxy, warpedMask.Proxy)); + + GC.KeepAlive(depth.Source); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(Rt.Source); + GC.KeepAlive(cameraMatrix.Source); } /// @@ -202,34 +130,19 @@ public static void WarpFrame( /// coefficient of the sensor error (0 by default). /// the method to use to compute the planes. public static void FindPlanes( - InputArray points3d, InputArray normals, OutputArray mask, OutputArray planeCoefficients, + InputArrayRef points3d, InputArrayRef normals, OutputArrayRef mask, OutputArrayRef planeCoefficients, int blockSize = 40, int minSize = 1600, double threshold = 0.01, double sensorErrorA = 0, double sensorErrorB = 0, double sensorErrorC = 0, RgbdPlaneMethod method = RgbdPlaneMethod.Default) { - if (points3d is null) - throw new ArgumentNullException(nameof(points3d)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - if (planeCoefficients is null) - throw new ArgumentNullException(nameof(planeCoefficients)); - points3d.ThrowIfDisposed(); - normals.ThrowIfDisposed(); - mask.ThrowIfNotReady(); - planeCoefficients.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ptcloud_findPlanes( - points3d.ToInputProxy(), normals.ToInputProxy(), mask.ToOutputProxy(), planeCoefficients.ToOutputProxy(), + points3d.Proxy, normals.Proxy, mask.Proxy, planeCoefficients.Proxy, blockSize, minSize, threshold, sensorErrorA, sensorErrorB, sensorErrorC, (int)method)); - mask.Fix(); - planeCoefficients.Fix(); - GC.KeepAlive(points3d); - GC.KeepAlive(normals); + GC.KeepAlive(points3d.Source); + GC.KeepAlive(normals.Source); } /// @@ -239,22 +152,14 @@ public static void FindPlanes( /// Output vertex coordinates, each value contains 3 floats. /// Output per-vertex normals, each value contains 3 floats (optional). /// Output per-vertex colors, each value contains 3 floats (optional). - public static void LoadPointCloud(string filename, OutputArray vertices, OutputArray? normals = null, OutputArray? rgb = null) + public static void LoadPointCloud(string filename, OutputArrayRef vertices, OutputArrayRef normals = default, OutputArrayRef rgb = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); - if (vertices is null) - throw new ArgumentNullException(nameof(vertices)); - vertices.ThrowIfNotReady(); - normals?.ThrowIfNotReady(); - rgb?.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_loadPointCloud(filename, vertices.ToOutputProxy(), normals?.ToOutputProxy() ?? default, rgb?.ToOutputProxy() ?? default)); + NativeMethods.ptcloud_loadPointCloud(filename, vertices.Proxy, normals.Proxy, rgb.Proxy)); - vertices.Fix(); - normals?.Fix(); - rgb?.Fix(); } /// @@ -264,22 +169,17 @@ public static void LoadPointCloud(string filename, OutputArray vertices, OutputA /// Vertex coordinates, each value contains 3 floats. /// Per-vertex normals, each value contains 3 floats (optional). /// Per-vertex colors, each value contains 3 floats (optional). - public static void SavePointCloud(string filename, InputArray vertices, InputArray? normals = null, InputArray? rgb = null) + public static void SavePointCloud(string filename, InputArrayRef vertices, InputArrayRef normals = default, InputArrayRef rgb = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); - if (vertices is null) - throw new ArgumentNullException(nameof(vertices)); - vertices.ThrowIfDisposed(); - normals?.ThrowIfDisposed(); - rgb?.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_savePointCloud(filename, vertices.ToInputProxy(), normals?.ToInputProxy() ?? default, rgb?.ToInputProxy() ?? default)); + NativeMethods.ptcloud_savePointCloud(filename, vertices.Proxy, normals.Proxy, rgb.Proxy)); - GC.KeepAlive(vertices); - GC.KeepAlive(normals); - GC.KeepAlive(rgb); + GC.KeepAlive(vertices.Source); + GC.KeepAlive(normals.Source); + GC.KeepAlive(rgb.Source); } /// @@ -292,27 +192,17 @@ public static void SavePointCloud(string filename, InputArray vertices, InputArr /// Output per-vertex colors, each value contains 3 floats (optional). /// Output per-vertex texture coordinates, each value contains 2 or 3 floats (optional). public static void LoadMesh( - string filename, OutputArray vertices, out Mat[] indices, - OutputArray? normals = null, OutputArray? colors = null, OutputArray? texCoords = null) + string filename, OutputArrayRef vertices, out Mat[] indices, + OutputArrayRef normals = default, OutputArrayRef colors = default, OutputArrayRef texCoords = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); - if (vertices is null) - throw new ArgumentNullException(nameof(vertices)); - vertices.ThrowIfNotReady(); - normals?.ThrowIfNotReady(); - colors?.ThrowIfNotReady(); - texCoords?.ThrowIfNotReady(); using var indicesVec = new VectorOfMat(); NativeMethods.HandleException( NativeMethods.ptcloud_loadMesh( - filename, vertices.ToOutputProxy(), indicesVec.CvPtr, normals?.ToOutputProxy() ?? default, colors?.ToOutputProxy() ?? default, texCoords?.ToOutputProxy() ?? default)); + filename, vertices.Proxy, indicesVec.CvPtr, normals.Proxy, colors.Proxy, texCoords.Proxy)); - vertices.Fix(); - normals?.Fix(); - colors?.Fix(); - texCoords?.Fix(); indices = indicesVec.ToArray(); } @@ -326,30 +216,24 @@ public static void LoadMesh( /// Per-vertex colors, each value contains 3 floats (optional). /// Per-vertex texture coordinates, each value contains 2 or 3 floats (optional). public static void SaveMesh( - string filename, InputArray vertices, IEnumerable indices, - InputArray? normals = null, InputArray? colors = null, InputArray? texCoords = null) + string filename, InputArrayRef vertices, IEnumerable indices, + InputArrayRef normals = default, InputArrayRef colors = default, InputArrayRef texCoords = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); - if (vertices is null) - throw new ArgumentNullException(nameof(vertices)); if (indices is null) throw new ArgumentNullException(nameof(indices)); - vertices.ThrowIfDisposed(); - normals?.ThrowIfDisposed(); - colors?.ThrowIfDisposed(); - texCoords?.ThrowIfDisposed(); var indicesArray = indices as Mat[] ?? indices.ToArray(); using var indicesVec = new VectorOfMat(indicesArray); NativeMethods.HandleException( NativeMethods.ptcloud_saveMesh( - filename, vertices.ToInputProxy(), indicesVec.CvPtr, normals?.ToInputProxy() ?? default, colors?.ToInputProxy() ?? default, texCoords?.ToInputProxy() ?? default)); + filename, vertices.Proxy, indicesVec.CvPtr, normals.Proxy, colors.Proxy, texCoords.Proxy)); - GC.KeepAlive(vertices); - GC.KeepAlive(normals); - GC.KeepAlive(colors); - GC.KeepAlive(texCoords); + GC.KeepAlive(vertices.Source); + GC.KeepAlive(normals.Source); + GC.KeepAlive(colors.Source); + GC.KeepAlive(texCoords.Source); GC.KeepAlive(indicesArray); } } diff --git a/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs b/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs index ee5666674..fcbf2c52a 100644 --- a/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs +++ b/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs @@ -36,13 +36,11 @@ public ArucoDetector(Dictionary dictionary, DetectorParameters detectorParams, R /// Basic marker detection. /// public void DetectMarkers( - InputArray image, + InputArrayRef image, out Point2f[][] corners, out int[] ids, out Point2f[][] rejectedImgPoints) { - if (image is null) - throw new ArgumentNullException(nameof(image)); ThrowIfDisposed(); using var cornersVec = new VectorOfVectorPoint2f(); @@ -51,12 +49,12 @@ public void DetectMarkers( NativeMethods.HandleException( NativeMethods.aruco_ArucoDetector_detectMarkers( - Handle, image.ToInputProxy(), cornersVec.CvPtr, idsVec.CvPtr, rejectedVec.CvPtr)); + Handle, image.Proxy, cornersVec.CvPtr, idsVec.CvPtr, rejectedVec.CvPtr)); corners = cornersVec.ToArray(); ids = idsVec.ToArray(); rejectedImgPoints = rejectedVec.ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } } diff --git a/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs b/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs index 810609cec..3b52ec6ff 100644 --- a/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs +++ b/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs @@ -99,31 +99,24 @@ public bool LegacyPattern /// /// Generate the board image. /// - public void GenerateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) + public void GenerateImage(Size outSize, OutputArrayRef img, int marginSize = 0, int borderBits = 1) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.aruco_CharucoBoard_generateImage(Handle, outSize, img.ToOutputProxy(), marginSize, borderBits)); - img.Fix(); + NativeMethods.aruco_CharucoBoard_generateImage(Handle, outSize, img.Proxy, marginSize, borderBits)); } /// /// Check whether the ChArUco markers are collinear. /// - public bool CheckCharucoCornersCollinear(InputArray charucoIds) + public bool CheckCharucoCornersCollinear(InputArrayRef charucoIds) { - if (charucoIds is null) - throw new ArgumentNullException(nameof(charucoIds)); - charucoIds.ThrowIfDisposed(); ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.aruco_CharucoBoard_checkCharucoCornersCollinear(Handle, charucoIds.ToInputProxy(), out var ret)); - GC.KeepAlive(charucoIds); + NativeMethods.aruco_CharucoBoard_checkCharucoCornersCollinear(Handle, charucoIds.Proxy, out var ret)); + GC.KeepAlive(charucoIds.Source); return ret != 0; } } diff --git a/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs b/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs index fd0f67d07..c6f8f1e4c 100644 --- a/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs +++ b/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs @@ -12,7 +12,7 @@ public class CharucoDetector : CvObject /// Creates CharucoDetector with default parameters. /// public CharucoDetector(CharucoBoard board) - : this(board, null, null, 2, false, true, new DetectorParameters(), new RefineParameters()) + : this(board, default, default, 2, false, true, new DetectorParameters(), new RefineParameters()) { } @@ -21,8 +21,8 @@ public CharucoDetector(CharucoBoard board) /// public CharucoDetector( CharucoBoard board, - InputArray? cameraMatrix, - InputArray? distCoeffs, + InputArrayRef cameraMatrix, + InputArrayRef distCoeffs, int minMarkers = 2, bool tryRefineMarkers = false, bool checkMarkers = true, @@ -32,8 +32,8 @@ public CharucoDetector( if (board is null) throw new ArgumentNullException(nameof(board)); board.ThrowIfDisposed(); - if (cameraMatrix is null != distCoeffs is null) - throw new ArgumentException("cameraMatrix and distCoeffs must both be null or both non-null."); + if ((cameraMatrix.Proxy.Kind == (int)ArrayProxyKind.None) != (distCoeffs.Proxy.Kind == (int)ArrayProxyKind.None)) + throw new ArgumentException("cameraMatrix and distCoeffs must both be omitted or both provided."); var dp = detectorParams ?? new DetectorParameters(); var rp = refineParams ?? new RefineParameters(); @@ -41,8 +41,8 @@ public CharucoDetector( NativeMethods.HandleException( NativeMethods.aruco_CharucoDetector_create( board.CvPtr, - cameraMatrix?.ToInputProxy() ?? default, - distCoeffs?.ToInputProxy() ?? default, + cameraMatrix.Proxy, + distCoeffs.Proxy, minMarkers, tryRefineMarkers, checkMarkers, ref dp, ref rp, out var ptr)); @@ -51,22 +51,20 @@ public CharucoDetector( static h => NativeMethods.HandleException(NativeMethods.aruco_CharucoDetector_delete(h)))); GC.KeepAlive(board); - GC.KeepAlive(cameraMatrix); - GC.KeepAlive(distCoeffs); + GC.KeepAlive(cameraMatrix.Source); + GC.KeepAlive(distCoeffs.Source); } /// /// Detect aruco markers and interpolate position of ChArUco board corners. /// public void DetectBoard( - InputArray image, + InputArrayRef image, out Point2f[] charucoCorners, out int[] charucoIds, out Point2f[][] markerCorners, out int[] markerIds) { - if (image is null) - throw new ArgumentNullException(nameof(image)); ThrowIfDisposed(); using var charucoCornersVec = new StdVector(); @@ -76,7 +74,7 @@ public void DetectBoard( NativeMethods.HandleException( NativeMethods.aruco_CharucoDetector_detectBoard( - Handle, image.ToInputProxy(), + Handle, image.Proxy, charucoCornersVec.CvPtr, charucoIdsVec.CvPtr, markerCornersVec.CvPtr, markerIdsVec.CvPtr)); @@ -85,21 +83,19 @@ public void DetectBoard( markerCorners = markerCornersVec.ToArray(); markerIds = markerIdsVec.ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// /// Detect ChArUco Diamond markers. /// public void DetectDiamonds( - InputArray image, + InputArrayRef image, out Point2f[][] diamondCorners, out Vec4i[] diamondIds, out Point2f[][] markerCorners, out int[] markerIds) { - if (image is null) - throw new ArgumentNullException(nameof(image)); ThrowIfDisposed(); using var diamondCornersVec = new VectorOfVectorPoint2f(); @@ -109,7 +105,7 @@ public void DetectDiamonds( NativeMethods.HandleException( NativeMethods.aruco_CharucoDetector_detectDiamonds( - Handle, image.ToInputProxy(), + Handle, image.Proxy, diamondCornersVec.CvPtr, diamondIdsVec.CvPtr, markerCornersVec.CvPtr, markerIdsVec.CvPtr)); @@ -118,6 +114,6 @@ public void DetectDiamonds( markerCorners = markerCornersVec.ToArray(); markerIds = markerIdsVec.ToArray(); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } } diff --git a/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs b/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs index 1b75b3b00..8ec02a11f 100644 --- a/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs +++ b/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs @@ -19,7 +19,7 @@ public static partial class Aruco /// positions of marker corners on input image. /// For N detected markers, the dimensions of this array should be Nx4.The order of the corners should be clockwise. /// vector of identifiers for markers in markersCorners. Optional, if not provided, ids are not painted. - public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corners, IEnumerable ids) + public static void DrawDetectedMarkers(InputOutputArrayRef image, Point2f[][] corners, IEnumerable ids) { DrawDetectedMarkers(image, corners, ids, new Scalar(0, 255, 0)); } @@ -33,10 +33,8 @@ public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corne /// vector of identifiers for markers in markersCorners. Optional, if not provided, ids are not painted. /// color of marker borders. Rest of colors (text color and first corner color) /// are calculated based on this one to improve visualization. - public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corners, IEnumerable? ids, Scalar borderColor) + public static void DrawDetectedMarkers(InputOutputArrayRef image, Point2f[][] corners, IEnumerable? ids, Scalar borderColor) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (corners is null) throw new ArgumentNullException(nameof(corners)); @@ -45,7 +43,7 @@ public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corne { NativeMethods.HandleException( NativeMethods.aruco_drawDetectedMarkers( - image.ToInputOutputProxy(), cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), + image.Proxy, cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), IntPtr.Zero, 0, borderColor)); } else @@ -53,10 +51,10 @@ public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corne var idxArray = ids.ToArray(); NativeMethods.HandleException( NativeMethods.aruco_drawDetectedMarkers( - image.ToInputOutputProxy(), cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), + image.Proxy, cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), idxArray, idxArray.Length, borderColor)); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -100,7 +98,7 @@ public static Dictionary ReadDictionary(string dictionaryFile) /// input/output image. It must have 1 or 3 channels. The number of channels is not altered. /// positions of diamond corners in the same format returned by detectCharucoDiamond(). (e.g std::vector<std::vector<cv::Point2f>>). For N detected markers, the dimensions of this array should be Nx4. The order of the corners should be clockwise. /// vector of identifiers for diamonds in diamondCorners, in the same format returned by detectCharucoDiamond() (e.g. std::vector<Vec4i>). Optional, if not provided, ids are not painted. - public static void DrawDetectedDiamonds(InputOutputArray image, Point2f[][] diamondCorners, IEnumerable? diamondIds = null) + public static void DrawDetectedDiamonds(InputOutputArrayRef image, Point2f[][] diamondCorners, IEnumerable? diamondIds = null) { DrawDetectedDiamonds(image, diamondCorners, diamondIds, new Scalar(0, 0, 255)); } @@ -112,11 +110,9 @@ public static void DrawDetectedDiamonds(InputOutputArray image, Point2f[][] diam /// positions of diamond corners in the same format returned by detectCharucoDiamond(). (e.g std::vector<std::vector<cv::Point2f>>). For N detected markers, the dimensions of this array should be Nx4. The order of the corners should be clockwise. /// vector of identifiers for diamonds in diamondCorners, in the same format returned by detectCharucoDiamond() (e.g. std::vector<Vec4i>). Optional, if not provided, ids are not painted. /// color of marker borders. Rest of colors (text color and first corner color) are calculated based on this one. - public static void DrawDetectedDiamonds(InputOutputArray image, + public static void DrawDetectedDiamonds(InputOutputArrayRef image, Point2f[][] diamondCorners, IEnumerable? diamondIds, Scalar borderColor) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (diamondCorners is null) throw new ArgumentNullException(nameof(diamondCorners)); @@ -125,7 +121,7 @@ public static void DrawDetectedDiamonds(InputOutputArray image, if (diamondIds is null) { NativeMethods.HandleException( - NativeMethods.aruco_drawDetectedDiamonds(image.ToInputOutputProxy(), + NativeMethods.aruco_drawDetectedDiamonds(image.Proxy, cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), IntPtr.Zero, borderColor)); } @@ -134,12 +130,12 @@ public static void DrawDetectedDiamonds(InputOutputArray image, using var ids = new StdVector(diamondIds); NativeMethods.HandleException( - NativeMethods.aruco_drawDetectedDiamonds(image.ToInputOutputProxy(), + NativeMethods.aruco_drawDetectedDiamonds(image.Proxy, cornersAddress.GetPointer(), cornersAddress.GetDim1Length(), cornersAddress.GetDim2Lengths(), ids.CvPtr, borderColor)); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -148,7 +144,7 @@ public static void DrawDetectedDiamonds(InputOutputArray image, /// input/output image. It must have 1 or 3 channels. The number of channels is not altered. /// vector of detected charuco corners. /// list of identifiers for each corner in charucoCorners. - public static void DrawDetectedCornersCharuco(InputOutputArray image, Point2f[] charucoCorners, IEnumerable? charucoIds = null) + public static void DrawDetectedCornersCharuco(InputOutputArrayRef image, Point2f[] charucoCorners, IEnumerable? charucoIds = null) { DrawDetectedCornersCharuco(image, charucoCorners, charucoIds, new Scalar(0, 0, 255)); } @@ -160,11 +156,9 @@ public static void DrawDetectedCornersCharuco(InputOutputArray image, Point2f[] /// vector of detected charuco corners. /// list of identifiers for each corner in charucoCorners. /// color of the square surrounding each corner. - public static void DrawDetectedCornersCharuco(InputOutputArray image, + public static void DrawDetectedCornersCharuco(InputOutputArrayRef image, Point2f[] charucoCorners, IEnumerable? charucoIds, Scalar cornerColor) { - if (image is null) - throw new ArgumentNullException(nameof(image)); if (charucoCorners is null) throw new ArgumentNullException(nameof(charucoCorners)); @@ -173,7 +167,7 @@ public static void DrawDetectedCornersCharuco(InputOutputArray image, if (charucoIds is null) { NativeMethods.HandleException( - NativeMethods.aruco_drawDetectedCornersCharuco(image.ToInputOutputProxy(), + NativeMethods.aruco_drawDetectedCornersCharuco(image.Proxy, charucoCornersVec.CvPtr, IntPtr.Zero, cornerColor)); } else @@ -181,11 +175,11 @@ public static void DrawDetectedCornersCharuco(InputOutputArray image, using var ids = new StdVector(charucoIds); NativeMethods.HandleException( - NativeMethods.aruco_drawDetectedCornersCharuco(image.ToInputOutputProxy(), + NativeMethods.aruco_drawDetectedCornersCharuco(image.Proxy, charucoCornersVec.CvPtr, ids.CvPtr, cornerColor)); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } } } diff --git a/src/OpenCvSharp/Modules/aruco/Dictionary.cs b/src/OpenCvSharp/Modules/aruco/Dictionary.cs index 2ee878500..031c4be0e 100644 --- a/src/OpenCvSharp/Modules/aruco/Dictionary.cs +++ b/src/OpenCvSharp/Modules/aruco/Dictionary.cs @@ -117,15 +117,12 @@ public bool Identify(Mat onlyBits, out int idx, out int rotation, double maxCorr /// /// /// - public int GetDistanceToId(InputArray bits, int id, bool allRotations = true) + public int GetDistanceToId(InputArrayRef bits, int id, bool allRotations = true) { - if (bits is null) - throw new ArgumentNullException(nameof(bits)); - bits.ThrowIfDisposed(); ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.aruco_Dictionary_getDistanceToId(Handle, bits.ToInputProxy(), id, allRotations ? 1 : 0, out var ret)); + NativeMethods.aruco_Dictionary_getDistanceToId(Handle, bits.Proxy, id, allRotations ? 1 : 0, out var ret)); return ret; } @@ -137,15 +134,12 @@ public int GetDistanceToId(InputArray bits, int id, bool allRotations = true) /// /// /// - public void GenerateImageMarker(int id, int sidePixels, OutputArray img, int borderBits = 1) + public void GenerateImageMarker(int id, int sidePixels, OutputArrayRef img, int borderBits = 1) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.aruco_Dictionary_generateImageMarker(Handle, id, sidePixels, img.ToOutputProxy(), borderBits)); + NativeMethods.aruco_Dictionary_generateImageMarker(Handle, id, sidePixels, img.Proxy, borderBits)); } diff --git a/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs b/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs index 4208b576d..84c47f81c 100644 --- a/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs +++ b/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs @@ -79,23 +79,19 @@ public void SetDetectorScales(IEnumerable sizes) /// optional output vector of vertices of the found barcode rectangle. Will be empty if not found. /// list of decoded string. /// list of decoded types. - public void DetectAndDecode(InputArray inputImage, out Point2f[] points, out string[] results, out string[] types) + public void DetectAndDecode(InputArrayRef inputImage, out Point2f[] points, out string[] results, out string[] types) { - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - inputImage.ThrowIfDisposed(); - using var pointsVec = new StdVector(); using var infos = new VectorOfString(); using var resultTypes = new VectorOfString(); NativeMethods.HandleException( NativeMethods.barcode_BarcodeDetector_detectAndDecodeWithType( - Handle, inputImage.ToInputProxy(), pointsVec.CvPtr, infos.CvPtr, resultTypes.CvPtr)); + Handle, inputImage.Proxy, pointsVec.CvPtr, infos.CvPtr, resultTypes.CvPtr)); points = pointsVec.ToArray(); results = infos.ToArray(); types = resultTypes.ToArray(); - GC.KeepAlive(inputImage); + GC.KeepAlive(inputImage.Source); } } diff --git a/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs b/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs index 206449ba8..ad080a646 100644 --- a/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs +++ b/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs @@ -75,15 +75,12 @@ public bool GetEnableSoftmaxPostProcessing() /// The input image. /// Top-1 predicted class id. /// Top-1 prediction confidence. - public void Classify(InputArray frame, out int classId, out float conf) + public void Classify(InputArrayRef frame, out int classId, out float conf) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.dnn_ClassificationModel_classify(Handle, frame.ToInputProxy(), out classId, out conf)); - GC.KeepAlive(frame); + NativeMethods.dnn_ClassificationModel_classify(Handle, frame.Proxy, out classId, out conf)); + GC.KeepAlive(frame.Source); } } diff --git a/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs b/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs index dd823761e..c3e0e6c8d 100644 --- a/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs +++ b/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs @@ -264,19 +264,16 @@ public static Mat BlobFromImages( /// input image (all with 1-, 3- or 4-channels). /// params with preprocessing parameters. If null, default params are used. /// 4-dimensional Mat. - public static Mat BlobFromImageWithParams(InputArray image, Image2BlobParams? param = null) + public static Mat BlobFromImageWithParams(InputArrayRef image, Image2BlobParams? param = null) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); param ??= new Image2BlobParams(); NativeMethods.HandleException( NativeMethods.dnn_blobFromImageWithParams( - image.ToInputProxy(), param.ScaleFactor, param.Size, param.Mean, + image.Proxy, param.ScaleFactor, param.Size, param.Mean, param.SwapRB ? 1 : 0, (int)param.Depth, (int)param.DataLayout, (int)param.PaddingMode, param.BorderValue, out var ret)); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); return new Mat(ret); } diff --git a/src/OpenCvSharp/Modules/dnn/DetectionModel.cs b/src/OpenCvSharp/Modules/dnn/DetectionModel.cs index b13665bce..0a4e6d0c8 100644 --- a/src/OpenCvSharp/Modules/dnn/DetectionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/DetectionModel.cs @@ -83,22 +83,19 @@ public bool GetNmsAcrossClasses() /// A threshold used to filter boxes by confidences. /// A threshold used in non maximum suppression. public void Detect( - InputArray frame, out int[] classIds, out float[] confidences, out Rect[] boxes, + InputArrayRef frame, out int[] classIds, out float[] confidences, out Rect[] boxes, float confThreshold = 0.5f, float nmsThreshold = 0.0f) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var classIdsVec = new StdVector(); using var confidencesVec = new StdVector(); using var boxesVec = new StdVector(); NativeMethods.HandleException( NativeMethods.dnn_DetectionModel_detect( - Handle, frame.ToInputProxy(), classIdsVec.CvPtr, confidencesVec.CvPtr, boxesVec.CvPtr, + Handle, frame.Proxy, classIdsVec.CvPtr, confidencesVec.CvPtr, boxesVec.CvPtr, confThreshold, nmsThreshold)); - GC.KeepAlive(frame); + GC.KeepAlive(frame.Source); classIds = classIdsVec.ToArray(); confidences = confidencesVec.ToArray(); diff --git a/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs b/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs index ad4304cbd..d7ff51c15 100644 --- a/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs +++ b/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs @@ -8,7 +8,7 @@ namespace OpenCvSharp.Dnn; /// Processing params of image to blob. /// It includes all possible image processing operations and corresponding parameters. /// -/// +/// public class Image2BlobParams { /// diff --git a/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs b/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs index ab8493936..d36a9f85f 100644 --- a/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs +++ b/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs @@ -53,17 +53,14 @@ public KeypointsModel(Net network) /// The input image. /// minimum confidence threshold to select a keypoint. /// a vector holding the x and y coordinates of each detected keypoint. - public Point2f[] Estimate(InputArray frame, float thresh = 0.5f) + public Point2f[] Estimate(InputArrayRef frame, float thresh = 0.5f) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var keypointsVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.dnn_KeypointsModel_estimate(Handle, frame.ToInputProxy(), keypointsVec.CvPtr, thresh)); - GC.KeepAlive(frame); + NativeMethods.dnn_KeypointsModel_estimate(Handle, frame.Proxy, keypointsVec.CvPtr, thresh)); + GC.KeepAlive(frame.Source); return keypointsVec.ToArray(); } } diff --git a/src/OpenCvSharp/Modules/dnn/Model.cs b/src/OpenCvSharp/Modules/dnn/Model.cs index 053acea07..c8fcd7609 100644 --- a/src/OpenCvSharp/Modules/dnn/Model.cs +++ b/src/OpenCvSharp/Modules/dnn/Model.cs @@ -169,17 +169,14 @@ public void SetInputParams(double scale = 1.0, Size? size = null, Scalar? mean = /// /// The input image. /// Allocated output blobs, which will store results of the computation. - public Mat[] Predict(InputArray frame) + public Mat[] Predict(InputArrayRef frame) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var outsVec = new VectorOfMat(); NativeMethods.HandleException( - NativeMethods.dnn_Model_predict(Handle, frame.ToInputProxy(), outsVec.CvPtr)); - GC.KeepAlive(frame); + NativeMethods.dnn_Model_predict(Handle, frame.Proxy, outsVec.CvPtr)); + GC.KeepAlive(frame.Source); return outsVec.ToArray(); } diff --git a/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs b/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs index f119ef7e8..c7c5ee5e9 100644 --- a/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs +++ b/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs @@ -51,19 +51,12 @@ public SegmentationModel(Net network) /// /// The input image. /// Allocated class prediction for each pixel. - public void Segment(InputArray frame, OutputArray mask) + public void Segment(InputArrayRef frame, OutputArrayRef mask) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - frame.ThrowIfDisposed(); - mask.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.dnn_SegmentationModel_segment(Handle, frame.ToInputProxy(), mask.ToOutputProxy())); - GC.KeepAlive(frame); - mask.Fix(); + NativeMethods.dnn_SegmentationModel_segment(Handle, frame.Proxy, mask.Proxy)); + GC.KeepAlive(frame.Source); } } diff --git a/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs b/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs index dba1ef91a..022b7981a 100644 --- a/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs @@ -30,18 +30,15 @@ protected TextDetectionModel() /// The input image. /// array with detections' quadrangles (4 points per result). /// array with detection confidences. - public void Detect(InputArray frame, out Point[][] detections, out float[] confidences) + public void Detect(InputArrayRef frame, out Point[][] detections, out float[] confidences) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var detectionsVec = new VectorOfVectorPoint(); using var confidencesVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.dnn_TextDetectionModel_detect(Handle, frame.ToInputProxy(), detectionsVec.CvPtr, confidencesVec.CvPtr)); - GC.KeepAlive(frame); + NativeMethods.dnn_TextDetectionModel_detect(Handle, frame.Proxy, detectionsVec.CvPtr, confidencesVec.CvPtr)); + GC.KeepAlive(frame.Source); detections = detectionsVec.ToArray(); confidences = confidencesVec.ToArray(); @@ -54,18 +51,15 @@ public void Detect(InputArray frame, out Point[][] detections, out float[] confi /// The input image. /// array with detections' RotatedRect results. /// array with detection confidences. - public void DetectTextRectangles(InputArray frame, out RotatedRect[] detections, out float[] confidences) + public void DetectTextRectangles(InputArrayRef frame, out RotatedRect[] detections, out float[] confidences) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var detectionsVec = new StdVector(); using var confidencesVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.dnn_TextDetectionModel_detectTextRectangles(Handle, frame.ToInputProxy(), detectionsVec.CvPtr, confidencesVec.CvPtr)); - GC.KeepAlive(frame); + NativeMethods.dnn_TextDetectionModel_detectTextRectangles(Handle, frame.Proxy, detectionsVec.CvPtr, confidencesVec.CvPtr)); + GC.KeepAlive(frame.Source); detections = detectionsVec.ToArray(); confidences = confidencesVec.ToArray(); diff --git a/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs b/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs index 495c239b9..1bd574961 100644 --- a/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs @@ -122,17 +122,14 @@ public void SetVocabulary(IEnumerable vocabulary) /// /// The input image. /// The text recognition result. - public string Recognize(InputArray frame) + public string Recognize(InputArrayRef frame) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfDisposed(); using var result = new StdString(); NativeMethods.HandleException( - NativeMethods.dnn_TextRecognitionModel_recognize(Handle, frame.ToInputProxy(), result.CvPtr)); - GC.KeepAlive(frame); + NativeMethods.dnn_TextRecognitionModel_recognize(Handle, frame.Proxy, result.CvPtr)); + GC.KeepAlive(frame.Source); return result.ToString(); } } diff --git a/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs b/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs index 028a0e2d6..e0c3dbfda 100644 --- a/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs +++ b/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs @@ -135,21 +135,14 @@ public void SetPreferableTarget(Target targetId) /// /// Image to upscale /// Destination upscaled image - public void Upsample(InputArray img, OutputArray result) + public void Upsample(InputArrayRef img, OutputArrayRef result) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - img.ThrowIfDisposed(); - result.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.dnn_superres_DnnSuperResImpl_upsample(Handle, img.ToInputProxy(), result.ToOutputProxy())); + NativeMethods.dnn_superres_DnnSuperResImpl_upsample(Handle, img.Proxy, result.Proxy)); - GC.KeepAlive(img); - result.Fix(); + GC.KeepAlive(img.Source); } /// @@ -161,11 +154,9 @@ public void Upsample(InputArray img, OutputArray result) /// Names of the output nodes in the neural network [SuppressMessage("Maintainability", "CA1508: Avoid dead conditional code")] public void UpsampleMultioutput( - InputArray img, out Mat[] imgsNew, IEnumerable scaleFactors, IEnumerable nodeNames) + InputArrayRef img, out Mat[] imgsNew, IEnumerable scaleFactors, IEnumerable nodeNames) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); if (scaleFactors is null) throw new ArgumentNullException(nameof(scaleFactors)); if (nodeNames is null) @@ -176,7 +167,7 @@ public void UpsampleMultioutput( var nodeNamesArray = nodeNames as string[] ?? nodeNames.ToArray(); NativeMethods.HandleException( NativeMethods.dnn_superres_DnnSuperResImpl_upsampleMultioutput( - Handle, img.ToInputProxy(), imgsNewVec.CvPtr, + Handle, img.Proxy, imgsNewVec.CvPtr, scaleFactorsArray, scaleFactorsArray.Length, nodeNamesArray, nodeNamesArray.Length)); diff --git a/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs b/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs index 4b79069cb..f07b78144 100644 --- a/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs +++ b/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs @@ -64,16 +64,13 @@ public void Update(IEnumerable src, IEnumerable labels) /// /// /// - public virtual int Predict(InputArray src) + public virtual int Predict(InputArrayRef src) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.face_FaceRecognizer_predict1(Handle, src.ToInputProxy(), out var ret)); - GC.KeepAlive(src); + NativeMethods.face_FaceRecognizer_predict1(Handle, src.Proxy, out var ret)); + GC.KeepAlive(src.Source); return ret; } @@ -83,16 +80,13 @@ public virtual int Predict(InputArray src) /// /// /// - public virtual void Predict(InputArray src, out int label, out double confidence) + public virtual void Predict(InputArrayRef src, out int label, out double confidence) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.face_FaceRecognizer_predict2(Handle, src.ToInputProxy(), out label, out confidence)); - GC.KeepAlive(src); + NativeMethods.face_FaceRecognizer_predict2(Handle, src.Proxy, out label, out confidence)); + GC.KeepAlive(src.Source); } /// diff --git a/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs b/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs index 2164a888d..d1fa5d5e1 100644 --- a/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs +++ b/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs @@ -39,27 +39,21 @@ public virtual void LoadModel(string model) /// The detected landmark points for each faces. /// public virtual bool Fit( - InputArray image, - InputArray faces, + InputArrayRef image, + InputArrayRef faces, out Point2f[][] landmarks) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (faces is null) - throw new ArgumentNullException(nameof(faces)); - image.ThrowIfDisposed(); - faces.ThrowIfDisposed(); int ret; using (var landmarx = new VectorOfVectorPoint2f()) { NativeMethods.HandleException( - NativeMethods.face_Facemark_fit(Handle, image.ToInputProxy(), faces.ToInputProxy(), landmarx.CvPtr, out ret)); + NativeMethods.face_Facemark_fit(Handle, image.Proxy, faces.Proxy, landmarx.CvPtr, out ret)); landmarks = landmarx.ToArray(); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/features/ANNIndex.cs b/src/OpenCvSharp/Modules/features/ANNIndex.cs index 4b9f1ab6e..a0d936310 100644 --- a/src/OpenCvSharp/Modules/features/ANNIndex.cs +++ b/src/OpenCvSharp/Modules/features/ANNIndex.cs @@ -34,15 +34,12 @@ public static ANNIndex Create(int dim, ANNIndexDistance distType = ANNIndexDista /// Adds feature vectors to the index. /// /// Matrix containing the feature vectors to index (num_features x feature_dimension). - public void AddItems(InputArray features) + public void AddItems(InputArrayRef features) { ThrowIfDisposed(); - if (features is null) - throw new ArgumentNullException(nameof(features)); - features.ThrowIfDisposed(); - NativeMethods.HandleException(NativeMethods.features_ANNIndex_addItems(Handle, features.ToInputProxy())); - GC.KeepAlive(features); + NativeMethods.HandleException(NativeMethods.features_ANNIndex_addItems(Handle, features.Proxy)); + GC.KeepAlive(features.Source); } /// @@ -63,24 +60,13 @@ public void Build(int trees = -1) /// Output matrix that will contain the distances to the K-nearest neighbors found. /// Number of nearest neighbors to search for. /// The maximum number of nodes to inspect; defaults to trees x knn when -1. - public void KnnSearch(InputArray query, OutputArray indices, OutputArray dists, int knn, int searchK = -1) + public void KnnSearch(InputArrayRef query, OutputArrayRef indices, OutputArrayRef dists, int knn, int searchK = -1) { ThrowIfDisposed(); - if (query is null) - throw new ArgumentNullException(nameof(query)); - if (indices is null) - throw new ArgumentNullException(nameof(indices)); - if (dists is null) - throw new ArgumentNullException(nameof(dists)); - query.ThrowIfDisposed(); - indices.ThrowIfNotReady(); - dists.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.features_ANNIndex_knnSearch(Handle, query.ToInputProxy(), indices.ToOutputProxy(), dists.ToOutputProxy(), knn, searchK)); - GC.KeepAlive(query); - indices.Fix(); - dists.Fix(); + NativeMethods.features_ANNIndex_knnSearch(Handle, query.Proxy, indices.Proxy, dists.Proxy, knn, searchK)); + GC.KeepAlive(query.Source); } /// diff --git a/src/OpenCvSharp/Modules/features/Feature2D.cs b/src/OpenCvSharp/Modules/features/Feature2D.cs index 1c264b472..69e21594d 100644 --- a/src/OpenCvSharp/Modules/features/Feature2D.cs +++ b/src/OpenCvSharp/Modules/features/Feature2D.cs @@ -116,24 +116,21 @@ public KeyPoint[] Detect(Mat image, Mat? mask = null) /// Mask specifying where to look for keypoints (optional). /// Must be a char matrix with non-zero values in the region of interest. /// The detected keypoints. - public KeyPoint[] Detect(InputArray image, InputArray? mask = null) + public KeyPoint[] Detect(InputArrayRef image, InputArrayRef mask = default) { - if (image is null) - throw new ArgumentNullException(nameof(image)); ThrowIfDisposed(); - image.ThrowIfDisposed(); try { using var keypoints = new StdVector(); NativeMethods.HandleException( - NativeMethods.features_Feature2D_detect_InputArray(Handle, image.ToInputProxy(), keypoints.CvPtr, mask?.ToInputProxy() ?? default)); + NativeMethods.features_Feature2D_detect_InputArray(Handle, image.Proxy, keypoints.CvPtr, mask.Proxy)); return keypoints.ToArray(); } finally { - GC.KeepAlive(image); - GC.KeepAlive(mask); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); } } @@ -178,21 +175,17 @@ public KeyPoint[][] Detect(IEnumerable images, IEnumerable? masks = nu /// The image. /// The input keypoints. Keypoints for which a descriptor cannot be computed are removed. /// Computed descriptors. Row i is the descriptor for KeyPoint i.param> - public virtual void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray descriptors) + public virtual void Compute(InputArrayRef image, ref KeyPoint[] keypoints, OutputArrayRef descriptors) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (descriptors is null) - throw new ArgumentNullException(nameof(descriptors)); ThrowIfDisposed(); using var keypointsVec = new StdVector(keypoints); NativeMethods.HandleException( - NativeMethods.features_Feature2D_compute1(Handle, image.ToInputProxy(), keypointsVec.CvPtr, descriptors.ToOutputProxy())); + NativeMethods.features_Feature2D_compute1(Handle, image.Proxy, keypointsVec.CvPtr, descriptors.Proxy)); keypoints = keypointsVec.ToArray(); - GC.KeepAlive(image); - GC.KeepAlive(descriptors); + GC.KeepAlive(image.Source); + GC.KeepAlive(descriptors.Source); } /// @@ -234,30 +227,23 @@ public virtual void Compute(IEnumerable images, ref KeyPoint[][] keypoints, /// /// public virtual void DetectAndCompute( - InputArray image, - InputArray? mask, + InputArrayRef image, + InputArrayRef mask, out KeyPoint[] keypoints, - OutputArray descriptors, + OutputArrayRef descriptors, bool useProvidedKeypoints = false) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (descriptors is null) - throw new ArgumentNullException(nameof(descriptors)); - image.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); using var keypointsVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.features_Feature2D_detectAndCompute(Handle, image.ToInputProxy(), mask?.ToInputProxy() ?? default, keypointsVec.CvPtr, descriptors.ToOutputProxy(), useProvidedKeypoints ? 1 : 0)); + NativeMethods.features_Feature2D_detectAndCompute(Handle, image.Proxy, mask.Proxy, keypointsVec.CvPtr, descriptors.Proxy, useProvidedKeypoints ? 1 : 0)); keypoints = keypointsVec.ToArray(); - GC.KeepAlive(image); - GC.KeepAlive(mask); - descriptors.Fix(); - GC.KeepAlive(descriptors); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(descriptors.Source); } /// diff --git a/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs b/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs index 106550950..fe62f46ac 100644 --- a/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs +++ b/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs @@ -63,20 +63,14 @@ public static LightGlueMatcher CreateFromMemory(byte[] modelData, float scoreThr /// Train image keypoints (Nx2 float matrix with x,y coordinates). /// Size of the query image (width, height). /// Size of the train image (width, height). - public void SetPairInfo(InputArray queryKpts, InputArray trainKpts, Size queryImageSize = default, Size trainImageSize = default) + public void SetPairInfo(InputArrayRef queryKpts, InputArrayRef trainKpts, Size queryImageSize = default, Size trainImageSize = default) { ThrowIfDisposed(); - if (queryKpts is null) - throw new ArgumentNullException(nameof(queryKpts)); - if (trainKpts is null) - throw new ArgumentNullException(nameof(trainKpts)); - queryKpts.ThrowIfDisposed(); - trainKpts.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.features_LightGlueMatcher_setPairInfo(Handle, queryKpts.ToInputProxy(), trainKpts.ToInputProxy(), queryImageSize, trainImageSize)); - GC.KeepAlive(queryKpts); - GC.KeepAlive(trainKpts); + NativeMethods.features_LightGlueMatcher_setPairInfo(Handle, queryKpts.Proxy, trainKpts.Proxy, queryImageSize, trainImageSize)); + GC.KeepAlive(queryKpts.Source); + GC.KeepAlive(trainKpts.Source); } /// diff --git a/src/OpenCvSharp/Modules/features/MSER.cs b/src/OpenCvSharp/Modules/features/MSER.cs index 7e4e78431..19f8cd8b6 100644 --- a/src/OpenCvSharp/Modules/features/MSER.cs +++ b/src/OpenCvSharp/Modules/features/MSER.cs @@ -142,23 +142,20 @@ public bool Pass2Only /// resulting list of point sets /// resulting bounding boxes public virtual void DetectRegions( - InputArray image, out Point[][] msers, out Rect[] bboxes) + InputArrayRef image, out Point[][] msers, out Rect[] bboxes) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); using (var msersVec = new VectorOfVectorPoint()) using (var bboxesVec = new StdVector()) { NativeMethods.HandleException( - NativeMethods.features_MSER_detectRegions(Handle, image.ToInputProxy(), msersVec.CvPtr, bboxesVec.CvPtr)); + NativeMethods.features_MSER_detectRegions(Handle, image.Proxy, msersVec.CvPtr, bboxesVec.CvPtr)); msers = msersVec.ToArray(); bboxes = bboxesVec.ToArray(); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } #endregion diff --git a/src/OpenCvSharp/Modules/flann/Index.cs b/src/OpenCvSharp/Modules/flann/Index.cs index 45b5f43b4..33f373575 100644 --- a/src/OpenCvSharp/Modules/flann/Index.cs +++ b/src/OpenCvSharp/Modules/flann/Index.cs @@ -13,17 +13,15 @@ public class Index : CvObject /// features – Matrix of type CV _ 32F containing the features(points) to index. The size of the matrix is num _ features x feature _ dimensionality. /// Structure containing the index parameters. The type of index that will be constructed depends on the type of this parameter. /// - public Index(InputArray features, IndexParams @params, FlannDistance distType = FlannDistance.L2) + public Index(InputArrayRef features, IndexParams @params, FlannDistance distType = FlannDistance.L2) { - if (features is null) - throw new ArgumentNullException(nameof(features)); if (@params is null) throw new ArgumentNullException(nameof(@params)); NativeMethods.HandleException( - NativeMethods.flann_Index_new(features.ToInputProxy(), @params.CvPtr, (int)distType, out var p)); + NativeMethods.flann_Index_new(features.Proxy, @params.CvPtr, (int)distType, out var p)); - GC.KeepAlive(features); + GC.KeepAlive(features.Source); GC.KeepAlive(@params); if (p == IntPtr.Zero) throw new OpenCvSharpException("Failed to create Index"); diff --git a/src/OpenCvSharp/Modules/img_hash/AverageHash.cs b/src/OpenCvSharp/Modules/img_hash/AverageHash.cs index 1b4231d12..684a4aedb 100644 --- a/src/OpenCvSharp/Modules/img_hash/AverageHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/AverageHash.cs @@ -36,7 +36,7 @@ public static AverageHash Create() /// input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. /// Hash value of input, it will contain 16 hex decimal number, return type is CV_8U /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); }*/ diff --git a/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs b/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs index b5b807edb..c9f428bd2 100644 --- a/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs @@ -63,7 +63,7 @@ public double[] GetMean() /// input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. /// Hash value of input, it will contain 16 hex decimal number, return type is CV_8U /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); }*/ diff --git a/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs b/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs index 75f86b08e..a01010ee6 100644 --- a/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs @@ -31,7 +31,7 @@ public static ColorMomentHash Create() // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs b/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs index 64038c640..ba76df8fe 100644 --- a/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs +++ b/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs @@ -18,23 +18,14 @@ protected ImgHashBase(IntPtr smartPtr, IntPtr rawPtr, Action release) /// input image want to compute hash value /// hash of the image /// - public virtual void Compute(InputArray inputArr, OutputArray outputArr) + public virtual void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { ThrowIfDisposed(); - if (inputArr is null) - throw new ArgumentNullException(nameof(inputArr)); - if (outputArr is null) - throw new ArgumentNullException(nameof(outputArr)); - - inputArr.ThrowIfDisposed(); - outputArr.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.img_hash_ImgHashBase_compute(Handle, inputArr.ToInputProxy(), outputArr.ToOutputProxy())); + NativeMethods.img_hash_ImgHashBase_compute(Handle, inputArr.Proxy, outputArr.Proxy)); - GC.KeepAlive(inputArr); - outputArr.Fix(); + GC.KeepAlive(inputArr.Source); } /// @@ -43,22 +34,14 @@ public virtual void Compute(InputArray inputArr, OutputArray outputArr) /// Hash value one /// Hash value two /// value indicate similarity between inOne and inTwo, the meaning of the value vary from algorithms to algorithms - public virtual double Compare(InputArray hashOne, InputArray hashTwo) + public virtual double Compare(InputArrayRef hashOne, InputArrayRef hashTwo) { ThrowIfDisposed(); - if (hashOne is null) - throw new ArgumentNullException(nameof(hashOne)); - if (hashTwo is null) - throw new ArgumentNullException(nameof(hashTwo)); - - hashOne.ThrowIfDisposed(); - hashTwo.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.img_hash_ImgHashBase_compare(Handle, hashOne.ToInputProxy(), hashTwo.ToInputProxy(), out var ret)); - GC.KeepAlive(hashOne); - GC.KeepAlive(hashOne); + NativeMethods.img_hash_ImgHashBase_compare(Handle, hashOne.Proxy, hashTwo.Proxy, out var ret)); + GC.KeepAlive(hashOne.Source); + GC.KeepAlive(hashOne.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs b/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs index 41b8bb66a..d1415f3f9 100644 --- a/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs @@ -89,7 +89,7 @@ public float Scale // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/PHash.cs b/src/OpenCvSharp/Modules/img_hash/PHash.cs index 24a9fe160..1393a91c0 100644 --- a/src/OpenCvSharp/Modules/img_hash/PHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/PHash.cs @@ -31,7 +31,7 @@ public static PHash Create() // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs b/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs index 7c2614a9e..9d5c68598 100644 --- a/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs @@ -75,7 +75,7 @@ public int NumOfAngleLine // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArray inputArr, OutputArray outputArr) + public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/imgproc/CLAHE.cs b/src/OpenCvSharp/Modules/imgproc/CLAHE.cs index 29f4ef617..92e639b10 100644 --- a/src/OpenCvSharp/Modules/imgproc/CLAHE.cs +++ b/src/OpenCvSharp/Modules/imgproc/CLAHE.cs @@ -42,23 +42,16 @@ public static CLAHE Create(double clipLimit = 40.0, Size? tileGridSize = null) /// /// Source image of type CV_8UC1 or CV_16UC1. /// Destination image. - public void Apply(InputArray src, OutputArray dst) + public void Apply(InputArrayRef src, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.imgproc_CLAHE_apply(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.imgproc_CLAHE_apply(Handle, src.Proxy, dst.Proxy)); - dst.Fix(); // Handle (a SafeHandle) keeps this alive across the call, so no GC.KeepAlive(this) is needed. - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// diff --git a/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs b/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs index 082820510..89178de66 100644 --- a/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs +++ b/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs @@ -1,7 +1,7 @@ namespace OpenCvSharp; /// -/// Flags for the FontFace-based +/// Flags for the FontFace-based /// and (OpenCV 5). /// [Flags] diff --git a/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs b/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs index a8a6d7787..ca2e50be7 100644 --- a/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs +++ b/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs @@ -1,7 +1,7 @@ namespace OpenCvSharp; /// -/// Parameters for the OpenCV 5 overload. +/// Parameters for the OpenCV 5 overload. /// Mirrors cv::Filter2DParams; all fields are optional and default to the OpenCV defaults. /// public class Filter2DParams diff --git a/src/OpenCvSharp/Modules/imgproc/FontFace.cs b/src/OpenCvSharp/Modules/imgproc/FontFace.cs index 3619381b2..9f7b45b40 100644 --- a/src/OpenCvSharp/Modules/imgproc/FontFace.cs +++ b/src/OpenCvSharp/Modules/imgproc/FontFace.cs @@ -4,7 +4,7 @@ namespace OpenCvSharp; /// -/// TrueType font face used by the FontFace-based +/// TrueType font face used by the FontFace-based /// and (OpenCV 5). /// public class FontFace : CvObject diff --git a/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs b/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs index 74ffc6239..05383c535 100644 --- a/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs +++ b/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs @@ -123,17 +123,14 @@ public int MaxBufferSize /// /// /// - public void SetTemplate(InputArray templ, Point? templCenter = null) + public void SetTemplate(InputArrayRef templ, Point? templCenter = null) { ThrowIfDisposed(); - if (templ is null) - throw new ArgumentNullException(nameof(templ)); - templ.ThrowIfDisposed(); var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( - NativeMethods.imgproc_GeneralizedHough_setTemplate1(Handle, templ.ToInputProxy(), templCenterValue)); - GC.KeepAlive(templ); + NativeMethods.imgproc_GeneralizedHough_setTemplate1(Handle, templ.Proxy, templCenterValue)); + GC.KeepAlive(templ.Source); } /// @@ -143,27 +140,18 @@ public void SetTemplate(InputArray templ, Point? templCenter = null) /// /// /// - public virtual void SetTemplate(InputArray edges, InputArray dx, InputArray dy, Point? templCenter = null) + public virtual void SetTemplate(InputArrayRef edges, InputArrayRef dx, InputArrayRef dy, Point? templCenter = null) { ThrowIfDisposed(); - if (edges is null) - throw new ArgumentNullException(nameof(edges)); - if (dx is null) - throw new ArgumentNullException(nameof(dx)); - if (dy is null) - throw new ArgumentNullException(nameof(dy)); - edges.ThrowIfDisposed(); - dx.ThrowIfDisposed(); - dy.ThrowIfDisposed(); var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); NativeMethods.HandleException( NativeMethods.imgproc_GeneralizedHough_setTemplate2( - Handle, edges.ToInputProxy(), dx.ToInputProxy(), dy.ToInputProxy(), templCenterValue)); + Handle, edges.Proxy, dx.Proxy, dy.Proxy, templCenterValue)); - GC.KeepAlive(edges); - GC.KeepAlive(dx); - GC.KeepAlive(dy); + GC.KeepAlive(edges.Source); + GC.KeepAlive(dx.Source); + GC.KeepAlive(dy.Source); } /// @@ -173,25 +161,15 @@ public virtual void SetTemplate(InputArray edges, InputArray dx, InputArray dy, /// /// public virtual void Detect( - InputArray image, OutputArray positions, OutputArray? votes = null) + InputArrayRef image, OutputArrayRef positions, OutputArrayRef votes = default) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (positions is null) - throw new ArgumentNullException(nameof(positions)); - image.ThrowIfDisposed(); - positions.ThrowIfNotReady(); - votes?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_GeneralizedHough_detect1( - Handle, image.ToInputProxy(), positions.ToOutputProxy(), votes?.ToOutputProxy() ?? default)); + Handle, image.Proxy, positions.Proxy, votes.Proxy)); - GC.KeepAlive(image); - GC.KeepAlive(positions); - GC.KeepAlive(votes); - positions.Fix(); - votes?.Fix(); + GC.KeepAlive(image.Source); + GC.KeepAlive(positions.Source); + GC.KeepAlive(votes.Source); } /// @@ -203,32 +181,16 @@ public virtual void Detect( /// /// public virtual void Detect( - InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray? votes = null) + InputArrayRef edges, InputArrayRef dx, InputArrayRef dy, OutputArrayRef positions, OutputArrayRef votes = default) { - if (edges is null) - throw new ArgumentNullException(nameof(edges)); - if (dx is null) - throw new ArgumentNullException(nameof(dx)); - if (dy is null) - throw new ArgumentNullException(nameof(dy)); - if (positions is null) - throw new ArgumentNullException(nameof(positions)); - edges.ThrowIfDisposed(); - dx.ThrowIfDisposed(); - dy.ThrowIfDisposed(); - positions.ThrowIfNotReady(); - votes?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.imgproc_GeneralizedHough_detect2( - Handle, edges.ToInputProxy(), dx.ToInputProxy(), dy.ToInputProxy(), positions.ToOutputProxy(), votes?.ToOutputProxy() ?? default)); - - GC.KeepAlive(edges); - GC.KeepAlive(dx); - GC.KeepAlive(dy); - GC.KeepAlive(positions); - GC.KeepAlive(votes); - positions.Fix(); - votes?.Fix(); + Handle, edges.Proxy, dx.Proxy, dy.Proxy, positions.Proxy, votes.Proxy)); + + GC.KeepAlive(edges.Source); + GC.KeepAlive(dx.Source); + GC.KeepAlive(dy.Source); + GC.KeepAlive(positions.Source); + GC.KeepAlive(votes.Source); } } diff --git a/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs b/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs index 3c0a51553..bbc458df2 100644 --- a/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs +++ b/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs @@ -134,15 +134,13 @@ public IntelligentScissorsMB SetEdgeFeatureCannyParameters( /// /// input image. Type is #CV_8UC1 / #CV_8UC3 /// - public IntelligentScissorsMB ApplyImage(InputArray image) + public IntelligentScissorsMB ApplyImage(InputArrayRef image) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); NativeMethods.HandleException( NativeMethods.imgproc_segmentation_IntelligentScissorsMB_applyImage( - CvPtr, image.ToInputProxy())); + CvPtr, image.Proxy)); return this; } @@ -157,20 +155,14 @@ public IntelligentScissorsMB ApplyImage(InputArray image) /// Optional parameter. Must be specified if subset of features is specified (non-specified features are calculated internally) /// public IntelligentScissorsMB ApplyImageFeatures( - InputArray nonEdge, InputArray gradientDirection, InputArray gradientMagnitude, - InputArray? image = null) + InputArrayRef nonEdge, InputArrayRef gradientDirection, InputArrayRef gradientMagnitude, + InputArrayRef image = default) { ThrowIfDisposed(); - if (nonEdge is null) - throw new ArgumentNullException(nameof(nonEdge)); - if (gradientDirection is null) - throw new ArgumentNullException(nameof(gradientDirection)); - if (gradientMagnitude is null) - throw new ArgumentNullException(nameof(gradientMagnitude)); NativeMethods.HandleException( NativeMethods.imgproc_segmentation_IntelligentScissorsMB_applyImageFeatures( - CvPtr, nonEdge.ToInputProxy(), gradientDirection.ToInputProxy(), gradientMagnitude.ToInputProxy(), image?.ToInputProxy() ?? default)); + CvPtr, nonEdge.Proxy, gradientDirection.Proxy, gradientMagnitude.Proxy, image.Proxy)); return this; } @@ -197,14 +189,12 @@ public void BuildMap(Point sourcePt) /// contour The list of pixels which contains optimal path between the source and the target points of the image. /// Type is CV_32SC2 (compatible with `std::vector<Point>`) /// Flag to indicate reverse order of retrived pixels (use "true" value to fetch points from the target to the source point) - public void GetContour(Point targetPt, OutputArray contour, bool backward = false) + public void GetContour(Point targetPt, OutputArrayRef contour, bool backward = false) { ThrowIfDisposed(); - if (contour is null) - throw new ArgumentNullException(nameof(contour)); NativeMethods.HandleException( NativeMethods.imgproc_segmentation_IntelligentScissorsMB_getContour( - CvPtr, targetPt, contour.ToOutputProxy(), backward ? 1 : 0)); + CvPtr, targetPt, contour.Proxy, backward ? 1 : 0)); } } diff --git a/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs b/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs index 79cda946a..6a36a1dee 100644 --- a/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs +++ b/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs @@ -49,30 +49,16 @@ public static LineSegmentDetector Create( /// Vector of precisions with which the lines are found. /// Vector containing number of false alarms in the line region, /// with precision of 10%. The bigger the value, logarithmically better the detection. - public virtual void Detect(InputArray image, OutputArray lines, - OutputArray? width = null, OutputArray? prec = null, OutputArray? nfa = null) + public virtual void Detect(InputArrayRef image, OutputArrayRef lines, + OutputArrayRef width = default, OutputArrayRef prec = default, OutputArrayRef nfa = default) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - image.ThrowIfDisposed(); - lines.ThrowIfNotReady(); - width?.ThrowIfNotReady(); - prec?.ThrowIfNotReady(); - nfa?.ThrowIfNotReady(); - - NativeMethods.imgproc_LineSegmentDetector_detect_OutputArray(Handle, image.ToInputProxy(), lines.ToOutputProxy(), - width?.ToOutputProxy() ?? default, prec?.ToOutputProxy() ?? default, nfa?.ToOutputProxy() ?? default); - GC.KeepAlive(image); - GC.KeepAlive(lines); - GC.KeepAlive(width); - GC.KeepAlive(prec); - GC.KeepAlive(nfa); - lines.Fix(); - width?.Fix(); - prec?.Fix(); - nfa?.Fix(); + NativeMethods.imgproc_LineSegmentDetector_detect_OutputArray(Handle, image.Proxy, lines.Proxy, + width.Proxy, prec.Proxy, nfa.Proxy); + GC.KeepAlive(image.Source); + GC.KeepAlive(lines.Source); + GC.KeepAlive(width.Source); + GC.KeepAlive(prec.Source); + GC.KeepAlive(nfa.Source); } /// @@ -86,19 +72,15 @@ public virtual void Detect(InputArray image, OutputArray lines, /// Vector of precisions with which the lines are found. /// Vector containing number of false alarms in the line region, /// with precision of 10%. The bigger the value, logarithmically better the detection. - public virtual void Detect(InputArray image, out Vec4f[] lines, + public virtual void Detect(InputArrayRef image, out Vec4f[] lines, out double[] width, out double[] prec, out double[] nfa) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - using (var linesVec = new StdVector()) using (var widthVec = new StdVector()) using (var precVec = new StdVector()) using (var nfaVec = new StdVector()) { - NativeMethods.imgproc_LineSegmentDetector_detect_vector(Handle, image.ToInputProxy(), + NativeMethods.imgproc_LineSegmentDetector_detect_vector(Handle, image.Proxy, linesVec.CvPtr, widthVec.CvPtr, precVec.CvPtr, nfaVec.CvPtr); lines = linesVec.ToArray(); @@ -106,7 +88,7 @@ public virtual void Detect(InputArray image, out Vec4f[] lines, prec = precVec.ToArray(); nfa = nfaVec.ToArray(); } - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// @@ -115,19 +97,11 @@ public virtual void Detect(InputArray image, out Vec4f[] lines, /// The image, where the liens will be drawn. /// Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. - public virtual void DrawSegments(InputOutputArray image, InputArray lines) + public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - image.ThrowIfNotReady(); - lines.ThrowIfDisposed(); - - NativeMethods.imgproc_LineSegmentDetector_drawSegments(Handle, image.ToInputOutputProxy(), lines.ToInputProxy()); - GC.KeepAlive(image); - image.Fix(); - GC.KeepAlive(lines); + NativeMethods.imgproc_LineSegmentDetector_drawSegments(Handle, image.Proxy, lines.Proxy); + GC.KeepAlive(image.Source); + GC.KeepAlive(lines.Source); } /// @@ -141,22 +115,13 @@ public virtual void DrawSegments(InputOutputArray image, InputArray lines) /// in the above mentioned colors. /// public virtual int CompareSegments( - Size size, InputArray lines1, InputArray lines2, InputOutputArray? image = null) + Size size, InputArrayRef lines1, InputArrayRef lines2, InputOutputArrayRef image = default) { - if (lines1 is null) - throw new ArgumentNullException(nameof(lines1)); - if (lines2 is null) - throw new ArgumentNullException(nameof(lines2)); - lines1.ThrowIfDisposed(); - lines2.ThrowIfDisposed(); - image?.ThrowIfNotReady(); - var ret = NativeMethods.imgproc_LineSegmentDetector_compareSegments( - Handle, size, lines1.ToInputProxy(), lines2.ToInputProxy(), image?.ToInputOutputProxy() ?? default); - GC.KeepAlive(lines1); - GC.KeepAlive(lines2); - GC.KeepAlive(image); - image?.Fix(); + Handle, size, lines1.Proxy, lines2.Proxy, image.Proxy); + GC.KeepAlive(lines1.Source); + GC.KeepAlive(lines2.Source); + GC.KeepAlive(image.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/ml/ANN_MLP.cs b/src/OpenCvSharp/Modules/ml/ANN_MLP.cs index 2bc45ab65..03ce7b38a 100644 --- a/src/OpenCvSharp/Modules/ml/ANN_MLP.cs +++ b/src/OpenCvSharp/Modules/ml/ANN_MLP.cs @@ -284,16 +284,14 @@ public virtual void SetActivationFunction(ActivationFunctions type, double param /// The last element - number of elements in the output layer.Default value is empty Mat. /// /// - public virtual void SetLayerSizes(InputArray layerSizes) + public virtual void SetLayerSizes(InputArrayRef layerSizes) { ThrowIfDisposed(); - if (layerSizes is null) - throw new ArgumentNullException(nameof(layerSizes)); NativeMethods.HandleException( - NativeMethods.ml_ANN_MLP_setLayerSizes(Handle, layerSizes.ToInputProxy())); + NativeMethods.ml_ANN_MLP_setLayerSizes(Handle, layerSizes.Proxy)); - GC.KeepAlive(layerSizes); + GC.KeepAlive(layerSizes.Source); } /// diff --git a/src/OpenCvSharp/Modules/ml/EM.cs b/src/OpenCvSharp/Modules/ml/EM.cs index e1f9f731a..93984da4e 100644 --- a/src/OpenCvSharp/Modules/ml/EM.cs +++ b/src/OpenCvSharp/Modules/ml/EM.cs @@ -197,36 +197,26 @@ public Mat[] GetCovs() /// // ReSharper disable once InconsistentNaming public virtual bool TrainEM( - InputArray samples, - OutputArray? logLikelihoods = null, - OutputArray? labels = null, - OutputArray? probs = null) + InputArrayRef samples, + OutputArrayRef logLikelihoods = default, + OutputArrayRef labels = default, + OutputArrayRef probs = default) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - samples.ThrowIfDisposed(); - - logLikelihoods?.ThrowIfNotReady(); - labels?.ThrowIfNotReady(); - probs?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_EM_trainEM( Handle, - samples.ToInputProxy(), - logLikelihoods?.ToOutputProxy() ?? default, - labels?.ToOutputProxy() ?? default, - probs?.ToOutputProxy() ?? default, + samples.Proxy, + logLikelihoods.Proxy, + labels.Proxy, + probs.Proxy, out var ret)); - logLikelihoods?.Fix(); - labels?.Fix(); - probs?.Fix(); - GC.KeepAlive(samples); - GC.KeepAlive(logLikelihoods); - GC.KeepAlive(labels); - GC.KeepAlive(probs); + GC.KeepAlive(samples.Source); + GC.KeepAlive(logLikelihoods.Source); + GC.KeepAlive(labels.Source); + GC.KeepAlive(probs.Source); return ret != 0; } @@ -252,50 +242,35 @@ public virtual bool TrainEM( /// The optional output matrix that contains posterior probabilities of each Gaussian /// mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. public virtual bool TrainE( - InputArray samples, - InputArray means0, - InputArray? covs0 = null, - InputArray? weights0 = null, - OutputArray? logLikelihoods = null, - OutputArray? labels = null, - OutputArray? probs = null) + InputArrayRef samples, + InputArrayRef means0, + InputArrayRef covs0 = default, + InputArrayRef weights0 = default, + OutputArrayRef logLikelihoods = default, + OutputArrayRef labels = default, + OutputArrayRef probs = default) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - if (means0 is null) - throw new ArgumentNullException(nameof(means0)); - samples.ThrowIfDisposed(); - means0.ThrowIfDisposed(); - - logLikelihoods?.ThrowIfNotReady(); - covs0?.ThrowIfDisposed(); - weights0?.ThrowIfDisposed(); - labels?.ThrowIfNotReady(); - probs?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_EM_trainE( Handle, - samples.ToInputProxy(), - means0.ToInputProxy(), - covs0?.ToInputProxy() ?? default, - weights0?.ToInputProxy() ?? default, - logLikelihoods?.ToOutputProxy() ?? default, - labels?.ToOutputProxy() ?? default, - probs?.ToOutputProxy() ?? default, + samples.Proxy, + means0.Proxy, + covs0.Proxy, + weights0.Proxy, + logLikelihoods.Proxy, + labels.Proxy, + probs.Proxy, out var ret)); - logLikelihoods?.Fix(); - labels?.Fix(); - probs?.Fix(); - GC.KeepAlive(samples); - GC.KeepAlive(means0); - GC.KeepAlive(covs0); - GC.KeepAlive(weights0); - GC.KeepAlive(logLikelihoods); - GC.KeepAlive(labels); - GC.KeepAlive(probs); + GC.KeepAlive(samples.Source); + GC.KeepAlive(means0.Source); + GC.KeepAlive(covs0.Source); + GC.KeepAlive(weights0.Source); + GC.KeepAlive(logLikelihoods.Source); + GC.KeepAlive(labels.Source); + GC.KeepAlive(probs.Source); return ret != 0; } @@ -314,42 +289,29 @@ public virtual bool TrainE( /// The optional output matrix that contains posterior probabilities of each Gaussian /// mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. public virtual bool TrainM( - InputArray samples, - InputArray probs0, - OutputArray? logLikelihoods = null, - OutputArray? labels = null, - OutputArray? probs = null) + InputArrayRef samples, + InputArrayRef probs0, + OutputArrayRef logLikelihoods = default, + OutputArrayRef labels = default, + OutputArrayRef probs = default) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - if (probs0 is null) - throw new ArgumentNullException(nameof(probs0)); - samples.ThrowIfDisposed(); - probs0.ThrowIfDisposed(); - - logLikelihoods?.ThrowIfNotReady(); - labels?.ThrowIfNotReady(); - probs?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_EM_trainM( Handle, - samples.ToInputProxy(), - probs0.ToInputProxy(), - logLikelihoods?.ToOutputProxy() ?? default, - labels?.ToOutputProxy() ?? default, - probs?.ToOutputProxy() ?? default, + samples.Proxy, + probs0.Proxy, + logLikelihoods.Proxy, + labels.Proxy, + probs.Proxy, out var ret)); - logLikelihoods?.Fix(); - labels?.Fix(); - probs?.Fix(); - GC.KeepAlive(samples); - GC.KeepAlive(probs0); - GC.KeepAlive(logLikelihoods); - GC.KeepAlive(labels); - GC.KeepAlive(probs); + GC.KeepAlive(samples.Source); + GC.KeepAlive(probs0.Source); + GC.KeepAlive(logLikelihoods.Source); + GC.KeepAlive(labels.Source); + GC.KeepAlive(probs.Source); return ret != 0; } @@ -361,19 +323,14 @@ public virtual bool TrainM( /// \f$1 \times dims\f$ or \f$dims \times 1\f$ size. /// Optional output matrix that contains posterior probabilities of each component /// given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. - public virtual Vec2d Predict2(InputArray sample, OutputArray? probs = null) + public virtual Vec2d Predict2(InputArrayRef sample, OutputArrayRef probs = default) { ThrowIfDisposed(); - if (sample is null) - throw new ArgumentNullException(nameof(sample)); - sample.ThrowIfDisposed(); - probs?.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ml_EM_predict2(Handle, sample.ToInputProxy(), probs?.ToOutputProxy() ?? default, out var ret)); - probs?.Fix(); - GC.KeepAlive(sample); - GC.KeepAlive(probs); + NativeMethods.ml_EM_predict2(Handle, sample.Proxy, probs.Proxy, out var ret)); + GC.KeepAlive(sample.Source); + GC.KeepAlive(probs.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/ml/KNearest.cs b/src/OpenCvSharp/Modules/ml/KNearest.cs index a34647e47..9549bdb03 100644 --- a/src/OpenCvSharp/Modules/ml/KNearest.cs +++ b/src/OpenCvSharp/Modules/ml/KNearest.cs @@ -152,30 +152,21 @@ public Types AlgorithmType /// Optional output distances from the input vectors to the corresponding neighbors. /// It is a single-precision floating-point matrix of `[number_of_samples] * k` size. /// - public float FindNearest(InputArray samples, int k, OutputArray results, - OutputArray? neighborResponses = null, OutputArray? dist = null) + public float FindNearest(InputArrayRef samples, int k, OutputArrayRef results, + OutputArrayRef neighborResponses = default, OutputArrayRef dist = default) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - if (results is null) - throw new ArgumentNullException(nameof(results)); - samples.ThrowIfDisposed(); - results.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_KNearest_findNearest( Handle, - samples.ToInputProxy(), k, results.ToOutputProxy(), - neighborResponses?.ToOutputProxy() ?? default, dist?.ToOutputProxy() ?? default, out var ret)); - - GC.KeepAlive(samples); - GC.KeepAlive(results); - GC.KeepAlive(neighborResponses); - GC.KeepAlive(dist); - results.Fix(); - neighborResponses?.Fix(); - dist?.Fix(); + samples.Proxy, k, results.Proxy, + neighborResponses.Proxy, dist.Proxy, out var ret)); + + GC.KeepAlive(samples.Source); + GC.KeepAlive(results.Source); + GC.KeepAlive(neighborResponses.Source); + GC.KeepAlive(dist.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/ml/LogisticRegression.cs b/src/OpenCvSharp/Modules/ml/LogisticRegression.cs index c2a364a3d..0f021cd15 100644 --- a/src/OpenCvSharp/Modules/ml/LogisticRegression.cs +++ b/src/OpenCvSharp/Modules/ml/LogisticRegression.cs @@ -184,19 +184,14 @@ public TermCriteria TermCriteria /// Predicted labels as a column matrix of type CV_32S. /// Not used. /// - public float Predict(InputArray samples, OutputArray? results = null, int flags = 0) + public float Predict(InputArrayRef samples, OutputArrayRef results = default, int flags = 0) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - samples.ThrowIfDisposed(); - results?.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ml_LogisticRegression_predict(Handle, samples.ToInputProxy(), results?.ToOutputProxy() ?? default, flags, out var ret)); - GC.KeepAlive(samples); - GC.KeepAlive(results); - results?.Fix(); + NativeMethods.ml_LogisticRegression_predict(Handle, samples.Proxy, results.Proxy, flags, out var ret)); + GC.KeepAlive(samples.Source); + GC.KeepAlive(results.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs b/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs index 73edea666..9e739515d 100644 --- a/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs +++ b/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs @@ -70,29 +70,17 @@ public static NormalBayesClassifier LoadFromString(string strModel) /// output vector outputs. The predicted class for a single input vector is returned by the method. /// The vector outputProbs contains the output probabilities corresponding to each element of result. /// - public float PredictProb(InputArray inputs, OutputArray outputs, - OutputArray outputProbs, int flags = 0) + public float PredictProb(InputArrayRef inputs, OutputArrayRef outputs, + OutputArrayRef outputProbs, int flags = 0) { ThrowIfDisposed(); - if (inputs is null) - throw new ArgumentNullException(nameof(inputs)); - if (outputs is null) - throw new ArgumentNullException(nameof(outputs)); - if (outputProbs is null) - throw new ArgumentNullException(nameof(outputProbs)); - - inputs.ThrowIfDisposed(); - outputs.ThrowIfNotReady(); - outputProbs.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_NormalBayesClassifier_predictProb( - Handle, inputs.ToInputProxy(), outputs.ToOutputProxy(), outputProbs.ToOutputProxy(), flags, out var ret)); - outputs.Fix(); - outputProbs.Fix(); - GC.KeepAlive(inputs); - GC.KeepAlive(outputs); - GC.KeepAlive(outputProbs); + Handle, inputs.Proxy, outputs.Proxy, outputProbs.Proxy, flags, out var ret)); + GC.KeepAlive(inputs.Source); + GC.KeepAlive(outputs.Source); + GC.KeepAlive(outputProbs.Source); return ret; } } diff --git a/src/OpenCvSharp/Modules/ml/SVM.cs b/src/OpenCvSharp/Modules/ml/SVM.cs index e10a0efb3..8467fb556 100644 --- a/src/OpenCvSharp/Modules/ml/SVM.cs +++ b/src/OpenCvSharp/Modules/ml/SVM.cs @@ -337,24 +337,15 @@ public Mat GetSupportVectors() /// within the matrix of support vectors (which can be retrieved by SVM::getSupportVectors). /// In the case of linear %SVM each decision function consists of a single "compressed" support vector. /// - public double GetDecisionFunction(int i, OutputArray alpha, OutputArray svidx) + public double GetDecisionFunction(int i, OutputArrayRef alpha, OutputArrayRef svidx) { ThrowIfDisposed(); - if (alpha is null) - throw new ArgumentNullException(nameof(alpha)); - if (svidx is null) - throw new ArgumentNullException(nameof(svidx)); - - alpha.ThrowIfNotReady(); - svidx.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ml_SVM_getDecisionFunction(Handle, i, alpha.ToOutputProxy(), svidx.ToOutputProxy(), out var ret)); + NativeMethods.ml_SVM_getDecisionFunction(Handle, i, alpha.Proxy, svidx.Proxy, out var ret)); - alpha.Fix(); - svidx.Fix(); - GC.KeepAlive(alpha); - GC.KeepAlive(svidx); + GC.KeepAlive(alpha.Source); + GC.KeepAlive(svidx.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/ml/StatModel.cs b/src/OpenCvSharp/Modules/ml/StatModel.cs index 5aa2ae9d8..0b2e28f4b 100644 --- a/src/OpenCvSharp/Modules/ml/StatModel.cs +++ b/src/OpenCvSharp/Modules/ml/StatModel.cs @@ -80,20 +80,14 @@ public virtual bool Train(TrainData trainData, int flags = 0) /// SampleTypes value /// vector of responses associated with the training samples. /// - public virtual bool Train(InputArray samples, SampleTypes layout, InputArray responses) + public virtual bool Train(InputArrayRef samples, SampleTypes layout, InputArrayRef responses) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - if (responses is null) - throw new ArgumentNullException(nameof(responses)); - samples.ThrowIfDisposed(); - responses.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ml_StatModel_train2(Handle, samples.ToInputProxy(), (int)layout, responses.ToInputProxy(), out var ret)); - GC.KeepAlive(samples); - GC.KeepAlive(responses); + NativeMethods.ml_StatModel_train2(Handle, samples.Proxy, (int)layout, responses.Proxy, out var ret)); + GC.KeepAlive(samples.Source); + GC.KeepAlive(responses.Source); return ret != 0; } @@ -109,7 +103,7 @@ public virtual bool Train(InputArray samples, SampleTypes layout, InputArray res /// sounds a bit confusing. /// the optional output responses. /// - public virtual float CalcError(TrainData data, bool test, OutputArray resp) + public virtual float CalcError(TrainData data, bool test, OutputArrayRef resp) { throw new NotImplementedException(); } @@ -121,20 +115,15 @@ public virtual float CalcError(TrainData data, bool test, OutputArray resp) /// The optional output matrix of results. /// The optional flags, model-dependent. /// - public virtual float Predict(InputArray samples, OutputArray? results = null, Flags flags = 0) + public virtual float Predict(InputArrayRef samples, OutputArrayRef results = default, Flags flags = 0) { ThrowIfDisposed(); - if (samples is null) - throw new ArgumentNullException(nameof(samples)); - samples.ThrowIfDisposed(); - results?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ml_StatModel_predict( - Handle, samples.ToInputProxy(), results?.ToOutputProxy() ?? default, (int) flags, out var ret)); - GC.KeepAlive(samples); - GC.KeepAlive(results); - results?.Fix(); + Handle, samples.Proxy, results.Proxy, (int) flags, out var ret)); + GC.KeepAlive(samples.Source); + GC.KeepAlive(results.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs b/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs index 419da185c..78fb836e5 100644 --- a/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs +++ b/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs @@ -65,10 +65,10 @@ public static FaceDetectorYN Create( public int Detect(Mat image, Mat faces) { ThrowIfDisposed(); - using InputArray iaImage = new(image); - using OutputArray oaFaces = new(faces); + InputArrayRef iaImage = image; + OutputArrayRef oaFaces = faces; NativeMethods.HandleException( - NativeMethods.objdetect_FaceDetectorYN_detect(Handle, iaImage.ToInputProxy(), oaFaces.ToOutputProxy(), out var result)); + NativeMethods.objdetect_FaceDetectorYN_detect(Handle, iaImage.Proxy, oaFaces.Proxy, out var result)); return result; } } diff --git a/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs b/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs index b34f3d350..950bba848 100644 --- a/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs +++ b/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs @@ -58,19 +58,15 @@ public void SetEpsY(double epsY) /// grayscale or color (BGR) image containing (or not) QR code. /// Output vector of vertices of the minimum-area quadrangle containing the code. /// - public bool Detect(InputArray img, out Point2f[] points) + public bool Detect(InputArrayRef img, out Point2f[] points) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - using var pointsVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.objdetect_QRCodeDetector_detect(Handle, img.ToInputProxy(), pointsVec.CvPtr, out var ret)); + NativeMethods.objdetect_QRCodeDetector_detect(Handle, img.Proxy, pointsVec.CvPtr, out var ret)); points = pointsVec.ToArray(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return ret != 0; } @@ -83,24 +79,20 @@ public bool Detect(InputArray img, out Point2f[] points) /// Quadrangle vertices found by detect() method (or some other algorithm). /// The optional output image containing rectified and binarized QR code /// - public string Decode(InputArray img, IEnumerable points, OutputArray? straightQrCode = null) + public string Decode(InputArrayRef img, IEnumerable points, OutputArrayRef straightQrCode = default) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (points is null) throw new ArgumentNullException(nameof(points)); - img.ThrowIfDisposed(); - straightQrCode?.ThrowIfNotReady(); using var pointsVec = new StdVector(points); using var resultString = new StdString(); NativeMethods.HandleException( NativeMethods.objdetect_QRCodeDetector_decode( - Handle, img.ToInputProxy(), pointsVec.CvPtr, straightQrCode?.ToOutputProxy() ?? default, resultString.CvPtr)); + Handle, img.Proxy, pointsVec.CvPtr, straightQrCode.Proxy, resultString.CvPtr)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); GC.KeepAlive(points); - GC.KeepAlive(straightQrCode); + GC.KeepAlive(straightQrCode.Source); return resultString.ToString(); } @@ -112,22 +104,17 @@ public string Decode(InputArray img, IEnumerable points, OutputArray? s /// optional output array of vertices of the found QR code quadrangle. Will be empty if not found. /// The optional output image containing rectified and binarized QR code /// - public string DetectAndDecode(InputArray img, out Point2f[] points, OutputArray? straightQrCode = null) + public string DetectAndDecode(InputArrayRef img, out Point2f[] points, OutputArrayRef straightQrCode = default) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - straightQrCode?.ThrowIfNotReady(); - using var pointsVec = new StdVector(); using var resultString = new StdString(); NativeMethods.HandleException( NativeMethods.objdetect_QRCodeDetector_detectAndDecode( - Handle, img.ToInputProxy(), pointsVec.CvPtr, straightQrCode?.ToOutputProxy() ?? default, resultString.CvPtr)); + Handle, img.Proxy, pointsVec.CvPtr, straightQrCode.Proxy, resultString.CvPtr)); points = pointsVec.ToArray(); - GC.KeepAlive(img); - GC.KeepAlive(straightQrCode); + GC.KeepAlive(img.Source); + GC.KeepAlive(straightQrCode.Source); return resultString.ToString(); } @@ -138,19 +125,15 @@ public string DetectAndDecode(InputArray img, out Point2f[] points, OutputArray? /// grayscale or color (BGR) image containing (or not) QR code. /// Output vector of vertices of the minimum-area quadrangle containing the codes. /// - public bool DetectMulti(InputArray img, out Point2f[] points) + public bool DetectMulti(InputArrayRef img, out Point2f[] points) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); - using var pointsVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.objdetect_QRCodeDetector_detectMulti(Handle, img.ToInputProxy(), pointsVec.CvPtr, out var ret)); + NativeMethods.objdetect_QRCodeDetector_detectMulti(Handle, img.Proxy, pointsVec.CvPtr, out var ret)); points = pointsVec.ToArray(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); return ret != 0; } @@ -163,7 +146,7 @@ public bool DetectMulti(InputArray img, out Point2f[] points) /// Quadrangle vertices found by detect() method (or some other algorithm). /// UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. /// - public bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo) + public bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo) { return DecodeMulti(img, points, out decodedInfo, out _, false); } @@ -177,7 +160,7 @@ public bool DecodeMulti(InputArray img, IEnumerable points, out string? /// UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. /// The optional output image containing rectified and binarized QR code /// - public bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode) + public bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode) { return DecodeMulti(img, points, out decodedInfo, out straightQrCode, true); } @@ -193,15 +176,11 @@ public bool DecodeMulti(InputArray img, IEnumerable points, out string? /// The optional output image containing rectified and binarized QR code /// to output /// - protected bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode, bool isOutputStraightQrCode) + protected bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode, bool isOutputStraightQrCode) { - if (img is null) - throw new ArgumentNullException(nameof(img)); if (points is null) throw new ArgumentNullException(nameof(points)); - img.ThrowIfDisposed(); - using var decodedInfoVec = new VectorOfString(); using var pointsVec = new StdVector(points); @@ -211,21 +190,21 @@ protected bool DecodeMulti(InputArray img, IEnumerable points, out stri using var straightQrCodeVec = new VectorOfMat(); NativeMethods.HandleException( NativeMethods.objdetect_QRCodeDetector_decodeMulti( - Handle, img.ToInputProxy(), pointsVec.CvPtr, decodedInfoVec.CvPtr, straightQrCodeVec.CvPtr, out ret)); + Handle, img.Proxy, pointsVec.CvPtr, decodedInfoVec.CvPtr, straightQrCodeVec.CvPtr, out ret)); straightQrCode = straightQrCodeVec.ToArray(); } else { NativeMethods.HandleException( NativeMethods.objdetect_QRCodeDetector_decodeMulti_NoStraightQrCode( - Handle, img.ToInputProxy(), pointsVec.CvPtr, decodedInfoVec.CvPtr, out ret)); + Handle, img.Proxy, pointsVec.CvPtr, decodedInfoVec.CvPtr, out ret)); straightQrCode = []; } // decode utf-8 bytes. decodedInfo = decodedInfoVec.ToArray(); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); GC.KeepAlive(points); return ret != 0; diff --git a/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs b/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs index 7059e612d..4d496bcfc 100644 --- a/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs +++ b/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs @@ -19,23 +19,15 @@ public static partial class OptFlow /// Current time in milliseconds or other units. /// Maximal duration of the motion track in the same units as timestamp . public static void UpdateMotionHistory( - InputArray silhouette, InputOutputArray mhi, + InputArrayRef silhouette, InputOutputArrayRef mhi, double timestamp, double duration) { - if (silhouette is null) - throw new ArgumentNullException(nameof(silhouette)); - if (mhi is null) - throw new ArgumentNullException(nameof(mhi)); - silhouette.ThrowIfDisposed(); - mhi.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.optflow_motempl_updateMotionHistory( - silhouette.ToInputProxy(), mhi.ToInputOutputProxy(), timestamp, duration)); + silhouette.Proxy, mhi.Proxy, timestamp, duration)); - mhi.Fix(); - GC.KeepAlive(silhouette); - GC.KeepAlive(mhi); + GC.KeepAlive(silhouette.Source); + GC.KeepAlive(mhi.Source); } /// @@ -53,28 +45,16 @@ public static void UpdateMotionHistory( /// min(delta1, delta2) <= M(x,y)-m(x,y) <= max(delta1, delta2). /// public static void CalcMotionGradient( - InputArray mhi, OutputArray mask, OutputArray orientation, + InputArrayRef mhi, OutputArrayRef mask, OutputArrayRef orientation, double delta1, double delta2, int apertureSize = 3) { - if (mhi is null) - throw new ArgumentNullException(nameof(mhi)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - if (orientation is null) - throw new ArgumentNullException(nameof(orientation)); - mhi.ThrowIfDisposed(); - mask.ThrowIfNotReady(); - orientation.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.optflow_motempl_calcMotionGradient( - mhi.ToInputProxy(), mask.ToOutputProxy(), orientation.ToOutputProxy(), delta1, delta2, apertureSize)); + mhi.Proxy, mask.Proxy, orientation.Proxy, delta1, delta2, apertureSize)); - mask.Fix(); - orientation.Fix(); - GC.KeepAlive(mhi); - GC.KeepAlive(mask); - GC.KeepAlive(orientation); + GC.KeepAlive(mhi.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(orientation.Source); } /// @@ -88,26 +68,16 @@ public static void CalcMotionGradient( /// Maximum duration of a motion track in milliseconds, passed to UpdateMotionHistory() . /// public static double CalcGlobalOrientation( - InputArray orientation, InputArray mask, InputArray mhi, + InputArrayRef orientation, InputArrayRef mask, InputArrayRef mhi, double timestamp, double duration) { - if (orientation is null) - throw new ArgumentNullException(nameof(orientation)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - if (mhi is null) - throw new ArgumentNullException(nameof(mhi)); - orientation.ThrowIfDisposed(); - mask.ThrowIfDisposed(); - mhi.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.optflow_motempl_calcGlobalOrientation( - orientation.ToInputProxy(), mask.ToInputProxy(), mhi.ToInputProxy(), timestamp, duration, out var ret)); + orientation.Proxy, mask.Proxy, mhi.Proxy, timestamp, duration, out var ret)); - GC.KeepAlive(orientation); - GC.KeepAlive(mask); - GC.KeepAlive(mhi); + GC.KeepAlive(orientation.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(mhi.Source); return ret; } @@ -121,26 +91,18 @@ public static double CalcGlobalOrientation( /// Current time in milliseconds or other units. /// Segmentation threshold that is recommended to be equal to the interval between motion history “steps” or greater. public static void SegmentMotion( - InputArray mhi, OutputArray segmask, + InputArrayRef mhi, OutputArrayRef segmask, out Rect[] boundingRects, double timestamp, double segThresh) { - if (mhi is null) - throw new ArgumentNullException(nameof(mhi)); - if (segmask is null) - throw new ArgumentNullException(nameof(segmask)); - mhi.ThrowIfDisposed(); - segmask.ThrowIfNotReady(); - using var br = new StdVector(); NativeMethods.HandleException( NativeMethods.optflow_motempl_segmentMotion( - mhi.ToInputProxy(), segmask.ToOutputProxy(), br.CvPtr, timestamp, segThresh)); + mhi.Proxy, segmask.Proxy, br.CvPtr, timestamp, segThresh)); boundingRects = br.ToArray(); - segmask.Fix(); - GC.KeepAlive(mhi); - GC.KeepAlive(segmask); + GC.KeepAlive(mhi.Source); + GC.KeepAlive(segmask.Source); } /// @@ -153,31 +115,21 @@ public static void SegmentMotion( /// Size of block through which we sum up when calculate cost function for pixel /// maximal flow that we search at each level public static void CalcOpticalFlowSF( - InputArray from, - InputArray to, - OutputArray flow, + InputArrayRef from, + InputArrayRef to, + OutputArrayRef flow, int layers, int averagingBlockSize, int maxFlow) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - if (flow is null) - throw new ArgumentNullException(nameof(flow)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - flow.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.optflow_calcOpticalFlowSF1( - from.ToInputProxy(), to.ToInputProxy(), flow.ToOutputProxy(), + from.Proxy, to.Proxy, flow.Proxy, layers, averagingBlockSize, maxFlow)); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(flow); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(flow.Source); } /// @@ -200,9 +152,9 @@ public static void CalcOpticalFlowSF( /// color sigma for bilateral upscale operation /// threshold to detect point with irregular flow - where flow should be recalculated after upscale public static void CalcOpticalFlowSF( - InputArray from, - InputArray to, - OutputArray flow, + InputArrayRef from, + InputArrayRef to, + OutputArrayRef flow, int layers, int averagingBlockSize, int maxFlow, @@ -217,27 +169,17 @@ public static void CalcOpticalFlowSF( double upscaleSigmaColor, double speedUpThr) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - if (flow is null) - throw new ArgumentNullException(nameof(flow)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - flow.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.optflow_calcOpticalFlowSF2( - from.ToInputProxy(), to.ToInputProxy(), flow.ToOutputProxy(), + from.Proxy, to.Proxy, flow.Proxy, layers, averagingBlockSize, maxFlow, sigmaDist, sigmaColor, postprocessWindow, sigmaDistFix, sigmaColorFix, occThr, upscaleAveragingRadius, upscaleSigmaDist, upscaleSigmaColor, speedUpThr)); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(flow); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(flow.Source); } /// @@ -256,9 +198,9 @@ public static void CalcOpticalFlowSF( /// see the respective parameter of the ximgproc::fastGlobalSmootherFilter() /// see the respective parameter of the ximgproc::fastGlobalSmootherFilter() public static void CalcOpticalFlowSparseToDense( - InputArray from, - InputArray to, - OutputArray flow, + InputArrayRef from, + InputArrayRef to, + OutputArrayRef flow, int gridStep = 8, int k = 128, float sigma = 0.05f, @@ -266,24 +208,14 @@ public static void CalcOpticalFlowSparseToDense( float fgsLambda = 500.0f, float fgsSigma = 1.5f) { - if (from is null) - throw new ArgumentNullException(nameof(from)); - if (to is null) - throw new ArgumentNullException(nameof(to)); - if (flow is null) - throw new ArgumentNullException(nameof(flow)); - from.ThrowIfDisposed(); - to.ThrowIfDisposed(); - flow.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.optflow_calcOpticalFlowSparseToDense( - from.ToInputProxy(), to.ToInputProxy(), flow.ToOutputProxy(), + from.Proxy, to.Proxy, flow.Proxy, gridStep, k, sigma, usePostProc ? 1 : 0, fgsLambda, fgsSigma)); - GC.KeepAlive(from); - GC.KeepAlive(to); - GC.KeepAlive(flow); + GC.KeepAlive(from.Source); + GC.KeepAlive(to.Source); + GC.KeepAlive(flow.Source); } } } diff --git a/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs b/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs index 8cf481d0e..1a258270a 100644 --- a/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs +++ b/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs @@ -18,15 +18,12 @@ protected CalibrateCRF(IntPtr smartPtr, IntPtr rawPtr, Action release) /// vector of input images /// 256x1 matrix with inverse camera response function /// vector of exposure time values for each image - public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable times) + public virtual void Process(IEnumerable src, OutputArrayRef dst, IEnumerable times) { if (src is null) throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); if (times is null) throw new ArgumentNullException(nameof(times)); - dst.ThrowIfNotReady(); var srcArray = src.Select(x => x.CvPtr).ToArray(); var timesArray = times.ToArray(); @@ -34,10 +31,9 @@ public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable release) /// result image /// vector of exposure time values for each image /// 256x1 matrix with inverse camera response function for each pixel value, it should have the same number of channels as images. - public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable times, InputArray response) + public virtual void Process(IEnumerable src, OutputArrayRef dst, IEnumerable times, InputArrayRef response) { if (src is null) throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); if (times is null) throw new ArgumentNullException(nameof(times)); - if (response is null) - throw new ArgumentNullException(nameof(response)); - dst.ThrowIfNotReady(); var srcArray = src.Select(s => s.CvPtr).ToArray(); var timesArray = times as float[] ?? times.ToArray(); @@ -36,12 +31,11 @@ public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable /// vector of input images /// result image - public void Process(IEnumerable src, OutputArray dst) + public void Process(IEnumerable src, OutputArrayRef dst) { if (src is null) throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - dst.ThrowIfNotReady(); var srcArray = src.Select(s => s.CvPtr).ToArray(); NativeMethods.HandleException( - NativeMethods.photo_MergeMertens_process(Handle, srcArray, srcArray.Length, dst.ToOutputProxy())); + NativeMethods.photo_MergeMertens_process(Handle, srcArray, srcArray.Length, dst.Proxy)); GC.KeepAlive(src); GC.KeepAlive(srcArray); - dst.Fix(); } } diff --git a/src/OpenCvSharp/Modules/photo/Tonemap.cs b/src/OpenCvSharp/Modules/photo/Tonemap.cs index 32f2f66ce..4c0e0f773 100644 --- a/src/OpenCvSharp/Modules/photo/Tonemap.cs +++ b/src/OpenCvSharp/Modules/photo/Tonemap.cs @@ -40,21 +40,12 @@ public static Tonemap Create(float gamma = 1f) /// /// source image - CV_32FC3 Mat (float 32 bits 3 channels) /// destination image - CV_32FC3 Mat with values in [0, 1] range - public virtual void Process(InputArray src, OutputArray dst) + public virtual void Process(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.photo_Tonemap_process(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.photo_Tonemap_process(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// diff --git a/src/OpenCvSharp/Modules/ptcloud/Odometry.cs b/src/OpenCvSharp/Modules/ptcloud/Odometry.cs index 4d2a599a6..a38a0c646 100644 --- a/src/OpenCvSharp/Modules/ptcloud/Odometry.cs +++ b/src/OpenCvSharp/Modules/ptcloud/Odometry.cs @@ -116,21 +116,17 @@ public void PrepareFrames(OdometryFrame srcFrame, OdometryFrame dstFrame) /// dst frame ("rotated" image). /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArray Rt) + public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArrayRef Rt) { ThrowIfDisposed(); if (srcFrame is null) throw new ArgumentNullException(nameof(srcFrame)); if (dstFrame is null) throw new ArgumentNullException(nameof(dstFrame)); - if (Rt is null) - throw new ArgumentNullException(nameof(Rt)); srcFrame.ThrowIfDisposed(); dstFrame.ThrowIfDisposed(); - Rt.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Odometry_compute_Frame(Handle, srcFrame.CvPtr, dstFrame.CvPtr, Rt.ToOutputProxy(), out var ret)); - Rt.Fix(); + NativeMethods.ptcloud_Odometry_compute_Frame(Handle, srcFrame.CvPtr, dstFrame.CvPtr, Rt.Proxy, out var ret)); GC.KeepAlive(srcFrame); GC.KeepAlive(dstFrame); return ret != 0; @@ -143,23 +139,13 @@ public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArray /// destination depth ("rotated" image). /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(InputArray srcDepth, InputArray dstDepth, OutputArray Rt) + public bool Compute(InputArrayRef srcDepth, InputArrayRef dstDepth, OutputArrayRef Rt) { ThrowIfDisposed(); - if (srcDepth is null) - throw new ArgumentNullException(nameof(srcDepth)); - if (dstDepth is null) - throw new ArgumentNullException(nameof(dstDepth)); - if (Rt is null) - throw new ArgumentNullException(nameof(Rt)); - srcDepth.ThrowIfDisposed(); - dstDepth.ThrowIfDisposed(); - Rt.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Odometry_compute_Depth(Handle, srcDepth.ToInputProxy(), dstDepth.ToInputProxy(), Rt.ToOutputProxy(), out var ret)); - Rt.Fix(); - GC.KeepAlive(srcDepth); - GC.KeepAlive(dstDepth); + NativeMethods.ptcloud_Odometry_compute_Depth(Handle, srcDepth.Proxy, dstDepth.Proxy, Rt.Proxy, out var ret)); + GC.KeepAlive(srcDepth.Source); + GC.KeepAlive(dstDepth.Source); return ret != 0; } @@ -172,31 +158,15 @@ public bool Compute(InputArray srcDepth, InputArray dstDepth, OutputArray Rt) /// destination RGB. /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(InputArray srcDepth, InputArray srcRGB, InputArray dstDepth, InputArray dstRGB, OutputArray Rt) + public bool Compute(InputArrayRef srcDepth, InputArrayRef srcRGB, InputArrayRef dstDepth, InputArrayRef dstRGB, OutputArrayRef Rt) { ThrowIfDisposed(); - if (srcDepth is null) - throw new ArgumentNullException(nameof(srcDepth)); - if (srcRGB is null) - throw new ArgumentNullException(nameof(srcRGB)); - if (dstDepth is null) - throw new ArgumentNullException(nameof(dstDepth)); - if (dstRGB is null) - throw new ArgumentNullException(nameof(dstRGB)); - if (Rt is null) - throw new ArgumentNullException(nameof(Rt)); - srcDepth.ThrowIfDisposed(); - srcRGB.ThrowIfDisposed(); - dstDepth.ThrowIfDisposed(); - dstRGB.ThrowIfDisposed(); - Rt.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Odometry_compute_DepthRGB(Handle, srcDepth.ToInputProxy(), srcRGB.ToInputProxy(), dstDepth.ToInputProxy(), dstRGB.ToInputProxy(), Rt.ToOutputProxy(), out var ret)); - Rt.Fix(); - GC.KeepAlive(srcDepth); - GC.KeepAlive(srcRGB); - GC.KeepAlive(dstDepth); - GC.KeepAlive(dstRGB); + NativeMethods.ptcloud_Odometry_compute_DepthRGB(Handle, srcDepth.Proxy, srcRGB.Proxy, dstDepth.Proxy, dstRGB.Proxy, Rt.Proxy, out var ret)); + GC.KeepAlive(srcDepth.Source); + GC.KeepAlive(srcRGB.Source); + GC.KeepAlive(dstDepth.Source); + GC.KeepAlive(dstRGB.Source); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs b/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs index 34e171c69..98bdf46ba 100644 --- a/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs +++ b/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs @@ -19,28 +19,23 @@ public class OdometryFrame : CvObject /// An BGR or grayscale image (or null if it's not required for the used ICP algorithm). /// A user-provided mask of valid pixels, should be CV_8UC1. /// A user-provided normals to the depth surface, should be CV_32FC4. - public OdometryFrame(InputArray? depth = null, InputArray? image = null, InputArray? mask = null, InputArray? normals = null) + public OdometryFrame(InputArrayRef depth = default, InputArrayRef image = default, InputArrayRef mask = default, InputArrayRef normals = default) { - depth?.ThrowIfDisposed(); - image?.ThrowIfDisposed(); - mask?.ThrowIfDisposed(); - normals?.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ptcloud_OdometryFrame_new( - depth?.ToInputProxy() ?? default, - image?.ToInputProxy() ?? default, - mask?.ToInputProxy() ?? default, - normals?.ToInputProxy() ?? default, + depth.Proxy, + image.Proxy, + mask.Proxy, + normals.Proxy, out var p)); if (p == IntPtr.Zero) throw new OpenCvSharpException($"Failed to create {nameof(OdometryFrame)}"); InitSafeHandle(p); - GC.KeepAlive(depth); - GC.KeepAlive(image); - GC.KeepAlive(mask); - GC.KeepAlive(normals); + GC.KeepAlive(depth.Source); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); + GC.KeepAlive(normals.Source); } /// @@ -64,85 +59,61 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) /// /// Gets the original user-provided BGR/Gray image. /// - public void GetImage(OutputArray image) + public void GetImage(OutputArrayRef image) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getImage(Handle, image.ToOutputProxy())); - image.Fix(); + NativeMethods.ptcloud_OdometryFrame_getImage(Handle, image.Proxy)); } /// /// Gets the gray image generated from the user-provided BGR/Gray image. /// - public void GetGrayImage(OutputArray image) + public void GetGrayImage(OutputArrayRef image) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getGrayImage(Handle, image.ToOutputProxy())); - image.Fix(); + NativeMethods.ptcloud_OdometryFrame_getGrayImage(Handle, image.Proxy)); } /// /// Gets the original user-provided depth image. /// - public void GetDepth(OutputArray depth) + public void GetDepth(OutputArrayRef depth) { ThrowIfDisposed(); - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - depth.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getDepth(Handle, depth.ToOutputProxy())); - depth.Fix(); + NativeMethods.ptcloud_OdometryFrame_getDepth(Handle, depth.Proxy)); } /// /// Gets the depth image generated for ICP algorithm needs. /// - public void GetProcessedDepth(OutputArray depth) + public void GetProcessedDepth(OutputArrayRef depth) { ThrowIfDisposed(); - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - depth.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getProcessedDepth(Handle, depth.ToOutputProxy())); - depth.Fix(); + NativeMethods.ptcloud_OdometryFrame_getProcessedDepth(Handle, depth.Proxy)); } /// /// Gets the valid pixels mask generated for the ICP calculations intersected with the user-provided mask. /// - public void GetMask(OutputArray mask) + public void GetMask(OutputArrayRef mask) { ThrowIfDisposed(); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - mask.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getMask(Handle, mask.ToOutputProxy())); - mask.Fix(); + NativeMethods.ptcloud_OdometryFrame_getMask(Handle, mask.Proxy)); } /// /// Gets the normals image either generated for the ICP calculations or user-provided. /// - public void GetNormals(OutputArray normals) + public void GetNormals(OutputArrayRef normals) { ThrowIfDisposed(); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getNormals(Handle, normals.ToOutputProxy())); - normals.Fix(); + NativeMethods.ptcloud_OdometryFrame_getNormals(Handle, normals.Proxy)); } /// @@ -162,15 +133,11 @@ public int GetPyramidLevels() /// Output image. /// Type of pyramid. /// Level in the pyramid. - public void GetPyramidAt(OutputArray img, OdometryFramePyramidType pyrType, long level) + public void GetPyramidAt(OutputArrayRef img, OdometryFramePyramidType pyrType, long level) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometryFrame_getPyramidAt(Handle, img.ToOutputProxy(), (int)pyrType, new IntPtr(level))); - img.Fix(); + NativeMethods.ptcloud_OdometryFrame_getPyramidAt(Handle, img.Proxy, (int)pyrType, new IntPtr(level))); } #endregion diff --git a/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs b/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs index 5211b69d3..7ff2f33aa 100644 --- a/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs +++ b/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs @@ -45,85 +45,64 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) /// /// Sets the camera matrix. /// - public void SetCameraMatrix(InputArray val) + public void SetCameraMatrix(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_setCameraMatrix(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_OdometrySettings_setCameraMatrix(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Gets the camera matrix. /// - public void GetCameraMatrix(OutputArray val) + public void GetCameraMatrix(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_getCameraMatrix(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_OdometrySettings_getCameraMatrix(Handle, val.Proxy)); } /// /// Sets the iteration counts. /// - public void SetIterCounts(InputArray val) + public void SetIterCounts(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_setIterCounts(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_OdometrySettings_setIterCounts(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Gets the iteration counts. /// - public void GetIterCounts(OutputArray val) + public void GetIterCounts(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_getIterCounts(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_OdometrySettings_getIterCounts(Handle, val.Proxy)); } /// /// Sets the minimum gradient magnitudes. /// - public void SetMinGradientMagnitudes(InputArray val) + public void SetMinGradientMagnitudes(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_setMinGradientMagnitudes(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_OdometrySettings_setMinGradientMagnitudes(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Gets the minimum gradient magnitudes. /// - public void GetMinGradientMagnitudes(OutputArray val) + public void GetMinGradientMagnitudes(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_OdometrySettings_getMinGradientMagnitudes(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_OdometrySettings_getMinGradientMagnitudes(Handle, val.Proxy)); } #endregion diff --git a/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs b/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs index 6c4287008..d0338dc0d 100644 --- a/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs +++ b/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs @@ -45,14 +45,13 @@ private static IntPtr GetRawPtr(IntPtr smartPtr) /// threshold in depth difference, used in LINEMOD algorithm. /// one of the methods to use. public static RgbdNormals Create( - int rows = 0, int cols = 0, int depth = 0, InputArray? K = null, int windowSize = 5, + int rows = 0, int cols = 0, int depth = 0, InputArrayRef K = default, int windowSize = 5, float diffThreshold = 50f, RgbdNormalsMethod method = RgbdNormalsMethod.RGBD_NORMALS_METHOD_FALS) { - K?.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.ptcloud_RgbdNormals_create( - rows, cols, depth, K?.ToInputProxy() ?? default, windowSize, diffThreshold, (int)method, out var p)); - GC.KeepAlive(K); + rows, cols, depth, K.Proxy, windowSize, diffThreshold, (int)method, out var p)); + GC.KeepAlive(K.Source); return new RgbdNormals(p); } @@ -73,19 +72,12 @@ public void Release() /// /// a rows x cols x 3 matrix of CV_32F/CV_64F or a rows x cols x 1 CV_16U. /// a rows x cols x 3 matrix. - public void Apply(InputArray points, OutputArray normals) + public void Apply(InputArrayRef points, OutputArrayRef normals) { ThrowIfDisposed(); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - points.ThrowIfDisposed(); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_RgbdNormals_apply(Handle, points.ToInputProxy(), normals.ToOutputProxy())); - normals.Fix(); - GC.KeepAlive(points); + NativeMethods.ptcloud_RgbdNormals_apply(Handle, points.Proxy, normals.Proxy)); + GC.KeepAlive(points.Source); } /// @@ -177,30 +169,23 @@ public int Depth /// Gets the calibration matrix. /// /// the output calibration matrix. - public void GetK(OutputArray val) + public void GetK(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_RgbdNormals_getK(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_RgbdNormals_getK(Handle, val.Proxy)); } /// /// Sets the calibration matrix. /// /// the calibration matrix to use. - public void SetK(InputArray val) + public void SetK(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_RgbdNormals_setK(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_RgbdNormals_setK(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// diff --git a/src/OpenCvSharp/Modules/ptcloud/Volume.cs b/src/OpenCvSharp/Modules/ptcloud/Volume.cs index 3b8767c4a..39f610e8f 100644 --- a/src/OpenCvSharp/Modules/ptcloud/Volume.cs +++ b/src/OpenCvSharp/Modules/ptcloud/Volume.cs @@ -66,19 +66,16 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) /// /// the object from which to take depth and image data. /// the pose of camera in global coordinates. - public void IntegrateFrame(OdometryFrame frame, InputArray pose) + public void IntegrateFrame(OdometryFrame frame, InputArrayRef pose) { ThrowIfDisposed(); if (frame is null) throw new ArgumentNullException(nameof(frame)); - if (pose is null) - throw new ArgumentNullException(nameof(pose)); frame.ThrowIfDisposed(); - pose.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_integrateFrame(Handle, frame.CvPtr, pose.ToInputProxy())); + NativeMethods.ptcloud_Volume_integrateFrame(Handle, frame.CvPtr, pose.Proxy)); GC.KeepAlive(frame); - GC.KeepAlive(pose); + GC.KeepAlive(pose.Source); } /// @@ -86,19 +83,13 @@ public void IntegrateFrame(OdometryFrame frame, InputArray pose) /// /// the depth image. /// the pose of camera in global coordinates. - public void Integrate(InputArray depth, InputArray pose) + public void Integrate(InputArrayRef depth, InputArrayRef pose) { ThrowIfDisposed(); - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - if (pose is null) - throw new ArgumentNullException(nameof(pose)); - depth.ThrowIfDisposed(); - pose.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_integrate(Handle, depth.ToInputProxy(), pose.ToInputProxy())); - GC.KeepAlive(depth); - GC.KeepAlive(pose); + NativeMethods.ptcloud_Volume_integrate(Handle, depth.Proxy, pose.Proxy)); + GC.KeepAlive(depth.Source); + GC.KeepAlive(pose.Source); } /// @@ -107,23 +98,14 @@ public void Integrate(InputArray depth, InputArray pose) /// the depth image. /// the color image (only for ColorTSDF). /// the pose of camera in global coordinates. - public void IntegrateColor(InputArray depth, InputArray image, InputArray pose) + public void IntegrateColor(InputArrayRef depth, InputArrayRef image, InputArrayRef pose) { ThrowIfDisposed(); - if (depth is null) - throw new ArgumentNullException(nameof(depth)); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (pose is null) - throw new ArgumentNullException(nameof(pose)); - depth.ThrowIfDisposed(); - image.ThrowIfDisposed(); - pose.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_integrateColor(Handle, depth.ToInputProxy(), image.ToInputProxy(), pose.ToInputProxy())); - GC.KeepAlive(depth); - GC.KeepAlive(image); - GC.KeepAlive(pose); + NativeMethods.ptcloud_Volume_integrateColor(Handle, depth.Proxy, image.Proxy, pose.Proxy)); + GC.KeepAlive(depth.Source); + GC.KeepAlive(image.Source); + GC.KeepAlive(pose.Source); } #endregion @@ -136,23 +118,12 @@ public void IntegrateColor(InputArray depth, InputArray image, InputArray pose) /// the pose of camera in global coordinates. /// image to store rendered points. /// image to store rendered normals corresponding to points. - public void Raycast(InputArray cameraPose, OutputArray points, OutputArray normals) + public void Raycast(InputArrayRef cameraPose, OutputArrayRef points, OutputArrayRef normals) { ThrowIfDisposed(); - if (cameraPose is null) - throw new ArgumentNullException(nameof(cameraPose)); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - cameraPose.ThrowIfDisposed(); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_raycast(Handle, cameraPose.ToInputProxy(), points.ToOutputProxy(), normals.ToOutputProxy())); - points.Fix(); - normals.Fix(); - GC.KeepAlive(cameraPose); + NativeMethods.ptcloud_Volume_raycast(Handle, cameraPose.Proxy, points.Proxy, normals.Proxy)); + GC.KeepAlive(cameraPose.Source); } /// @@ -162,27 +133,12 @@ public void Raycast(InputArray cameraPose, OutputArray points, OutputArray norma /// image to store rendered points. /// image to store rendered normals corresponding to points. /// image to store rendered colors corresponding to points (only for ColorTSDF). - public void RaycastColor(InputArray cameraPose, OutputArray points, OutputArray normals, OutputArray colors) + public void RaycastColor(InputArrayRef cameraPose, OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) { ThrowIfDisposed(); - if (cameraPose is null) - throw new ArgumentNullException(nameof(cameraPose)); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - if (colors is null) - throw new ArgumentNullException(nameof(colors)); - cameraPose.ThrowIfDisposed(); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); - colors.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_raycastColor(Handle, cameraPose.ToInputProxy(), points.ToOutputProxy(), normals.ToOutputProxy(), colors.ToOutputProxy())); - points.Fix(); - normals.Fix(); - colors.Fix(); - GC.KeepAlive(cameraPose); + NativeMethods.ptcloud_Volume_raycastColor(Handle, cameraPose.Proxy, points.Proxy, normals.Proxy, colors.Proxy)); + GC.KeepAlive(cameraPose.Source); } /// @@ -194,27 +150,13 @@ public void RaycastColor(InputArray cameraPose, OutputArray points, OutputArray /// camera raycast intrinsics. /// image to store rendered points. /// image to store rendered normals corresponding to points. - public void RaycastEx(InputArray cameraPose, int height, int width, InputArray K, OutputArray points, OutputArray normals) + public void RaycastEx(InputArrayRef cameraPose, int height, int width, InputArrayRef K, OutputArrayRef points, OutputArrayRef normals) { ThrowIfDisposed(); - if (cameraPose is null) - throw new ArgumentNullException(nameof(cameraPose)); - if (K is null) - throw new ArgumentNullException(nameof(K)); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - cameraPose.ThrowIfDisposed(); - K.ThrowIfDisposed(); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_raycastEx(Handle, cameraPose.ToInputProxy(), height, width, K.ToInputProxy(), points.ToOutputProxy(), normals.ToOutputProxy())); - points.Fix(); - normals.Fix(); - GC.KeepAlive(cameraPose); - GC.KeepAlive(K); + NativeMethods.ptcloud_Volume_raycastEx(Handle, cameraPose.Proxy, height, width, K.Proxy, points.Proxy, normals.Proxy)); + GC.KeepAlive(cameraPose.Source); + GC.KeepAlive(K.Source); } /// @@ -227,31 +169,13 @@ public void RaycastEx(InputArray cameraPose, int height, int width, InputArray K /// image to store rendered points. /// image to store rendered normals corresponding to points. /// image to store rendered colors corresponding to points (only for ColorTSDF). - public void RaycastExColor(InputArray cameraPose, int height, int width, InputArray K, OutputArray points, OutputArray normals, OutputArray colors) + public void RaycastExColor(InputArrayRef cameraPose, int height, int width, InputArrayRef K, OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) { ThrowIfDisposed(); - if (cameraPose is null) - throw new ArgumentNullException(nameof(cameraPose)); - if (K is null) - throw new ArgumentNullException(nameof(K)); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - if (colors is null) - throw new ArgumentNullException(nameof(colors)); - cameraPose.ThrowIfDisposed(); - K.ThrowIfDisposed(); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); - colors.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_raycastExColor(Handle, cameraPose.ToInputProxy(), height, width, K.ToInputProxy(), points.ToOutputProxy(), normals.ToOutputProxy(), colors.ToOutputProxy())); - points.Fix(); - normals.Fix(); - colors.Fix(); - GC.KeepAlive(cameraPose); - GC.KeepAlive(K); + NativeMethods.ptcloud_Volume_raycastExColor(Handle, cameraPose.Proxy, height, width, K.Proxy, points.Proxy, normals.Proxy, colors.Proxy)); + GC.KeepAlive(cameraPose.Source); + GC.KeepAlive(K.Source); } #endregion @@ -263,19 +187,12 @@ public void RaycastExColor(InputArray cameraPose, int height, int width, InputAr /// /// the input existing points. /// the storage of normals (corresponding to input points). - public void FetchNormals(InputArray points, OutputArray normals) + public void FetchNormals(InputArrayRef points, OutputArrayRef normals) { ThrowIfDisposed(); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - points.ThrowIfDisposed(); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_fetchNormals(Handle, points.ToInputProxy(), normals.ToOutputProxy())); - normals.Fix(); - GC.KeepAlive(points); + NativeMethods.ptcloud_Volume_fetchNormals(Handle, points.Proxy, normals.Proxy)); + GC.KeepAlive(points.Source); } /// @@ -283,19 +200,11 @@ public void FetchNormals(InputArray points, OutputArray normals) /// /// the storage of all points. /// the storage of all normals, corresponding to points. - public void FetchPointsNormals(OutputArray points, OutputArray normals) + public void FetchPointsNormals(OutputArrayRef points, OutputArrayRef normals) { ThrowIfDisposed(); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_fetchPointsNormals(Handle, points.ToOutputProxy(), normals.ToOutputProxy())); - points.Fix(); - normals.Fix(); + NativeMethods.ptcloud_Volume_fetchPointsNormals(Handle, points.Proxy, normals.Proxy)); } /// @@ -304,23 +213,11 @@ public void FetchPointsNormals(OutputArray points, OutputArray normals) /// the storage of all points. /// the storage of all normals, corresponding to points. /// the storage of all colors, corresponding to points (only for ColorTSDF). - public void FetchPointsNormalsColors(OutputArray points, OutputArray normals, OutputArray colors) + public void FetchPointsNormalsColors(OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) { ThrowIfDisposed(); - if (points is null) - throw new ArgumentNullException(nameof(points)); - if (normals is null) - throw new ArgumentNullException(nameof(normals)); - if (colors is null) - throw new ArgumentNullException(nameof(colors)); - points.ThrowIfNotReady(); - normals.ThrowIfNotReady(); - colors.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_fetchPointsNormalsColors(Handle, points.ToOutputProxy(), normals.ToOutputProxy(), colors.ToOutputProxy())); - points.Fix(); - normals.Fix(); - colors.Fix(); + NativeMethods.ptcloud_Volume_fetchPointsNormalsColors(Handle, points.Proxy, normals.Proxy, colors.Proxy)); } #endregion @@ -364,15 +261,11 @@ public long GetTotalVolumeUnits() /// /// 6-float 1d array containing (min_x, min_y, min_z, max_x, max_y, max_z) in volume coordinates. /// bounding box calculation precision. - public void GetBoundingBox(OutputArray bb, VolumeBoundingBoxPrecision precision) + public void GetBoundingBox(OutputArrayRef bb, VolumeBoundingBoxPrecision precision) { ThrowIfDisposed(); - if (bb is null) - throw new ArgumentNullException(nameof(bb)); - bb.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_Volume_getBoundingBox(Handle, bb.ToOutputProxy(), (int)precision)); - bb.Fix(); + NativeMethods.ptcloud_Volume_getBoundingBox(Handle, bb.Proxy, (int)precision)); } /// diff --git a/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs b/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs index e84d3747f..8a86cda13 100644 --- a/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs +++ b/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs @@ -251,135 +251,103 @@ public float RaycastStepFactor /// Sets volume pose. /// /// input value. - public void SetVolumePose(InputArray val) + public void SetVolumePose(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_setVolumePose(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_VolumeSettings_setVolumePose(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Gets volume pose. /// /// output value. - public void GetVolumePose(OutputArray val) + public void GetVolumePose(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_getVolumePose(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_VolumeSettings_getVolumePose(Handle, val.Proxy)); } /// /// Sets resolution of voxel space. /// /// input value. - public void SetVolumeResolution(InputArray val) + public void SetVolumeResolution(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_setVolumeResolution(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_VolumeSettings_setVolumeResolution(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Gets resolution of voxel space. /// /// output value. - public void GetVolumeResolution(OutputArray val) + public void GetVolumeResolution(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_getVolumeResolution(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_VolumeSettings_getVolumeResolution(Handle, val.Proxy)); } /// /// Returns 3 integers representing strides by x, y and z dimension. /// /// output value. - public void GetVolumeStrides(OutputArray val) + public void GetVolumeStrides(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_getVolumeStrides(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_VolumeSettings_getVolumeStrides(Handle, val.Proxy)); } /// /// Sets intrinsics of camera for integrations. /// /// input value. - public void SetCameraIntegrateIntrinsics(InputArray val) + public void SetCameraIntegrateIntrinsics(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_setCameraIntegrateIntrinsics(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_VolumeSettings_setCameraIntegrateIntrinsics(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Returns intrinsics of camera for integrations. /// /// output value. - public void GetCameraIntegrateIntrinsics(OutputArray val) + public void GetCameraIntegrateIntrinsics(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_getCameraIntegrateIntrinsics(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_VolumeSettings_getCameraIntegrateIntrinsics(Handle, val.Proxy)); } /// /// Sets camera intrinsics for raycast image. /// /// input value. - public void SetCameraRaycastIntrinsics(InputArray val) + public void SetCameraRaycastIntrinsics(InputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_setCameraRaycastIntrinsics(Handle, val.ToInputProxy())); - GC.KeepAlive(val); + NativeMethods.ptcloud_VolumeSettings_setCameraRaycastIntrinsics(Handle, val.Proxy)); + GC.KeepAlive(val.Source); } /// /// Returns camera intrinsics for raycast image. /// /// output value. - public void GetCameraRaycastIntrinsics(OutputArray val) + public void GetCameraRaycastIntrinsics(OutputArrayRef val) { ThrowIfDisposed(); - if (val is null) - throw new ArgumentNullException(nameof(val)); - val.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ptcloud_VolumeSettings_getCameraRaycastIntrinsics(Handle, val.ToOutputProxy())); - val.Fix(); + NativeMethods.ptcloud_VolumeSettings_getCameraRaycastIntrinsics(Handle, val.Proxy)); } #endregion diff --git a/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs b/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs index adf873792..4306f5d44 100644 --- a/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs +++ b/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs @@ -32,21 +32,14 @@ public static MotionSaliencyBinWangApr2014 Create() /// Input image frame (grayscale, CV_8UC1). /// The computed binary saliency map. /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) + public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (saliencyMap is null) - throw new ArgumentNullException(nameof(saliencyMap)); - image.ThrowIfDisposed(); - saliencyMap.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.saliency_MotionSaliencyBinWangApr2014_computeSaliency( - Handle, image.ToInputProxy(), saliencyMap.ToOutputProxy(), out var ret)); - GC.KeepAlive(image); - saliencyMap.Fix(); + Handle, image.Proxy, saliencyMap.Proxy, out var ret)); + GC.KeepAlive(image.Source); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs b/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs index 24bb29484..d36e960f5 100644 --- a/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs +++ b/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs @@ -37,18 +37,15 @@ public static ObjectnessBING Create() /// Sorted by descending objectness score. /// /// true if the computation succeeded. - public virtual bool ComputeSaliency(InputArray image, out Vec4i[] objectnessBoundingBox) + public virtual bool ComputeSaliency(InputArrayRef image, out Vec4i[] objectnessBoundingBox) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); using var vec = new StdVector(); NativeMethods.HandleException( NativeMethods.saliency_ObjectnessBING_computeSaliency( - Handle, image.ToInputProxy(), vec.CvPtr, out var ret)); - GC.KeepAlive(image); + Handle, image.Proxy, vec.CvPtr, out var ret)); + GC.KeepAlive(image.Source); objectnessBoundingBox = vec.ToArray(); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs b/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs index 35bdc5a99..3969d19ba 100644 --- a/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs +++ b/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs @@ -32,21 +32,14 @@ public static StaticSaliencyFineGrained Create() /// The input image. /// The computed saliency map. /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) + public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (saliencyMap is null) - throw new ArgumentNullException(nameof(saliencyMap)); - image.ThrowIfDisposed(); - saliencyMap.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.saliency_StaticSaliencyFineGrained_computeSaliency( - Handle, image.ToInputProxy(), saliencyMap.ToOutputProxy(), out var ret)); - GC.KeepAlive(image); - saliencyMap.Fix(); + Handle, image.Proxy, saliencyMap.Proxy, out var ret)); + GC.KeepAlive(image.Source); return ret != 0; } @@ -56,21 +49,14 @@ public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) /// The input saliency map. /// The computed binary map. /// true if the binary map was computed successfully. - public virtual bool ComputeBinaryMap(InputArray saliencyMap, OutputArray binaryMap) + public virtual bool ComputeBinaryMap(InputArrayRef saliencyMap, OutputArrayRef binaryMap) { ThrowIfDisposed(); - if (saliencyMap is null) - throw new ArgumentNullException(nameof(saliencyMap)); - if (binaryMap is null) - throw new ArgumentNullException(nameof(binaryMap)); - saliencyMap.ThrowIfDisposed(); - binaryMap.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.saliency_StaticSaliencyFineGrained_computeBinaryMap( - Handle, saliencyMap.ToInputProxy(), binaryMap.ToOutputProxy(), out var ret)); - GC.KeepAlive(saliencyMap); - binaryMap.Fix(); + Handle, saliencyMap.Proxy, binaryMap.Proxy, out var ret)); + GC.KeepAlive(saliencyMap.Source); return ret != 0; } } diff --git a/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs b/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs index cd43cf9d0..56e1516ca 100644 --- a/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs +++ b/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs @@ -32,21 +32,14 @@ public static StaticSaliencySpectralResidual Create() /// The input image. /// The computed saliency map (CV_32FC1). /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) + public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (saliencyMap is null) - throw new ArgumentNullException(nameof(saliencyMap)); - image.ThrowIfDisposed(); - saliencyMap.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.saliency_StaticSaliencySpectralResidual_computeSaliency( - Handle, image.ToInputProxy(), saliencyMap.ToOutputProxy(), out var ret)); - GC.KeepAlive(image); - saliencyMap.Fix(); + Handle, image.Proxy, saliencyMap.Proxy, out var ret)); + GC.KeepAlive(image.Source); return ret != 0; } @@ -56,21 +49,14 @@ public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) /// The input saliency map (CV_32FC1). /// The computed binary map. /// true if the binary map was computed successfully. - public virtual bool ComputeBinaryMap(InputArray saliencyMap, OutputArray binaryMap) + public virtual bool ComputeBinaryMap(InputArrayRef saliencyMap, OutputArrayRef binaryMap) { ThrowIfDisposed(); - if (saliencyMap is null) - throw new ArgumentNullException(nameof(saliencyMap)); - if (binaryMap is null) - throw new ArgumentNullException(nameof(binaryMap)); - saliencyMap.ThrowIfDisposed(); - binaryMap.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.saliency_StaticSaliencySpectralResidual_computeBinaryMap( - Handle, saliencyMap.ToInputProxy(), binaryMap.ToOutputProxy(), out var ret)); - GC.KeepAlive(saliencyMap); - binaryMap.Fix(); + Handle, saliencyMap.Proxy, binaryMap.Proxy, out var ret)); + GC.KeepAlive(saliencyMap.Source); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs b/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs index bea574c62..cdb8d9961 100644 --- a/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs +++ b/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs @@ -81,20 +81,13 @@ public static EMDL1HistogramCostExtractor CreateEMDL1HistogramCostExtractor( /// First signature: a single-column float matrix where each row is a histogram bin value. /// Second signature, same format and size as signature1. /// The EMDL1 distance. - public static float EMDL1(InputArray signature1, InputArray signature2) + public static float EMDL1(InputArrayRef signature1, InputArrayRef signature2) { - if (signature1 is null) - throw new ArgumentNullException(nameof(signature1)); - if (signature2 is null) - throw new ArgumentNullException(nameof(signature2)); - signature1.ThrowIfDisposed(); - signature2.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.shape_EMDL1(signature1.ToInputProxy(), signature2.ToInputProxy(), out var ret)); + NativeMethods.shape_EMDL1(signature1.Proxy, signature2.Proxy, out var ret)); - GC.KeepAlive(signature1); - GC.KeepAlive(signature2); + GC.KeepAlive(signature1.Source); + GC.KeepAlive(signature2.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs b/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs index beb0ecf8c..acf680ea2 100644 --- a/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs @@ -18,26 +18,16 @@ protected HistogramCostExtractor(IntPtr smartPtr, IntPtr rawPtr, Action /// Second set of descriptors. /// Output cost matrix. public virtual void BuildCostMatrix( - InputArray descriptors1, InputArray descriptors2, OutputArray costMatrix) + InputArrayRef descriptors1, InputArrayRef descriptors2, OutputArrayRef costMatrix) { ThrowIfDisposed(); - if (descriptors1 is null) - throw new ArgumentNullException(nameof(descriptors1)); - if (descriptors2 is null) - throw new ArgumentNullException(nameof(descriptors2)); - if (costMatrix is null) - throw new ArgumentNullException(nameof(costMatrix)); - descriptors1.ThrowIfDisposed(); - descriptors2.ThrowIfDisposed(); - costMatrix.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.shape_HistogramCostExtractor_buildCostMatrix( - Handle, descriptors1.ToInputProxy(), descriptors2.ToInputProxy(), costMatrix.ToOutputProxy())); + Handle, descriptors1.Proxy, descriptors2.Proxy, costMatrix.Proxy)); - GC.KeepAlive(descriptors1); - GC.KeepAlive(descriptors2); - costMatrix.Fix(); + GC.KeepAlive(descriptors1.Source); + GC.KeepAlive(descriptors2.Source); } /// diff --git a/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs b/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs index a8370a37a..d2dfd40cb 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs @@ -255,21 +255,15 @@ public float StdDev /// /// Image corresponding to the shape defined by contours1. /// Image corresponding to the shape defined by contours2. - public void SetImages(InputArray image1, InputArray image2) + public void SetImages(InputArrayRef image1, InputArrayRef image2) { ThrowIfDisposed(); - if (image1 is null) - throw new ArgumentNullException(nameof(image1)); - if (image2 is null) - throw new ArgumentNullException(nameof(image2)); - image1.ThrowIfDisposed(); - image2.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.shape_ShapeContextDistanceExtractor_setImages(Handle, image1.ToInputProxy(), image2.ToInputProxy())); + NativeMethods.shape_ShapeContextDistanceExtractor_setImages(Handle, image1.Proxy, image2.Proxy)); - GC.KeepAlive(image1); - GC.KeepAlive(image2); + GC.KeepAlive(image1.Source); + GC.KeepAlive(image2.Source); } /// @@ -278,23 +272,15 @@ public void SetImages(InputArray image1, InputArray image2) /// /// Image corresponding to the shape defined by contours1. /// Image corresponding to the shape defined by contours2. - public void GetImages(OutputArray image1, OutputArray image2) + public void GetImages(OutputArrayRef image1, OutputArrayRef image2) { ThrowIfDisposed(); - if (image1 is null) - throw new ArgumentNullException(nameof(image1)); - if (image2 is null) - throw new ArgumentNullException(nameof(image2)); - image1.ThrowIfNotReady(); - image2.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.shape_ShapeContextDistanceExtractor_getImages(Handle, image1.ToOutputProxy(), image2.ToOutputProxy())); + NativeMethods.shape_ShapeContextDistanceExtractor_getImages(Handle, image1.Proxy, image2.Proxy)); - image1.Fix(); - image2.Fix(); - GC.KeepAlive(image1); - GC.KeepAlive(image2); + GC.KeepAlive(image1.Source); + GC.KeepAlive(image2.Source); } #endregion diff --git a/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs b/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs index e329d59b5..b69b715cf 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs @@ -19,22 +19,16 @@ protected ShapeDistanceExtractor(IntPtr smartPtr, IntPtr rawPtr, Action /// Contour defining second shape. /// /// - public virtual float ComputeDistance(InputArray contour1, InputArray contour2) + public virtual float ComputeDistance(InputArrayRef contour1, InputArrayRef contour2) { ThrowIfDisposed(); - if (contour1 is null) - throw new ArgumentNullException(nameof(contour1)); - if (contour2 is null) - throw new ArgumentNullException(nameof(contour2)); - contour1.ThrowIfDisposed(); - contour2.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.shape_ShapeDistanceExtractor_computeDistance( - Handle, contour1.ToInputProxy(), contour2.ToInputProxy(), out var ret)); + Handle, contour1.Proxy, contour2.Proxy, out var ret)); - GC.KeepAlive(contour1); - GC.KeepAlive(contour2); + GC.KeepAlive(contour1.Source); + GC.KeepAlive(contour2.Source); return ret; } diff --git a/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs b/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs index 6484bab46..ee804a9fa 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs @@ -27,27 +27,21 @@ protected ShapeTransformer(IntPtr smartPtr, IntPtr rawPtr, Action releas /// Contour defining second shape (to which the first will be transformed). /// Vector of matching points between the two contours. public virtual void EstimateTransformation( - InputArray transformingShape, - InputArray targetShape, + InputArrayRef transformingShape, + InputArrayRef targetShape, IEnumerable matches) { ThrowIfDisposed(); - if (transformingShape is null) - throw new ArgumentNullException(nameof(transformingShape)); - if (targetShape is null) - throw new ArgumentNullException(nameof(targetShape)); if (matches is null) throw new ArgumentNullException(nameof(matches)); - transformingShape.ThrowIfDisposed(); - targetShape.ThrowIfDisposed(); using var matchesVec = new StdVector(matches); NativeMethods.HandleException( NativeMethods.shape_ShapeTransformer_estimateTransformation( - Handle, transformingShape.ToInputProxy(), targetShape.ToInputProxy(), matchesVec.CvPtr)); + Handle, transformingShape.Proxy, targetShape.Proxy, matchesVec.CvPtr)); - GC.KeepAlive(transformingShape); - GC.KeepAlive(targetShape); + GC.KeepAlive(transformingShape.Source); + GC.KeepAlive(targetShape.Source); } /// @@ -56,20 +50,15 @@ public virtual void EstimateTransformation( /// Contour (set of points) to apply the transformation to. /// Output contour. If null, only the cost is returned without writing the output. /// The transformation cost. - public virtual float ApplyTransformation(InputArray input, OutputArray? output = null) + public virtual float ApplyTransformation(InputArrayRef input, OutputArrayRef output = default) { ThrowIfDisposed(); - if (input is null) - throw new ArgumentNullException(nameof(input)); - input.ThrowIfDisposed(); - output?.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.shape_ShapeTransformer_applyTransformation( - Handle, input.ToInputProxy(), output?.ToOutputProxy() ?? default, out var ret)); + Handle, input.Proxy, output.Proxy, out var ret)); - GC.KeepAlive(input); - output?.Fix(); + GC.KeepAlive(input.Source); return ret; } @@ -83,30 +72,23 @@ public virtual float ApplyTransformation(InputArray input, OutputArray? output = /// Border extrapolation method. Default: BorderTypes.Constant. /// Value used for BorderTypes.Constant borders. Default: black. public virtual void WarpImage( - InputArray transformingImage, - OutputArray output, + InputArrayRef transformingImage, + OutputArrayRef output, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) { ThrowIfDisposed(); - if (transformingImage is null) - throw new ArgumentNullException(nameof(transformingImage)); - if (output is null) - throw new ArgumentNullException(nameof(output)); - transformingImage.ThrowIfDisposed(); - output.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.shape_ShapeTransformer_warpImage( Handle, - transformingImage.ToInputProxy(), - output.ToOutputProxy(), + transformingImage.Proxy, + output.Proxy, (int)flags, (int)borderMode, borderValue.GetValueOrDefault(Scalar.All(0)))); - GC.KeepAlive(transformingImage); - output.Fix(); + GC.KeepAlive(transformingImage.Source); } } \ No newline at end of file diff --git a/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs b/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs index 35df38ca1..e6dfef25b 100644 --- a/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs +++ b/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs @@ -23,24 +23,13 @@ protected StereoMatcher(IntPtr smartPtr, IntPtr rawPtr, Action release) /// Output disparity map. It has the same size as the input images. Some algorithms, /// like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map(where each disparity value has 4 fractional bits), /// whereas other algorithms output 32 - bit floating - point disparity map. - public virtual void Compute(InputArray left, InputArray right, OutputArray disparity) + public virtual void Compute(InputArrayRef left, InputArrayRef right, OutputArrayRef disparity) { - if (left is null) - throw new ArgumentNullException(nameof(left)); - if (right is null) - throw new ArgumentNullException(nameof(right)); - if (disparity is null) - throw new ArgumentNullException(nameof(disparity)); - left.ThrowIfDisposed(); - right.ThrowIfDisposed(); - disparity.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.stereo_StereoMatcher_compute(Handle, left.ToInputProxy(), right.ToInputProxy(), disparity.ToOutputProxy())); + NativeMethods.stereo_StereoMatcher_compute(Handle, left.Proxy, right.Proxy, disparity.Proxy)); - GC.KeepAlive(left); - GC.KeepAlive(right); - disparity.Fix(); + GC.KeepAlive(left.Source); + GC.KeepAlive(right.Source); } /// diff --git a/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs b/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs index 7c76fce1f..e715aa6a0 100644 --- a/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs +++ b/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs @@ -64,15 +64,12 @@ public static ImageFeatures[] ComputeImageFeatures( /// public static ImageFeatures ComputeImageFeatures( Feature2D featuresFinder, - InputArray image, - InputArray? mask = null) + InputArrayRef image, + InputArrayRef mask = default) { if (featuresFinder is null) throw new ArgumentNullException(nameof(featuresFinder)); - if (image is null) - throw new ArgumentNullException(nameof(image)); featuresFinder.ThrowIfDisposed(); - image.ThrowIfDisposed(); var descriptorsMat = new Mat(); using var keypointsVec = new StdVector(); @@ -85,12 +82,12 @@ public static ImageFeatures ComputeImageFeatures( unsafe { NativeMethods.HandleException( - NativeMethods.stitching_computeImageFeatures2(featuresFinder.RawPtr, image.ToInputProxy(), &wImageFeatures, mask?.ToInputProxy() ?? default)); + NativeMethods.stitching_computeImageFeatures2(featuresFinder.RawPtr, image.Proxy, &wImageFeatures, mask.Proxy)); } GC.KeepAlive(featuresFinder); - GC.KeepAlive(image); - GC.KeepAlive(mask); + GC.KeepAlive(image.Source); + GC.KeepAlive(mask.Source); GC.KeepAlive(descriptorsMat); return new ImageFeatures( diff --git a/src/OpenCvSharp/Modules/stitching/Stitcher.cs b/src/OpenCvSharp/Modules/stitching/Stitcher.cs index c31946e75..f9bc40011 100644 --- a/src/OpenCvSharp/Modules/stitching/Stitcher.cs +++ b/src/OpenCvSharp/Modules/stitching/Stitcher.cs @@ -269,32 +269,25 @@ public double WorkScale #region Methods - public Status EstimateTransform(InputArray images) + public Status EstimateTransform(InputArrayRef images) { - if (images is null) - throw new ArgumentNullException(nameof(images)); - images.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_estimateTransform_InputArray1(Handle, images.ToInputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_estimateTransform_InputArray1(Handle, images.Proxy, out var ret)); - GC.KeepAlive(images); + GC.KeepAlive(images.Source); return (Status)ret; } - public Status EstimateTransform(InputArray images, Rect[][] rois) + public Status EstimateTransform(InputArrayRef images, Rect[][] rois) { - if (images is null) - throw new ArgumentNullException(nameof(images)); if (rois is null) throw new ArgumentNullException(nameof(rois)); - images.ThrowIfDisposed(); using var roisPointer = new ArrayAddress2(rois); NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_estimateTransform_InputArray2(Handle, images.ToInputProxy(), roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), out var ret)); + NativeMethods.stitching_Stitcher_estimateTransform_InputArray2(Handle, images.Proxy, roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), out var ret)); - GC.KeepAlive(images); + GC.KeepAlive(images.Source); return (Status)ret; } @@ -332,53 +325,36 @@ public Status EstimateTransform(IEnumerable images, Rect[][] rois) return (Status)ret; } - public Status ComposePanorama(OutputArray pano) + public Status ComposePanorama(OutputArrayRef pano) { - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - pano.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_composePanorama1(Handle, pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_composePanorama1(Handle, pano.Proxy, out var ret)); - pano.Fix(); - GC.KeepAlive(pano); + GC.KeepAlive(pano.Source); return (Status)ret; } - public Status ComposePanorama(InputArray images, OutputArray pano) + public Status ComposePanorama(InputArrayRef images, OutputArrayRef pano) { - if (images is null) - throw new ArgumentNullException(nameof(images)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - images.ThrowIfDisposed(); - pano.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_composePanorama2_InputArray(Handle, images.ToInputProxy(), pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_composePanorama2_InputArray(Handle, images.Proxy, pano.Proxy, out var ret)); - pano.Fix(); - GC.KeepAlive(images); - GC.KeepAlive(pano); + GC.KeepAlive(images.Source); + GC.KeepAlive(pano.Source); return (Status)ret; } - public Status ComposePanorama(IEnumerable images, OutputArray pano) + public Status ComposePanorama(IEnumerable images, OutputArrayRef pano) { if (images is null) throw new ArgumentNullException(nameof(images)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - pano.ThrowIfNotReady(); var imagesPtrs = images.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_composePanorama2_MatArray(Handle, imagesPtrs, imagesPtrs.Length, pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_composePanorama2_MatArray(Handle, imagesPtrs, imagesPtrs.Length, pano.Proxy, out var ret)); - pano.Fix(); GC.KeepAlive(images); - GC.KeepAlive(pano); + GC.KeepAlive(pano.Source); return (Status)ret; } @@ -388,21 +364,13 @@ public Status ComposePanorama(IEnumerable images, OutputArray pano) /// Input images. /// Final pano. /// Status code. - public Status Stitch(InputArray images, OutputArray pano) + public Status Stitch(InputArrayRef images, OutputArrayRef pano) { - if (images is null) - throw new ArgumentNullException(nameof(images)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - images.ThrowIfDisposed(); - pano.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_stitch1_InputArray(Handle, images.ToInputProxy(), pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_stitch1_InputArray(Handle, images.Proxy, pano.Proxy, out var ret)); - GC.KeepAlive(images); - GC.KeepAlive(pano); - pano.Fix(); + GC.KeepAlive(images.Source); + GC.KeepAlive(pano.Source); return (Status)ret; } @@ -413,22 +381,18 @@ public Status Stitch(InputArray images, OutputArray pano) /// Input images. /// Final pano. /// Status code. - public Status Stitch(IEnumerable images, OutputArray pano) + public Status Stitch(IEnumerable images, OutputArrayRef pano) { if (images is null) throw new ArgumentNullException(nameof(images)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - pano.ThrowIfNotReady(); var imagesPtrs = images.Select(x => x.CvPtr).ToArray(); NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_stitch1_MatArray(Handle, imagesPtrs, imagesPtrs.Length, pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_stitch1_MatArray(Handle, imagesPtrs, imagesPtrs.Length, pano.Proxy, out var ret)); GC.KeepAlive(images); - GC.KeepAlive(pano); - pano.Fix(); + GC.KeepAlive(pano.Source); return (Status)ret; } @@ -440,24 +404,17 @@ public Status Stitch(IEnumerable images, OutputArray pano) /// Region of interest rectangles. /// Final pano. /// Status code. - public Status Stitch(InputArray images, Rect[][] rois, OutputArray pano) + public Status Stitch(InputArrayRef images, Rect[][] rois, OutputArrayRef pano) { - if (images is null) - throw new ArgumentNullException(nameof(images)); if (rois is null) throw new ArgumentNullException(nameof(rois)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - images.ThrowIfDisposed(); - pano.ThrowIfNotReady(); using var roisPointer = new ArrayAddress2(rois); NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_stitch2_InputArray(Handle, images.ToInputProxy(), roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_stitch2_InputArray(Handle, images.Proxy, roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), pano.Proxy, out var ret)); - pano.Fix(); - GC.KeepAlive(images); - GC.KeepAlive(pano); + GC.KeepAlive(images.Source); + GC.KeepAlive(pano.Source); return (Status)ret; } @@ -468,25 +425,21 @@ public Status Stitch(InputArray images, Rect[][] rois, OutputArray pano) /// Region of interest rectangles. /// Final pano. /// Status code. - public Status Stitch(IEnumerable images, Rect[][] rois, OutputArray pano) + public Status Stitch(IEnumerable images, Rect[][] rois, OutputArrayRef pano) { if (images is null) throw new ArgumentNullException(nameof(images)); if (rois is null) throw new ArgumentNullException(nameof(rois)); - if (pano is null) - throw new ArgumentNullException(nameof(pano)); - pano.ThrowIfNotReady(); var imagesPtrs = images.Select(x => x.CvPtr).ToArray(); using var roisPointer = new ArrayAddress2(rois); NativeMethods.HandleException( - NativeMethods.stitching_Stitcher_stitch2_MatArray(Handle, imagesPtrs, imagesPtrs.Length, roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), pano.ToOutputProxy(), out var ret)); + NativeMethods.stitching_Stitcher_stitch2_MatArray(Handle, imagesPtrs, imagesPtrs.Length, roisPointer.GetPointer(), roisPointer.GetDim1Length(), roisPointer.GetDim2Lengths(), pano.Proxy, out var ret)); - pano.Fix(); GC.KeepAlive(images); - GC.KeepAlive(pano); + GC.KeepAlive(pano.Source); return (Status)ret; } diff --git a/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs b/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs index b78bff822..a6c923457 100644 --- a/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs +++ b/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs @@ -100,28 +100,15 @@ public virtual void CollectGarbage() /// /// /// - public virtual void Calc(InputArray frame0, InputArray frame1, OutputArray flow1, OutputArray? flow2 = null) + public virtual void Calc(InputArrayRef frame0, InputArrayRef frame1, OutputArrayRef flow1, OutputArrayRef flow2 = default) { - if (frame0 is null) - throw new ArgumentNullException(nameof(frame0)); - if (frame1 is null) - throw new ArgumentNullException(nameof(frame1)); - if (flow1 is null) - throw new ArgumentNullException(nameof(flow1)); - frame0.ThrowIfDisposed(); - frame1.ThrowIfDisposed(); - flow1.ThrowIfNotReady(); - flow2?.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.superres_DenseOpticalFlowExt_calc( - Handle, frame0.ToInputProxy(), frame1.ToInputProxy(), flow1.ToOutputProxy(), flow2?.ToOutputProxy() ?? default)); + Handle, frame0.Proxy, frame1.Proxy, flow1.Proxy, flow2.Proxy)); - GC.KeepAlive(frame0); - GC.KeepAlive(frame1); - GC.KeepAlive(flow1); - GC.KeepAlive(flow2); - flow1.Fix(); - flow2?.Fix(); + GC.KeepAlive(frame0.Source); + GC.KeepAlive(frame1.Source); + GC.KeepAlive(flow1.Source); + GC.KeepAlive(flow2.Source); } } diff --git a/src/OpenCvSharp/Modules/superres/FrameSource.cs b/src/OpenCvSharp/Modules/superres/FrameSource.cs index 802220b03..c070f65ed 100644 --- a/src/OpenCvSharp/Modules/superres/FrameSource.cs +++ b/src/OpenCvSharp/Modules/superres/FrameSource.cs @@ -88,18 +88,14 @@ public static FrameSource CreateFrameSource_Camera(int deviceId) /// /// /// - public virtual void NextFrame(OutputArray frame) + public virtual void NextFrame(OutputArrayRef frame) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.superres_FrameSource_nextFrame(Handle, frame.ToOutputProxy())); + NativeMethods.superres_FrameSource_nextFrame(Handle, frame.Proxy)); - frame.Fix(); - GC.KeepAlive(frame); + GC.KeepAlive(frame.Source); } /// diff --git a/src/OpenCvSharp/Modules/superres/SuperResolution.cs b/src/OpenCvSharp/Modules/superres/SuperResolution.cs index 4f210ac93..a02b9a62c 100644 --- a/src/OpenCvSharp/Modules/superres/SuperResolution.cs +++ b/src/OpenCvSharp/Modules/superres/SuperResolution.cs @@ -77,17 +77,13 @@ public virtual void SetInput(FrameSource fs) /// Process next frame from input and return output result. /// /// Output result - public virtual void NextFrame(OutputArray frame) + public virtual void NextFrame(OutputArrayRef frame) { ThrowIfDisposed(); - if (frame is null) - throw new ArgumentNullException(nameof(frame)); - frame.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.superres_SuperResolution_nextFrame(Handle, frame.ToOutputProxy())); - frame.Fix(); - GC.KeepAlive(frame); + NativeMethods.superres_SuperResolution_nextFrame(Handle, frame.Proxy)); + GC.KeepAlive(frame.Source); } /// @@ -120,7 +116,7 @@ protected virtual void InitImpl(FrameSource fs) /// /// /// - protected virtual void ProcessImpl(FrameSource fs, OutputArray output) + protected virtual void ProcessImpl(FrameSource fs, OutputArrayRef output) { } diff --git a/src/OpenCvSharp/Modules/text/Cv2.Text.cs b/src/OpenCvSharp/Modules/text/Cv2.Text.cs index f9908d77e..4ed6eade9 100644 --- a/src/OpenCvSharp/Modules/text/Cv2.Text.cs +++ b/src/OpenCvSharp/Modules/text/Cv2.Text.cs @@ -27,26 +27,18 @@ public static partial class Text /// paper and returns all possible regions where text is likely to occur. /// a vector of resulting bounding boxes where probability of finding text is high public static Rect[] DetectTextSWT( - InputArray input, bool darkOnLight, OutputArray? draw = null, OutputArray? chainBBs = null) + InputArrayRef input, bool darkOnLight, OutputArrayRef draw = default, OutputArrayRef chainBBs = default) { - if (input is null) - throw new ArgumentNullException(nameof(input)); - input.ThrowIfDisposed(); - draw?.ThrowIfNotReady(); - chainBBs?.ThrowIfNotReady(); - using var result = new StdVector(); NativeMethods.HandleException( NativeMethods.text_detectTextSWT( - input.ToInputProxy(), + input.Proxy, result.CvPtr, darkOnLight ? 1 : 0, - draw?.ToOutputProxy() ?? default, - chainBBs?.ToOutputProxy() ?? default)); + draw.Proxy, + chainBBs.Proxy)); - GC.KeepAlive(input); - draw?.Fix(); - chainBBs?.Fix(); + GC.KeepAlive(input.Source); return result.ToArray(); } diff --git a/src/OpenCvSharp/Modules/text/TextDetector.cs b/src/OpenCvSharp/Modules/text/TextDetector.cs index ef1760635..a06d9108f 100644 --- a/src/OpenCvSharp/Modules/text/TextDetector.cs +++ b/src/OpenCvSharp/Modules/text/TextDetector.cs @@ -14,21 +14,17 @@ public abstract class TextDetector : CvObject /// an image to process /// a vector of Rect that will store the detected word bounding box /// a vector of float that will be updated with the confidence the classifier has for the selected bounding box - public virtual void Detect(InputArray inputImage, out Rect[] bbox, out float[] confidence) + public virtual void Detect(InputArrayRef inputImage, out Rect[] bbox, out float[] confidence) { - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - inputImage.ThrowIfDisposed(); - using (var bboxVec = new StdVector()) using (var confidenceVec = new StdVector()) { NativeMethods.HandleException( - NativeMethods.text_TextDetector_detect(Handle, inputImage.ToInputProxy(), bboxVec.CvPtr, confidenceVec.CvPtr)); + NativeMethods.text_TextDetector_detect(Handle, inputImage.Proxy, bboxVec.CvPtr, confidenceVec.CvPtr)); bbox = bboxVec.ToArray(); confidence = confidenceVec.ToArray(); } - GC.KeepAlive(inputImage); + GC.KeepAlive(inputImage.Source); } } diff --git a/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs b/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs index 8cb0b9384..c9ce72d59 100644 --- a/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs +++ b/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs @@ -70,21 +70,17 @@ internal TextDetectorCNN(IntPtr p) /// an image to process /// a vector of Rect that will store the detected word bounding box /// a vector of float that will be updated with the confidence the classifier has for the selected bounding box - public override void Detect(InputArray inputImage, out Rect[] bbox, out float[] confidence) + public override void Detect(InputArrayRef inputImage, out Rect[] bbox, out float[] confidence) { - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - inputImage.ThrowIfDisposed(); - using var bboxVec = new StdVector(); using var confidenceVec = new StdVector(); NativeMethods.HandleException( NativeMethods.text_TextDetectorCNN_detect( - Handle, inputImage.ToInputProxy(), bboxVec.CvPtr, confidenceVec.CvPtr)); + Handle, inputImage.Proxy, bboxVec.CvPtr, confidenceVec.CvPtr)); bbox = bboxVec.ToArray(); confidence = confidenceVec.ToArray(); - GC.KeepAlive(inputImage); + GC.KeepAlive(inputImage.Source); } } diff --git a/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs b/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs index f430b42e4..e44965812 100644 --- a/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs +++ b/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs @@ -60,16 +60,12 @@ public static TrackerCSRT Create(Params parameters) /// /// /// - public virtual void SetInitialMask(InputArray mask) + public virtual void SetInitialMask(InputArrayRef mask) { - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - mask.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.tracking_TrackerCSRT_setInitialMask(RawPtr, mask.ToInputProxy())); + NativeMethods.tracking_TrackerCSRT_setInitialMask(RawPtr, mask.Proxy)); - GC.KeepAlive(mask); + GC.KeepAlive(mask.Source); } #pragma warning disable CA1034 diff --git a/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs b/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs index 0d3ae9438..c2a760d80 100644 --- a/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs +++ b/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs @@ -19,36 +19,23 @@ protected BackgroundSubtractor(IntPtr smartPtr, IntPtr rawPtr, Action re /// /// /// - public virtual void Apply(InputArray image, OutputArray fgmask, double learningRate = -1) + public virtual void Apply(InputArrayRef image, OutputArrayRef fgmask, double learningRate = -1) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (fgmask is null) - throw new ArgumentNullException(nameof(fgmask)); - image.ThrowIfDisposed(); - fgmask.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.video_BackgroundSubtractor_apply(Handle, image.ToInputProxy(), fgmask.ToOutputProxy(), learningRate)); + NativeMethods.video_BackgroundSubtractor_apply(Handle, image.Proxy, fgmask.Proxy, learningRate)); - fgmask.Fix(); - GC.KeepAlive(image); - GC.KeepAlive(fgmask); + GC.KeepAlive(image.Source); + GC.KeepAlive(fgmask.Source); } /// /// computes a background image /// /// - public virtual void GetBackgroundImage(OutputArray backgroundImage) + public virtual void GetBackgroundImage(OutputArrayRef backgroundImage) { - if (backgroundImage is null) - throw new ArgumentNullException(nameof(backgroundImage)); - backgroundImage.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.video_BackgroundSubtractor_getBackgroundImage(Handle, backgroundImage.ToOutputProxy())); - GC.KeepAlive(backgroundImage); - backgroundImage.Fix(); + NativeMethods.video_BackgroundSubtractor_getBackgroundImage(Handle, backgroundImage.Proxy)); + GC.KeepAlive(backgroundImage.Source); } } diff --git a/src/OpenCvSharp/Modules/videoio/VideoCapture.cs b/src/OpenCvSharp/Modules/videoio/VideoCapture.cs index 1253711c4..b150d5d82 100644 --- a/src/OpenCvSharp/Modules/videoio/VideoCapture.cs +++ b/src/OpenCvSharp/Modules/videoio/VideoCapture.cs @@ -1146,17 +1146,13 @@ public bool Grab() /// the video frame is returned here. If no frames has been grabbed the image will be empty. /// it could be a frame index or a driver specific flag /// - public bool Retrieve(OutputArray image, int flag = 0) + public bool Retrieve(OutputArrayRef image, int flag = 0) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.videoio_VideoCapture_retrieve_OutputArray(Handle, image.ToOutputProxy(), flag, out var ret)); + NativeMethods.videoio_VideoCapture_retrieve_OutputArray(Handle, image.Proxy, flag, out var ret)); - image.Fix(); return ret != 0; } @@ -1170,17 +1166,13 @@ public bool Retrieve(OutputArray image, int flag = 0) /// the video frame is returned here. If no frames has been grabbed the image will be empty. /// non-zero streamIdx is only valid for multi-head camera live streams /// - public bool Retrieve(OutputArray image, CameraChannels streamIdx) + public bool Retrieve(OutputArrayRef image, CameraChannels streamIdx) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.videoio_VideoCapture_retrieve_OutputArray(Handle, image.ToOutputProxy(), (int)streamIdx, out var ret)); + NativeMethods.videoio_VideoCapture_retrieve_OutputArray(Handle, image.Proxy, (int)streamIdx, out var ret)); - image.Fix(); return ret != 0; } @@ -1259,17 +1251,13 @@ public Mat RetrieveMat() /// frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). /// /// `false` if no frames has been grabbed - public bool Read(OutputArray image) + public bool Read(OutputArrayRef image) { ThrowIfDisposed(); - if(image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.videoio_VideoCapture_read_OutputArray(Handle, image.ToOutputProxy(), out var ret)); + NativeMethods.videoio_VideoCapture_read_OutputArray(Handle, image.Proxy, out var ret)); - image.Fix(); return ret != 0; } diff --git a/src/OpenCvSharp/Modules/videoio/VideoWriter.cs b/src/OpenCvSharp/Modules/videoio/VideoWriter.cs index c7aaee013..1a7c0c53a 100644 --- a/src/OpenCvSharp/Modules/videoio/VideoWriter.cs +++ b/src/OpenCvSharp/Modules/videoio/VideoWriter.cs @@ -308,17 +308,14 @@ public void Release() /// /// the written frame. /// - public void Write(InputArray image) + public void Write(InputArrayRef image) { ThrowIfDisposed(); - if(image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.videoio_VideoWriter_write(Handle, image.ToInputProxy())); + NativeMethods.videoio_VideoWriter_write(Handle, image.Proxy)); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); } /// diff --git a/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs b/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs index b1b5a9e10..9fa44d6c4 100644 --- a/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs +++ b/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs @@ -47,20 +47,16 @@ public WeChatQRCode( /// Will be empty if not found. /// /// list of decoded string. - public string[] DetectAndDecode(InputArray inputImage, out Point2f[][] points) + public string[] DetectAndDecode(InputArrayRef inputImage, out Point2f[][] points) { - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - inputImage.ThrowIfDisposed(); - using var pointsVec = new VectorOfVectorPoint2f(); using var texts = new VectorOfString(); NativeMethods.HandleException( NativeMethods.wechat_qrcode_WeChatQRCode_detectAndDecode_points( - Handle, inputImage.ToInputProxy(), pointsVec.CvPtr, texts.CvPtr)); + Handle, inputImage.Proxy, pointsVec.CvPtr, texts.CvPtr)); points = pointsVec.ToArray(); - GC.KeepAlive(inputImage); + GC.KeepAlive(inputImage.Source); return texts.ToArray(); } @@ -75,20 +71,16 @@ public string[] DetectAndDecode(InputArray inputImage, out Point2f[][] points) /// Will be empty if not found. /// /// list of decoded string. - public string[] DetectAndDecodeRaw(InputArray inputImage, out Mat[] bbox) + public string[] DetectAndDecodeRaw(InputArrayRef inputImage, out Mat[] bbox) { - if (inputImage is null) - throw new ArgumentNullException(nameof(inputImage)); - inputImage.ThrowIfDisposed(); - using var bboxVec = new VectorOfMat(); using var texts = new VectorOfString(); NativeMethods.HandleException( NativeMethods.wechat_qrcode_WeChatQRCode_detectAndDecode( - Handle, inputImage.ToInputProxy(), bboxVec.CvPtr, texts.CvPtr)); + Handle, inputImage.Proxy, bboxVec.CvPtr, texts.CvPtr)); bbox = bboxVec.ToArray(); - GC.KeepAlive(inputImage); + GC.KeepAlive(inputImage.Source); return texts.ToArray(); } } diff --git a/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs b/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs index c37d42c4a..8be5756ce 100644 --- a/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs +++ b/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs @@ -91,26 +91,22 @@ public Mat GetVocabulary() /// pointIdxsOfClusters Indices of keypoints that belong to the cluster. /// This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster(word of vocabulary) returned if it is non-zero. /// Descriptors of the image keypoints that are returned if they are non-zero. - public void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray imgDescriptor, + public void Compute(InputArrayRef image, ref KeyPoint[] keypoints, OutputArrayRef imgDescriptor, out int[][] pointIdxsOfClusters, Mat? descriptors = null) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (imgDescriptor is null) - throw new ArgumentNullException(nameof(imgDescriptor)); using (var keypointsVec = new StdVector(keypoints)) using (var pointIdxsOfClustersVec = new VectorOfVectorInt32()) { NativeMethods.HandleException( - NativeMethods.xfeatures2d_BOWImgDescriptorExtractor_compute11(Handle, image.ToInputProxy(), keypointsVec.CvPtr, - imgDescriptor.ToOutputProxy(), pointIdxsOfClustersVec.CvPtr, Cv2.ToPtr(descriptors))); + NativeMethods.xfeatures2d_BOWImgDescriptorExtractor_compute11(Handle, image.Proxy, keypointsVec.CvPtr, + imgDescriptor.Proxy, pointIdxsOfClustersVec.CvPtr, Cv2.ToPtr(descriptors))); keypoints = keypointsVec.ToArray(); pointIdxsOfClusters = pointIdxsOfClustersVec.ToArray(); } - GC.KeepAlive(image); - GC.KeepAlive(imgDescriptor); + GC.KeepAlive(image.Source); + GC.KeepAlive(imgDescriptor.Source); GC.KeepAlive(descriptors); } @@ -121,23 +117,19 @@ public void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray imgD /// Computed output image descriptor. /// Indices of keypoints that belong to the cluster. /// This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster(word of vocabulary) returned if it is non-zero. - public void Compute(InputArray keypointDescriptors, OutputArray imgDescriptor, out int[][] pointIdxsOfClusters) + public void Compute(InputArrayRef keypointDescriptors, OutputArrayRef imgDescriptor, out int[][] pointIdxsOfClusters) { ThrowIfDisposed(); - if (keypointDescriptors is null) - throw new ArgumentNullException(nameof(keypointDescriptors)); - if (imgDescriptor is null) - throw new ArgumentNullException(nameof(imgDescriptor)); using (var pointIdxsOfClustersVec = new VectorOfVectorInt32()) { NativeMethods.HandleException( NativeMethods.xfeatures2d_BOWImgDescriptorExtractor_compute12( - Handle, keypointDescriptors.ToInputProxy(), imgDescriptor.ToOutputProxy(), pointIdxsOfClustersVec.CvPtr)); + Handle, keypointDescriptors.Proxy, imgDescriptor.Proxy, pointIdxsOfClustersVec.CvPtr)); pointIdxsOfClusters = pointIdxsOfClustersVec.ToArray(); } - GC.KeepAlive(keypointDescriptors); - GC.KeepAlive(imgDescriptor); + GC.KeepAlive(keypointDescriptors.Source); + GC.KeepAlive(imgDescriptor.Source); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs b/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs index 4515d92d1..aaaa9a80b 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs @@ -132,20 +132,12 @@ public static class RL /// resulting run length encoded image. /// threshold value. /// thresholding type (only cv::THRESH_BINARY and cv::THRESH_BINARY_INV are supported) - public static void Threshold(InputArray src, OutputArray rlDest, double thresh, ThresholdTypes type) + public static void Threshold(InputArrayRef src, OutputArrayRef rlDest, double thresh, ThresholdTypes type) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (rlDest is null) - throw new ArgumentNullException(nameof(rlDest)); - src.ThrowIfDisposed(); - rlDest.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_rl_threshold(src.ToInputProxy(), rlDest.ToOutputProxy(), thresh, (int)type)); + NativeMethods.ximgproc_rl_threshold(src.Proxy, rlDest.Proxy, thresh, (int)type)); - GC.KeepAlive(src); - rlDest.Fix(); + GC.KeepAlive(src.Source); } /// @@ -156,26 +148,15 @@ public static void Threshold(InputArray src, OutputArray rlDest, double thresh, /// kernel /// position of the anchor within the element; default value (0, 0) is usually the element center. public static void Dilate( - InputArray rlSrc, OutputArray rlDest, InputArray rlKernel, Point? anchor = null) + InputArrayRef rlSrc, OutputArrayRef rlDest, InputArrayRef rlKernel, Point? anchor = null) { - if (rlSrc is null) - throw new ArgumentNullException(nameof(rlSrc)); - if (rlDest is null) - throw new ArgumentNullException(nameof(rlDest)); - if (rlKernel is null) - throw new ArgumentNullException(nameof(rlKernel)); - rlSrc.ThrowIfDisposed(); - rlDest.ThrowIfNotReady(); - rlKernel.ThrowIfDisposed(); - var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); NativeMethods.HandleException( - NativeMethods.ximgproc_rl_dilate(rlSrc.ToInputProxy(), rlDest.ToOutputProxy(), rlKernel.ToInputProxy(), anchorValue)); + NativeMethods.ximgproc_rl_dilate(rlSrc.Proxy, rlDest.Proxy, rlKernel.Proxy, anchorValue)); - GC.KeepAlive(rlSrc); - rlDest.Fix(); - GC.KeepAlive(rlKernel); + GC.KeepAlive(rlSrc.Source); + GC.KeepAlive(rlKernel.Source); } /// @@ -189,26 +170,15 @@ public static void Dilate( /// position of the anchor within the element; default value (0, 0) /// is usually the element center. public static void Erode( - InputArray rlSrc, OutputArray rlDest, InputArray rlKernel, bool bBoundaryOn = true, Point? anchor = null) + InputArrayRef rlSrc, OutputArrayRef rlDest, InputArrayRef rlKernel, bool bBoundaryOn = true, Point? anchor = null) { - if (rlSrc is null) - throw new ArgumentNullException(nameof(rlSrc)); - if (rlDest is null) - throw new ArgumentNullException(nameof(rlDest)); - if (rlKernel is null) - throw new ArgumentNullException(nameof(rlKernel)); - rlSrc.ThrowIfDisposed(); - rlDest.ThrowIfNotReady(); - rlKernel.ThrowIfDisposed(); - var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); NativeMethods.HandleException( - NativeMethods.ximgproc_rl_erode(rlSrc.ToInputProxy(), rlDest.ToOutputProxy(), rlKernel.ToInputProxy(), bBoundaryOn ? 1 : 0, anchorValue)); + NativeMethods.ximgproc_rl_erode(rlSrc.Proxy, rlDest.Proxy, rlKernel.Proxy, bBoundaryOn ? 1 : 0, anchorValue)); - GC.KeepAlive(rlSrc); - rlDest.Fix(); - GC.KeepAlive(rlKernel); + GC.KeepAlive(rlSrc.Source); + GC.KeepAlive(rlKernel.Source); } /// @@ -231,20 +201,12 @@ public static Mat GetStructuringElement(MorphShapes shape, Size ksize) /// image to paint into (currently only single channel images). /// run length encoded image /// all foreground pixel of the binary image are set to this value - public static void Paint(InputOutputArray image, InputArray rlSrc, Scalar value) + public static void Paint(InputOutputArrayRef image, InputArrayRef rlSrc, Scalar value) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (rlSrc is null) - throw new ArgumentNullException(nameof(rlSrc)); - image.ThrowIfNotReady(); - rlSrc.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.ximgproc_rl_paint(image.ToInputOutputProxy(), rlSrc.ToInputProxy(), value)); + NativeMethods.ximgproc_rl_paint(image.Proxy, rlSrc.Proxy, value)); - image.Fix(); - GC.KeepAlive(rlSrc); + GC.KeepAlive(rlSrc.Source); } /// @@ -253,15 +215,12 @@ public static void Paint(InputOutputArray image, InputArray rlSrc, Scalar value) /// /// /// - public static bool IsRLMorphologyPossible(InputArray rlStructuringElement) + public static bool IsRLMorphologyPossible(InputArrayRef rlStructuringElement) { - if (rlStructuringElement is null) - throw new ArgumentNullException(nameof(rlStructuringElement)); - NativeMethods.HandleException( - NativeMethods.ximgproc_rl_isRLMorphologyPossible(rlStructuringElement.ToInputProxy(), out var ret)); + NativeMethods.ximgproc_rl_isRLMorphologyPossible(rlStructuringElement.Proxy, out var ret)); - GC.KeepAlive(rlStructuringElement); + GC.KeepAlive(rlStructuringElement.Source); return ret != 0; } @@ -273,19 +232,14 @@ public static bool IsRLMorphologyPossible(InputArray rlStructuringElement) /// result /// image size (to be used if an "on" boundary should be used in erosion, using the default /// means that the size is computed from the extension of the input) - public static void CreateRLEImage(IEnumerable runs, OutputArray res, Size? size = null) + public static void CreateRLEImage(IEnumerable runs, OutputArrayRef res, Size? size = null) { - if (res is null) - throw new ArgumentNullException(nameof(res)); - res.ThrowIfNotReady(); - var runsArray = runs as Point3i[] ?? runs.ToArray(); var sizeValue = size.GetValueOrDefault(new Size(0, 0)); NativeMethods.HandleException( - NativeMethods.ximgproc_rl_createRLEImage(runsArray, runsArray.Length, res.ToOutputProxy(), sizeValue)); + NativeMethods.ximgproc_rl_createRLEImage(runsArray, runsArray.Length, res.Proxy, sizeValue)); - res.Fix(); } /// @@ -299,27 +253,16 @@ public static void CreateRLEImage(IEnumerable runs, OutputArray res, Si /// to be on for erosion operations (True: works in the same way as the default of cv::erode, False: is a little faster) /// position of the anchor within the element; default value (0, 0) is usually the element center. public static void MorphologyEx( - InputArray rlSrc, OutputArray rlDest, MorphTypes op, InputArray rlKernel, + InputArrayRef rlSrc, OutputArrayRef rlDest, MorphTypes op, InputArrayRef rlKernel, bool bBoundaryOnForErosion = true, Point? anchor = null) { - if (rlSrc is null) - throw new ArgumentNullException(nameof(rlSrc)); - if (rlDest is null) - throw new ArgumentNullException(nameof(rlDest)); - if (rlKernel is null) - throw new ArgumentNullException(nameof(rlKernel)); - rlSrc.ThrowIfDisposed(); - rlDest.ThrowIfNotReady(); - rlKernel.ThrowIfDisposed(); - var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); NativeMethods.HandleException( - NativeMethods.ximgproc_rl_morphologyEx(rlSrc.ToInputProxy(), rlDest.ToOutputProxy(), (int)op, rlKernel.ToInputProxy(), bBoundaryOnForErosion ? 1 : 0, anchorValue)); + NativeMethods.ximgproc_rl_morphologyEx(rlSrc.Proxy, rlDest.Proxy, (int)op, rlKernel.Proxy, bBoundaryOnForErosion ? 1 : 0, anchorValue)); - GC.KeepAlive(rlSrc); - rlDest.Fix(); - GC.KeepAlive(rlKernel); + GC.KeepAlive(rlSrc.Source); + GC.KeepAlive(rlKernel.Source); } } @@ -350,8 +293,8 @@ public static void MorphologyEx( /// Other techniques can be specified, see cv::ximgproc::LocalBinarizationMethods. /// The user-adjustable parameter used by Sauvola's technique. This is the dynamic range of standard deviation. public static void NiblackThreshold( - InputArray src, - OutputArray dst, + InputArrayRef src, + OutputArrayRef dst, double maxValue, ThresholdTypes type, int blockSize, @@ -359,19 +302,11 @@ public static void NiblackThreshold( LocalBinarizationMethods binarizationMethod = LocalBinarizationMethods.Niblack, double r = 128) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_niBlackThreshold(src.ToInputProxy(), dst.ToOutputProxy(), maxValue, (int)type, blockSize, k, (int)binarizationMethod, r)); + NativeMethods.ximgproc_niBlackThreshold(src.Proxy, dst.Proxy, maxValue, (int)type, blockSize, k, (int)binarizationMethod, r)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -382,21 +317,13 @@ public static void NiblackThreshold( /// Destination image of the same size and the same type as src. The function can work in-place. /// Value that defines which thinning algorithm should be used. public static void Thinning( - InputArray src, OutputArray dst, + InputArrayRef src, OutputArrayRef dst, ThinningTypes thinningType = ThinningTypes.ZHANGSUEN) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_thinning(src.ToInputProxy(), dst.ToOutputProxy(), (int)thinningType)); + NativeMethods.ximgproc_thinning(src.Proxy, dst.Proxy, (int)thinningType)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -408,20 +335,12 @@ public static void Thinning( /// The amount of time to step forward by on each iteration (normally, it's between 0 and 1). /// sensitivity to the edges /// The number of iterations - public static void AnisotropicDiffusion(InputArray src, OutputArray dst, float alpha, float k, int niters) + public static void AnisotropicDiffusion(InputArrayRef src, OutputArrayRef dst, float alpha, float k, int niters) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_anisotropicDiffusion(src.ToInputProxy(), dst.ToOutputProxy(), alpha, k, niters)); + NativeMethods.ximgproc_anisotropicDiffusion(src.Proxy, dst.Proxy, alpha, k, niters)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } #region brightedges.hpp @@ -459,20 +378,12 @@ public static void BrightEdges(Mat original, Mat edgeView, int contrast = 1, int /// /// Source 8-bit, 32-bit or 64-bit image, with 3-channel image. /// result CV_64FC4 a quaternion image( 4 chanels zero channel and B,G,R). - public static void CreateQuaternionImage(InputArray img, OutputArray qimg) + public static void CreateQuaternionImage(InputArrayRef img, OutputArrayRef qimg) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (qimg is null) - throw new ArgumentNullException(nameof(qimg)); - img.ThrowIfDisposed(); - qimg.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_createQuaternionImage(img.ToInputProxy(), qimg.ToOutputProxy())); + NativeMethods.ximgproc_createQuaternionImage(img.Proxy, qimg.Proxy)); - GC.KeepAlive(img); - qimg.Fix(); + GC.KeepAlive(img.Source); } /// @@ -480,20 +391,12 @@ public static void CreateQuaternionImage(InputArray img, OutputArray qimg) /// /// quaternion image. /// conjugate of qimg - public static void QConj(InputArray qimg, OutputArray qcimg) + public static void QConj(InputArrayRef qimg, OutputArrayRef qcimg) { - if (qimg is null) - throw new ArgumentNullException(nameof(qimg)); - if (qcimg is null) - throw new ArgumentNullException(nameof(qcimg)); - qimg.ThrowIfDisposed(); - qcimg.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_qconj(qimg.ToInputProxy(), qcimg.ToOutputProxy())); + NativeMethods.ximgproc_qconj(qimg.Proxy, qcimg.Proxy)); - GC.KeepAlive(qimg); - qcimg.Fix(); + GC.KeepAlive(qimg.Source); } /// @@ -501,20 +404,12 @@ public static void QConj(InputArray qimg, OutputArray qcimg) /// /// quaternion image. /// conjugate of qimg - public static void QUnitary(InputArray qimg, OutputArray qnimg) + public static void QUnitary(InputArrayRef qimg, OutputArrayRef qnimg) { - if (qimg is null) - throw new ArgumentNullException(nameof(qimg)); - if (qnimg is null) - throw new ArgumentNullException(nameof(qnimg)); - qimg.ThrowIfDisposed(); - qnimg.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_qunitary(qimg.ToInputProxy(), qnimg.ToOutputProxy())); + NativeMethods.ximgproc_qunitary(qimg.Proxy, qnimg.Proxy)); - GC.KeepAlive(qimg); - qnimg.Fix(); + GC.KeepAlive(qimg.Source); } /// @@ -523,24 +418,13 @@ public static void QUnitary(InputArray qimg, OutputArray qnimg) /// quaternion image. /// quaternion image. /// product dst(I)=src1(I) . src2(I) - public static void QMultiply(InputArray src1, InputArray src2, OutputArray dst) + public static void QMultiply(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) { - if (src1 is null) - throw new ArgumentNullException(nameof(src1)); - if (src2 is null) - throw new ArgumentNullException(nameof(src2)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src1.ThrowIfDisposed(); - src2.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_qmultiply(src1.ToInputProxy(), src2.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.ximgproc_qmultiply(src1.Proxy, src2.Proxy, dst.Proxy)); - GC.KeepAlive(src1); - GC.KeepAlive(src2); - dst.Fix(); + GC.KeepAlive(src1.Source); + GC.KeepAlive(src2.Source); } /// @@ -550,20 +434,12 @@ public static void QMultiply(InputArray src1, InputArray src2, OutputArray dst) /// quaternion image in dual space. /// quaternion image in dual space. only DFT_INVERSE flags is supported /// true the hypercomplex exponential is to be multiplied on the left (false on the right ). - public static void QDft(InputArray img, OutputArray qimg, DftFlags flags, bool sideLeft) + public static void QDft(InputArrayRef img, OutputArrayRef qimg, DftFlags flags, bool sideLeft) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (qimg is null) - throw new ArgumentNullException(nameof(qimg)); - img.ThrowIfDisposed(); - qimg.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_qdft(img.ToInputProxy(), qimg.ToOutputProxy(), (int)flags, sideLeft ? 1 : 0)); + NativeMethods.ximgproc_qdft(img.Proxy, qimg.Proxy, (int)flags, sideLeft ? 1 : 0)); - GC.KeepAlive(img); - qimg.Fix(); + GC.KeepAlive(img.Source); } /// @@ -572,24 +448,13 @@ public static void QDft(InputArray img, OutputArray qimg, DftFlags flags, bool s /// Image where the search is running. It must be 3 channels image /// Searched template. It must be not greater than the source image and have 3 channels /// Map of comparison results. It must be single-channel 64-bit floating-point - public static void ColorMatchTemplate(InputArray img, InputArray templ, OutputArray result) + public static void ColorMatchTemplate(InputArrayRef img, InputArrayRef templ, OutputArrayRef result) { - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (templ is null) - throw new ArgumentNullException(nameof(templ)); - if (result is null) - throw new ArgumentNullException(nameof(result)); - img.ThrowIfDisposed(); - templ.ThrowIfDisposed(); - result.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_colorMatchTemplate(img.ToInputProxy(), templ.ToInputProxy(), result.ToOutputProxy())); + NativeMethods.ximgproc_colorMatchTemplate(img.Proxy, templ.Proxy, result.Proxy)); - GC.KeepAlive(img); - GC.KeepAlive(templ); - result.Fix(); + GC.KeepAlive(img.Source); + GC.KeepAlive(templ.Source); } #endregion @@ -603,20 +468,12 @@ public static void ColorMatchTemplate(InputArray img, InputArray templ, OutputAr /// result CV_32FC image with same number of channel than _op. /// double see paper /// double see paper - public static void GradientDericheY(InputArray op, OutputArray dst, double alpha, double omega) + public static void GradientDericheY(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) { - if (op is null) - throw new ArgumentNullException(nameof(op)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - op.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_GradientDericheY(op.ToInputProxy(), dst.ToOutputProxy(), alpha, omega)); + NativeMethods.ximgproc_GradientDericheY(op.Proxy, dst.Proxy, alpha, omega)); - GC.KeepAlive(op); - dst.Fix(); + GC.KeepAlive(op.Source); } /// @@ -626,20 +483,12 @@ public static void GradientDericheY(InputArray op, OutputArray dst, double alpha /// result CV_32FC image with same number of channel than _op. /// double see paper /// double see paper - public static void GradientDericheX(InputArray op, OutputArray dst, double alpha, double omega) + public static void GradientDericheX(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) { - if (op is null) - throw new ArgumentNullException(nameof(op)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - op.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_GradientDericheX(op.ToInputProxy(), dst.ToOutputProxy(), alpha, omega)); + NativeMethods.ximgproc_GradientDericheX(op.Proxy, dst.Proxy, alpha, omega)); - GC.KeepAlive(op); - dst.Fix(); + GC.KeepAlive(op.Source); } #endregion @@ -713,7 +562,7 @@ public static EdgeBoxes CreateEdgeBoxes( /// // ReSharper disable once InconsistentNaming public static DTFilter CreateDTFilter( - InputArray guide, double sigmaSpatial, double sigmaColor, + InputArrayRef guide, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { return OpenCvSharp.XImgProc.DTFilter.Create(guide, sigmaSpatial, sigmaColor, mode, numIters); @@ -735,25 +584,14 @@ public static DTFilter CreateDTFilter( /// filtering 2D signals in the article. /// optional number of iterations used for filtering, 3 is quite enough. // ReSharper disable once InconsistentNaming - public static void DTFilter(InputArray guide, InputArray src, OutputArray dst, double sigmaSpatial, + public static void DTFilter(InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - guide.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_dtFilter(guide.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), sigmaSpatial, sigmaColor, (int)mode, numIters)); + NativeMethods.ximgproc_dtFilter(guide.Proxy, src.Proxy, dst.Proxy, sigmaSpatial, sigmaColor, (int)mode, numIters)); - GC.KeepAlive(guide); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(guide.Source); + GC.KeepAlive(src.Source); } /// @@ -766,7 +604,7 @@ public static void DTFilter(InputArray guide, InputArray src, OutputArray dst, d /// space into bilateralFilter. /// public static GuidedFilter CreateGuidedFilter( - InputArray guide, int radius, double eps) + InputArrayRef guide, int radius, double eps) { return OpenCvSharp.XImgProc.GuidedFilter.Create(guide, radius, eps); } @@ -786,25 +624,14 @@ public static GuidedFilter CreateGuidedFilter( /// space into bilateralFilter. /// optional depth of the output image. public static void GuidedFilter( - InputArray guide, InputArray src, OutputArray dst, + InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, int radius, double eps, int dDepth = -1) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - guide.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_guidedFilter(guide.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), radius, eps, dDepth)); + NativeMethods.ximgproc_guidedFilter(guide.Proxy, src.Proxy, dst.Proxy, radius, eps, dDepth)); - GC.KeepAlive(guide); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(guide.Source); + GC.KeepAlive(src.Source); } /// @@ -836,25 +663,14 @@ public static AdaptiveManifoldFilter CreateAMFilter( /// original paper. // ReSharper disable once InconsistentNaming public static void AMFilter( - InputArray joint, InputArray src, OutputArray dst, double sigmaS, double sigmaR, + InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, double sigmaS, double sigmaR, bool adjustOutliers = false) { - if (joint is null) - throw new ArgumentNullException(nameof(joint)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - joint.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_amFilter(joint.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), sigmaS, sigmaR, adjustOutliers ? 1 : 0)); + NativeMethods.ximgproc_amFilter(joint.Proxy, src.Proxy, dst.Proxy, sigmaS, sigmaR, adjustOutliers ? 1 : 0)); - GC.KeepAlive(joint); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(joint.Source); + GC.KeepAlive(src.Source); } /// @@ -874,26 +690,15 @@ public static void AMFilter( /// proportional to sigmaSpace. /// public static void JointBilateralFilter( - InputArray joint, InputArray src, OutputArray dst, int d, + InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, int d, double sigmaColor, double sigmaSpace, BorderTypes borderType = BorderTypes.Default) { - if (joint is null) - throw new ArgumentNullException(nameof(joint)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - joint.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_jointBilateralFilter( - joint.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), d, sigmaColor, sigmaSpace, (int)borderType)); + joint.Proxy, src.Proxy, dst.Proxy, d, sigmaColor, sigmaSpace, (int)borderType)); - GC.KeepAlive(joint); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(joint.Source); + GC.KeepAlive(src.Source); } /// @@ -909,21 +714,13 @@ public static void JointBilateralFilter( /// Range blur parameter for texture blurring. Larger value makes result to be more blurred. When the /// value is negative, it is automatically calculated as described in the paper. public static void BilateralTextureFilter( - InputArray src, OutputArray dst, int fr = 3, int numIter = 1, double sigmaAlpha = -1.0, double sigmaAvg = -1.0) + InputArrayRef src, OutputArrayRef dst, int fr = 3, int numIter = 1, double sigmaAlpha = -1.0, double sigmaAvg = -1.0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_bilateralTextureFilter( - src.ToInputProxy(), dst.ToOutputProxy(), fr, numIter, sigmaAlpha, sigmaAvg)); + src.Proxy, dst.Proxy, fr, numIter, sigmaAlpha, sigmaAvg)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -943,22 +740,14 @@ public static void BilateralTextureFilter( /// Number of iterations of joint edge-preserving filtering applied on the source image. /// public static void RollingGuidanceFilter( - InputArray src, OutputArray dst, int d = -1, double sigmaColor = 25, + InputArrayRef src, OutputArrayRef dst, int d = -1, double sigmaColor = 25, double sigmaSpace = 3, int numOfIter = 4, BorderTypes borderType = BorderTypes.Default) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_rollingGuidanceFilter( - src.ToInputProxy(), dst.ToOutputProxy(), d, sigmaColor, sigmaSpace, numOfIter, (int)borderType)); + src.Proxy, dst.Proxy, d, sigmaColor, sigmaSpace, numOfIter, (int)borderType)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -976,31 +765,17 @@ public static void RollingGuidanceFilter( /// number of iterations used for solver, 25 is usually enough. /// convergence tolerance used for solver. public static void FastBilateralSolverFilter( - InputArray guide, InputArray src, InputArray confidence, - OutputArray dst, double sigmaSpatial = 8, double sigmaLuma = 8, double sigmaChroma = 8, + InputArrayRef guide, InputArrayRef src, InputArrayRef confidence, + OutputArrayRef dst, double sigmaSpatial = 8, double sigmaLuma = 8, double sigmaChroma = 8, double lambda = 128.0, int numIter = 25, double maxTol = 1e-5) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (confidence is null) - throw new ArgumentNullException(nameof(confidence)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - guide.ThrowIfDisposed(); - src.ThrowIfDisposed(); - confidence.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_fastBilateralSolverFilter( - guide.ToInputProxy(), src.ToInputProxy(), confidence.ToInputProxy(), dst.ToOutputProxy(), sigmaSpatial, sigmaLuma, sigmaChroma, lambda, numIter, maxTol)); + guide.Proxy, src.Proxy, confidence.Proxy, dst.Proxy, sigmaSpatial, sigmaLuma, sigmaChroma, lambda, numIter, maxTol)); - GC.KeepAlive(guide); - GC.KeepAlive(src); - GC.KeepAlive(confidence); - dst.Fix(); + GC.KeepAlive(guide.Source); + GC.KeepAlive(src.Source); + GC.KeepAlive(confidence.Source); } /// @@ -1014,7 +789,7 @@ public static void FastBilateralSolverFilter( /// number of iterations used for filtering, 3 is usually enough. /// public static FastGlobalSmootherFilter CreateFastGlobalSmootherFilter( - InputArray guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) + InputArrayRef guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { return OpenCvSharp.XImgProc.FastGlobalSmootherFilter.Create(guide, lambda, sigmaColor, lambdaAttenuation, numIter); } @@ -1032,26 +807,15 @@ public static FastGlobalSmootherFilter CreateFastGlobalSmootherFilter( /// it should be 0.25. Setting it to 1.0 may lead to streaking artifacts. /// number of iterations used for filtering, 3 is usually enough. public static void FastGlobalSmootherFilter( - InputArray guide, InputArray src, OutputArray dst, double lambda, double sigmaColor, + InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - guide.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_fastGlobalSmootherFilter( - guide.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), lambda, sigmaColor, lambdaAttenuation, numIter)); + guide.Proxy, src.Proxy, dst.Proxy, lambda, sigmaColor, lambdaAttenuation, numIter)); - GC.KeepAlive(guide); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(guide.Source); + GC.KeepAlive(src.Source); } /// @@ -1061,21 +825,13 @@ public static void FastGlobalSmootherFilter( /// destination image. /// parameter defining the smooth term weight. /// parameter defining the increasing factor of the weight of the gradient data term. - public static void L0Smooth(InputArray src, OutputArray dst, double lambda = 0.02, double kappa = 2.0) + public static void L0Smooth(InputArrayRef src, OutputArrayRef dst, double lambda = 0.02, double kappa = 2.0) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_l0Smooth( - src.ToInputProxy(), dst.ToOutputProxy(), lambda, kappa)); + src.Proxy, dst.Proxy, lambda, kappa)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } #endregion @@ -1089,20 +845,12 @@ public static void L0Smooth(InputArray src, OutputArray dst, double lambda = 0.0 /// Destination image of the same size and type as src. /// Diameter of each pixel neighborhood that is used during filtering. Must be greater or equal 3. /// Threshold, which distinguishes between noise, outliers, and data. - public static void EdgePreservingFilter(InputArray src, OutputArray dst, int d, double threshold) + public static void EdgePreservingFilter(InputArrayRef src, OutputArrayRef dst, int d, double threshold) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_edgePreservingFilter(src.ToInputProxy(), dst.ToOutputProxy(), d, threshold)); + NativeMethods.ximgproc_edgePreservingFilter(src.Proxy, dst.Proxy, d, threshold)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } #endregion @@ -1124,21 +872,13 @@ public static void EdgePreservingFilter(InputArray src, OutputArray dst, int d, /// The destination estimated covariance matrix. Output matrix will be size (windowRows*windowCols, windowRows*windowCols). /// The number of rows in the window. /// The number of cols in the window. - public static void CovarianceEstimation(InputArray src, OutputArray dst, int windowRows, int windowCols) + public static void CovarianceEstimation(InputArrayRef src, OutputArrayRef dst, int windowRows, int windowCols) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_covarianceEstimation(src.ToInputProxy(), dst.ToOutputProxy(), windowRows, windowCols)); + NativeMethods.ximgproc_covarianceEstimation(src.Proxy, dst.Proxy, windowRows, windowCols)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } #endregion @@ -1155,26 +895,18 @@ public static void CovarianceEstimation(InputArray src, OutputArray dst, int win /// The operation to be applied, see cv::HoughOp /// Specifies to do or not to do image skewing, see cv::HoughDeskewOption public static void FastHoughTransform( - InputArray src, - OutputArray dst, + InputArrayRef src, + OutputArrayRef dst, MatType dstMatDepth, AngleRangeOption angleRange = AngleRangeOption.ARO_315_135, HoughOP op = HoughOP.FHT_ADD, HoughDeskewOption makeSkew = HoughDeskewOption.DESKEW) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_FastHoughTransform(src.ToInputProxy(), dst.ToOutputProxy(), dstMatDepth, (int)angleRange, (int)op, (int)makeSkew)); + NativeMethods.ximgproc_FastHoughTransform(src.Proxy, dst.Proxy, dstMatDepth, (int)angleRange, (int)op, (int)makeSkew)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -1193,18 +925,14 @@ public static void FastHoughTransform( /// Coordinates of line segment corresponded by point in Hough space. public static Vec4i HoughPoint2Line( Point houghPoint, - InputArray srcImgInfo, + InputArrayRef srcImgInfo, AngleRangeOption angleRange = AngleRangeOption.ARO_315_135, HoughDeskewOption makeSkew = HoughDeskewOption.DESKEW, RulesOption rules = RulesOption.IGNORE_BORDERS) { - if (srcImgInfo is null) - throw new ArgumentNullException(nameof(srcImgInfo)); - srcImgInfo.ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.ximgproc_HoughPoint2Line(houghPoint, srcImgInfo.ToInputProxy(), (int)angleRange, (int)makeSkew, (int)rules, out Vec4i ret)); - GC.KeepAlive(srcImgInfo); + NativeMethods.ximgproc_HoughPoint2Line(houghPoint, srcImgInfo.Proxy, (int)angleRange, (int)makeSkew, (int)rules, out Vec4i ret)); + GC.KeepAlive(srcImgInfo.Source); return ret; } @@ -1249,7 +977,7 @@ public static FastLineDetector CreateFastLineDetector( /// Chooses the enforcement of superpixel compactness factor of superpixel /// // ReSharper disable once InconsistentNaming - public static SuperpixelLSC CreateSuperpixelLSC(InputArray image, int regionSize = 10, float ratio = 0.075f) + public static SuperpixelLSC CreateSuperpixelLSC(InputArrayRef image, int regionSize = 10, float ratio = 0.075f) { return SuperpixelLSC.Create(image, regionSize, ratio); } @@ -1265,21 +993,13 @@ public static SuperpixelLSC CreateSuperpixelLSC(InputArray image, int regionSize /// Result CV_32F image with same number of channel than op. /// double see paper /// double see paper - public static void GradientPaillouY(InputArray op, OutputArray dst, double alpha, double omega) + public static void GradientPaillouY(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) { - if (op is null) - throw new ArgumentNullException(nameof(op)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - op.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_GradientPaillouY(op.ToInputProxy(), dst.ToOutputProxy(), alpha, omega)); + NativeMethods.ximgproc_GradientPaillouY(op.Proxy, dst.Proxy, alpha, omega)); - GC.KeepAlive(op); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(op.Source); + GC.KeepAlive(dst.Source); } /// @@ -1289,21 +1009,13 @@ public static void GradientPaillouY(InputArray op, OutputArray dst, double alpha /// Result CV_32F image with same number of channel than op. /// double see paper /// double see paper - public static void GradientPaillouX(InputArray op, OutputArray dst, double alpha, double omega) + public static void GradientPaillouX(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) { - if (op is null) - throw new ArgumentNullException(nameof(op)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - op.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_GradientPaillouX(op.ToInputProxy(), dst.ToOutputProxy(), alpha, omega)); + NativeMethods.ximgproc_GradientPaillouX(op.Proxy, dst.Proxy, alpha, omega)); - GC.KeepAlive(op); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(op.Source); + GC.KeepAlive(dst.Source); } #endregion @@ -1315,23 +1027,19 @@ public static void GradientPaillouX(InputArray op, OutputArray dst, double alpha /// /// Given transformed image. /// Transformation matrix corresponding to inversed image transformation - public static double[,] PeiLinNormalization(InputArray i) + public static double[,] PeiLinNormalization(InputArrayRef i) { - if (i is null) - throw new ArgumentNullException(nameof(i)); - i.ThrowIfDisposed(); - double[,] ret = new double[2, 3]; unsafe { fixed (double* retPointer = ret) { NativeMethods.HandleException( - NativeMethods.ximgproc_PeiLinNormalization_Mat23d(i.ToInputProxy(), retPointer)); + NativeMethods.ximgproc_PeiLinNormalization_Mat23d(i.Proxy, retPointer)); } } - GC.KeepAlive(i); + GC.KeepAlive(i.Source); return ret; } @@ -1340,20 +1048,12 @@ public static void GradientPaillouX(InputArray op, OutputArray dst, double alpha /// /// Given transformed image. /// Inversed image transformation. - public static void PeiLinNormalization(InputArray i, OutputArray t) + public static void PeiLinNormalization(InputArrayRef i, OutputArrayRef t) { - if (i is null) - throw new ArgumentNullException(nameof(i)); - if (t is null) - throw new ArgumentNullException(nameof(t)); - i.ThrowIfDisposed(); - t.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.ximgproc_PeiLinNormalization_OutputArray(i.ToInputProxy(), t.ToOutputProxy())); + NativeMethods.ximgproc_PeiLinNormalization_OutputArray(i.Proxy, t.Proxy)); - GC.KeepAlive(i); - t.Fix(); + GC.KeepAlive(i.Source); } #endregion @@ -1443,28 +1143,17 @@ public static StructuredEdgeDetection CreateStructuredEdgeDetection(string model /// A 0-1 mask that has the same size with I. This mask is used to ignore the effect of some pixels. If the pixel value on mask is 0, /// the pixel will be ignored when maintaining the joint-histogram.This is useful for applications like optical flow occlusion handling. public static void WeightedMedianFilter( - InputArray joint, InputArray src, OutputArray dst, int r, - double sigma = 25.5, WMFWeightType weightType = WMFWeightType.EXP, InputArray? mask = null) + InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, int r, + double sigma = 25.5, WMFWeightType weightType = WMFWeightType.EXP, InputArrayRef mask = default) { - if (joint is null) - throw new ArgumentNullException(nameof(joint)); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - joint.ThrowIfDisposed(); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( NativeMethods.ximgproc_weightedMedianFilter( - joint.ToInputProxy(), src.ToInputProxy(), dst.ToOutputProxy(), r, sigma, (int)weightType, mask?.ToInputProxy() ?? default)); + joint.Proxy, src.Proxy, dst.Proxy, r, sigma, (int)weightType, mask.Proxy)); - GC.KeepAlive(joint); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); - GC.KeepAlive(mask); + GC.KeepAlive(joint.Source); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); + GC.KeepAlive(mask.Source); } #endregion diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs index 2d5581170..fbef4aa39 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs @@ -300,23 +300,17 @@ public virtual float Kappa /// edge image. /// orientation map. /// proposal boxes. - public virtual void GetBoundingBoxes(InputArray edgeMap, InputArray orientationMap, out Rect[] boxes) + public virtual void GetBoundingBoxes(InputArrayRef edgeMap, InputArrayRef orientationMap, out Rect[] boxes) { ThrowIfDisposed(); - if (edgeMap is null) - throw new ArgumentNullException(nameof(edgeMap)); - if (orientationMap is null) - throw new ArgumentNullException(nameof(orientationMap)); - edgeMap.ThrowIfDisposed(); - orientationMap.ThrowIfDisposed(); using var boxesVec = new StdVector(); NativeMethods.HandleException( NativeMethods.ximgproc_EdgeBoxes_getBoundingBoxes( - Handle, edgeMap.ToInputProxy(), orientationMap.ToInputProxy(), boxesVec.CvPtr)); + Handle, edgeMap.Proxy, orientationMap.Proxy, boxesVec.CvPtr)); boxes = boxesVec.ToArray(); - GC.KeepAlive(edgeMap); - GC.KeepAlive(orientationMap); + GC.KeepAlive(edgeMap.Source); + GC.KeepAlive(orientationMap.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs index e55973a28..374ae81be 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs @@ -127,48 +127,37 @@ public static EdgeDrawing Create() /// Detects edges in a grayscale or color image and prepares them to detect lines and ellipses. /// /// 8-bit, single-channel (CV_8UC1) or color (CV_8UC3, CV_8UC4) input image. - public virtual void DetectEdges(InputArray src) + public virtual void DetectEdges(InputArrayRef src) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - src.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeDrawing_detectEdges(Handle, src.ToInputProxy())); - GC.KeepAlive(src); + NativeMethods.ximgproc_EdgeDrawing_detectEdges(Handle, src.Proxy)); + GC.KeepAlive(src.Source); } /// /// Returns the edge image prepared by . /// /// 8-bit, single-channel output image. - public virtual void GetEdgeImage(OutputArray dst) + public virtual void GetEdgeImage(OutputArrayRef dst) { ThrowIfDisposed(); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeDrawing_getEdgeImage(Handle, dst.ToOutputProxy())); - dst.Fix(); + NativeMethods.ximgproc_EdgeDrawing_getEdgeImage(Handle, dst.Proxy)); } /// /// Returns the gradient image prepared by . /// /// 16-bit, single-channel output image. - public virtual void GetGradientImage(OutputArray dst) + public virtual void GetGradientImage(OutputArrayRef dst) { ThrowIfDisposed(); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeDrawing_getGradientImage(Handle, dst.ToOutputProxy())); - dst.Fix(); + NativeMethods.ximgproc_EdgeDrawing_getGradientImage(Handle, dst.Proxy)); } /// @@ -186,7 +175,7 @@ public virtual Point[][] GetSegments() } /// - /// Returns for each line found in its edge segment index in + /// Returns for each line found in its edge segment index in /// . /// /// Edge segment indices of detected lines. @@ -205,16 +194,12 @@ public virtual int[] GetSegmentIndicesOfLines() /// Call before calling this function. /// /// Output Vec4f array: start point (x1,y1) and end point (x2,y2) of each line. - public virtual void DetectLines(OutputArray lines) + public virtual void DetectLines(OutputArrayRef lines) { ThrowIfDisposed(); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - lines.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeDrawing_detectLines(Handle, lines.ToOutputProxy())); - lines.Fix(); + NativeMethods.ximgproc_EdgeDrawing_detectLines(Handle, lines.Proxy)); } /// @@ -240,16 +225,12 @@ public virtual Vec4f[] DetectLines() /// Output Vec6d array: center point and perimeter for circles; /// center point, axes and angle for ellipses. /// - public virtual void DetectEllipses(OutputArray ellipses) + public virtual void DetectEllipses(OutputArrayRef ellipses) { ThrowIfDisposed(); - if (ellipses is null) - throw new ArgumentNullException(nameof(ellipses)); - ellipses.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeDrawing_detectEllipses(Handle, ellipses.ToOutputProxy())); - ellipses.Fix(); + NativeMethods.ximgproc_EdgeDrawing_detectEllipses(Handle, ellipses.Proxy)); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs index 0c061f866..76c59a8f4 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs @@ -181,23 +181,15 @@ public bool UseRNG /// filtering image with any numbers of channels. /// output image. /// optional joint (also called as guided) image with any numbers of channels. - public virtual void Filter(InputArray src, OutputArray dst, InputArray? joint = null) + public virtual void Filter(InputArrayRef src, OutputArrayRef dst, InputArrayRef joint = default) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - joint?.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.ximgproc_AdaptiveManifoldFilter_filter( - Handle, src.ToInputProxy(), dst.ToOutputProxy(), joint?.ToInputProxy() ?? default)); + Handle, src.Proxy, dst.Proxy, joint.Proxy)); - GC.KeepAlive(src); - dst.Fix(); - GC.KeepAlive(joint); + GC.KeepAlive(src.Source); + GC.KeepAlive(joint.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs index 0cda7b00f..079df14e5 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs @@ -31,18 +31,14 @@ private DTFilter(IntPtr smartPtr, IntPtr rawPtr) /// optional number of iterations used for filtering, 3 is quite enough. /// public static DTFilter Create( - InputArray guide, double sigmaSpatial, double sigmaColor, + InputArrayRef guide, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - guide.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createDTFilter( - guide.ToInputProxy(), sigmaSpatial, sigmaColor, (int)mode, numIters, out var smartPtr)); + guide.Proxy, sigmaSpatial, sigmaColor, (int)mode, numIters, out var smartPtr)); - GC.KeepAlive(guide); + GC.KeepAlive(guide.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_DTFilter_get(smartPtr, out var rawPtr)); return new DTFilter(smartPtr, rawPtr); } @@ -54,21 +50,14 @@ public static DTFilter Create( /// /// /// - public virtual void Filter(InputArray src, OutputArray dst, int dDepth = -1) + public virtual void Filter(InputArrayRef src, OutputArrayRef dst, int dDepth = -1) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_DTFilter_filter( - Handle, src.ToInputProxy(), dst.ToOutputProxy(), dDepth)); + Handle, src.Proxy, dst.Proxy, dDepth)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs index c2303db8c..b22e187b4 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs @@ -29,18 +29,14 @@ private FastBilateralSolverFilter(IntPtr smartPtr, IntPtr rawPtr) /// convergence tolerance used for solver. /// public static FastBilateralSolverFilter Create( - InputArray guide, double sigmaSpatial, double sigmaLuma, double sigmaChroma, + InputArrayRef guide, double sigmaSpatial, double sigmaLuma, double sigmaChroma, double lambda = 128.0, int numIter = 25, double maxTol = 1e-5) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - guide.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createFastBilateralSolverFilter( - guide.ToInputProxy(), sigmaSpatial, sigmaLuma, sigmaChroma, lambda, numIter, maxTol, out var smartPtr)); + guide.Proxy, sigmaSpatial, sigmaLuma, sigmaChroma, lambda, numIter, maxTol, out var smartPtr)); - GC.KeepAlive(guide); + GC.KeepAlive(guide.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_FastBilateralSolverFilter_get(smartPtr, out var rawPtr)); return new FastBilateralSolverFilter(smartPtr, rawPtr); } @@ -51,25 +47,15 @@ public static FastBilateralSolverFilter Create( /// source image for filtering with unsigned 8-bit or signed 16-bit or floating-point 32-bit depth and up to 3 channels. /// confidence image with unsigned 8-bit or floating-point 32-bit confidence and 1 channel. /// destination image. - public virtual void Filter(InputArray src, InputArray confidence, OutputArray dst) + public virtual void Filter(InputArrayRef src, InputArrayRef confidence, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (confidence is null) - throw new ArgumentNullException(nameof(confidence)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - confidence.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_FastBilateralSolverFilter_filter( - Handle, src.ToInputProxy(), confidence.ToInputProxy(), dst.ToOutputProxy())); + Handle, src.Proxy, confidence.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(confidence); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(confidence.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs index a871aa640..e8d983f42 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs @@ -28,17 +28,13 @@ private FastGlobalSmootherFilter(IntPtr smartPtr, IntPtr rawPtr) /// number of iterations used for filtering, 3 is usually enough. /// public static FastGlobalSmootherFilter Create( - InputArray guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) + InputArrayRef guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - guide.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createFastGlobalSmootherFilter( - guide.ToInputProxy(), lambda, sigmaColor, lambdaAttenuation, numIter, out var smartPtr)); + guide.Proxy, lambda, sigmaColor, lambdaAttenuation, numIter, out var smartPtr)); - GC.KeepAlive(guide); + GC.KeepAlive(guide.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_FastGlobalSmootherFilter_get(smartPtr, out var rawPtr)); return new FastGlobalSmootherFilter(smartPtr, rawPtr); } @@ -48,21 +44,14 @@ public static FastGlobalSmootherFilter Create( /// /// source image for filtering with unsigned 8-bit or signed 16-bit or floating-point 32-bit depth and up to 4 channels. /// destination image. - public virtual void Filter(InputArray src, OutputArray dst) + public virtual void Filter(InputArrayRef src, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_FastGlobalSmootherFilter_filter( - Handle, src.ToInputProxy(), dst.ToOutputProxy())); + Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs index 745234d7a..a42cff955 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs @@ -27,17 +27,13 @@ private GuidedFilter(IntPtr smartPtr, IntPtr rawPtr) /// space into bilateralFilter. /// public static GuidedFilter Create( - InputArray guide, int radius, double eps) + InputArrayRef guide, int radius, double eps) { - if (guide is null) - throw new ArgumentNullException(nameof(guide)); - guide.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createGuidedFilter( - guide.ToInputProxy(), radius, eps, out var smartPtr)); + guide.Proxy, radius, eps, out var smartPtr)); - GC.KeepAlive(guide); + GC.KeepAlive(guide.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_GuidedFilter_get(smartPtr, out var rawPtr)); return new GuidedFilter(smartPtr, rawPtr); } @@ -48,21 +44,14 @@ public static GuidedFilter Create( /// filtering image with any numbers of channels. /// output image. /// optional depth of the output image. dDepth can be set to -1, which will be equivalent to src.depth(). - public virtual void Filter(InputArray src, OutputArray dst, int dDepth = -1) + public virtual void Filter(InputArrayRef src, OutputArrayRef dst, int dDepth = -1) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_GuidedFilter_filter( - Handle, src.ToInputProxy(), dst.ToOutputProxy(), dDepth)); + Handle, src.Proxy, dst.Proxy, dDepth)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs b/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs index 50b0656e6..8e9f8a910 100644 --- a/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs +++ b/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs @@ -48,21 +48,14 @@ public static FastLineDetector Create( /// and ending point of a line. Where Vec4f is (x1, y1, x2, y2), /// point 1 is the start, point 2 - end.Returned lines are directed so that the /// brighter side is on their left. - public virtual void Detect(InputArray image, OutputArray lines) + public virtual void Detect(InputArrayRef image, OutputArrayRef lines) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); - image.ThrowIfDisposed(); - lines.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_FastLineDetector_detect_OutputArray(Handle, image.ToInputProxy(), lines.ToOutputProxy())); - GC.KeepAlive(image); - GC.KeepAlive(lines); - lines.Fix(); + NativeMethods.ximgproc_FastLineDetector_detect_OutputArray(Handle, image.Proxy, lines.Proxy)); + GC.KeepAlive(image.Source); + GC.KeepAlive(lines.Source); } /// @@ -76,17 +69,14 @@ public virtual void Detect(InputArray image, OutputArray lines) /// and ending point of a line. Where Vec4f is (x1, y1, x2, y2), /// point 1 is the start, point 2 - end.Returned lines are directed so that the /// brighter side is on their left. - public virtual Vec4f[] Detect(InputArray image) + public virtual Vec4f[] Detect(InputArrayRef image) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); using var lines = new StdVector(); NativeMethods.HandleException( - NativeMethods.ximgproc_FastLineDetector_detect_vector(Handle, image.ToInputProxy(), lines.CvPtr)); - GC.KeepAlive(image); + NativeMethods.ximgproc_FastLineDetector_detect_vector(Handle, image.Proxy, lines.CvPtr)); + GC.KeepAlive(image.Source); return lines.ToArray(); } @@ -96,20 +86,15 @@ public virtual Vec4f[] Detect(InputArray image) /// The image, where the lines will be drawn. Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. /// If true, arrow heads will be drawn. - public virtual void DrawSegments(InputOutputArray image, InputArray lines, + public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines, bool drawArrow = false) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - if (lines is null) - throw new ArgumentNullException(nameof(lines)); NativeMethods.HandleException( - NativeMethods.ximgproc_FastLineDetector_drawSegments_InputArray(Handle, image.ToInputOutputProxy(), lines.ToInputProxy(), drawArrow ? 1 : 0)); - GC.KeepAlive(image); - image.Fix(); - GC.KeepAlive(lines); + NativeMethods.ximgproc_FastLineDetector_drawSegments_InputArray(Handle, image.Proxy, lines.Proxy, drawArrow ? 1 : 0)); + GC.KeepAlive(image.Source); + GC.KeepAlive(lines.Source); } /// @@ -118,20 +103,17 @@ public virtual void DrawSegments(InputOutputArray image, InputArray lines, /// The image, where the lines will be drawn. Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. /// If true, arrow heads will be drawn. - public virtual void DrawSegments(InputOutputArray image, IEnumerable lines, bool drawArrow = false) + public virtual void DrawSegments(InputOutputArrayRef image, IEnumerable lines, bool drawArrow = false) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); if (lines is null) throw new ArgumentNullException(nameof(lines)); using var linesVec = new StdVector(lines); NativeMethods.HandleException( NativeMethods.ximgproc_FastLineDetector_drawSegments_vector( - Handle, image.ToInputOutputProxy(), linesVec.CvPtr, drawArrow ? 1 : 0)); + Handle, image.Proxy, linesVec.CvPtr, drawArrow ? 1 : 0)); - GC.KeepAlive(image); - image.Fix(); + GC.KeepAlive(image.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs b/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs index 79c68fbee..4d25516c3 100644 --- a/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs @@ -57,14 +57,10 @@ public static RidgeDetectionFilter Create( /// /// InputArray as supported by Sobel. img can be 1-Channel or 3-Channels. /// OutputAray of structure as RidgeDetectionFilter::ddepth. Output image with ridges. - public virtual void GetRidgeFilteredImage(InputArray src, OutputArray dst) + public virtual void GetRidgeFilteredImage(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ximgproc_RidgeDetectionFilter_getRidgeFilteredImage(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.ximgproc_RidgeDetectionFilter_getRidgeFilteredImage(Handle, src.Proxy, dst.Proxy)); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs index 44281f97e..693b160bd 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs @@ -99,21 +99,15 @@ public virtual int MinSize /// /// The input image. Any number of channel (1 (Eg: Gray), 3 (Eg: RGB), 4 (Eg: RGB-D)) can be provided /// The output segmentation. It's a CV_32SC1 Mat with the same number of cols and rows as input image, with an unique, sequential, id for each pixel. - public virtual void ProcessImage(InputArray src, OutputArray dst) + public virtual void ProcessImage(InputArrayRef src, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ximgproc_segmentation_GraphSegmentation_processImage(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.ximgproc_segmentation_GraphSegmentation_processImage(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs index e13db65f6..af2f9a42f 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs @@ -33,17 +33,14 @@ public static SelectiveSearchSegmentation Create() /// Set a image used by switch* functions to initialize the class /// /// The image - public virtual void SetBaseImage(InputArray img) + public virtual void SetBaseImage(InputArrayRef img) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentation_setBaseImage(Handle, img.ToInputProxy())); + NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentation_setBaseImage(Handle, img.Proxy)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -88,17 +85,14 @@ public virtual void SwitchToSelectiveSearchQuality(int baseK = 150, int incK = 1 /// Add a new image in the list of images to process. /// /// The image - public virtual void AddImage(InputArray img) + public virtual void AddImage(InputArrayRef img) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); NativeMethods.HandleException( - NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentation_addImage(Handle, img.ToInputProxy())); + NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentation_addImage(Handle, img.Proxy)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs index b0556c05d..cbe6e1d40 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs @@ -31,26 +31,17 @@ protected SelectiveSearchSegmentationStrategy(IntPtr smartPtr, IntPtr rawPtr, Ac /// A segementation of the image. The parameter must be the same size of img. /// The sizes of different regions /// If not set to -1, try to cache pre-computations. If the same set og (img, regions, size) is used, the image_id need to be the same. - public virtual void SetImage(InputArray img, InputArray regions, InputArray sizes, int imageId = -1) + public virtual void SetImage(InputArrayRef img, InputArrayRef regions, InputArrayRef sizes, int imageId = -1) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (regions is null) - throw new ArgumentNullException(nameof(regions)); - if (sizes is null) - throw new ArgumentNullException(nameof(sizes)); - img.ThrowIfDisposed(); - regions.ThrowIfDisposed(); - sizes.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentationStrategy_setImage( - Handle, img.ToInputProxy(), regions.ToInputProxy(), sizes.ToInputProxy(), imageId)); + Handle, img.Proxy, regions.Proxy, sizes.Proxy, imageId)); - GC.KeepAlive(img); - GC.KeepAlive(regions); - GC.KeepAlive(sizes); + GC.KeepAlive(img.Source); + GC.KeepAlive(regions.Source); + GC.KeepAlive(sizes.Source); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs index 2ce2119bb..f44492699 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs @@ -23,26 +23,17 @@ private SelectiveSearchSegmentationStrategyMultiple(IntPtr smartPtr, IntPtr rawP /// A segementation of the image. The parameter must be the same size of img. /// The sizes of different regions /// If not set to -1, try to cache pre-computations. If the same set og (img, regions, size) is used, the image_id need to be the same. - public new virtual void SetImage(InputArray img, InputArray regions, InputArray sizes, int imageId = -1) + public new virtual void SetImage(InputArrayRef img, InputArrayRef regions, InputArrayRef sizes, int imageId = -1) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - if (regions is null) - throw new ArgumentNullException(nameof(regions)); - if (sizes is null) - throw new ArgumentNullException(nameof(sizes)); - img.ThrowIfDisposed(); - regions.ThrowIfDisposed(); - sizes.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.ximgproc_segmentation_SelectiveSearchSegmentationStrategy_setImage( - Handle, img.ToInputProxy(), regions.ToInputProxy(), sizes.ToInputProxy(), imageId)); + Handle, img.Proxy, regions.Proxy, sizes.Proxy, imageId)); - GC.KeepAlive(img); - GC.KeepAlive(regions); - GC.KeepAlive(sizes); + GC.KeepAlive(img.Source); + GC.KeepAlive(regions.Source); + GC.KeepAlive(sizes.Source); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs b/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs index 5946d1117..95b8a6c9b 100644 --- a/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs +++ b/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs @@ -39,23 +39,17 @@ public static StructuredEdgeDetection Create(string model, RFFeatureGetter? howT /// edge image. /// orientation map. /// proposal boxes. - public virtual void GetBoundingBoxes(InputArray edgeMap, InputArray orientationMap, out Rect[] boxes) + public virtual void GetBoundingBoxes(InputArrayRef edgeMap, InputArrayRef orientationMap, out Rect[] boxes) { ThrowIfDisposed(); - if (edgeMap is null) - throw new ArgumentNullException(nameof(edgeMap)); - if (orientationMap is null) - throw new ArgumentNullException(nameof(orientationMap)); - edgeMap.ThrowIfDisposed(); - orientationMap.ThrowIfDisposed(); using var boxesVec = new StdVector(); NativeMethods.HandleException( - NativeMethods.ximgproc_EdgeBoxes_getBoundingBoxes(Handle, edgeMap.ToInputProxy(), orientationMap.ToInputProxy(), boxesVec.CvPtr)); + NativeMethods.ximgproc_EdgeBoxes_getBoundingBoxes(Handle, edgeMap.Proxy, orientationMap.Proxy, boxesVec.CvPtr)); boxes = boxesVec.ToArray(); - GC.KeepAlive(edgeMap); - GC.KeepAlive(orientationMap); + GC.KeepAlive(edgeMap.Source); + GC.KeepAlive(orientationMap.Source); } /// @@ -64,21 +58,14 @@ public virtual void GetBoundingBoxes(InputArray edgeMap, InputArray orientationM /// /// source image (RGB, float, in [0;1]) to detect edges /// destination image (grayscale, float, in [0;1]) where edges are drawn - public virtual void DetectEdges(InputArray src, OutputArray dst) + public virtual void DetectEdges(InputArrayRef src, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_StructuredEdgeDetection_detectEdges(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.ximgproc_StructuredEdgeDetection_detectEdges(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -86,21 +73,14 @@ public virtual void DetectEdges(InputArray src, OutputArray dst) /// /// edge image. /// orientation image. - public virtual void ComputeOrientation(InputArray src, OutputArray dst) + public virtual void ComputeOrientation(InputArrayRef src, OutputArrayRef dst) { ThrowIfDisposed(); - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( - NativeMethods.ximgproc_StructuredEdgeDetection_computeOrientation(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.ximgproc_StructuredEdgeDetection_computeOrientation(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } /// @@ -113,27 +93,17 @@ public virtual void ComputeOrientation(InputArray src, OutputArray dst) /// radius for boundary suppression. /// multiplier for conservative suppression. /// enables/disables parallel computing. - public virtual void EdgesNms(InputArray edgeImage, InputArray orientationImage, OutputArray dst, + public virtual void EdgesNms(InputArrayRef edgeImage, InputArrayRef orientationImage, OutputArrayRef dst, int r = 2, int s = 0, float m = 1, bool isParallel = true) { ThrowIfDisposed(); - if (edgeImage is null) - throw new ArgumentNullException(nameof(edgeImage)); - if (orientationImage is null) - throw new ArgumentNullException(nameof(orientationImage)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - edgeImage.ThrowIfDisposed(); - orientationImage.ThrowIfDisposed(); - dst.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_StructuredEdgeDetection_edgesNms( - Handle, edgeImage.ToInputProxy(), orientationImage.ToInputProxy(), dst.ToOutputProxy(), r, s, m, isParallel ? 1 : 0)); + Handle, edgeImage.Proxy, orientationImage.Proxy, dst.Proxy, r, s, m, isParallel ? 1 : 0)); - GC.KeepAlive(edgeImage); - GC.KeepAlive(orientationImage); - dst.Fix(); + GC.KeepAlive(edgeImage.Source); + GC.KeepAlive(orientationImage.Source); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs index 767af8c82..1aa65fda3 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs @@ -37,17 +37,13 @@ private SuperpixelLSC(IntPtr smartPtr, IntPtr rawPtr) /// Chooses the enforcement of superpixel compactness factor of superpixel /// public static SuperpixelLSC Create( - InputArray image, int regionSize = 10, float ratio = 0.075f) + InputArrayRef image, int regionSize = 10, float ratio = 0.075f) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createSuperpixelLSC( - image.ToInputProxy(), regionSize, ratio, out var smartPtr)); + image.Proxy, regionSize, ratio, out var smartPtr)); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_SuperpixelLSC_get(smartPtr, out var rawPtr)); return new SuperpixelLSC(smartPtr, rawPtr); } @@ -95,17 +91,13 @@ public virtual void Iterate(int numIterations = 10) /// /// Return: A CV_32SC1 integer array containing the labels of the superpixel /// segmentation.The labels are in the range[0, getNumberOfSuperpixels()]. - public virtual void GetLabels(OutputArray labelsOut) + public virtual void GetLabels(OutputArrayRef labelsOut) { ThrowIfDisposed(); - if (labelsOut is null) - throw new ArgumentNullException(nameof(labelsOut)); - labelsOut.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelLSC_getLabels( - Handle, labelsOut.ToOutputProxy())); - labelsOut.Fix(); + Handle, labelsOut.Proxy)); } /// @@ -114,17 +106,13 @@ public virtual void GetLabels(OutputArray labelsOut) /// /// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelLSC_getLabelContourMask( - Handle, image.ToOutputProxy(), thickLine ? 1 : 0)); - image.Fix(); + Handle, image.Proxy, thickLine ? 1 : 0)); } /// diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs index 66e87f4f7..d4ffdaa28 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs @@ -90,18 +90,15 @@ public virtual int GetNumberOfSuperpixels() /// channels must match with the initialized image size & channels with the function /// createSuperpixelSEEDS(). It should be in HSV or Lab color space.Lab is a bit better, but also slower. /// Number of pixel level iterations. Higher number improves the result. - public virtual void Iterate(InputArray img, int numIterations = 10) + public virtual void Iterate(InputArrayRef img, int numIterations = 10) { ThrowIfDisposed(); - if (img is null) - throw new ArgumentNullException(nameof(img)); - img.ThrowIfDisposed(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelSEEDS_iterate( - Handle, img.ToInputProxy(), numIterations)); + Handle, img.Proxy, numIterations)); - GC.KeepAlive(img); + GC.KeepAlive(img.Source); } /// @@ -113,17 +110,13 @@ public virtual void Iterate(InputArray img, int numIterations = 10) /// /// Return: A CV_32UC1 integer array containing the labels of the superpixel /// segmentation.The labels are in the range[0, getNumberOfSuperpixels()]. - public virtual void GetLabels(OutputArray labelsOut) + public virtual void GetLabels(OutputArrayRef labelsOut) { ThrowIfDisposed(); - if (labelsOut is null) - throw new ArgumentNullException(nameof(labelsOut)); - labelsOut.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelSEEDS_getLabels( - Handle, labelsOut.ToOutputProxy())); - labelsOut.Fix(); + Handle, labelsOut.Proxy)); } /// @@ -132,16 +125,12 @@ public virtual void GetLabels(OutputArray labelsOut) /// /// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelSEEDS_getLabelContourMask( - Handle, image.ToOutputProxy(), thickLine ? 1 : 0)); - image.Fix(); + Handle, image.Proxy, thickLine ? 1 : 0)); } } diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs index 2e2c45c02..e81cbb423 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs @@ -34,20 +34,16 @@ private SuperpixelSLIC(IntPtr smartPtr, IntPtr rawPtr) /// Chooses the enforcement of superpixel smoothness factor of superpixel /// public static SuperpixelSLIC Create( - InputArray image, + InputArrayRef image, SLICType algorithm = SLICType.SLICO, int regionSize = 10, float ruler = 10.0f) { - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfDisposed(); - NativeMethods.HandleException( NativeMethods.ximgproc_createSuperpixelSLIC( - image.ToInputProxy(), (int)algorithm, regionSize, ruler, out var smartPtr)); + image.Proxy, (int)algorithm, regionSize, ruler, out var smartPtr)); - GC.KeepAlive(image); + GC.KeepAlive(image.Source); NativeMethods.HandleException(NativeMethods.ximgproc_Ptr_SuperpixelSLIC_get(smartPtr, out var rawPtr)); return new SuperpixelSLIC(smartPtr, rawPtr); } @@ -95,17 +91,13 @@ public virtual void Iterate(int numIterations = 10) /// the range[0, getNumberOfSuperpixels()]. /// /// - public virtual void GetLabels(OutputArray labelsOut) + public virtual void GetLabels(OutputArrayRef labelsOut) { ThrowIfDisposed(); - if (labelsOut is null) - throw new ArgumentNullException(nameof(labelsOut)); - labelsOut.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelSLIC_getLabels( - Handle, labelsOut.ToOutputProxy())); - labelsOut.Fix(); + Handle, labelsOut.Proxy)); } /// @@ -114,17 +106,13 @@ public virtual void GetLabels(OutputArray labelsOut) /// /// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) { ThrowIfDisposed(); - if (image is null) - throw new ArgumentNullException(nameof(image)); - image.ThrowIfNotReady(); NativeMethods.HandleException( NativeMethods.ximgproc_SuperpixelSLIC_getLabelContourMask( - Handle, image.ToOutputProxy(), thickLine ? 1 : 0)); - image.Fix(); + Handle, image.Proxy, thickLine ? 1 : 0)); } /// diff --git a/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs b/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs index c72102baa..43d403354 100644 --- a/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs +++ b/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs @@ -42,9 +42,9 @@ public static partial class XPhoto /// Type of the orthogonal transform used in collaborative filtering step. /// Currently only Haar transform is supported. public static void Bm3dDenoising( - InputArray src, - InputOutputArray dstStep1, - OutputArray dstStep2, + InputArrayRef src, + InputOutputArrayRef dstStep1, + OutputArrayRef dstStep2, float h = 1, int templateWindowSize = 4, int searchWindowSize = 16, @@ -57,23 +57,10 @@ public static void Bm3dDenoising( Bm3dSteps step = Bm3dSteps.STEPALL, TransformTypes transformType = TransformTypes.HAAR) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dstStep1 is null) - throw new ArgumentNullException(nameof(dstStep1)); - if (dstStep2 is null) - throw new ArgumentNullException(nameof(dstStep2)); - - src.ThrowIfDisposed(); - dstStep1.ThrowIfNotReady(); - dstStep2.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_bm3dDenoising1(src.ToInputProxy(), dstStep1.ToInputOutputProxy(), dstStep2.ToOutputProxy(), h, templateWindowSize, searchWindowSize, blockMatchingStep1, blockMatchingStep2, groupSize, slidingStep, beta, (int) normType, (int) step, (int) transformType)); + NativeMethods.xphoto_bm3dDenoising1(src.Proxy, dstStep1.Proxy, dstStep2.Proxy, h, templateWindowSize, searchWindowSize, blockMatchingStep1, blockMatchingStep2, groupSize, slidingStep, beta, (int) normType, (int) step, (int) transformType)); - GC.KeepAlive(src); - dstStep1.Fix(); - dstStep2.Fix(); + GC.KeepAlive(src.Source); } /// @@ -101,8 +88,8 @@ public static void Bm3dDenoising( /// Type of the orthogonal transform used in collaborative filtering step. /// Currently only Haar transform is supported. public static void Bm3dDenoising( - InputArray src, - OutputArray dst, + InputArrayRef src, + OutputArrayRef dst, float h = 1, int templateWindowSize = 4, int searchWindowSize = 16, @@ -115,18 +102,10 @@ public static void Bm3dDenoising( Bm3dSteps step = Bm3dSteps.STEPALL, TransformTypes transformType = TransformTypes.HAAR) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_bm3dDenoising2(src.ToInputProxy(), dst.ToOutputProxy(), h, templateWindowSize, searchWindowSize, blockMatchingStep1, blockMatchingStep2, groupSize, slidingStep, beta, (int) normType, (int) step, (int) transformType)); + NativeMethods.xphoto_bm3dDenoising2(src.Proxy, dst.Proxy, h, templateWindowSize, searchWindowSize, blockMatchingStep1, blockMatchingStep2, groupSize, slidingStep, beta, (int) normType, (int) step, (int) transformType)); - GC.KeepAlive(src); - dst.Fix(); + GC.KeepAlive(src.Source); } #endregion @@ -204,21 +183,14 @@ public static void Inpaint(Mat src, Mat mask, Mat dst, OpenCvSharp.XPhoto.Inpain /// image is divided by dynRatio before histogram processing /// color space conversion code(see ColorConversionCodes). Histogram will used only first plane public static void OilPainting( - InputArray src, OutputArray dst, int size, int dynRatio, + InputArrayRef src, OutputArrayRef dst, int size, int dynRatio, ColorConversionCodes? code = null) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_oilPainting(src.ToInputProxy(), dst.ToOutputProxy(), size, dynRatio, code.HasValue ? (int)code : -1)); + NativeMethods.xphoto_oilPainting(src.Proxy, dst.Proxy, size, dynRatio, code.HasValue ? (int)code : -1)); - GC.KeepAlive(src); - GC.KeepAlive(dst); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } #endregion @@ -234,21 +206,13 @@ public static void OilPainting( /// gain for the B channel /// gain for the G channel /// gain for the R channel - public static void ApplyChannelGains(InputArray src, OutputArray dst, float gainB, float gainG, float gainR) + public static void ApplyChannelGains(InputArrayRef src, OutputArrayRef dst, float gainB, float gainG, float gainR) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_applyChannelGains(src.ToInputProxy(), dst.ToOutputProxy(), gainB, gainG, gainR)); + NativeMethods.xphoto_applyChannelGains(src.Proxy, dst.Proxy, gainB, gainG, gainR)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// diff --git a/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs b/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs index fdf4b40b6..232bca894 100644 --- a/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs @@ -54,20 +54,12 @@ public float SaturationThreshold /// /// Input image /// White balancing result - public override void BalanceWhite(InputArray src, OutputArray dst) + public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_GrayworldWB_balanceWhite(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.xphoto_GrayworldWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } } diff --git a/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs b/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs index cf0370747..a7facb0b2 100644 --- a/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs @@ -92,21 +92,13 @@ public float SaturationThreshold /// /// Input image /// White balancing result - public override void BalanceWhite(InputArray src, OutputArray dst) + public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_LearningBasedWB_balanceWhite(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.xphoto_LearningBasedWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } /// @@ -114,20 +106,12 @@ public override void BalanceWhite(InputArray src, OutputArray dst) /// /// Input three-channel image (BGR color space is assumed). /// An array of four (r,g) chromaticity tuples corresponding to the features listed above. - public void ExtractSimpleFeatures(InputArray src, OutputArray dst) + public void ExtractSimpleFeatures(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_LearningBasedWB_extractSimpleFeatures(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.xphoto_LearningBasedWB_extractSimpleFeatures(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } } diff --git a/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs b/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs index 4839ec16f..a41386097 100644 --- a/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs @@ -132,21 +132,13 @@ public float P /// /// Input image /// White balancing result - public override void BalanceWhite(InputArray src, OutputArray dst) + public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) { - if (src is null) - throw new ArgumentNullException(nameof(src)); - if (dst is null) - throw new ArgumentNullException(nameof(dst)); - src.ThrowIfDisposed(); - dst.ThrowIfNotReady(); - NativeMethods.HandleException( - NativeMethods.xphoto_SimpleWB_balanceWhite(Handle, src.ToInputProxy(), dst.ToOutputProxy())); + NativeMethods.xphoto_SimpleWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); - GC.KeepAlive(src); - GC.KeepAlive(dst); - dst.Fix(); + GC.KeepAlive(src.Source); + GC.KeepAlive(dst.Source); } } diff --git a/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs b/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs index b36f0b290..c0b1183ea 100644 --- a/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs +++ b/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs @@ -14,5 +14,5 @@ protected WhiteBalancer(IntPtr smartPtr, IntPtr rawPtr, Action release) /// /// Input image /// White balancing result - public abstract void BalanceWhite(InputArray src, OutputArray dst); + public abstract void BalanceWhite(InputArrayRef src, OutputArrayRef dst); } From 6ba97cd182018ba765acd4bc4c933b48db34e103 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 19:54:38 +0900 Subject: [PATCH 26/29] Fix test call sites broken by the Modules/ InputArrayRef migration (issue #1976 step 5, part 20 follow-up) - Null-literal arguments for now non-nullable *Ref parameters (mask/ element/etc.) changed to `default` across several test files. - Removed BarcodeDetectorTest.DetectAndDecode_NullImage_ThrowsArgumentNullException and WeChatQRCodeTest.DetectAndDecode_NullInput_ThrowsArgumentNullException: both asserted an ArgumentNullException from passing `null!` for an InputArrayRef parameter, which the type system now rejects at compile time instead -- the runtime check the test covered no longer exists. --- test/OpenCvSharp.Tests/aruco/ArucoTest.cs | 2 +- .../OpenCvSharp.Tests/barcode/BarcodeDetectorTest.cs | 8 -------- .../features/FlannBasedMatcherTest.cs | 12 ++++++------ test/OpenCvSharp.Tests/features/ORBTest.cs | 2 +- test/OpenCvSharp.Tests/ml/EMTest.cs | 4 ++-- test/OpenCvSharp.Tests/ptcloud/PtCloudTest.cs | 2 +- .../wechat_qrcode/WeChatQRCodeTest.cs | 11 ----------- .../xfeatures2d/BOWImgDescriptorExtractorTest.cs | 2 +- test/OpenCvSharp.Tests/xfeatures2d/SURFTest.cs | 2 +- 9 files changed, 13 insertions(+), 32 deletions(-) diff --git a/test/OpenCvSharp.Tests/aruco/ArucoTest.cs b/test/OpenCvSharp.Tests/aruco/ArucoTest.cs index b14ce0a6b..f08d39567 100644 --- a/test/OpenCvSharp.Tests/aruco/ArucoTest.cs +++ b/test/OpenCvSharp.Tests/aruco/ArucoTest.cs @@ -330,7 +330,7 @@ public void CharucoDetector_CreateWithAllParams() using var board = new CharucoBoard(5, 7, 0.04f, 0.02f, dict); var dp = new DetectorParameters(); var rp = new RefineParameters(); - using var detector = new CharucoDetector(board, null, null, 2, false, true, dp, rp); + using var detector = new CharucoDetector(board, default, default, 2, false, true, dp, rp); Assert.NotNull(detector); } diff --git a/test/OpenCvSharp.Tests/barcode/BarcodeDetectorTest.cs b/test/OpenCvSharp.Tests/barcode/BarcodeDetectorTest.cs index a9834d268..1ee164b15 100644 --- a/test/OpenCvSharp.Tests/barcode/BarcodeDetectorTest.cs +++ b/test/OpenCvSharp.Tests/barcode/BarcodeDetectorTest.cs @@ -32,14 +32,6 @@ public void Constructor_EmptyPaths() // Argument validation // ----------------------------------------------------------------------- - [Fact] - public void DetectAndDecode_NullImage_ThrowsArgumentNullException() - { - using var bd = new BarcodeDetector(); - Assert.Throws( - () => bd.DetectAndDecode(null!, out _, out _, out _)); - } - [Fact] public void SetDetectorScales_NullArgument_ThrowsArgumentNullException() { diff --git a/test/OpenCvSharp.Tests/features/FlannBasedMatcherTest.cs b/test/OpenCvSharp.Tests/features/FlannBasedMatcherTest.cs index 3d36c06b9..550208516 100644 --- a/test/OpenCvSharp.Tests/features/FlannBasedMatcherTest.cs +++ b/test/OpenCvSharp.Tests/features/FlannBasedMatcherTest.cs @@ -14,8 +14,8 @@ public void Mathing() using var orb = ORB.Create(500); using var descriptor1 = new Mat(); using var descriptor2 = new Mat(); - orb.DetectAndCompute(img1, null, out _, descriptor1); - orb.DetectAndCompute(img2, null, out _, descriptor2); + orb.DetectAndCompute(img1, default, out _, descriptor1); + orb.DetectAndCompute(img2, default, out _, descriptor2); // Flann needs the descriptors to be of type CV_32F Assert.Equal(MatType.CV_8UC1, descriptor1.Type()); @@ -46,8 +46,8 @@ public void MathingWithKDTreeIndexParams() using var orb = ORB.Create(500); using var descriptor1 = new Mat(); using var descriptor2 = new Mat(); - orb.DetectAndCompute(img1, null, out _, descriptor1); - orb.DetectAndCompute(img2, null, out _, descriptor2); + orb.DetectAndCompute(img1, default, out _, descriptor1); + orb.DetectAndCompute(img2, default, out _, descriptor2); using var indexParams = new KDTreeIndexParams(); @@ -80,8 +80,8 @@ public void MathingWithLshIndexParams() using var orb = ORB.Create(500); using var descriptor1 = new Mat(); using var descriptor2 = new Mat(); - orb.DetectAndCompute(img1, null, out _, descriptor1); - orb.DetectAndCompute(img2, null, out _, descriptor2); + orb.DetectAndCompute(img1, default, out _, descriptor1); + orb.DetectAndCompute(img2, default, out _, descriptor2); using var indexParams = new LshIndexParams(12, 20, 2); diff --git a/test/OpenCvSharp.Tests/features/ORBTest.cs b/test/OpenCvSharp.Tests/features/ORBTest.cs index 5ef55ea9f..217214958 100644 --- a/test/OpenCvSharp.Tests/features/ORBTest.cs +++ b/test/OpenCvSharp.Tests/features/ORBTest.cs @@ -37,7 +37,7 @@ public void DetectAndCompute() using (var orb = ORB.Create(500)) using (Mat descriptor = new Mat()) { - orb.DetectAndCompute(gray, null, out var keyPoints, descriptor); + orb.DetectAndCompute(gray, default, out var keyPoints, descriptor); testOutputHelper.WriteLine($"keyPoints has {keyPoints.Length} items."); testOutputHelper.WriteLine($"descriptor has {descriptor.Rows} items."); diff --git a/test/OpenCvSharp.Tests/ml/EMTest.cs b/test/OpenCvSharp.Tests/ml/EMTest.cs index 5cbbde1b4..56ec85214 100644 --- a/test/OpenCvSharp.Tests/ml/EMTest.cs +++ b/test/OpenCvSharp.Tests/ml/EMTest.cs @@ -66,7 +66,7 @@ public void TrainE() using var means0 = Mat.FromPixelData(2, 2, MatType.CV_32F, means0Data); using var labels = new Mat(); - var ok = em.TrainE(samples, means0, null, null, null, labels); + var ok = em.TrainE(samples, means0, default, default, default, labels); Assert.True(ok); Assert.Equal(40, labels.Rows); } @@ -88,7 +88,7 @@ public void TrainM() using var probs0 = Mat.FromPixelData(40, 2, MatType.CV_32F, probs0Data); using var labels = new Mat(); - var ok = em.TrainM(samples, probs0, null, labels); + var ok = em.TrainM(samples, probs0, default, labels); Assert.True(ok); Assert.Equal(40, labels.Rows); } diff --git a/test/OpenCvSharp.Tests/ptcloud/PtCloudTest.cs b/test/OpenCvSharp.Tests/ptcloud/PtCloudTest.cs index a5f3fb25c..6634a6ea6 100644 --- a/test/OpenCvSharp.Tests/ptcloud/PtCloudTest.cs +++ b/test/OpenCvSharp.Tests/ptcloud/PtCloudTest.cs @@ -177,7 +177,7 @@ public void WarpFrameSmoke() try { - Cv2.WarpFrame(depth, null, null, rt, cameraMatrix, warpedDepth); + Cv2.WarpFrame(depth, default, default, rt, cameraMatrix, warpedDepth); testOutputHelper.WriteLine($"WarpFrame produced empty={warpedDepth.Empty()}"); } catch (Exception ex) when (ex is OpenCvSharpException or OpenCVException) diff --git a/test/OpenCvSharp.Tests/wechat_qrcode/WeChatQRCodeTest.cs b/test/OpenCvSharp.Tests/wechat_qrcode/WeChatQRCodeTest.cs index 5b18312bf..ccf47ac25 100644 --- a/test/OpenCvSharp.Tests/wechat_qrcode/WeChatQRCodeTest.cs +++ b/test/OpenCvSharp.Tests/wechat_qrcode/WeChatQRCodeTest.cs @@ -36,17 +36,6 @@ public void Constructor_NullArguments_ThrowsArgumentNullException( Assert.Throws(() => new OpenCvSharp.WeChatQRCode(a!, b!)); } - /// - /// DetectAndDecode must throw ArgumentNullException when inputImage is null. - /// Does not require model files. - /// - [Fact] - public void DetectAndDecode_NullInput_ThrowsArgumentNullException() - { - using var qr = new OpenCvSharp.WeChatQRCode(); - Assert.Throws(() => qr.DetectAndDecode(null!, out _)); - } - /// /// Grayscale image containing 2 QR codes. Both must be decoded correctly. /// diff --git a/test/OpenCvSharp.Tests/xfeatures2d/BOWImgDescriptorExtractorTest.cs b/test/OpenCvSharp.Tests/xfeatures2d/BOWImgDescriptorExtractorTest.cs index 989bfe8f0..ca32a24bb 100644 --- a/test/OpenCvSharp.Tests/xfeatures2d/BOWImgDescriptorExtractorTest.cs +++ b/test/OpenCvSharp.Tests/xfeatures2d/BOWImgDescriptorExtractorTest.cs @@ -85,7 +85,7 @@ public void RunTest() using (var bowTrainer = new BOWKMeansTrainer(200, tc, 1, KMeansFlags.PpCenters)) { var descriptors = new Mat(); - descriptorExtractor.DetectAndCompute(img, null, out keypoints, descriptors); + descriptorExtractor.DetectAndCompute(img, default, out keypoints, descriptors); using var featuresUnclustered = new Mat(); featuresUnclustered.PushBack(descriptors); diff --git a/test/OpenCvSharp.Tests/xfeatures2d/SURFTest.cs b/test/OpenCvSharp.Tests/xfeatures2d/SURFTest.cs index 85d76d824..e6c786ac3 100644 --- a/test/OpenCvSharp.Tests/xfeatures2d/SURFTest.cs +++ b/test/OpenCvSharp.Tests/xfeatures2d/SURFTest.cs @@ -38,7 +38,7 @@ public void DetectAndCompute() using (var surf = SURF.Create(500)) using (Mat descriptor = new Mat()) { - surf.DetectAndCompute(gray, null, out var keyPoints, descriptor); + surf.DetectAndCompute(gray, default, out var keyPoints, descriptor); testOutputHelper.WriteLine($"keyPoints has {keyPoints.Length} items."); testOutputHelper.WriteLine($"descriptor has {descriptor.Rows} items."); From 3bd6ef7b43be72bfc743f934be719309b209e2cb Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 20:11:21 +0900 Subject: [PATCH 27/29] Delete legacy class-based InputArray/OutputArray/InputOutputArray (issue #1976 step 5, final cleanup part 1) All call sites were migrated to the *Ref ref structs in prior commits; this removes the now-dead classes. InOutArrayKind (and the KIND_SHIFT/ KIND_MASK constants that backed it) is deleted alongside InputArray: it only existed to support InputArray.Kind(), one of the ~25 introspection methods (GetMat/Empty/Type/IsMat/etc.) that turned out to have zero callers and zero tests when the *Ref types were designed, and so was never ported. Zero build fallout confirms every caller had already moved to InputArrayRef/OutputArrayRef/InputOutputArrayRef. --- .../Modules/core/Enum/InOutArrayKind.cs | 29 - src/OpenCvSharp/Modules/core/InputArray.cs | 1041 ----------------- .../Modules/core/InputOutputArray.cs | 75 -- src/OpenCvSharp/Modules/core/OutputArray.cs | 177 --- 4 files changed, 1322 deletions(-) delete mode 100644 src/OpenCvSharp/Modules/core/Enum/InOutArrayKind.cs delete mode 100644 src/OpenCvSharp/Modules/core/InputArray.cs delete mode 100644 src/OpenCvSharp/Modules/core/InputOutputArray.cs delete mode 100644 src/OpenCvSharp/Modules/core/OutputArray.cs diff --git a/src/OpenCvSharp/Modules/core/Enum/InOutArrayKind.cs b/src/OpenCvSharp/Modules/core/Enum/InOutArrayKind.cs deleted file mode 100644 index 57a0f0d59..000000000 --- a/src/OpenCvSharp/Modules/core/Enum/InOutArrayKind.cs +++ /dev/null @@ -1,29 +0,0 @@ -#pragma warning disable 1591 -#pragma warning disable CA2217 // Do not mark enums with FlagsAttribute - -namespace OpenCvSharp; - -/// -/// -/// -[Flags] -public enum InOutArrayKind -{ - None = 0, - Mat = 1 << InputArray.KIND_SHIFT, - Matx = 2 << InputArray.KIND_SHIFT, - StdVector = 3 << InputArray.KIND_SHIFT, - VectorVector = 4 << InputArray.KIND_SHIFT, - VectorMat = 5 << InputArray.KIND_SHIFT, - Expr = 6 << InputArray.KIND_SHIFT, - OpenGLBuffer = 7 << InputArray.KIND_SHIFT, - CudaHostMem = 8 << InputArray.KIND_SHIFT, - CudaGpuMat = 9 << InputArray.KIND_SHIFT, - UMat = 10 << InputArray.KIND_SHIFT, - StdVectorUMat = 11 << InputArray.KIND_SHIFT, - StdBoolVector = 12 << InputArray.KIND_SHIFT, - StdVectorCudaGpuMat = 13 << InputArray.KIND_SHIFT, - - FixedType = 0x8000 << InputArray.KIND_SHIFT, - FixedSize = 0x4000 << InputArray.KIND_SHIFT, -} diff --git a/src/OpenCvSharp/Modules/core/InputArray.cs b/src/OpenCvSharp/Modules/core/InputArray.cs deleted file mode 100644 index 5f8d38693..000000000 --- a/src/OpenCvSharp/Modules/core/InputArray.cs +++ /dev/null @@ -1,1041 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; -using OpenCvSharp.Internal; -using OpenCvSharp.Internal.Vectors; - -#pragma warning disable CA1002 // Do not expose generic lists - -namespace OpenCvSharp; - -/// -/// Proxy data type for passing Mat's and vector<>'s as input parameters -/// -public class InputArray : CvObject -{ - private object? obj; - - // A resource materialized by this InputArray itself (e.g. the Mat produced from a - // MatExpr). Unlike 'obj', which is merely kept alive, this is disposed with the InputArray. - private Mat? ownedDisposable; - -#pragma warning disable 1591 - // ReSharper disable InconsistentNaming - public const int KIND_SHIFT = 16; - public const int KIND_MASK = ~(0x8000 << KIND_SHIFT | 0x4000 << KIND_SHIFT) - (1 << KIND_SHIFT) + 1; - // ReSharper restore InconsistentNaming -#pragma warning restore 1591 - - // Migration scaffold (issue #1976, strategy 3): wraps this class's native cv::_InputArray* as an - // ArrayProxy so externs can move to the ArrayProxy ABI one module at a time while InputArray is - // still a class. The caller must keep this object alive across the native call (GC.KeepAlive). - internal InputArrayProxy ToInputProxy() => new() { Handle = CvPtr, Kind = (int)ArrayProxyKind.RawInputArray }; - - #region Init & Disposal - - /// - /// Constructor - /// - /// - internal InputArray(IntPtr ptr) - { - if (ptr != IntPtr.Zero) - SetSafeHandle(new OpenCvPtrSafeHandle(ptr, ownsHandle: true, - releaseAction: p => NativeMethods.core_InputArray_delete(p))); - } - - /// - /// Constructor - /// - /// - // ReSharper disable once SuggestBaseTypeForParameter - internal InputArray(Mat? mat) - { - obj = mat; - if (mat is null) - return; - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byMat(mat.CvPtr, out var p)); - GC.KeepAlive(mat); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete(ptr))); - } - - /// - /// Constructor - /// - /// - // ReSharper disable once SuggestBaseTypeForParameter - internal InputArray(UMat? mat) - { - obj = mat; - if (mat is null) - return; - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byUMat(mat.CvPtr, out var p)); - GC.KeepAlive(mat); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete(ptr))); - } - - /// - /// Constructor - /// - /// - // ReSharper disable once SuggestBaseTypeForParameter - internal InputArray(NativeMatExpr? expr) - { - if (expr is null) - return; - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byMatExpr(expr.CvPtr, out var p)); - GC.KeepAlive(expr); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete(ptr))); - } - - /// - /// Constructor. Materializes the lazy expression into a Mat that this InputArray owns and - /// disposes together with itself. - /// - /// - internal InputArray(MatExpr? node) - { - if (node is null) - return; - var mat = node.ToMat(); - ownedDisposable = mat; - obj = mat; - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byMat(mat.CvPtr, out var p)); - GC.KeepAlive(mat); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete(ptr))); - } - - /// - /// Constructor - /// - /// - internal InputArray(Scalar val) - { - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byScalar(val, out var scalarHandle, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => NativeMethods.core_InputArray_delete_withScalar(ptr, scalarHandle))); - } - - /// - /// Constructor - /// - /// - internal InputArray(double val) - { - var hglobal = Marshal.AllocHGlobal(sizeof(double)); - Marshal.StructureToPtr(val, hglobal, false); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byDouble(hglobal, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - Marshal.FreeHGlobal(hglobal); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(byte[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVecb(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(short[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVecs(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(ushort[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVecw(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(int[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVeci(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(float[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVecf(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Constructor - /// - /// - internal InputArray(double[] vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - if (vec.Length == 0) - throw new ArgumentException("Empty array.", nameof(vec)); - var gch = GCHandle.Alloc(vec, GCHandleType.Pinned); - NativeMethods.HandleException( - NativeMethods.core_InputArray_new_byVecd(gch.AddrOfPinnedObject(), vec.Length, out var p)); - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle: true, - releaseAction: ptr => - { - if (gch.IsAllocated) gch.Free(); - NativeMethods.core_InputArray_delete(ptr); - })); - } - - /// - /// Releases managed resources - /// - protected override void DisposeManaged() - { - GC.KeepAlive(obj); - obj = null; - ownedDisposable?.Dispose(); - ownedDisposable = null; - base.DisposeManaged(); - } - - #endregion - - #region Create - - /// - /// Creates a proxy class of the specified Mat - /// - /// - /// - public static InputArray Create(Mat? mat) => new(mat); - - /// - /// Creates a proxy class of the specified Mat - /// - /// - /// - public static InputArray Create(UMat mat) => new(mat); - - /// - /// Creates a proxy class of the specified matrix expression (materializing it to a Mat). - /// - /// - /// - public static InputArray Create(MatExpr node) => new(node); - - /// - /// Creates a proxy class of the specified Scalar - /// - /// - /// - public static InputArray Create(Scalar val) => new(val); - - /// - /// Creates a proxy class of the specified double - /// - /// - /// - public static InputArray Create(double val) => new(val); - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// - public static InputArray Create(IEnumerable enumerable) - where T : struct - { - if (enumerable is null) - throw new ArgumentNullException(nameof(enumerable)); - var list = new List(enumerable); - return Create(list.ToArray()); - } - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// Matrix depth and channels for converting array to cv::Mat - /// - public static InputArray Create(IEnumerable enumerable, MatType type) - where T : struct - { - if (enumerable is null) - throw new ArgumentNullException(nameof(enumerable)); - var list = new List(enumerable); - return Create(list.ToArray(), type); - } - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// - public static InputArray Create(T[] array) - where T : struct - { - var type = EstimateType(typeof(T)); - return Create(array, type); - } - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// Matrix depth and channels for converting array to cv::Mat - /// - public static InputArray Create(T[] array, MatType type) - where T : struct - { - if (array is null) - throw new ArgumentNullException(nameof(array)); - if (array.Length == 0) - throw new ArgumentException("array.Length == 0"); - - var rows = array.Length; - var mat = Mat.FromPixelData(rows, 1, type, array); - return new InputArray(mat); - } - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// - public static InputArray Create(T[,] array) - where T : struct - { - var type = EstimateType(typeof(T)); - return Create(array, type); - } - - /// - /// Creates a proxy class of the specified list - /// - /// Array object - /// Matrix depth and channels for converting array to cv::Mat - /// - public static InputArray Create(T[,] array, MatType type) - where T : struct - { - if (array is null) - throw new ArgumentNullException(nameof(array)); - var rows = array.GetLength(0); - var cols = array.GetLength(1); - if (rows == 0) - throw new ArgumentException("array.GetLength(0) == 0"); - if (cols == 0) - throw new ArgumentException("array.GetLength(1) == 0"); - var mat = Mat.FromPixelData(rows, cols, type, array); - return new InputArray(mat); - } - - /// - /// Creates a proxy class of the specified Vec*b - /// - /// - /// - public static InputArray Create(IVec vec) - { - if (vec is null) - throw new ArgumentNullException(nameof(vec)); - - return vec switch - { -#pragma warning disable CA2000 - Vec2b v => new InputArray(new[] { v.Item0, v.Item1 }), - Vec3b v => new InputArray(new[] { v.Item0, v.Item1, v.Item2 }), - Vec4b v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3 }), - Vec6b v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5 }), - Vec2s v => new InputArray(new[] { v.Item0, v.Item1 }), - Vec3s v => new InputArray(new[] { v.Item0, v.Item1, v.Item2 }), - Vec4s v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3 }), - Vec6s v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5 }), - Vec2w v => new InputArray(new[] { v.Item0, v.Item1 }), - Vec3w v => new InputArray(new[] { v.Item0, v.Item1, v.Item2 }), - Vec4w v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3 }), - Vec6w v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5 }), - Vec2i v => new InputArray(new[] { v.Item0, v.Item1 }), - Vec3i v => new InputArray(new[] { v.Item0, v.Item1, v.Item2 }), - Vec4i v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3 }), - Vec6i v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5 }), - Vec2f v => new InputArray(new[] { v.Item0, v.Item1 }), - Vec3f v => new InputArray(new[] { v.Item0, v.Item1, v.Item2 }), - Vec4f v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3 }), - Vec6f v => new InputArray(new[] { v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5 }), - Vec2d v => new InputArray([v.Item0, v.Item1]), - Vec3d v => new InputArray([v.Item0, v.Item1, v.Item2]), - Vec4d v => new InputArray([v.Item0, v.Item1, v.Item2, v.Item3]), - Vec6d v => new InputArray([v.Item0, v.Item1, v.Item2, v.Item3, v.Item4, v.Item5]), -#pragma warning restore CA2000 - _ => throw new ArgumentException($"Not supported type: '{vec.GetType().Name}'", nameof(vec)) - }; - } - - /// - /// - /// - /// - /// - private static MatType EstimateType(Type t) - { - if (!t.GetTypeInfo().IsValueType) - throw new ArgumentException("Reference type is not supported."); - - // Primitive types -#if false - if (t == typeof(byte)) - return MatType.CV_8UC1; - if (t == typeof(sbyte)) - return MatType.CV_8SC1; - if (t == typeof(ushort) || t == typeof(char)) - return MatType.CV_16UC1; - if (t == typeof(short)) - return MatType.CV_16SC1; - if (t == typeof(int) || t == typeof(uint)) - return MatType.CV_32SC1; - if (t == typeof(float)) - return MatType.CV_32FC1; - if (t == typeof(double)) - return MatType.CV_64FC1; -#else - var code = System.Type.GetTypeCode(t); - switch (code) - { - case TypeCode.Byte: - return MatType.CV_8UC1; - case TypeCode.SByte: - return MatType.CV_8SC1; - case TypeCode.UInt16: - return MatType.CV_16UC1; - case TypeCode.Int16: - case TypeCode.Char: - return MatType.CV_16SC1; - case TypeCode.UInt32: - case TypeCode.Int32: - return MatType.CV_32SC1; - case TypeCode.Single: - return MatType.CV_32FC1; - case TypeCode.Double: - return MatType.CV_64FC1; - } -#endif - - // OpenCV struct types - if (t == typeof(Point)) - return MatType.CV_32SC2; - if (t == typeof(Point2f)) - return MatType.CV_32FC2; - if (t == typeof(Point2d)) - return MatType.CV_64FC2; - if (t == typeof(Point3i)) - return MatType.CV_32SC3; - if (t == typeof(Point3f)) - return MatType.CV_32FC3; - if (t == typeof(Point3d)) - return MatType.CV_64FC3; - if (t == typeof(Range)) - return MatType.CV_32SC2; - if (t == typeof(Rangef)) - return MatType.CV_32FC2; - if (t == typeof(Rect)) - return MatType.CV_32SC4; - if (t == typeof(Size)) - return MatType.CV_32SC2; - if (t == typeof(Size2f)) - return MatType.CV_32FC2; - - if (t == typeof(Vec2b)) - return MatType.CV_8UC2; - if (t == typeof(Vec3b)) - return MatType.CV_8UC3; - if (t == typeof(Vec4b)) - return MatType.CV_8UC4; - if (t == typeof(Vec6b)) - return MatType.CV_8UC(6); - if (t == typeof(Vec2s)) - return MatType.CV_16SC2; - if (t == typeof(Vec3s)) - return MatType.CV_16SC3; - if (t == typeof(Vec4s)) - return MatType.CV_16SC4; - if (t == typeof(Vec6s)) - return MatType.CV_16SC(6); - if (t == typeof(Vec2w)) - return MatType.CV_16UC2; - if (t == typeof(Vec3w)) - return MatType.CV_16UC3; - if (t == typeof(Vec4w)) - return MatType.CV_16UC4; - if (t == typeof(Vec6w)) - return MatType.CV_16UC(6); - if (t == typeof(Vec2i)) - return MatType.CV_32SC2; - if (t == typeof(Vec3i)) - return MatType.CV_32SC3; - if (t == typeof(Vec4i)) - return MatType.CV_32SC4; - if (t == typeof(Vec6i)) - return MatType.CV_32SC(6); - if (t == typeof(Vec2f)) - return MatType.CV_32FC2; - if (t == typeof(Vec3f)) - return MatType.CV_32FC3; - if (t == typeof(Vec4f)) - return MatType.CV_32FC4; - if (t == typeof(Vec6f)) - return MatType.CV_32FC(6); - if (t == typeof(Vec2d)) - return MatType.CV_64FC2; - if (t == typeof(Vec3d)) - return MatType.CV_64FC3; - if (t == typeof(Vec4d)) - return MatType.CV_64FC4; - if (t == typeof(Vec6d)) - return MatType.CV_64FC(6); - - throw new ArgumentException("Not supported value type for InputArray"); - } - #endregion - - #region Cast - -#pragma warning disable 1591 -#pragma warning disable CA2225 - - public static implicit operator InputArray(Mat? mat) => Create(mat); - - public static implicit operator InputArray(UMat mat) => Create(mat); - - public static implicit operator InputArray(MatExpr node) => Create(node); - - public static implicit operator InputArray(Scalar val) => Create(val); - - public static implicit operator InputArray(double val) => Create(val); - - public static implicit operator InputArray(Vec2b vec) => Create(vec); - public static implicit operator InputArray(Vec3b vec) => Create(vec); - public static implicit operator InputArray(Vec4b vec) => Create(vec); - public static implicit operator InputArray(Vec6b vec) => Create(vec); - public static implicit operator InputArray(Vec2s vec) => Create(vec); - public static implicit operator InputArray(Vec3s vec) => Create(vec); - public static implicit operator InputArray(Vec4s vec) => Create(vec); - public static implicit operator InputArray(Vec6s vec) => Create(vec); - public static implicit operator InputArray(Vec2w vec) => Create(vec); - public static implicit operator InputArray(Vec3w vec) => Create(vec); - public static implicit operator InputArray(Vec4w vec) => Create(vec); - public static implicit operator InputArray(Vec6w vec) => Create(vec); - public static implicit operator InputArray(Vec2i vec) => Create(vec); - public static implicit operator InputArray(Vec3i vec) => Create(vec); - public static implicit operator InputArray(Vec4i vec) => Create(vec); - public static implicit operator InputArray(Vec6i vec) => Create(vec); - public static implicit operator InputArray(Vec2f vec) => Create(vec); - public static implicit operator InputArray(Vec3f vec) => Create(vec); - public static implicit operator InputArray(Vec4f vec) => Create(vec); - public static implicit operator InputArray(Vec6f vec) => Create(vec); - public static implicit operator InputArray(Vec2d vec) => Create(vec); - public static implicit operator InputArray(Vec3d vec) => Create(vec); - public static implicit operator InputArray(Vec4d vec) => Create(vec); - public static implicit operator InputArray(Vec6d vec) => Create(vec); -#pragma warning restore CA2225 -#pragma warning restore 1591 - - #endregion - - #region Methods - - /// - /// - /// - /// - /// - public Mat GetMat(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getMat(Handle, i, out var ret)); - return new Mat(ret); - } - - /// - /// - /// - /// - public Mat[] GetMatVector() - { - ThrowIfDisposed(); - using var vec = new VectorOfMat(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getMatVector(Handle, vec.CvPtr)); - return vec.ToArray(); - } - - /// - /// - /// - /// - /// - public UMat GetUMat(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getUMat(Handle, i, out var ret)); - return new UMat(ret); - } - - /// - /// - /// - /// - public int GetFlags() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getFlags(Handle, out var ret)); - return ret; - } - - /// - /// - /// - /// - public IntPtr GetObj() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getObj(Handle, out var ret)); - return ret; - } - - /// - /// - /// - /// - public Size GetSz() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_getSz(Handle, out var ret)); - return ret; - } - - /// - /// - /// - public InOutArrayKind Kind() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_kind(Handle, out var ret)); - return (InOutArrayKind)ret; - } - - /// - /// - /// - /// - /// - public int Dims(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_dims(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public int Cols(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_cols(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public int Rows(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_rows(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public Size Size(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_size(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - /// - // ReSharper disable once InconsistentNaming - public int SizeND(int[] sz, int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_sizend(Handle, sz, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public bool SameSize(InputArray arr) - { - if (arr is null) - throw new ArgumentNullException(nameof(arr)); - arr.ThrowIfDisposed(); - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_sameSize(Handle, arr.CvPtr, out var ret)); - GC.KeepAlive(arr); - return ret != 0; - } - - /// - /// - /// - /// - /// - public long Total(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_total(Handle, i, out var ret)); - return ret.ToInt64(); - } - - /// - /// - /// - /// - /// - public int Type(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_type(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public int Depth(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_depth(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public int Channels(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_channels(Handle, i, out var ret)); - return ret; - } - - /// - /// - /// - /// - /// - public bool IsContinuous(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isContinuous(Handle, i, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - /// - public bool IsSubmatrix(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isSubmatrix(Handle, i, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - /// - public bool Empty() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_empty(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public void CopyTo(OutputArray arr) - { - if (arr is null) - throw new ArgumentNullException(nameof(arr)); - arr.ThrowIfNotReady(); - ThrowIfDisposed(); - - NativeMethods.HandleException( - NativeMethods.core_InputArray_copyTo1(Handle, arr.CvPtr)); - - GC.KeepAlive(arr); - } - - /// - /// - /// - /// - /// - public void CopyTo(OutputArray arr, InputArray mask) - { - if (arr is null) - throw new ArgumentNullException(nameof(arr)); - if (mask is null) - throw new ArgumentNullException(nameof(mask)); - arr.ThrowIfNotReady(); - mask.ThrowIfDisposed(); - ThrowIfDisposed(); - - NativeMethods.HandleException( - NativeMethods.core_InputArray_copyTo2(Handle, arr.CvPtr, mask.CvPtr)); - - arr.Fix(); - GC.KeepAlive(arr); - GC.KeepAlive(mask); - } - - /// - /// - /// - /// - /// - public long Offset(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_offset(Handle, i, out var ret)); - return ret.ToInt64(); - } - - /// - /// - /// - /// - /// - public long Step(int i = -1) - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_step(Handle, i, out var ret)); - return ret.ToInt64(); - } - - /// - /// - /// - /// - public bool IsMat() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isMat(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsUMat() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isUMat(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsMatVector() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isMatVector(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsUMatVector() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isUMatVector(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsMatx() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isMatx(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsVector() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isVector(Handle, out var ret)); - return ret != 0; - } - - /// - /// - /// - /// - public bool IsGpuMatVector() - { - ThrowIfDisposed(); - NativeMethods.HandleException( - NativeMethods.core_InputArray_isGpuMatVector(Handle, out var ret)); - return ret != 0; - } - - #endregion -} diff --git a/src/OpenCvSharp/Modules/core/InputOutputArray.cs b/src/OpenCvSharp/Modules/core/InputOutputArray.cs deleted file mode 100644 index 6a7543890..000000000 --- a/src/OpenCvSharp/Modules/core/InputOutputArray.cs +++ /dev/null @@ -1,75 +0,0 @@ - -using System.Diagnostics.CodeAnalysis; - -namespace OpenCvSharp; - -/// -/// Proxy data type for passing Mat's and vector<>'s as input parameters. -/// Synonym for OutputArray. -/// -public class InputOutputArray : OutputArray -{ - // Migration scaffold (issue #1976, strategy 3): wraps this class's native cv::_InputOutputArray* - // as an ArrayProxy so externs taking _InputOutputArray* can move to the ArrayProxy ABI one module - // at a time. The caller must keep this object alive across the native call (GC.KeepAlive). - internal InputOutputArrayProxy ToInputOutputProxy() => new() { Handle = CvPtr, Kind = (int)ArrayProxyKind.RawInputOutputArray }; - - /// - /// Constructor - /// - /// - internal InputOutputArray(Mat mat) - : base(mat) - { - } - - /// - /// Constructor - /// - /// - internal InputOutputArray(UMat mat) - : base(mat) - { - } - - /// - /// Creates a proxy class of the specified Mat - /// - /// - /// - public new static InputOutputArray Create(Mat mat) - { - return new(mat); - } - - /// - /// Creates a proxy class of the specified UMat - /// - /// - /// - public new static InputOutputArray Create(UMat mat) - { - return new(mat); - } - - /// - /// - /// - /// - [SuppressMessage("Microsoft.Design", "CA2225: Operator overloads have named alternates")] - public static implicit operator InputOutputArray(Mat mat) - { - return new(mat); - } - - /// - /// - /// - /// - /// - [SuppressMessage("Microsoft.Design", "CA2225: Operator overloads have named alternates")] - public static implicit operator InputOutputArray(UMat mat) - { - return new(mat); - } -} diff --git a/src/OpenCvSharp/Modules/core/OutputArray.cs b/src/OpenCvSharp/Modules/core/OutputArray.cs deleted file mode 100644 index 128897d32..000000000 --- a/src/OpenCvSharp/Modules/core/OutputArray.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using OpenCvSharp.Internal; - -namespace OpenCvSharp; - -/// -/// Proxy datatype for passing Mat's as output parameters -/// -public class OutputArray : CvObject -{ - private readonly object obj; - - // Migration scaffold (issue #1976, strategy 3): wraps this class's native cv::_OutputArray* as an - // ArrayProxy so externs can move to the ArrayProxy ABI one module at a time while OutputArray is - // still a class. The caller must keep this object alive across the native call (GC.KeepAlive). - internal OutputArrayProxy ToOutputProxy() => new() { Handle = CvPtr, Kind = (int)ArrayProxyKind.RawOutputArray }; - - #region Init & Disposal - - /// - /// Constructor - /// - /// - internal OutputArray(Mat mat) - { - if (mat is null) - throw new ArgumentNullException(nameof(mat)); - NativeMethods.HandleException( - NativeMethods.core_OutputArray_new_byMat(mat.CvPtr, out var p)); - GC.KeepAlive(mat); - obj = mat; - InitSafeHandle(p); - } - - /// - /// Constructor - /// - /// - internal OutputArray(UMat mat) - { - if (mat is null) - throw new ArgumentNullException(nameof(mat)); - NativeMethods.HandleException( - NativeMethods.core_OutputArray_new_byUMat(mat.CvPtr, out var p)); - GC.KeepAlive(mat); - obj = mat; - InitSafeHandle(p); - } - - /// - /// Releases unmanaged resources - /// - - private void InitSafeHandle(IntPtr p, bool ownsHandle = true) - { - SetSafeHandle(new OpenCvPtrSafeHandle(p, ownsHandle, - static h => NativeMethods.HandleException(NativeMethods.core_OutputArray_delete(h)))); - } - - #endregion - - #region Cast - - /// - /// - /// - /// - /// - [SuppressMessage("Microsoft.Design", "CA2225: Operator overloads have named alternates")] - public static implicit operator OutputArray(Mat mat) - { - return new(mat); - } - - /// - /// - /// - /// - /// - [SuppressMessage("Microsoft.Design", "CA2225: Operator overloads have named alternates")] - public static implicit operator OutputArray(UMat umat) - { - return new(umat); - } - - #endregion - - #region Methods - - /// - /// - /// - /// - public bool IsMat() - { - return obj is Mat; - } - - /// - /// - /// - /// - public bool IsUMat() - { - return obj is UMat; - } - - /// - /// - /// - /// - public virtual Mat? GetMat() - { - return obj as Mat; - } - - /// - /// - /// - public virtual void AssignResult() - { - if (!IsReady()) - throw new NotSupportedException(); - } - - /// - /// - /// - public void Fix() - { - AssignResult(); - Dispose(); - } - - /// - /// - /// - /// - public bool IsReady() - { - return - ptr != IntPtr.Zero && - !IsDisposed && - IsMat() || IsUMat(); - } - /// - /// - /// - /// - public void ThrowIfNotReady() - { - if (!IsReady()) - throw new OpenCvSharpException("Invalid OutputArray"); - } - - /// - /// Creates a proxy class of the specified matrix - /// - /// - /// - public static OutputArray Create(Mat mat) - { - return new (mat); - } - - /// - /// Creates a proxy class of the specified matrix - /// - /// - /// - public static OutputArray Create(UMat mat) - { - return new (mat); - } - - #endregion -} From d517a6f4a7aec0592118a9aafba32bb0c9d134a3 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 20:13:57 +0900 Subject: [PATCH 28/29] Remove Cv2_experimental.cs PoC scaffolding (issue #1976 step 5, final cleanup part 2) TransposeRef/AddRef/CompleteSymmRef were the original proof-of-concept for the ref-struct design and call the exact same native functions as the now-migrated Cv2.Transpose/Add/CompleteSymm, making them pure duplicates. Rewired InputArrayRefTest.cs to exercise the same allocation-free and Create(...) factory behavior through the real, permanent Cv2 methods instead of the deleted PoC ones, so the zero-allocation regression coverage isn't lost. --- src/OpenCvSharp/Cv2/Cv2_experimental.cs | 46 ----- .../core/InputArrayRefTest.cs | 157 +++--------------- 2 files changed, 20 insertions(+), 183 deletions(-) delete mode 100644 src/OpenCvSharp/Cv2/Cv2_experimental.cs diff --git a/src/OpenCvSharp/Cv2/Cv2_experimental.cs b/src/OpenCvSharp/Cv2/Cv2_experimental.cs deleted file mode 100644 index dfddd2122..000000000 --- a/src/OpenCvSharp/Cv2/Cv2_experimental.cs +++ /dev/null @@ -1,46 +0,0 @@ -using OpenCvSharp.Internal; - -namespace OpenCvSharp; - -// FOUNDATION (issue: InputArray/OutputArray ref-struct redesign). -// A few functions wired through the ref-struct proxy path to prove the end-to-end design: -// implicit Mat/Scalar/... -> InputArrayRef/OutputArrayRef (stack, no alloc) -> extern receives an -// ArrayProxy BY VALUE -> native rebuilds cv::_InputArray/_OutputArray on its stack. No managed or -// native _InputArray object is allocated per call. -static partial class Cv2 -{ - /// - /// FOUNDATION: Transposes a matrix through the allocation-free ref-struct proxy path. - /// - public static void TransposeRef(InputArrayRef src, OutputArrayRef dst) - { - NativeMethods.HandleException( - NativeMethods.core_transpose(src.Proxy, dst.Proxy)); - GC.KeepAlive(src.Source); - GC.KeepAlive(dst.Source); - } - - /// - /// FOUNDATION: Per-element addition through the ref-struct proxy path. Either operand may be a - /// Mat/UMat or a Scalar/double — scalars travel inline (no allocation). - /// - public static void AddRef(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) - { - NativeMethods.HandleException( - NativeMethods.core_add(src1.Proxy, src2.Proxy, dst.Proxy, default, -1)); - GC.KeepAlive(src1.Source); - GC.KeepAlive(src2.Source); - GC.KeepAlive(dst.Source); - } - - /// - /// FOUNDATION: Copies the lower/upper half of a square matrix onto the other half, in place, - /// through the ref-struct proxy path (exercises the InputOutputArray proxy). - /// - public static void CompleteSymmRef(InputOutputArrayRef mtx, bool lowerToUpper = false) - { - NativeMethods.HandleException( - NativeMethods.core_completeSymm(mtx.Proxy, lowerToUpper ? 1 : 0)); - GC.KeepAlive(mtx.Source); - } -} diff --git a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs index a7379a338..a0aa02f7c 100644 --- a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs +++ b/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs @@ -4,11 +4,9 @@ namespace OpenCvSharp.Tests.Core; /// -/// PROTOTYPE proof for the ref-struct InputArray/OutputArray redesign: one function -/// () wired through the handle+kind proxy path. Verifies numeric -/// correctness against the existing class-based path and, crucially, that repeated calls allocate -/// nothing on the managed heap (the implicit-conversion temporaries live on the stack and the -/// native _InputArray is built extern-side). +/// Verifies the ref-struct InputArray/OutputArray design (issue #1976): implicit conversions from +/// Mat/UMat/MatExpr/Scalar/double/Vec are allocation-free, and the explicit Create(...) factory +/// methods behave the same as their implicit-conversion equivalents. /// public class InputArrayRefTest : TestBase { @@ -20,137 +18,49 @@ private static Mat Float3x3(params float[] v) } [Fact] - public void TransposeRef_MatchesClassBasedTranspose() - { - using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - - using var actual = new Mat(); - Cv2.TransposeRef(src, actual); // Mat -> InputArrayRef/OutputArrayRef (ref struct) - - using var expected = new Mat(); - Cv2.Transpose(src, expected); // existing class-based InputArray/OutputArray path - - ImageEquals(expected, actual); - } - - [Fact] - public void TransposeRef_IsAllocationFree() + public void Transpose_IsAllocationFree() { using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); using var dst = new Mat(); - // Warm up JIT / one-time setup. - Cv2.TransposeRef(src, dst); + Cv2.Transpose(src, dst); // warmup var before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < 1000; i++) - Cv2.TransposeRef(src, dst); + Cv2.Transpose(src, dst); var after = GC.GetAllocatedBytesForCurrentThread(); Assert.Equal(0, after - before); } [Fact] - public void AddRef_MatPlusMat_Matches() - { - using var a = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - using var b = Float3x3(9, 8, 7, 6, 5, 4, 3, 2, 1); - - using var actual = new Mat(); - Cv2.AddRef(a, b, actual); - - using var expected = new Mat(); - Cv2.Add(a, b, expected); - - ImageEquals(expected, actual); - } - - [Fact] - public void AddRef_MatPlusScalar_Matches() - { - using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - var s = new Scalar(10); - - using var actual = new Mat(); - Cv2.AddRef(src, s, actual); // InputArrayRef(Scalar) — scalar travels inline - - using var expected = new Mat(); - Cv2.Add(src, s, expected); // class path (Scalar -> InputArray) - - ImageEquals(expected, actual); - } - - [Fact] - public void AddRef_MatPlusDouble_Matches() - { - using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - - using var actual = new Mat(); - Cv2.AddRef(src, 5.0, actual); // InputArrayRef(double) - - using var expected = new Mat(); - Cv2.Add(src, new Scalar(5.0), expected); - - ImageEquals(expected, actual); - } - - [Fact] - public void AddRef_MatPlusScalar_IsAllocationFree() + public void Add_MatPlusScalar_IsAllocationFree() { using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); var s = new Scalar(10); using var dst = new Mat(); - Cv2.AddRef(src, s, dst); // warmup + Cv2.Add(src, s, dst); // warmup var before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < 1000; i++) - Cv2.AddRef(src, s, dst); + Cv2.Add(src, s, dst); var after = GC.GetAllocatedBytesForCurrentThread(); Assert.Equal(0, after - before); } [Fact] - public void AddRef_MatPlusMatExpr_Matches() - { - using var a = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - using var b = Float3x3(9, 8, 7, 6, 5, 4, 3, 2, 1); - - using var actual = new Mat(); - Cv2.AddRef(a, a + b, actual); // (a + b) is a MatExpr -> InputArrayRef(MatExpr) - - using var expected = new Mat(); - Cv2.Add(a, a + b, expected); // class path (MatExpr -> InputArray) - - ImageEquals(expected, actual); - } - - [Fact] - public void TransposeRef_Vec_Matches() - { - var v = new Vec3d(1, 2, 3); - - using var actual = new Mat(); - Cv2.TransposeRef(v, actual); // Vec3d -> InputArrayRef(Vec), travels inline - - using var expected = new Mat(); - Cv2.Transpose(v, expected); // Vec3d -> class InputArray(Vec) - - ImageEquals(expected, actual); - } - - [Fact] - public void TransposeRef_Vec_IsAllocationFree() + public void Transpose_Vec_IsAllocationFree() { var v = new Vec3d(1, 2, 3); using var dst = new Mat(); - Cv2.TransposeRef(v, dst); // warmup + Cv2.Transpose(v, dst); // warmup var before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < 1000; i++) - Cv2.TransposeRef(v, dst); + Cv2.Transpose(v, dst); var after = GC.GetAllocatedBytesForCurrentThread(); Assert.Equal(0, after - before); @@ -175,43 +85,16 @@ public void MinMax_InputArray_WriteThrough() ImageEquals(expectedMax, mx); } - [Fact] - public void CompleteSymmRef_Matches() - { - using var actual = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - Cv2.CompleteSymmRef(actual); // InputOutputArrayRef (in-place) - - using var expected = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - Cv2.CompleteSymm(expected); // class InputOutputArray path - - ImageEquals(expected, actual); - } - - [Fact] - public void CompleteSymmRef_IsAllocationFree() - { - using var m = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); - - Cv2.CompleteSymmRef(m); // warmup - - var before = GC.GetAllocatedBytesForCurrentThread(); - for (var i = 0; i < 1000; i++) - Cv2.CompleteSymmRef(m); - var after = GC.GetAllocatedBytesForCurrentThread(); - - Assert.Equal(0, after - before); - } - [Fact] public void Create_FromVec_MatchesImplicitConversion() { var v = new Vec3d(1, 2, 3); using var actual = new Mat(); - Cv2.TransposeRef(InputArrayRef.Create(v), actual); + Cv2.Transpose(InputArrayRef.Create(v), actual); using var expected = new Mat(); - Cv2.TransposeRef(v, expected); + Cv2.Transpose(v, expected); ImageEquals(expected, actual); } @@ -227,11 +110,11 @@ public void Create_From2DArray_MatchesManuallyBuiltMat() }; using var actual = new Mat(); - Cv2.TransposeRef(InputArrayRef.Create(a), actual); + Cv2.Transpose(InputArrayRef.Create(a), actual); using var src = Mat.FromPixelData(3, 3, MatType.CV_64FC1, a); using var expected = new Mat(); - Cv2.TransposeRef(src, expected); + Cv2.Transpose(src, expected); ImageEquals(expected, actual); } @@ -242,11 +125,11 @@ public void Create_From1DArray_MatchesManuallyBuiltMat() double[] a = [1, 2, 3, 4, 5, 6]; using var actual = new Mat(); - Cv2.TransposeRef(InputArrayRef.Create(a), actual); + Cv2.Transpose(InputArrayRef.Create(a), actual); using var src = Mat.FromPixelData(6, 1, MatType.CV_64FC1, a); using var expected = new Mat(); - Cv2.TransposeRef(src, expected); + Cv2.Transpose(src, expected); ImageEquals(expected, actual); } @@ -257,10 +140,10 @@ public void Create_FromMat_MatchesImplicitConversion() using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); using var actual = new Mat(); - Cv2.TransposeRef(InputArrayRef.Create(src), actual); + Cv2.Transpose(InputArrayRef.Create(src), actual); using var expected = new Mat(); - Cv2.TransposeRef(src, expected); + Cv2.Transpose(src, expected); ImageEquals(expected, actual); } From 51a378671b5182bbf098f289e1f7f49863c528d5 Mon Sep 17 00:00:00 2001 From: shimat Date: Thu, 2 Jul 2026 20:20:47 +0900 Subject: [PATCH 29/29] Rename InputArrayRef/OutputArrayRef/InputOutputArrayRef to their final names (issue #1976 step 5, final cleanup part 3) Mechanical rename now that the class-based InputArray/OutputArray/ InputOutputArray are gone and the names are free: InputArrayRef -> InputArray OutputArrayRef -> OutputArray InputOutputArrayRef -> InputOutputArray Single-pass whole-word regex per name (no placeholder/2-pass needed, unlike the earlier MatExprNode->MatExpr rename, since these three names don't overlap as substrings of each other and the target names weren't already in use). Renamed the defining file InputArrayRef.cs -> InputArray.cs and the test file/class InputArrayRefTest(.cs) -> InputArrayTest. Also dropped the ArrayProxyKind.RawInputArray/RawOutputArray/ RawInputOutputArray migration-scaffold enum values and rewrote the file-header comment in InputArray.cs: both were explicitly documented as "removed once the type flip is complete", which it now is. Nothing in the codebase ever constructed a proxy with those Kind values anymore (they existed solely so externs could wrap a class-based InputArray/OutputArray/InputOutputArray handle during the incremental ArrayProxy ABI migration). This completes issue #1976 step 5: InputArray/OutputArray/ InputOutputArray are now ref structs everywhere, matching their original class-based public API names. --- src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs | 36 +- src/OpenCvSharp/Cv2/Cv2_calib.cs | 54 +-- src/OpenCvSharp/Cv2/Cv2_core.cs | 254 +++++++------- src/OpenCvSharp/Cv2/Cv2_features.cs | 10 +- src/OpenCvSharp/Cv2/Cv2_geometry.cs | 218 ++++++------ src/OpenCvSharp/Cv2/Cv2_highgui.cs | 6 +- src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs | 6 +- src/OpenCvSharp/Cv2/Cv2_imgproc.cs | 332 +++++++++--------- src/OpenCvSharp/Cv2/Cv2_objdetect.cs | 16 +- src/OpenCvSharp/Cv2/Cv2_photo.cs | 32 +- src/OpenCvSharp/Cv2/Cv2_ptcloud.cs | 30 +- src/OpenCvSharp/Cv2/Cv2_stereo.cs | 56 +-- src/OpenCvSharp/Cv2/Cv2_video.cs | 40 +-- .../Modules/aruco/ArucoDetector.cs | 2 +- src/OpenCvSharp/Modules/aruco/CharucoBoard.cs | 4 +- .../Modules/aruco/CharucoDetector.cs | 8 +- src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs | 12 +- src/OpenCvSharp/Modules/aruco/Dictionary.cs | 4 +- .../Modules/barcode/BarcodeDetector.cs | 2 +- .../core/{InputArrayRef.cs => InputArray.cs} | 212 ++++++----- src/OpenCvSharp/Modules/core/LDA.cs | 12 +- src/OpenCvSharp/Modules/core/Mat/Mat.cs | 14 +- src/OpenCvSharp/Modules/core/Mat/UMat.cs | 12 +- src/OpenCvSharp/Modules/core/PCA.cs | 16 +- src/OpenCvSharp/Modules/core/RNG.cs | 6 +- src/OpenCvSharp/Modules/core/SVD.cs | 18 +- .../Modules/dnn/ClassificationModel.cs | 2 +- src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs | 2 +- src/OpenCvSharp/Modules/dnn/DetectionModel.cs | 2 +- .../Modules/dnn/Image2BlobParams.cs | 2 +- src/OpenCvSharp/Modules/dnn/KeypointsModel.cs | 2 +- src/OpenCvSharp/Modules/dnn/Model.cs | 2 +- .../Modules/dnn/SegmentationModel.cs | 2 +- .../Modules/dnn/TextDetectionModel.cs | 4 +- .../Modules/dnn/TextRecognitionModel.cs | 2 +- .../Modules/dnn_superres/DnnSuperResImpl.cs | 4 +- .../face/FaceRecognizer/FaceRecognizer.cs | 4 +- .../Modules/face/Facemark/Facemark.cs | 4 +- src/OpenCvSharp/Modules/features/ANNIndex.cs | 4 +- src/OpenCvSharp/Modules/features/Feature2D.cs | 10 +- .../Modules/features/LightGlueMatcher.cs | 2 +- src/OpenCvSharp/Modules/features/MSER.cs | 2 +- src/OpenCvSharp/Modules/flann/Index.cs | 2 +- .../Modules/img_hash/AverageHash.cs | 2 +- .../Modules/img_hash/BlockMeanHash.cs | 2 +- .../Modules/img_hash/ColorMomentHash.cs | 2 +- .../Modules/img_hash/ImgHashBase.cs | 4 +- .../Modules/img_hash/MarrHildrethHash.cs | 2 +- src/OpenCvSharp/Modules/img_hash/PHash.cs | 2 +- .../Modules/img_hash/RadialVarianceHash.cs | 2 +- src/OpenCvSharp/Modules/imgproc/CLAHE.cs | 2 +- .../Modules/imgproc/Enum/PutTextFlags.cs | 2 +- .../Modules/imgproc/Filter2DParams.cs | 2 +- src/OpenCvSharp/Modules/imgproc/FontFace.cs | 2 +- .../Modules/imgproc/GeneralizedHough.cs | 8 +- .../Modules/imgproc/IntelligentScissorsMB.cs | 8 +- .../Modules/imgproc/LineSegmentDetector.cs | 10 +- src/OpenCvSharp/Modules/imgproc/Moments.cs | 4 +- src/OpenCvSharp/Modules/ml/ANN_MLP.cs | 2 +- src/OpenCvSharp/Modules/ml/EM.cs | 34 +- src/OpenCvSharp/Modules/ml/KNearest.cs | 4 +- .../Modules/ml/LogisticRegression.cs | 2 +- .../Modules/ml/NormalBayesClassifier.cs | 4 +- src/OpenCvSharp/Modules/ml/SVM.cs | 2 +- src/OpenCvSharp/Modules/ml/StatModel.cs | 6 +- .../Modules/objdetect/FaceDetectorYN.cs | 4 +- .../Modules/objdetect/QRCodeDetector.cs | 14 +- .../Modules/optflow/Cv2.OptFlow.cs | 26 +- src/OpenCvSharp/Modules/photo/CalibrateCRF.cs | 2 +- .../Modules/photo/MergeExposures.cs | 2 +- src/OpenCvSharp/Modules/photo/MergeMertens.cs | 2 +- src/OpenCvSharp/Modules/photo/Tonemap.cs | 2 +- src/OpenCvSharp/Modules/ptcloud/Odometry.cs | 6 +- .../Modules/ptcloud/OdometryFrame.cs | 16 +- .../Modules/ptcloud/OdometrySettings.cs | 12 +- .../Modules/ptcloud/RgbdNormals.cs | 8 +- src/OpenCvSharp/Modules/ptcloud/Volume.cs | 22 +- .../Modules/ptcloud/VolumeSettings.cs | 18 +- .../Modules/quality/QualityBRISQUE.cs | 4 +- .../Modules/quality/QualityBase.cs | 4 +- .../Modules/quality/QualityGMSD.cs | 4 +- src/OpenCvSharp/Modules/quality/QualityMSE.cs | 4 +- .../Modules/quality/QualityPSNR.cs | 4 +- .../Modules/quality/QualitySSIM.cs | 4 +- .../saliency/MotionSaliencyBinWangApr2014.cs | 2 +- .../Modules/saliency/ObjectnessBING.cs | 2 +- .../saliency/StaticSaliencyFineGrained.cs | 4 +- .../StaticSaliencySpectralResidual.cs | 4 +- src/OpenCvSharp/Modules/shape/Cv2.Shape.cs | 2 +- .../Modules/shape/HistogramCostExtractor.cs | 2 +- .../shape/ShapeContextDistanceExtractor.cs | 4 +- .../Modules/shape/ShapeDistanceExtractor.cs | 2 +- .../Modules/shape/ShapeTransformer.cs | 10 +- .../Modules/stereo/StereoMatcher.cs | 2 +- .../Modules/stitching/Cv2.Detail.cs | 4 +- src/OpenCvSharp/Modules/stitching/Stitcher.cs | 18 +- .../Modules/superres/DenseOpticalFlowExt.cs | 2 +- .../Modules/superres/FrameSource.cs | 2 +- .../Modules/superres/SuperResolution.cs | 4 +- src/OpenCvSharp/Modules/text/Cv2.Text.cs | 2 +- src/OpenCvSharp/Modules/text/TextDetector.cs | 2 +- .../Modules/text/TextDetectorCNN.cs | 2 +- .../Modules/tracking/TrackerCSRT.cs | 2 +- .../Modules/video/BackgroundSubtractor.cs | 4 +- .../Modules/videoio/VideoCapture.cs | 6 +- .../Modules/videoio/VideoWriter.cs | 2 +- .../Modules/wechat_qrcode/WeChatQRCode.cs | 4 +- .../xfeatures2d/BOWImgDescriptorExtractor.cs | 4 +- .../Modules/ximgproc/Cv2.XImgProc.cs | 88 ++--- src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs | 2 +- .../Modules/ximgproc/EdgeDrawing.cs | 12 +- .../EdgeFilter/AdaptiveManifoldFilter.cs | 2 +- .../Modules/ximgproc/EdgeFilter/DTFilter.cs | 4 +- .../EdgeFilter/FastBilateralSolverFilter.cs | 4 +- .../EdgeFilter/FastGlobalSmootherFilter.cs | 4 +- .../ximgproc/EdgeFilter/GuidedFilter.cs | 4 +- .../Modules/ximgproc/FastLineDetector.cs | 8 +- .../Modules/ximgproc/RidgeDetectionFilter.cs | 2 +- .../Segmentation/GraphSegmentation.cs | 2 +- .../SelectiveSearchSegmentation.cs | 4 +- .../SelectiveSearchSegmentationStrategy.cs | 2 +- ...ctiveSearchSegmentationStrategyMultiple.cs | 2 +- .../ximgproc/StructuredEdgeDetection.cs | 8 +- .../ximgproc/Superpixel/SuperpixelLSC.cs | 6 +- .../ximgproc/Superpixel/SuperpixelSEEDS.cs | 6 +- .../ximgproc/Superpixel/SuperpixelSLIC.cs | 6 +- src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs | 14 +- src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs | 2 +- .../Modules/xphoto/LearningBasedWB.cs | 4 +- src/OpenCvSharp/Modules/xphoto/SimpleWB.cs | 2 +- .../Modules/xphoto/WhiteBalancer.cs | 2 +- test/OpenCvSharp.Tests/core/CoreTest.cs | 4 +- ...InputArrayRefTest.cs => InputArrayTest.cs} | 10 +- .../core/SolveEquationTest.cs | 6 +- test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs | 4 +- 135 files changed, 1011 insertions(+), 1025 deletions(-) rename src/OpenCvSharp/Modules/core/{InputArrayRef.cs => InputArray.cs} (65%) rename test/OpenCvSharp.Tests/core/{InputArrayRefTest.cs => InputArrayTest.cs} (93%) diff --git a/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs b/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs index 80ed66070..dfb2c5fcc 100644 --- a/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs +++ b/src/OpenCvSharp/Cv2/Cv2_calib.FishEye.cs @@ -34,8 +34,8 @@ public static class FishEye /// rotation vector, translation vector, and the skew.In the old interface different components of /// the jacobian are returned via different output parameters. public static void ProjectPoints( - InputArrayRef objectPoints, OutputArrayRef imagePoints, InputArrayRef rvec, InputArrayRef tvec, - InputArrayRef k, InputArrayRef d, double alpha = 0, OutputArrayRef jacobian = default) + InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, + InputArray k, InputArray d, double alpha = 0, OutputArray jacobian = default) { NativeMethods.HandleException( NativeMethods.calib_fisheye_projectPoints2( @@ -64,7 +64,7 @@ public static void ProjectPoints( /// Input vector of distortion coefficients /// The skew coefficient. public static void DistortPoints( - InputArrayRef undistorted, OutputArrayRef distorted, InputArrayRef k, InputArrayRef d, double alpha = 0) + InputArray undistorted, OutputArray distorted, InputArray k, InputArray d, double alpha = 0) { NativeMethods.HandleException( NativeMethods.calib_fisheye_distortPoints( @@ -89,7 +89,7 @@ public static void DistortPoints( /// Input vector of distortion coefficients. /// The skew coefficient. public static void DistortPoints( - InputArrayRef undistorted, OutputArrayRef distorted, InputArrayRef kundistorted, InputArrayRef k, InputArrayRef d, double alpha = 0) + InputArray undistorted, OutputArray distorted, InputArray kundistorted, InputArray k, InputArray d, double alpha = 0) { NativeMethods.HandleException( NativeMethods.calib_fisheye_distortPoints2( @@ -114,8 +114,8 @@ public static void DistortPoints( /// New camera matrix (3x3) or new projection matrix (3x4) // ReSharper disable once MemberHidesStaticFromOuterClass public static void UndistortPoints( - InputArrayRef distorted, OutputArrayRef undistorted, - InputArrayRef k, InputArrayRef d, InputArrayRef r = default, InputArrayRef p = default) + InputArray distorted, OutputArray undistorted, + InputArray k, InputArray d, InputArray r = default, InputArray p = default) { NativeMethods.HandleException( NativeMethods.calib_fisheye_undistortPoints( @@ -142,8 +142,8 @@ public static void UndistortPoints( /// The first output map. /// The second output map. public static void InitUndistortRectifyMap( - InputArrayRef k, InputArrayRef d, InputArrayRef r, InputArrayRef p, - Size size, int m1type, OutputArrayRef map1, OutputArrayRef map2) + InputArray k, InputArray d, InputArray r, InputArray p, + Size size, int m1type, OutputArray map1, OutputArray map2) { NativeMethods.HandleException( NativeMethods.calib_fisheye_initUndistortRectifyMap( @@ -168,8 +168,8 @@ public static void InitUndistortRectifyMap( /// may additionally scale and shift the result by using a different matrix. /// public static void UndistortImage( - InputArrayRef distorted, OutputArrayRef undistorted, - InputArrayRef k, InputArrayRef d, InputArrayRef knew = default, Size newSize = default) + InputArray distorted, OutputArray undistorted, + InputArray k, InputArray d, InputArray knew = default, Size newSize = default) { NativeMethods.HandleException( NativeMethods.calib_fisheye_undistortImage( @@ -196,8 +196,8 @@ public static void UndistortImage( /// /// Divisor for new focal length. public static void EstimateNewCameraMatrixForUndistortRectify( - InputArrayRef k, InputArrayRef d, Size imageSize, InputArrayRef r, - OutputArrayRef p, double balance = 0.0, Size newSize = default, double fovScale = 1.0) + InputArray k, InputArray d, Size imageSize, InputArray r, + OutputArray p, double balance = 0.0, Size newSize = default, double fovScale = 1.0) { NativeMethods.HandleException( NativeMethods.calib_fisheye_estimateNewCameraMatrixForUndistortRectify( @@ -230,7 +230,7 @@ public static void EstimateNewCameraMatrixForUndistortRectify( /// public static double Calibrate( IEnumerable objectPoints, IEnumerable imagePoints, - Size imageSize, InputOutputArrayRef k, InputOutputArrayRef d, + Size imageSize, InputOutputArray k, InputOutputArray d, out IEnumerable rvecs, out IEnumerable tvecs, FishEyeCalibrationFlags flags = 0, TermCriteria? criteria = null) { @@ -290,9 +290,9 @@ public static double Calibrate( /// length.Balance is in range of[0, 1]. /// Divisor for new focal length. public static void StereoRectify( - InputArrayRef k1, InputArrayRef d1, InputArrayRef k2, InputArrayRef d2, - Size imageSize, InputArrayRef r, InputArrayRef tvec, OutputArrayRef r1, OutputArrayRef r2, - OutputArrayRef p1, OutputArrayRef p2, OutputArrayRef q, FishEyeCalibrationFlags flags, Size newImageSize = default, + InputArray k1, InputArray d1, InputArray k2, InputArray d2, + Size imageSize, InputArray r, InputArray tvec, OutputArray r1, OutputArray r2, + OutputArray p1, OutputArray p2, OutputArray q, FishEyeCalibrationFlags flags, Size newImageSize = default, double balance = 0.0, double fovScale = 1.0) { NativeMethods.HandleException( @@ -335,8 +335,8 @@ public static void StereoRectify( /// public static double StereoCalibrate( IEnumerable objectPoints, IEnumerable imagePoints1, IEnumerable imagePoints2, - InputOutputArrayRef k1, InputOutputArrayRef d1, InputOutputArrayRef k2, InputOutputArrayRef d2, Size imageSize, - OutputArrayRef r, OutputArrayRef t, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.FixIntrinsic, + InputOutputArray k1, InputOutputArray d1, InputOutputArray k2, InputOutputArray d2, Size imageSize, + OutputArray r, OutputArray t, FishEyeCalibrationFlags flags = FishEyeCalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { if (objectPoints is null) diff --git a/src/OpenCvSharp/Cv2/Cv2_calib.cs b/src/OpenCvSharp/Cv2/Cv2_calib.cs index eca927022..c128f4568 100644 --- a/src/OpenCvSharp/Cv2/Cv2_calib.cs +++ b/src/OpenCvSharp/Cv2/Cv2_calib.cs @@ -84,9 +84,9 @@ public static Mat InitCameraMatrix2D( /// The function returns true if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). /// Otherwise, if the function fails to find all the corners or reorder them, it returns false. public static bool FindChessboardCorners( - InputArrayRef image, + InputArray image, Size patternSize, - OutputArrayRef corners, + OutputArray corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) { NativeMethods.HandleException( @@ -106,7 +106,7 @@ public static bool FindChessboardCorners( /// The function returns true if all of the corners are found and they are placed in a certain order (row by row, left to right in every row). /// Otherwise, if the function fails to find all the corners or reorder them, it returns false. public static bool FindChessboardCorners( - InputArrayRef image, + InputArray image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) @@ -130,9 +130,9 @@ public static bool FindChessboardCorners( /// feature detector that finds blobs like dark circles on light background. /// public static bool FindCirclesGrid( - InputArrayRef image, + InputArray image, Size patternSize, - OutputArrayRef centers, + OutputArray centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, FeatureDetector? blobDetector = null) { @@ -155,7 +155,7 @@ public static bool FindCirclesGrid( /// feature detector that finds blobs like dark circles on light background. /// public static bool FindCirclesGrid( - InputArrayRef image, + InputArray image, Size patternSize, out Point2f[] centers, FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, @@ -199,8 +199,8 @@ public static double CalibrateCamera( IEnumerable objectPoints, IEnumerable imagePoints, Size imageSize, - InputOutputArrayRef cameraMatrix, - InputOutputArrayRef distCoeffs, + InputOutputArray cameraMatrix, + InputOutputArray distCoeffs, out Mat[] rvecs, out Mat[] tvecs, CalibrationFlags flags = CalibrationFlags.None, @@ -330,10 +330,10 @@ public static double CalibrateCamera( public static double RegisterCameras( IEnumerable objectPoints1, IEnumerable objectPoints2, IEnumerable imagePoints1, IEnumerable imagePoints2, - InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, CameraModel cameraModel1, - InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, CameraModel cameraModel2, - InputOutputArrayRef r, InputOutputArrayRef t, OutputArrayRef e, OutputArrayRef f, - OutputArrayRef perViewErrors, int flags = 0, TermCriteria? criteria = null) + InputArray cameraMatrix1, InputArray distCoeffs1, CameraModel cameraModel1, + InputArray cameraMatrix2, InputArray distCoeffs2, CameraModel cameraModel2, + InputOutputArray r, InputOutputArray t, OutputArray e, OutputArray f, + OutputArray perViewErrors, int flags = 0, TermCriteria? criteria = null) { if (objectPoints1 is null) throw new ArgumentNullException(nameof(objectPoints1)); @@ -397,10 +397,10 @@ public static double CalibrateMultiview( IEnumerable objPoints, IReadOnlyList> imagePoints, IEnumerable imageSize, - InputArrayRef detectionMask, - InputArrayRef models, + InputArray detectionMask, + InputArray models, out Mat[] ks, out Mat[] distortions, out Mat[] rs, out Mat[] ts, - InputArrayRef flagsForIntrinsics = default, + InputArray flagsForIntrinsics = default, int flags = 0, TermCriteria? criteria = null) { @@ -478,10 +478,10 @@ public static double StereoCalibrate( IReadOnlyList objectPoints, IReadOnlyList imagePoints1, IReadOnlyList imagePoints2, - InputOutputArrayRef cameraMatrix1, InputOutputArrayRef distCoeffs1, - InputOutputArrayRef cameraMatrix2, InputOutputArrayRef distCoeffs2, - Size imageSize, OutputArrayRef R, - OutputArrayRef T, OutputArrayRef E, OutputArrayRef F, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, OutputArray R, + OutputArray T, OutputArray E, OutputArray F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { @@ -548,8 +548,8 @@ public static double StereoCalibrate( IEnumerable> imagePoints2, double[,] cameraMatrix1, double[] distCoeffs1, double[,] cameraMatrix2, double[] distCoeffs2, - Size imageSize, OutputArrayRef R, - OutputArrayRef T, OutputArrayRef E, OutputArrayRef F, + Size imageSize, OutputArray R, + OutputArray T, OutputArray E, OutputArray F, CalibrationFlags flags = CalibrationFlags.FixIntrinsic, TermCriteria? criteria = null) { @@ -637,8 +637,8 @@ public static void CalibrateHandEye( IEnumerable t_gripper2base, IEnumerable R_target2cam, IEnumerable t_target2cam, - OutputArrayRef R_cam2gripper, - OutputArrayRef t_cam2gripper, + OutputArray R_cam2gripper, + OutputArray t_cam2gripper, HandEyeCalibrationMethod method = HandEyeCalibrationMethod.TSAI) { if (R_gripper2base is null) @@ -719,10 +719,10 @@ public static void CalibrateRobotWorldHandEye( IEnumerable t_world2cam, IEnumerable R_base2gripper, IEnumerable t_base2gripper, - OutputArrayRef R_base2world, - OutputArrayRef t_base2world, - OutputArrayRef R_gripper2cam, - OutputArrayRef t_gripper2cam, + OutputArray R_base2world, + OutputArray t_base2world, + OutputArray R_gripper2cam, + OutputArray t_gripper2cam, RobotWorldHandEyeCalibrationMethod method = RobotWorldHandEyeCalibrationMethod.SHAH) { if (R_world2cam is null) diff --git a/src/OpenCvSharp/Cv2/Cv2_core.cs b/src/OpenCvSharp/Cv2/Cv2_core.cs index 86e8b419e..deba9cd85 100644 --- a/src/OpenCvSharp/Cv2/Cv2_core.cs +++ b/src/OpenCvSharp/Cv2/Cv2_core.cs @@ -43,7 +43,7 @@ public static int BorderInterpolate(int p, int len, BorderTypes borderType) /// Specify how much pixels in each direction from the source image rectangle one needs to extrapolate /// The border type /// The border value if borderType == Constant - public static void CopyMakeBorder(InputArrayRef src, OutputArrayRef dst, int top, int bottom, int left, int right, + public static void CopyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, BorderTypes borderType, Scalar? value = null) { var value0 = value.GetValueOrDefault(new Scalar()); @@ -63,7 +63,7 @@ public static void CopyMakeBorder(InputArrayRef src, OutputArrayRef dst, int top /// The destination array; it will have the same size and same type as src1 /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Add(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, + public static void Add(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = default, int dtype = -1) { NativeMethods.HandleException( @@ -85,7 +85,7 @@ public static void Add(InputArrayRef src1, InputArrayRef src2, OutputArrayRef ds /// The destination array; it will have the same size and same type as src1 /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, + public static void Subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = default, int dtype = -1) { NativeMethods.HandleException( @@ -107,7 +107,7 @@ public static void Subtract(InputArrayRef src1, InputArrayRef src2, OutputArrayR /// The destination array; it will have the same size and same type as src1 /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(InputArrayRef src1, Scalar src2, OutputArrayRef dst, InputArrayRef mask = default, + public static void Subtract(InputArray src1, Scalar src2, OutputArray dst, InputArray mask = default, int dtype = -1) { NativeMethods.HandleException( @@ -128,7 +128,7 @@ public static void Subtract(InputArrayRef src1, Scalar src2, OutputArrayRef dst, /// The destination array; it will have the same size and same type as src1 /// The optional operation mask, 8-bit single channel array; specifies elements of the destination array to be changed. [By default this is skipped] /// - public static void Subtract(Scalar src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default, + public static void Subtract(Scalar src1, InputArray src2, OutputArray dst, InputArray mask = default, int dtype = -1) { NativeMethods.HandleException( @@ -149,7 +149,7 @@ public static void Subtract(Scalar src1, InputArrayRef src2, OutputArrayRef dst, /// The destination array; will have the same size and the same type as src1 /// The optional scale factor. [By default this is 1] /// - public static void Multiply(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, double scale = 1, int dtype = -1) + public static void Multiply(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1) { NativeMethods.HandleException( NativeMethods.core_multiply( @@ -168,7 +168,7 @@ public static void Multiply(InputArrayRef src1, InputArrayRef src2, OutputArrayR /// The destination array; will have the same size and same type as src2 /// Scale factor [By default this is 1] /// - public static void Divide(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, double scale = 1, MatType? dtype = null) + public static void Divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, MatType? dtype = null) { NativeMethods.HandleException( NativeMethods.core_divide2( @@ -186,7 +186,7 @@ public static void Divide(InputArrayRef src1, InputArrayRef src2, OutputArrayRef /// The first source array /// The destination array; will have the same size and same type as src2 /// - public static void Divide(double scale, InputArrayRef src2, OutputArrayRef dst, int dtype = -1) + public static void Divide(double scale, InputArray src2, OutputArray dst, int dtype = -1) { NativeMethods.HandleException( NativeMethods.core_divide1(scale, src2.Proxy, dst.Proxy, dtype)); @@ -202,7 +202,7 @@ public static void Divide(double scale, InputArrayRef src2, OutputArrayRef dst, /// /// /// - public static void ScaleAdd(InputArrayRef src1, double alpha, InputArrayRef src2, OutputArrayRef dst) + public static void ScaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_scaleAdd(src1.Proxy, alpha, src2.Proxy, dst.Proxy)); @@ -222,8 +222,8 @@ public static void ScaleAdd(InputArrayRef src1, double alpha, InputArrayRef src2 /// /// /// - public static void AddWeighted(InputArrayRef src1, double alpha, InputArrayRef src2, - double beta, double gamma, OutputArrayRef dst, int dtype = -1) + public static void AddWeighted(InputArray src1, double alpha, InputArray src2, + double beta, double gamma, OutputArray dst, int dtype = -1) { NativeMethods.HandleException( NativeMethods.core_addWeighted( @@ -241,7 +241,7 @@ public static void AddWeighted(InputArrayRef src1, double alpha, InputArrayRef s /// The destination array /// The optional scale factor. [By default this is 1] /// The optional delta added to the scaled values. [By default this is 0] - public static void ConvertScaleAbs(InputArrayRef src, OutputArrayRef dst, double alpha = 1, double beta = 0) + public static void ConvertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0) { NativeMethods.HandleException( NativeMethods.core_convertScaleAbs(src.Proxy, dst.Proxy, alpha, beta)); @@ -261,7 +261,7 @@ public static void ConvertScaleAbs(InputArrayRef src, OutputArrayRef dst, double /// Destination array; /// will have the same size and the same number of channels as src, /// and the same depth as lut - public static void LUT(InputArrayRef src, InputArrayRef lut, OutputArrayRef dst) + public static void LUT(InputArray src, InputArray lut, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_LUT(src.Proxy, lut.Proxy, dst.Proxy)); @@ -282,7 +282,7 @@ public static void LUT(InputArrayRef src, InputArrayRef lut, OutputArrayRef dst) /// Destination array; /// will have the same size and the same number of channels as src, /// and the same depth as lut - public static void LUT(InputArrayRef src, byte[] lut, OutputArrayRef dst) + public static void LUT(InputArray src, byte[] lut, OutputArray dst) { if (lut is null) throw new ArgumentNullException(nameof(lut)); @@ -298,7 +298,7 @@ public static void LUT(InputArrayRef src, byte[] lut, OutputArrayRef dst) /// /// The source array; must have 1 to 4 channels /// - public static Scalar Sum(InputArrayRef src) + public static Scalar Sum(InputArray src) { NativeMethods.HandleException( NativeMethods.core_sum(src.Proxy, out var ret)); @@ -312,7 +312,7 @@ public static Scalar Sum(InputArrayRef src) /// /// Single-channel array /// number of non-zero elements in mtx - public static int CountNonZero(InputArrayRef mtx) + public static int CountNonZero(InputArray mtx) { NativeMethods.HandleException( NativeMethods.core_countNonZero(mtx.Proxy, out var ret)); @@ -326,7 +326,7 @@ public static int CountNonZero(InputArrayRef mtx) /// /// /// - public static void FindNonZero(InputArrayRef src, OutputArrayRef idx) + public static void FindNonZero(InputArray src, OutputArray idx) { NativeMethods.HandleException( NativeMethods.core_findNonZero(src.Proxy, idx.Proxy)); @@ -342,7 +342,7 @@ public static void FindNonZero(InputArrayRef src, OutputArrayRef idx) /// (so that the result can be stored in Scalar) /// The optional operation mask /// - public static Scalar Mean(InputArrayRef src, InputArrayRef mask = default) + public static Scalar Mean(InputArray src, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_mean(src.Proxy, mask.Proxy, out var ret)); @@ -361,7 +361,7 @@ public static Scalar Mean(InputArrayRef src, InputArrayRef mask = default) /// The output parameter: computed standard deviation /// The optional operation mask public static void MeanStdDev( - InputArrayRef src, OutputArrayRef mean, OutputArrayRef stddev, InputArrayRef mask = default) + InputArray src, OutputArray mean, OutputArray stddev, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_meanStdDev_OutputArray( @@ -382,7 +382,7 @@ public static void MeanStdDev( /// The output parameter: computed standard deviation /// The optional operation mask public static void MeanStdDev( - InputArrayRef src, out Scalar mean, out Scalar stddev, InputArrayRef mask = default) + InputArray src, out Scalar mean, out Scalar stddev, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_meanStdDev_Scalar( @@ -399,8 +399,8 @@ public static void MeanStdDev( /// Type of the norm /// The optional operation mask /// - public static double Norm(InputArrayRef src1, - NormTypes normType = NormTypes.L2, InputArrayRef mask = default) + public static double Norm(InputArray src1, + NormTypes normType = NormTypes.L2, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_norm1(src1.Proxy, (int)normType, mask.Proxy, out var ret)); @@ -418,8 +418,8 @@ public static double Norm(InputArrayRef src1, /// Type of the norm /// The optional operation mask /// - public static double Norm(InputArrayRef src1, InputArrayRef src2, - NormTypes normType = NormTypes.L2, InputArrayRef mask = default) + public static double Norm(InputArray src1, InputArray src2, + NormTypes normType = NormTypes.L2, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_norm2(src1.Proxy, src2.Proxy, (int)normType, mask.Proxy, out var ret)); @@ -441,7 +441,7 @@ public static double Norm(InputArrayRef src1, InputArrayRef src2, /// the maximum pixel value (255 by default) /// // ReSharper disable once InconsistentNaming - public static double PSNR(InputArrayRef src1, InputArrayRef src2, double r = 255.0) + public static double PSNR(InputArray src1, InputArray src2, double r = 255.0) { NativeMethods.HandleException( NativeMethods.core_PSNR(src1.Proxy, src2.Proxy, r, out var ret)); @@ -464,11 +464,11 @@ public static double PSNR(InputArrayRef src1, InputArrayRef src2, double r = 255 /// /// /// - public static void BatchDistance(InputArrayRef src1, InputArrayRef src2, + public static void BatchDistance(InputArray src1, InputArray src2, // ReSharper disable once IdentifierTypo - OutputArrayRef dist, int dtype, OutputArrayRef nidx, + OutputArray dist, int dtype, OutputArray nidx, NormTypes normType = NormTypes.L2, - int k = 0, InputArrayRef mask = default, + int k = 0, InputArray mask = default, int update = 0, bool crosscheck = false) { NativeMethods.HandleException( @@ -498,8 +498,8 @@ public static void BatchDistance(InputArrayRef src1, InputArrayRef src2, /// the destination array will have the same type as src, /// otherwise it will have the same number of channels as src and the depth =CV_MAT_DEPTH(rtype) /// The optional operation mask - public static void Normalize(InputArrayRef src, InputOutputArrayRef dst, double alpha = 1, double beta = 0, - NormTypes normType = NormTypes.L2, int dtype = -1, InputArrayRef mask = default) + public static void Normalize(InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, + NormTypes normType = NormTypes.L2, int dtype = -1, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_normalize( @@ -518,7 +518,7 @@ public static void Normalize(InputArrayRef src, InputOutputArrayRef dst, double /// except for axis being reduced - it should be set to 1. /// Axis to reduce along /// Whether to get the index of first or last occurrence of max - public static void ReduceArgMax(InputArrayRef src, OutputArrayRef dst, int axis, bool lastIndex = false) + public static void ReduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false) { NativeMethods.HandleException( NativeMethods.core_reduceArgMax(src.Proxy, dst.Proxy, axis, lastIndex)); @@ -535,7 +535,7 @@ public static void ReduceArgMax(InputArrayRef src, OutputArrayRef dst, int axis, /// except for axis being reduced - it should be set to 1. /// Axis to reduce along /// Whether to get the index of first or last occurrence of min - public static void ReduceArgMin(InputArrayRef src, OutputArrayRef dst, int axis, bool lastIndex = false) + public static void ReduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false) { NativeMethods.HandleException( NativeMethods.core_reduceArgMin(src.Proxy, dst.Proxy, axis, lastIndex)); @@ -550,7 +550,7 @@ public static void ReduceArgMin(InputArrayRef src, OutputArrayRef dst, int axis, /// The source single-channel array /// Pointer to returned minimum value /// Pointer to returned maximum value - public static void MinMaxLoc(InputArrayRef src, out double minVal, out double maxVal) + public static void MinMaxLoc(InputArray src, out double minVal, out double maxVal) { NativeMethods.HandleException( NativeMethods.core_minMaxLoc1(src.Proxy, out minVal, out maxVal)); @@ -564,7 +564,7 @@ public static void MinMaxLoc(InputArrayRef src, out double minVal, out double ma /// The source single-channel array /// Pointer to returned minimum location /// Pointer to returned maximum location - public static void MinMaxLoc(InputArrayRef src, out Point minLoc, out Point maxLoc) + public static void MinMaxLoc(InputArray src, out Point minLoc, out Point maxLoc) { MinMaxLoc(src, out _, out _, out minLoc, out maxLoc); } @@ -578,8 +578,8 @@ public static void MinMaxLoc(InputArrayRef src, out Point minLoc, out Point maxL /// Pointer to returned minimum location /// Pointer to returned maximum location /// The optional mask used to select a sub-array - public static void MinMaxLoc(InputArrayRef src, out double minVal, out double maxVal, - out Point minLoc, out Point maxLoc, InputArrayRef mask = default) + public static void MinMaxLoc(InputArray src, out double minVal, out double maxVal, + out Point minLoc, out Point maxLoc, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_minMaxLoc2( @@ -595,7 +595,7 @@ public static void MinMaxLoc(InputArrayRef src, out double minVal, out double ma /// The source single-channel array /// Pointer to returned minimum value /// Pointer to returned maximum value - public static void MinMaxIdx(InputArrayRef src, out double minVal, out double maxVal) + public static void MinMaxIdx(InputArray src, out double minVal, out double maxVal) { NativeMethods.HandleException( NativeMethods.core_minMaxIdx1(src.Proxy, out minVal, out maxVal)); @@ -609,7 +609,7 @@ public static void MinMaxIdx(InputArrayRef src, out double minVal, out double ma /// The source single-channel array /// /// - public static void MinMaxIdx(InputArrayRef src, int[] minIdx, int[] maxIdx) + public static void MinMaxIdx(InputArray src, int[] minIdx, int[] maxIdx) { MinMaxIdx(src, out _, out _, minIdx, maxIdx); } @@ -623,8 +623,8 @@ public static void MinMaxIdx(InputArrayRef src, int[] minIdx, int[] maxIdx) /// /// /// - public static void MinMaxIdx(InputArrayRef src, out double minVal, out double maxVal, - int[] minIdx, int[] maxIdx, InputArrayRef mask = default) + public static void MinMaxIdx(InputArray src, out double minVal, out double maxVal, + int[] minIdx, int[] maxIdx, InputArray mask = default) { if (minIdx is null) throw new ArgumentNullException(nameof(minIdx)); @@ -650,7 +650,7 @@ public static void MinMaxIdx(InputArrayRef src, out double minVal, out double ma /// /// When it is negative, the destination vector will have /// the same type as the source matrix, otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), mtx.channels()) - public static void Reduce(InputArrayRef src, OutputArrayRef dst, ReduceDimension dim, ReduceTypes rtype, int dtype) + public static void Reduce(InputArray src, OutputArray dst, ReduceDimension dim, ReduceTypes rtype, int dtype) { NativeMethods.HandleException( NativeMethods.core_reduce(src.Proxy, dst.Proxy, (int)dim, (int)rtype, dtype)); @@ -771,7 +771,7 @@ public static void MixChannels(ReadOnlySpan src, ReadOnlySpan dst, int /// /// /// - public static void ExtractChannel(InputArrayRef src, OutputArrayRef dst, int coi) + public static void ExtractChannel(InputArray src, OutputArray dst, int coi) { NativeMethods.HandleException( NativeMethods.core_extractChannel(src.Proxy, dst.Proxy, coi)); @@ -786,7 +786,7 @@ public static void ExtractChannel(InputArrayRef src, OutputArrayRef dst, int coi /// /// /// - public static void InsertChannel(InputArrayRef src, InputOutputArrayRef dst, int coi) + public static void InsertChannel(InputArray src, InputOutputArray dst, int coi) { NativeMethods.HandleException( NativeMethods.core_insertChannel(src.Proxy, dst.Proxy, coi)); @@ -803,7 +803,7 @@ public static void InsertChannel(InputArrayRef src, InputOutputArrayRef dst, int /// Specifies how to flip the array: /// 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, /// and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas. - public static void Flip(InputArrayRef src, OutputArrayRef dst, FlipMode flipCode) + public static void Flip(InputArray src, OutputArray dst, FlipMode flipCode) { NativeMethods.HandleException( NativeMethods.core_flip(src.Proxy, dst.Proxy, (int) flipCode)); @@ -820,7 +820,7 @@ public static void Flip(InputArrayRef src, OutputArrayRef dst, FlipMode flipCode /// The size is the same with ROTATE_180, and the rows and cols are switched for /// ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE. /// an enum to specify how to rotate the array. - public static void Rotate(InputArrayRef src, OutputArrayRef dst, RotateFlags rotateCode) + public static void Rotate(InputArray src, OutputArray dst, RotateFlags rotateCode) { NativeMethods.HandleException( NativeMethods.core_rotate(src.Proxy, dst.Proxy, (int)rotateCode)); @@ -836,7 +836,7 @@ public static void Rotate(InputArrayRef src, OutputArrayRef dst, RotateFlags rot /// How many times the src is repeated along the vertical axis /// How many times the src is repeated along the horizontal axis /// The destination array; will have the same type as src - public static void Repeat(InputArrayRef src, int ny, int nx, OutputArrayRef dst) + public static void Repeat(InputArray src, int ny, int nx, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_repeat1(src.Proxy, ny, nx, dst.Proxy)); @@ -870,7 +870,7 @@ public static Mat Repeat(Mat src, int ny, int nx) /// /// input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. /// output array. It has the same number of rows and depth as the src, and the sum of cols of the src. - public static void HConcat(ReadOnlySpan src, OutputArrayRef dst) + public static void HConcat(ReadOnlySpan src, OutputArray dst) { if (src.Length == 0) throw new ArgumentException("src is empty", nameof(src)); @@ -898,7 +898,7 @@ public static void HConcat(ReadOnlySpan src, OutputArrayRef dst) /// first input array to be considered for horizontal concatenation. /// second input array to be considered for horizontal concatenation. /// output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. - public static void HConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void HConcat(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_hconcat2(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -913,7 +913,7 @@ public static void HConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRe /// /// input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. /// output array. It has the same number of cols and depth as the src, and the sum of rows of the src. - public static void VConcat(ReadOnlySpan src, OutputArrayRef dst) + public static void VConcat(ReadOnlySpan src, OutputArray dst) { if (src.Length == 0) throw new ArgumentException("src.Count == 0", nameof(src)); @@ -941,7 +941,7 @@ public static void VConcat(ReadOnlySpan src, OutputArrayRef dst) /// first input array to be considered for vertical concatenation. /// second input array to be considered for vertical concatenation. /// output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. - public static void VConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void VConcat(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_vconcat2(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -958,7 +958,7 @@ public static void VConcat(InputArrayRef src1, InputArrayRef src2, OutputArrayRe /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseAnd(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) + public static void BitwiseAnd(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_bitwise_and(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); @@ -976,7 +976,7 @@ public static void BitwiseAnd(InputArrayRef src1, InputArrayRef src2, OutputArra /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseOr(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) + public static void BitwiseOr(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_bitwise_or(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); @@ -994,7 +994,7 @@ public static void BitwiseOr(InputArrayRef src1, InputArrayRef src2, OutputArray /// second input array or a scalar. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseXor(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, InputArrayRef mask = default) + public static void BitwiseXor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_bitwise_xor(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); @@ -1011,7 +1011,7 @@ public static void BitwiseXor(InputArrayRef src1, InputArrayRef src2, OutputArra /// input array. /// output array that has the same size and type as the input /// optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. - public static void BitwiseNot(InputArrayRef src, OutputArrayRef dst, InputArrayRef mask = default) + public static void BitwiseNot(InputArray src, OutputArray dst, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_bitwise_not(src.Proxy, dst.Proxy, mask.Proxy)); @@ -1027,7 +1027,7 @@ public static void BitwiseNot(InputArrayRef src, OutputArrayRef dst, InputArrayR /// first input array or a scalar. /// second input array or a scalar. /// output array that has the same size and type as input arrays. - public static void Absdiff(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void Absdiff(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_absdiff(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -1045,7 +1045,7 @@ public static void Absdiff(InputArrayRef src1, InputArrayRef src2, OutputArrayRe /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask of the same size as \*this. Its non-zero elements indicate which matrix /// elements need to be copied.The mask has to be of type CV_8U and can have 1 or multiple channels. - public static void CopyTo(InputArrayRef src, OutputArrayRef dst, InputArrayRef mask = default) + public static void CopyTo(InputArray src, OutputArray dst, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.core_copyTo(src.Proxy, dst.Proxy, mask.Proxy)); @@ -1062,7 +1062,7 @@ public static void CopyTo(InputArrayRef src, OutputArrayRef dst, InputArrayRef m /// inclusive lower boundary array or a scalar. /// inclusive upper boundary array or a scalar. /// output array of the same size as src and CV_8U type. - public static void InRange(InputArrayRef src, InputArrayRef lowerb, InputArrayRef upperb, OutputArrayRef dst) + public static void InRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_inRange_InputArray(src.Proxy, lowerb.Proxy, upperb.Proxy, dst.Proxy)); @@ -1080,7 +1080,7 @@ public static void InRange(InputArrayRef src, InputArrayRef lowerb, InputArrayRe /// inclusive lower boundary array or a scalar. /// inclusive upper boundary array or a scalar. /// output array of the same size as src and CV_8U type. - public static void InRange(InputArrayRef src, Scalar lowerb, Scalar upperb, OutputArrayRef dst) + public static void InRange(InputArray src, Scalar lowerb, Scalar upperb, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_inRange_Scalar(src.Proxy, lowerb, upperb, dst.Proxy)); @@ -1097,7 +1097,7 @@ public static void InRange(InputArrayRef src, Scalar lowerb, Scalar upperb, Outp /// output array of type ref CV_8U that has the same size and the same number of channels as the input arrays. /// a flag, that specifies correspondence between the arrays (cv::CmpTypes) // ReSharper disable once IdentifierTypo - public static void Compare(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, CmpTypes cmpop) + public static void Compare(InputArray src1, InputArray src2, OutputArray dst, CmpTypes cmpop) { NativeMethods.HandleException( NativeMethods.core_compare(src1.Proxy, src2.Proxy, dst.Proxy, (int) cmpop)); @@ -1113,7 +1113,7 @@ public static void Compare(InputArrayRef src1, InputArrayRef src2, OutputArrayRe /// /// /// - public static void Min(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void Min(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_min1(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -1177,7 +1177,7 @@ public static void Min(Mat src1, double src2, Mat dst) /// /// /// - public static void Max(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void Max(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_max1(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -1240,7 +1240,7 @@ public static void Max(Mat src1, double src2, Mat dst) /// /// The source floating-point array /// The destination array; will have the same size and the same type as src - public static void Sqrt(InputArrayRef src, OutputArrayRef dst) + public static void Sqrt(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_sqrt(src.Proxy, dst.Proxy)); @@ -1255,7 +1255,7 @@ public static void Sqrt(InputArrayRef src, OutputArrayRef dst) /// The source array /// The exponent of power /// The destination array; will have the same size and the same type as src - public static void Pow(InputArrayRef src, double power, OutputArrayRef dst) + public static void Pow(InputArray src, double power, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_pow_Mat(src.Proxy, power, dst.Proxy)); @@ -1269,7 +1269,7 @@ public static void Pow(InputArrayRef src, double power, OutputArrayRef dst) /// /// The source array /// The destination array; will have the same size and same type as src - public static void Exp(InputArrayRef src, OutputArrayRef dst) + public static void Exp(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_exp_Mat(src.Proxy, dst.Proxy)); @@ -1283,7 +1283,7 @@ public static void Exp(InputArrayRef src, OutputArrayRef dst) /// /// The source array /// The destination array; will have the same size and same type as src - public static void Log(InputArrayRef src, OutputArrayRef dst) + public static void Log(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_log_Mat(src.Proxy, dst.Proxy)); @@ -1302,8 +1302,8 @@ public static void Log(InputArrayRef src, OutputArrayRef dst) /// output array of x-coordinates of 2D vectors; it has the same size and type as angle. /// output array of y-coordinates of 2D vectors; it has the same size and type as angle. /// when true, the input angles are measured in degrees, otherwise, they are measured in radians. - public static void PolarToCart(InputArrayRef magnitude, InputArrayRef angle, - OutputArrayRef x, OutputArrayRef y, bool angleInDegrees = false) + public static void PolarToCart(InputArray magnitude, InputArray angle, + OutputArray x, OutputArray y, bool angleInDegrees = false) { NativeMethods.HandleException( NativeMethods.core_polarToCart(magnitude.Proxy, angle.Proxy, x.Proxy, y.Proxy, angleInDegrees ? 1 : 0)); @@ -1323,8 +1323,8 @@ public static void PolarToCart(InputArrayRef magnitude, InputArrayRef angle, /// output array of angles that has the same size and type as x; /// the angles are measured in radians(from 0 to 2\*Pi) or in degrees(0 to 360 degrees). /// a flag, indicating whether the angles are measured in radians(which is by default), or in degrees. - public static void CartToPolar(InputArrayRef x, InputArrayRef y, - OutputArrayRef magnitude, OutputArrayRef angle, bool angleInDegrees = false) + public static void CartToPolar(InputArray x, InputArray y, + OutputArray magnitude, OutputArray angle, bool angleInDegrees = false) { NativeMethods.HandleException( NativeMethods.core_cartToPolar(x.Proxy, y.Proxy, magnitude.Proxy, angle.Proxy, angleInDegrees ? 1 : 0)); @@ -1342,7 +1342,7 @@ public static void CartToPolar(InputArrayRef x, InputArrayRef y, /// input array of y-coordinates of 2D vectors; it must have the same size and the same type as x. /// output array of vector angles; it has the same size and same type as x. /// when true, the function calculates the angle in degrees, otherwise, they are measured in radians. - public static void Phase(InputArrayRef x, InputArrayRef y, OutputArrayRef angle, bool angleInDegrees = false) + public static void Phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false) { NativeMethods.HandleException( NativeMethods.core_phase(x.Proxy, y.Proxy, angle.Proxy, angleInDegrees ? 1 : 0)); @@ -1358,7 +1358,7 @@ public static void Phase(InputArrayRef x, InputArrayRef y, OutputArrayRef angle, /// floating-point array of x-coordinates of the vectors. /// floating-point array of y-coordinates of the vectors; it must have the same size as x. /// output array of the same size and type as x. - public static void Magnitude(InputArrayRef x, InputArrayRef y, OutputArrayRef magnitude) + public static void Magnitude(InputArray x, InputArray y, OutputArray magnitude) { NativeMethods.HandleException( NativeMethods.core_magnitude_Mat(x.Proxy, y.Proxy, magnitude.Proxy)); @@ -1376,7 +1376,7 @@ public static void Magnitude(InputArrayRef x, InputArrayRef y, OutputArrayRef ma /// return false when the array elements are out of range, /// or they throw an exception. /// - public static bool CheckRange(InputArrayRef src, bool quiet = true) + public static bool CheckRange(InputArray src, bool quiet = true) { return CheckRange(src, quiet, out _); } @@ -1393,7 +1393,7 @@ public static bool CheckRange(InputArrayRef src, bool quiet = true) /// The inclusive lower boundary of valid values range /// The exclusive upper boundary of valid values range /// - public static bool CheckRange(InputArrayRef src, bool quiet, out Point pos, + public static bool CheckRange(InputArray src, bool quiet, out Point pos, double minVal = double.MinValue, double maxVal = double.MaxValue) { NativeMethods.HandleException( @@ -1407,7 +1407,7 @@ public static bool CheckRange(InputArrayRef src, bool quiet, out Point pos, /// /// /// - public static void PatchNaNs(InputOutputArrayRef a, double val = 0) + public static void PatchNaNs(InputOutputArray a, double val = 0) { NativeMethods.HandleException( NativeMethods.core_patchNaNs(a.Proxy, val)); @@ -1426,8 +1426,8 @@ public static void PatchNaNs(InputOutputArrayRef a, double val = 0) /// /// // ReSharper disable once IdentifierTypo - public static void Gemm(InputArrayRef src1, InputArrayRef src2, double alpha, - InputArrayRef src3, double gamma, OutputArrayRef dst, GemmFlags flags = GemmFlags.None) + public static void Gemm(InputArray src1, InputArray src2, double alpha, + InputArray src3, double gamma, OutputArray dst, GemmFlags flags = GemmFlags.None) { NativeMethods.HandleException( NativeMethods.core_gemm(src1.Proxy, src2.Proxy, alpha, src3.Proxy, gamma, dst.Proxy, (int) flags)); @@ -1454,8 +1454,8 @@ public static void Gemm(InputArrayRef src1, InputArrayRef src2, double alpha, /// When it’s negative, the destination matrix will have the /// same type as src . Otherwise, it will have type=CV_MAT_DEPTH(rtype), /// which should be either CV_32F or CV_64F - public static void MulTransposed(InputArrayRef src, OutputArrayRef dst, bool aTa, - InputArrayRef delta = default, double scale = 1, int dtype = -1) + public static void MulTransposed(InputArray src, OutputArray dst, bool aTa, + InputArray delta = default, double scale = 1, int dtype = -1) { NativeMethods.HandleException( NativeMethods.core_mulTransposed(src.Proxy, dst.Proxy, aTa ? 1 : 0, delta.Proxy, scale, dtype)); @@ -1470,7 +1470,7 @@ public static void MulTransposed(InputArrayRef src, OutputArrayRef dst, bool aTa /// /// The source array /// The destination array of the same type as src - public static void Transpose(InputArrayRef src, OutputArrayRef dst) + public static void Transpose(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_transpose(src.Proxy, dst.Proxy)); @@ -1485,7 +1485,7 @@ public static void Transpose(InputArrayRef src, OutputArrayRef dst) /// The source array; must have as many channels (1 to 4) as mtx.cols or mtx.cols-1 /// The destination array; will have the same size and depth as src and as many channels as mtx.rows /// The transformation matrix - public static void Transform(InputArrayRef src, OutputArrayRef dst, InputArrayRef m) + public static void Transform(InputArray src, OutputArray dst, InputArray m) { NativeMethods.HandleException( NativeMethods.core_transform(src.Proxy, dst.Proxy, m.Proxy)); @@ -1502,7 +1502,7 @@ public static void Transform(InputArrayRef src, OutputArrayRef dst, InputArrayRe /// each element is 2D/3D vector to be transformed /// The destination array; it will have the same size and same type as src /// 3x3 or 4x4 transformation matrix - public static void PerspectiveTransform(InputArrayRef src, OutputArrayRef dst, InputArrayRef m) + public static void PerspectiveTransform(InputArray src, OutputArray dst, InputArray m) { NativeMethods.HandleException( NativeMethods.core_perspectiveTransform(src.Proxy, dst.Proxy, m.Proxy)); @@ -1615,7 +1615,7 @@ public static Point3d[] PerspectiveTransform(IEnumerable src, Mat m) /// If true, the lower half is copied to the upper half, /// otherwise the upper half is copied to the lower half // ReSharper disable once IdentifierTypo - public static void CompleteSymm(InputOutputArrayRef mtx, bool lowerToUpper = false) + public static void CompleteSymm(InputOutputArray mtx, bool lowerToUpper = false) { NativeMethods.HandleException( NativeMethods.core_completeSymm(mtx.Proxy, lowerToUpper ? 1 : 0)); @@ -1628,7 +1628,7 @@ public static void CompleteSymm(InputOutputArrayRef mtx, bool lowerToUpper = fal /// /// The matrix to initialize (not necessarily square) /// The value to assign to the diagonal elements - public static void SetIdentity(InputOutputArrayRef mtx, Scalar? s = null) + public static void SetIdentity(InputOutputArray mtx, Scalar? s = null) { var s0 = s.GetValueOrDefault(new Scalar(1)); NativeMethods.HandleException( @@ -1642,7 +1642,7 @@ public static void SetIdentity(InputOutputArrayRef mtx, Scalar? s = null) /// /// The input matrix; must have CV_32FC1 or CV_64FC1 type and square size /// determinant of the specified matrix. - public static double Determinant(InputArrayRef mtx) + public static double Determinant(InputArray mtx) { NativeMethods.HandleException( NativeMethods.core_determinant(mtx.Proxy, out var ret)); @@ -1656,7 +1656,7 @@ public static double Determinant(InputArrayRef mtx) /// /// The source matrix /// - public static Scalar Trace(InputArrayRef mtx) + public static Scalar Trace(InputArray mtx) { NativeMethods.HandleException( NativeMethods.core_trace(mtx.Proxy, out var ret)); @@ -1672,7 +1672,7 @@ public static Scalar Trace(InputArrayRef mtx) /// The destination matrix; will have NxM size and the same type as src /// The inversion method /// - public static double Invert(InputArrayRef src, OutputArrayRef dst, + public static double Invert(InputArray src, OutputArray dst, DecompTypes flags = DecompTypes.LU) { NativeMethods.HandleException( @@ -1691,7 +1691,7 @@ public static double Invert(InputArrayRef src, OutputArrayRef dst, /// /// /// - public static bool Solve(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, + public static bool Solve(InputArray src1, InputArray src2, OutputArray dst, DecompTypes flags = DecompTypes.LU) { NativeMethods.HandleException( @@ -1716,7 +1716,7 @@ public static bool Solve(InputArrayRef src1, InputArrayRef src2, OutputArrayRef /// // ReSharper disable once InconsistentNaming // ReSharper disable once IdentifierTypo - public static SolveLPResult SolveLP(InputArrayRef func, InputArrayRef constr, OutputArrayRef z) + public static SolveLPResult SolveLP(InputArray func, InputArray constr, OutputArray z) { NativeMethods.HandleException( NativeMethods.core_solveLP(func.Proxy, constr.Proxy, z.Proxy, out var ret)); @@ -1733,7 +1733,7 @@ public static SolveLPResult SolveLP(InputArrayRef func, InputArrayRef constr, Ou /// The source single-channel array /// The destination array of the same size and the same type as src /// The operation flags, a combination of the SortFlag values - public static void Sort(InputArrayRef src, OutputArrayRef dst, SortFlags flags) + public static void Sort(InputArray src, OutputArray dst, SortFlags flags) { NativeMethods.HandleException( NativeMethods.core_sort(src.Proxy, dst.Proxy, (int) flags)); @@ -1748,7 +1748,7 @@ public static void Sort(InputArrayRef src, OutputArrayRef dst, SortFlags flags) /// The source single-channel array /// The destination integer array of the same size as src /// The operation flags, a combination of SortFlag values - public static void SortIdx(InputArrayRef src, OutputArrayRef dst, SortFlags flags) + public static void SortIdx(InputArray src, OutputArray dst, SortFlags flags) { NativeMethods.HandleException( NativeMethods.core_sortIdx(src.Proxy, dst.Proxy, (int) flags)); @@ -1763,7 +1763,7 @@ public static void SortIdx(InputArrayRef src, OutputArrayRef dst, SortFlags flag /// The equation coefficients, an array of 3 or 4 elements /// The destination array of real roots which will have 1 or 3 elements /// - public static int SolveCubic(InputArrayRef coeffs, OutputArrayRef roots) + public static int SolveCubic(InputArray coeffs, OutputArray roots) { NativeMethods.HandleException( NativeMethods.core_solveCubic(coeffs.Proxy, roots.Proxy, out var ret)); @@ -1780,7 +1780,7 @@ public static int SolveCubic(InputArrayRef coeffs, OutputArrayRef roots) /// The destination (complex) array of roots /// The maximum number of iterations the algorithm does /// - public static double SolvePoly(InputArrayRef coeffs, OutputArrayRef roots, int maxIters = 300) + public static double SolvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300) { NativeMethods.HandleException( NativeMethods.core_solvePoly(coeffs.Proxy, roots.Proxy, maxIters, out var ret)); @@ -1801,7 +1801,7 @@ public static double SolvePoly(InputArrayRef coeffs, OutputArrayRef roots, int m /// It will have the same size and the same type as src; The eigenvectors are stored /// as subsequent matrix rows, in the same order as the corresponding eigenvalues /// - public static bool Eigen(InputArrayRef src, OutputArrayRef eigenvalues, OutputArrayRef eigenvectors) + public static bool Eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors) { NativeMethods.HandleException( NativeMethods.core_eigen(src.Proxy, eigenvalues.Proxy, eigenvectors.Proxy, out var ret)); @@ -1818,7 +1818,7 @@ public static bool Eigen(InputArrayRef src, OutputArrayRef eigenvalues, OutputAr /// input matrix (CV_32FC1 or CV_64FC1 type). /// output vector of eigenvalues (type is the same type as src). /// output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. - public static void EigenNonSymmetric(InputArrayRef src, OutputArrayRef eigenvalues, OutputArrayRef eigenvectors) + public static void EigenNonSymmetric(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors) { NativeMethods.HandleException( NativeMethods.core_eigenNonSymmetric(src.Proxy, eigenvalues.Proxy, eigenvectors.Proxy)); @@ -1872,8 +1872,8 @@ public static void CalcCovarMatrix( /// operation flags - see CovarFlags. /// type of the matrixl; it equals 'CV_64F' by default. public static void CalcCovarMatrix( - InputArrayRef samples, OutputArrayRef covar, - InputOutputArrayRef mean, CovarFlags flags, MatType? ctype = null) + InputArray samples, OutputArray covar, + InputOutputArray mean, CovarFlags flags, MatType? ctype = null) { var ctypeValue = ctype.GetValueOrDefault(MatType.CV_64F); NativeMethods.HandleException( @@ -1893,8 +1893,8 @@ public static void CalcCovarMatrix( /// Number of components that PCA should /// retain; by default, all the components are retained. public static void PCACompute( - InputArrayRef data, InputOutputArrayRef mean, - OutputArrayRef eigenvectors, int maxComponents = 0) + InputArray data, InputOutputArray mean, + OutputArray eigenvectors, int maxComponents = 0) { NativeMethods.HandleException( NativeMethods.core_PCACompute(data.Proxy, mean.Proxy, eigenvectors.Proxy, maxComponents)); @@ -1914,8 +1914,8 @@ public static void PCACompute( /// Number of components that PCA should /// retain; by default, all the components are retained. public static void PCACompute( - InputArrayRef data, InputOutputArrayRef mean, - OutputArrayRef eigenvectors, OutputArrayRef eigenvalues, int maxComponents = 0) + InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, int maxComponents = 0) { NativeMethods.HandleException( NativeMethods.core_PCACompute2(data.Proxy, mean.Proxy, eigenvectors.Proxy, eigenvalues.Proxy, maxComponents)); @@ -1935,8 +1935,8 @@ public static void PCACompute( /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. public static void PCAComputeVar( - InputArrayRef data, InputOutputArrayRef mean, - OutputArrayRef eigenvectors, double retainedVariance) + InputArray data, InputOutputArray mean, + OutputArray eigenvectors, double retainedVariance) { NativeMethods.HandleException( NativeMethods.core_PCAComputeVar(data.Proxy, mean.Proxy, eigenvectors.Proxy, retainedVariance)); @@ -1956,8 +1956,8 @@ public static void PCAComputeVar( /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. public static void PCAComputeVar( - InputArrayRef data, InputOutputArrayRef mean, - OutputArrayRef eigenvectors, OutputArrayRef eigenvalues, double retainedVariance) + InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, double retainedVariance) { NativeMethods.HandleException( NativeMethods.core_PCAComputeVar2(data.Proxy, mean.Proxy, eigenvectors.Proxy, eigenvalues.Proxy, retainedVariance)); @@ -1975,8 +1975,8 @@ public static void PCAComputeVar( /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. /// eigenvectors of the covariation matrix /// output vectors - public static void PCAProject(InputArrayRef data, InputArrayRef mean, - InputArrayRef eigenvectors, OutputArrayRef result) + public static void PCAProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result) { NativeMethods.HandleException( NativeMethods.core_PCAProject(data.Proxy, mean.Proxy, eigenvectors.Proxy, result.Proxy)); @@ -1994,8 +1994,8 @@ public static void PCAProject(InputArrayRef data, InputArrayRef mean, /// optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. /// eigenvectors of the covariation matrix /// output vectors - public static void PCABackProject(InputArrayRef data, InputArrayRef mean, - InputArrayRef eigenvectors, OutputArrayRef result) + public static void PCABackProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result) { NativeMethods.HandleException( NativeMethods.core_PCABackProject(data.Proxy, mean.Proxy, eigenvectors.Proxy, result.Proxy)); @@ -2017,8 +2017,8 @@ public static void PCABackProject(InputArrayRef data, InputArrayRef mean, // ReSharper disable once InconsistentNaming // ReSharper disable once IdentifierTypo public static void SVDecomp( - InputArrayRef src, OutputArrayRef w, - OutputArrayRef u, OutputArrayRef vt, SVD.Flags flags = SVD.Flags.None) + InputArray src, OutputArray w, + OutputArray u, OutputArray vt, SVD.Flags flags = SVD.Flags.None) { NativeMethods.HandleException( NativeMethods.core_SVDecomp(src.Proxy, w.Proxy, u.Proxy, vt.Proxy, (int) flags)); @@ -2039,8 +2039,8 @@ public static void SVDecomp( /// output // ReSharper disable once InconsistentNaming public static void SVBackSubst( - InputArrayRef w, InputArrayRef u, InputArrayRef vt, - InputArrayRef rhs, OutputArrayRef dst) + InputArray w, InputArray u, InputArray vt, + InputArray rhs, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_SVBackSubst(w.Proxy, u.Proxy, vt.Proxy, rhs.Proxy, dst.Proxy)); @@ -2059,7 +2059,7 @@ public static void SVBackSubst( /// second 1D input vector. /// inverse covariance matrix. /// - public static double Mahalanobis(InputArrayRef v1, InputArrayRef v2, InputArrayRef icovar) + public static double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar) { NativeMethods.HandleException( NativeMethods.core_Mahalanobis(v1.Proxy, v2.Proxy, icovar.Proxy, out var ret)); @@ -2082,7 +2082,7 @@ public static double Mahalanobis(InputArrayRef v1, InputArrayRef v2, InputArrayR /// thus the function can handle the rest of the rows more efficiently and /// thus save some time. This technique is very useful for computing array cross-correlation /// or convolution using DFT - public static void Dft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + public static void Dft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) { NativeMethods.HandleException( NativeMethods.core_dft(src.Proxy, dst.Proxy, (int) flags, nonzeroRows)); @@ -2103,7 +2103,7 @@ public static void Dft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = D /// thus the function can handle the rest of the rows more efficiently and /// thus save some time. This technique is very useful for computing array cross-correlation /// or convolution using DFT - public static void Idft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + public static void Idft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) { NativeMethods.HandleException( NativeMethods.core_idft(src.Proxy, dst.Proxy, (int) flags, nonzeroRows)); @@ -2118,7 +2118,7 @@ public static void Idft(InputArrayRef src, OutputArrayRef dst, DftFlags flags = /// The source floating-point array /// The destination array; will have the same size and same type as src /// Transformation flags, a combination of DctFlag2 values - public static void Dct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = DctFlags.None) + public static void Dct(InputArray src, OutputArray dst, DctFlags flags = DctFlags.None) { NativeMethods.HandleException( NativeMethods.core_dct(src.Proxy, dst.Proxy, (int) flags)); @@ -2133,7 +2133,7 @@ public static void Dct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = D /// The source floating-point array /// The destination array; will have the same size and same type as src /// Transformation flags, a combination of DctFlag2 values - public static void Idct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = DctFlags.None) + public static void Idct(InputArray src, OutputArray dst, DctFlags flags = DctFlags.None) { NativeMethods.HandleException( NativeMethods.core_idct(src.Proxy, dst.Proxy, (int) flags)); @@ -2152,7 +2152,7 @@ public static void Idct(InputArrayRef src, OutputArrayRef dst, DctFlags flags = /// each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. /// optional flag that conjugates the second input array before the multiplication (true) or not (false). public static void MulSpectrums( - InputArrayRef a, InputArrayRef b, OutputArrayRef c, + InputArray a, InputArray b, OutputArray c, DftFlags flags, bool conjB = false) { NativeMethods.HandleException( @@ -2205,7 +2205,7 @@ public static RNG SetTheRNG(ulong state) /// The array must be pre-allocated and have 1 to 4 channels /// The inclusive lower boundary of the generated random numbers /// The exclusive upper boundary of the generated random numbers - public static void Randu(InputOutputArrayRef dst, InputArrayRef low, InputArrayRef high) + public static void Randu(InputOutputArray dst, InputArray low, InputArray high) { NativeMethods.HandleException( NativeMethods.core_randu_InputArray(dst.Proxy, low.Proxy, high.Proxy)); @@ -2223,7 +2223,7 @@ public static void Randu(InputOutputArrayRef dst, InputArrayRef low, InputArrayR /// The inclusive lower boundary of the generated random numbers /// The exclusive upper boundary of the generated random numbers // ReSharper disable once IdentifierTypo - public static void Randu(InputOutputArrayRef dst, Scalar low, Scalar high) + public static void Randu(InputOutputArray dst, Scalar low, Scalar high) { NativeMethods.HandleException( NativeMethods.core_randu_Scalar(dst.Proxy, low, high)); @@ -2239,7 +2239,7 @@ public static void Randu(InputOutputArrayRef dst, Scalar low, Scalar high) /// The mean value (expectation) of the generated random numbers /// The standard deviation of the generated random numbers // ReSharper disable once IdentifierTypo - public static void Randn(InputOutputArrayRef dst, InputArrayRef mean, InputArrayRef stddev) + public static void Randn(InputOutputArray dst, InputArray mean, InputArray stddev) { NativeMethods.HandleException( NativeMethods.core_randn_InputArray(dst.Proxy, mean.Proxy, stddev.Proxy)); @@ -2256,7 +2256,7 @@ public static void Randn(InputOutputArrayRef dst, InputArrayRef mean, InputArray /// The array must be pre-allocated and have 1 to 4 channels /// The mean value (expectation) of the generated random numbers /// The standard deviation of the generated random numbers - public static void Randn(InputOutputArrayRef dst, Scalar mean, Scalar stddev) + public static void Randn(InputOutputArray dst, Scalar mean, Scalar stddev) { NativeMethods.HandleException( NativeMethods.core_randn_Scalar(dst.Proxy, mean, stddev)); @@ -2270,7 +2270,7 @@ public static void Randn(InputOutputArrayRef dst, Scalar mean, Scalar stddev) /// The input/output numerical 1D array /// The scale factor that determines the number of random swap operations. // ReSharper disable once IdentifierTypo - public static void RandShuffle(InputOutputArrayRef dst, double iterFactor) + public static void RandShuffle(InputOutputArray dst, double iterFactor) { NativeMethods.HandleException( NativeMethods.core_randShuffle(dst.Proxy, iterFactor, IntPtr.Zero)); @@ -2286,7 +2286,7 @@ public static void RandShuffle(InputOutputArrayRef dst, double iterFactor) /// The optional random number generator used for shuffling. /// If it is null, theRng() is used instead. // ReSharper disable once IdentifierTypo - public static void RandShuffle(InputOutputArrayRef dst, double iterFactor, ref RNG rng) + public static void RandShuffle(InputOutputArray dst, double iterFactor, ref RNG rng) { var state = rng.State; NativeMethods.HandleException( @@ -2315,8 +2315,8 @@ public static void RandShuffle(InputOutputArrayRef dst, double iterFactor, ref R /// value are returned by the function. Basically, you can use only the core of the function, /// set the number of attempts to 1, initialize labels each time using a custom algorithm, /// pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. - public static double Kmeans(InputArrayRef data, int k, InputOutputArrayRef bestLabels, - TermCriteria criteria, int attempts, KMeansFlags flags, OutputArrayRef centers = default) + public static double Kmeans(InputArray data, int k, InputOutputArray bestLabels, + TermCriteria criteria, int attempts, KMeansFlags flags, OutputArray centers = default) { NativeMethods.HandleException( NativeMethods.core_kmeans( @@ -2707,7 +2707,7 @@ public static bool SetBreakOnError(bool flag) /// /// /// - public static string Format(InputArrayRef mtx, FormatType format = FormatType.Default) + public static string Format(InputArray mtx, FormatType format = FormatType.Default) { using var buf = new StdString(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Cv2/Cv2_features.cs b/src/OpenCvSharp/Cv2/Cv2_features.cs index 2cb6c7fdd..1135dd398 100644 --- a/src/OpenCvSharp/Cv2/Cv2_features.cs +++ b/src/OpenCvSharp/Cv2/Cv2_features.cs @@ -19,7 +19,7 @@ static partial class Cv2 /// if true, non-maximum suppression is applied to /// detected corners (keypoints). /// keypoints detected on the image. - public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSupression = true) + public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupression = true) { using var kp = new StdVector(); NativeMethods.HandleException( @@ -38,7 +38,7 @@ public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSup /// detected corners (keypoints). /// one of the three neighborhoods as defined in the paper /// keypoints detected on the image. - public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSupression, FASTType type) + public static KeyPoint[] FAST(InputArray image, int threshold, bool nonmaxSupression, FASTType type) { using var kp = new StdVector(); NativeMethods.HandleException( @@ -57,7 +57,7 @@ public static KeyPoint[] FAST(InputArrayRef image, int threshold, bool nonmaxSup /// detected corners (keypoints). /// one of the four neighborhoods as defined in the paper /// keypoints detected on the image. - public static KeyPoint[] AGAST(InputArrayRef image, int threshold, bool nonmaxSuppression, AgastFeatureDetector.DetectorType type) + public static KeyPoint[] AGAST(InputArray image, int threshold, bool nonmaxSuppression, AgastFeatureDetector.DetectorType type) { using var vector = new StdVector(); NativeMethods.HandleException( @@ -75,9 +75,9 @@ public static KeyPoint[] AGAST(InputArrayRef image, int threshold, bool nonmaxSu /// Color of keypoints. /// Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags. public static void DrawKeypoints( - InputArrayRef image, + InputArray image, IEnumerable keypoints, - InputOutputArrayRef outImage, + InputOutputArray outImage, Scalar? color = null, DrawMatchesFlags flags = DrawMatchesFlags.Default) { diff --git a/src/OpenCvSharp/Cv2/Cv2_geometry.cs b/src/OpenCvSharp/Cv2/Cv2_geometry.cs index d1051a31e..b9132b70e 100644 --- a/src/OpenCvSharp/Cv2/Cv2_geometry.cs +++ b/src/OpenCvSharp/Cv2/Cv2_geometry.cs @@ -19,7 +19,7 @@ static partial class Cv2 /// Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). /// Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. /// Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial derivatives of the output array components with respect to the input array components. - public static void Rodrigues(InputArrayRef src, OutputArrayRef dst, OutputArrayRef jacobian = default) + public static void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian = default) { NativeMethods.HandleException( NativeMethods.geometry_Rodrigues(src.Proxy, dst.Proxy, jacobian.Proxy)); @@ -83,11 +83,11 @@ public static void Rodrigues(double[,] matrix, out double[] vector, out double[, /// Confidence level, between 0 and 1. /// public static Mat FindHomography( - InputArrayRef srcPoints, - InputArrayRef dstPoints, + InputArray srcPoints, + InputArray dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, - OutputArrayRef mask = default, + OutputArray mask = default, int maxIters = 2000, double confidence = 0.995) { @@ -120,7 +120,7 @@ public static Mat FindHomography( IEnumerable dstPoints, HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, - OutputArrayRef mask = default, + OutputArray mask = default, int maxIters = 2000, double confidence = 0.995) { @@ -153,9 +153,9 @@ public static Mat FindHomography( /// /// public static Mat FindHomography( - InputArrayRef srcPoints, - InputArrayRef dstPoints, - OutputArrayRef mask, + InputArray srcPoints, + InputArray dstPoints, + OutputArray mask, UsacParams? @params) { var p = (@params ?? new UsacParams()).ToNativeStruct(); @@ -180,8 +180,8 @@ public static Mat FindHomography( /// Optional output 3x3 rotation matrix around y-axis. /// Optional output 3x3 rotation matrix around z-axis. /// - public static Vec3d RQDecomp3x3(InputArrayRef src, OutputArrayRef mtxR, OutputArrayRef mtxQ, - OutputArrayRef qx = default, OutputArrayRef qy = default, OutputArrayRef qz = default) + public static Vec3d RQDecomp3x3(InputArray src, OutputArray mtxR, OutputArray mtxQ, + OutputArray qx = default, OutputArray qy = default, OutputArray qz = default) { NativeMethods.HandleException( NativeMethods.geometry_RQDecomp3x3_InputArray( @@ -254,14 +254,14 @@ public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] /// Optional 3x3 rotation matrix around z-axis. /// ptional three-element vector containing three Euler angles of rotation in degrees. public static void DecomposeProjectionMatrix( - InputArrayRef projMatrix, - OutputArrayRef cameraMatrix, - OutputArrayRef rotMatrix, - OutputArrayRef transVect, - OutputArrayRef rotMatrixX = default, - OutputArrayRef rotMatrixY = default, - OutputArrayRef rotMatrixZ = default, - OutputArrayRef eulerAngles = default) + InputArray projMatrix, + OutputArray cameraMatrix, + OutputArray rotMatrix, + OutputArray transVect, + OutputArray rotMatrixX = default, + OutputArray rotMatrixY = default, + OutputArray rotMatrixZ = default, + OutputArray eulerAngles = default) { NativeMethods.HandleException( NativeMethods.geometry_decomposeProjectionMatrix_InputArray( @@ -355,8 +355,8 @@ public static void DecomposeProjectionMatrix(double[,] projMatrix, /// First output derivative matrix d(A*B)/dA of size A.rows*B.cols X A.rows*A.cols . /// Second output derivative matrix d(A*B)/dB of size A.rows*B.cols X B.rows*B.cols . public static void MatMulDeriv( - InputArrayRef a, InputArrayRef b, - OutputArrayRef dABdA, OutputArrayRef dABdB) + InputArray a, InputArray b, + OutputArray dABdA, OutputArray dABdB) { NativeMethods.HandleException( NativeMethods.geometry_matMulDeriv(a.Proxy, b.Proxy, dABdA.Proxy, dABdB.Proxy)); @@ -382,13 +382,13 @@ public static void MatMulDeriv( /// Optional output derivatives of rvec3 or tvec3 with regard to rvec1, rvec2, tvec1 and tvec2, respectively. /// Optional output derivatives of rvec3 or tvec3 with regard to rvec1, rvec2, tvec1 and tvec2, respectively. public static void ComposeRT( - InputArrayRef rvec1, InputArrayRef tvec1, - InputArrayRef rvec2, InputArrayRef tvec2, - OutputArrayRef rvec3, OutputArrayRef tvec3, - OutputArrayRef dr3dr1 = default, OutputArrayRef dr3dt1 = default, - OutputArrayRef dr3dr2 = default, OutputArrayRef dr3dt2 = default, - OutputArrayRef dt3dr1 = default, OutputArrayRef dt3dt1 = default, - OutputArrayRef dt3dr2 = default, OutputArrayRef dt3dt2 = default) + InputArray rvec1, InputArray tvec1, + InputArray rvec2, InputArray tvec2, + OutputArray rvec3, OutputArray tvec3, + OutputArray dr3dr1 = default, OutputArray dr3dt1 = default, + OutputArray dr3dr2 = default, OutputArray dr3dt2 = default, + OutputArray dt3dr1 = default, OutputArray dt3dt1 = default, + OutputArray dt3dr2 = default, OutputArray dt3dt2 = default) { NativeMethods.HandleException( NativeMethods.geometry_composeRT_InputArray( @@ -523,13 +523,13 @@ public static void ComposeRT(double[] rvec1, double[] tvec1, /// If the parameter is not 0, the function assumes that the aspect ratio (fx/fy) /// is fixed and correspondingly adjusts the jacobian matrix. public static void ProjectPoints( - InputArrayRef objectPoints, - InputArrayRef rvec, - InputArrayRef tvec, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - OutputArrayRef imagePoints, - OutputArrayRef jacobian = default, + InputArray objectPoints, + InputArray rvec, + InputArray tvec, + InputArray cameraMatrix, + InputArray distCoeffs, + OutputArray imagePoints, + OutputArray jacobian = default, double aspectRatio = 0) { NativeMethods.HandleException( @@ -630,11 +630,11 @@ public static void ProjectPoints( /// the rotation and translation vectors, respectively, and further optimizes them. /// Method for solving a PnP problem: public static void SolvePnP( - InputArrayRef objectPoints, - InputArrayRef imagePoints, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - OutputArrayRef rvec, OutputArrayRef tvec, + InputArray objectPoints, + InputArray imagePoints, + InputArray cameraMatrix, + InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess = false, SolvePnPMethod flags = SolvePnPMethod.Iterative) { @@ -730,17 +730,17 @@ public static void SolvePnP( /// Output vector that contains indices of inliers in objectPoints and imagePoints . /// Method for solving a PnP problem public static void SolvePnPRansac( - InputArrayRef objectPoints, - InputArrayRef imagePoints, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - OutputArrayRef rvec, - OutputArrayRef tvec, + InputArray objectPoints, + InputArray imagePoints, + InputArray cameraMatrix, + InputArray distCoeffs, + OutputArray rvec, + OutputArray tvec, bool useExtrinsicGuess = false, int iterationsCount = 100, float reprojectionError = 8.0f, double confidence = 0.99, - OutputArrayRef inliers = default, + OutputArray inliers = default, SolvePnPMethod flags = SolvePnPMethod.Iterative) { NativeMethods.HandleException( @@ -860,7 +860,7 @@ public static void SolvePnPRansac( /// Principal point in pixels. /// fy / fx public static void CalibrationMatrixValues( - InputArrayRef cameraMatrix, Size imageSize, + InputArray cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, out double fovx, out double fovy, out double focalLength, out Point2d principalPoint, out double aspectRatio) @@ -924,8 +924,8 @@ public static void CalibrationMatrixValues( /// subset of the source image (determined by alpha) to the corrected image. /// optimal new camera matrix public static Mat GetOptimalNewCameraMatrix( - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, + InputArray cameraMatrix, + InputArray distCoeffs, Size imageSize, double alpha, Size newImgSize, @@ -990,7 +990,7 @@ public static Mat GetOptimalNewCameraMatrix( /// /// Input vector of N-dimensional points. /// Output vector of N+1-dimensional points. - public static void ConvertPointsToHomogeneous(InputArrayRef src, OutputArrayRef dst) + public static void ConvertPointsToHomogeneous(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.geometry_convertPointsToHomogeneous_InputArray(src.Proxy, dst.Proxy)); @@ -1040,7 +1040,7 @@ public static Vec4f[] ConvertPointsToHomogeneous(IEnumerable src) /// /// Input vector of N-dimensional points. /// Output vector of N-1-dimensional points. - public static void ConvertPointsFromHomogeneous(InputArrayRef src, OutputArrayRef dst) + public static void ConvertPointsFromHomogeneous(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.geometry_convertPointsFromHomogeneous_InputArray(src.Proxy, dst.Proxy)); @@ -1088,7 +1088,7 @@ public static Vec3f[] ConvertPointsFromHomogeneous(IEnumerable src) /// /// Input array or vector of 2D, 3D, or 4D points. /// Output vector of 2D, 3D, or 4D points. - public static void ConvertPointsHomogeneous(InputArrayRef src, OutputArrayRef dst) + public static void ConvertPointsHomogeneous(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.geometry_convertPointsHomogeneous(src.Proxy, dst.Proxy)); @@ -1112,10 +1112,10 @@ public static void ConvertPointsHomogeneous(InputArrayRef src, OutputArrayRef ds /// to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. For other methods, it is set to all 1’s. /// fundamental matrix public static Mat FindFundamentalMat( - InputArrayRef points1, InputArrayRef points2, + InputArray points1, InputArray points2, FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArrayRef mask = default) + OutputArray mask = default) { NativeMethods.HandleException( NativeMethods.geometry_findFundamentalMat_InputArray( @@ -1149,7 +1149,7 @@ public static Mat FindFundamentalMat( FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArrayRef mask = default) + OutputArray mask = default) { if (points1 is null) throw new ArgumentNullException(nameof(points1)); @@ -1190,7 +1190,7 @@ public static Mat FindFundamentalMat( FundamentalMatMethods method = FundamentalMatMethods.Ransac, double param1 = 3.0, double param2 = 0.99, - OutputArrayRef mask = default) + OutputArray mask = default) { if (points1 is null) throw new ArgumentNullException(nameof(points1)); @@ -1217,7 +1217,7 @@ public static Mat FindFundamentalMat( /// Output array of N elements; every element marks an inlier (1) or outlier (0). /// USAC parameters. Null uses the defaults. /// The estimated fundamental matrix. - public static Mat FindFundamentalMat(InputArrayRef points1, InputArrayRef points2, OutputArrayRef mask, UsacParams? @params) + public static Mat FindFundamentalMat(InputArray points1, InputArray points2, OutputArray mask, UsacParams? @params) { var p = (@params ?? new UsacParams()).ToNativeStruct(); NativeMethods.HandleException( @@ -1238,10 +1238,10 @@ public static Mat FindFundamentalMat(InputArrayRef points1, InputArrayRef points /// Fundamental matrix that can be estimated using findFundamentalMat() or stereoRectify() . /// Output vector of the epipolar lines corresponding to the points in the other image. /// Each line ax + by + c=0 is encoded by 3 numbers (a, b, c) . - public static void ComputeCorrespondEpilines(InputArrayRef points, + public static void ComputeCorrespondEpilines(InputArray points, int whichImage, - InputArrayRef F, - OutputArrayRef lines) + InputArray F, + OutputArray lines) { NativeMethods.HandleException( NativeMethods.geometry_computeCorrespondEpilines_InputArray( @@ -1333,9 +1333,9 @@ public static Point3f[] ComputeCorrespondEpilines(IEnumerable points, /// it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. /// 4xN array of reconstructed points in homogeneous coordinates. public static void TriangulatePoints( - InputArrayRef projMatr1, InputArrayRef projMatr2, - InputArrayRef projPoints1, InputArrayRef projPoints2, - OutputArrayRef points4D) + InputArray projMatr1, InputArray projMatr2, + InputArray projPoints1, InputArray projPoints2, + OutputArray points4D) { NativeMethods.HandleException( NativeMethods.geometry_triangulatePoints_InputArray( @@ -1409,8 +1409,8 @@ public static Vec4d[] TriangulatePoints( /// The optimized points1. /// The optimized points2. public static void CorrectMatches( - InputArrayRef F, InputArrayRef points1, InputArrayRef points2, - OutputArrayRef newPoints1, OutputArrayRef newPoints2) + InputArray F, InputArray points1, InputArray points2, + OutputArray newPoints1, OutputArray newPoints2) { NativeMethods.HandleException( NativeMethods.geometry_correctMatches_InputArray( @@ -1479,9 +1479,9 @@ public static void CorrectMatches( /// This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible pose hypotheses by doing cheirality check. /// The cheirality check basically means that the triangulated 3D points should have positive depth. public static int RecoverPose( - InputArrayRef E, InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, - OutputArrayRef R, OutputArrayRef t, - InputOutputArrayRef mask = default) + InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, + OutputArray R, OutputArray t, + InputOutputArray mask = default) { NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray1( @@ -1513,9 +1513,9 @@ public static int RecoverPose( /// This function decomposes an essential matrix using decomposeEssentialMat and then verifies possible pose hypotheses by doing cheirality check. /// The cheirality check basically means that the triangulated 3D points should have positive depth. public static int RecoverPose( - InputArrayRef E, InputArrayRef points1, InputArrayRef points2, - OutputArrayRef R, OutputArrayRef t, double focal, Point2d pp, - InputOutputArrayRef mask = default) + InputArray E, InputArray points1, InputArray points2, + OutputArray R, OutputArray t, double focal, Point2d pp, + InputOutputArray mask = default) { NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray2( @@ -1548,9 +1548,9 @@ public static int RecoverPose( /// The cheirality check basically means that the triangulated 3D points should have positive depth. /// 3d points which were reconstructed by triangulation. public static int RecoverPose( - InputArrayRef E, InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, - OutputArrayRef R, OutputArrayRef t, double distanceTresh, - InputOutputArrayRef mask = default, OutputArrayRef triangulatedPoints = default) + InputArray E, InputArray points1, InputArray points2, InputArray cameraMatrix, + OutputArray R, OutputArray t, double distanceTresh, + InputOutputArray mask = default, OutputArray triangulatedPoints = default) { NativeMethods.HandleException( NativeMethods.geometry_recoverPose_InputArray3( @@ -1583,10 +1583,10 @@ public static int RecoverPose( /// Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. /// essential matrix public static Mat FindEssentialMat( - InputArrayRef points1, InputArrayRef points2, InputArrayRef cameraMatrix, + InputArray points1, InputArray points2, InputArray cameraMatrix, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, - OutputArrayRef mask = default) + OutputArray mask = default) { NativeMethods.HandleException( NativeMethods.geometry_findEssentialMat_InputArray1( @@ -1618,10 +1618,10 @@ public static Mat FindEssentialMat( /// Output array of N elements, every element of which is set to 0 for outliers and to 1 for the other points. The array is computed only in the RANSAC and LMedS methods. /// essential matrix public static Mat FindEssentialMat( - InputArrayRef points1, InputArrayRef points2, double focal, Point2d pp, + InputArray points1, InputArray points2, double focal, Point2d pp, EssentialMatMethod method = EssentialMatMethod.Ransac, double prob = 0.999, double threshold = 1.0, - OutputArrayRef mask = default) + OutputArray mask = default) { NativeMethods.HandleException( NativeMethods.geometry_findEssentialMat_InputArray2( @@ -1645,8 +1645,8 @@ public static Mat FindEssentialMat( /// Anything between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation significantly. /// Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. /// - public static int EstimateAffine3D(InputArrayRef src, InputArrayRef dst, - OutputArrayRef outVal, OutputArrayRef inliers, + public static int EstimateAffine3D(InputArray src, InputArray dst, + OutputArray outVal, OutputArray inliers, double ransacThreshold = 3, double confidence = 0.99) { NativeMethods.HandleException( @@ -1666,7 +1666,7 @@ public static int EstimateAffine3D(InputArrayRef src, InputArrayRef dst, /// F fundamental matrix /// The computed Sampson distance. /// https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp#L1109 - public static double SampsonDistance(InputArrayRef pt1, InputArrayRef pt2, InputArrayRef f) + public static double SampsonDistance(InputArray pt1, InputArray pt2, InputArray f) { NativeMethods.HandleException( NativeMethods.geometry_sampsonDistance_InputArray(pt1.Proxy, pt2.Proxy, f.Proxy, out var ret)); @@ -1720,7 +1720,7 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// Passing 0 will disable refining, so the output matrix will be output of robust method. /// Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation could not be estimated. public static Mat? EstimateAffine2D( - InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, + InputArray from, InputArray to, OutputArray inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 10) @@ -1752,7 +1752,7 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// /// Output 2D affine transformation (4 degrees of freedom) matrix 2x3 or empty matrix if transformation could not be estimated. public static Mat? EstimateAffinePartial2D( - InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, + InputArray from, InputArray to, OutputArray inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 10) @@ -1779,8 +1779,8 @@ public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) /// Array of plane normal matrices. /// public static int DecomposeHomographyMat( - InputArrayRef h, - InputArrayRef k, + InputArray h, + InputArray k, out Mat[] rotations, out Mat[] translations, out Mat[] normals) @@ -1818,10 +1818,10 @@ public static int DecomposeHomographyMat( public static void FilterHomographyDecompByVisibleRefpoints( IEnumerable rotations, IEnumerable normals, - InputArrayRef beforePoints, - InputArrayRef afterPoints, - OutputArrayRef possibleSolutions, - InputArrayRef pointsMask = default) + InputArray beforePoints, + InputArray afterPoints, + OutputArray possibleSolutions, + InputArray pointsMask = default) { if (rotations is null) throw new ArgumentNullException(nameof(rotations)); @@ -1853,7 +1853,7 @@ public static void FilterHomographyDecompByVisibleRefpoints( /// the camera matrix that is either an exact copy of the input cameraMatrix /// (when centerPrinicipalPoint=false), or the modified one (when centerPrincipalPoint=true). public static Mat GetDefaultNewCameraMatrix( - InputArrayRef cameraMatrix, Size? imgSize = null, bool centerPrincipalPoint = false) + InputArray cameraMatrix, Size? imgSize = null, bool centerPrincipalPoint = false) { var imgSize0 = imgSize.GetValueOrDefault(new Size()); @@ -1880,12 +1880,12 @@ public static Mat GetDefaultNewCameraMatrix( /// P1 or P2 computed by stereoRectify() can be passed here. If the matrix is empty, /// the identity new camera matrix is used. public static void UndistortPoints( - InputArrayRef src, - OutputArrayRef dst, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - InputArrayRef r = default, - InputArrayRef p = default) + InputArray src, + OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray r = default, + InputArray p = default) { NativeMethods.HandleException( NativeMethods.geometry_undistortPoints( @@ -1917,12 +1917,12 @@ public static void UndistortPoints( /// the identity new camera matrix is used. /// public static void UndistortPointsIter( - InputArrayRef src, - OutputArrayRef dst, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - InputArrayRef r = default, - InputArrayRef p = default, + InputArray src, + OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray r = default, + InputArray p = default, TermCriteria? termCriteria = null) { NativeMethods.HandleException( @@ -1950,8 +1950,8 @@ public static void UndistortPointsIter( /// Input/Output translation vector. Input values are used as the initial solution. /// Criteria when to stop the Levenberg-Marquardt iterative algorithm. public static void SolvePnPRefineLM( - InputArrayRef objectPoints, InputArrayRef imagePoints, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, - InputOutputArrayRef rvec, InputOutputArrayRef tvec, TermCriteria? criteria = null) + InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, TermCriteria? criteria = null) { var c = criteria ?? new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 20, 1.1920929e-07); NativeMethods.HandleException( @@ -1980,8 +1980,8 @@ public static void SolvePnPRefineLM( /// Criteria when to stop the iterative algorithm. /// Gain for the virtual visual servoing control law. public static void SolvePnPRefineVVS( - InputArrayRef objectPoints, InputArrayRef imagePoints, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, - InputOutputArrayRef rvec, InputOutputArrayRef tvec, TermCriteria? criteria = null, double vvsLambda = 1) + InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, TermCriteria? criteria = null, double vvsLambda = 1) { var c = criteria ?? new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 20, 1.1920929e-07); NativeMethods.HandleException( @@ -2004,7 +2004,7 @@ public static void SolvePnPRefineVVS( /// One possible rotation matrix. /// Another possible rotation matrix. /// One possible translation (up to scale). - public static void DecomposeEssentialMat(InputArrayRef e, OutputArrayRef r1, OutputArrayRef r2, OutputArrayRef t) + public static void DecomposeEssentialMat(InputArray e, OutputArray r1, OutputArray r2, OutputArray t) { NativeMethods.HandleException( NativeMethods.geometry_decomposeEssentialMat(e.Proxy, r1.Proxy, r2.Proxy, t.Proxy)); @@ -2026,7 +2026,7 @@ public static void DecomposeEssentialMat(InputArrayRef e, OutputArrayRef r1, Out /// Confidence level, between 0 and 1. /// True if a translation was found. public static bool EstimateTranslation3D( - InputArrayRef src, InputArrayRef dst, OutputArrayRef outVal, OutputArrayRef inliers, + InputArray src, InputArray dst, OutputArray outVal, OutputArray inliers, double ransacThreshold = 3, double confidence = 0.99) { NativeMethods.HandleException( @@ -2051,7 +2051,7 @@ public static bool EstimateTranslation3D( /// Maximum number of iterations of refining algorithm (Levenberg-Marquardt). /// The estimated 2D translation vector. public static Vec2d EstimateTranslation2D( - InputArrayRef from, InputArrayRef to, OutputArrayRef inliers = default, + InputArray from, InputArray to, OutputArray inliers = default, RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, ulong maxIters = 2000, double confidence = 0.99, ulong refineIters = 0) { diff --git a/src/OpenCvSharp/Cv2/Cv2_highgui.cs b/src/OpenCvSharp/Cv2/Cv2_highgui.cs index a31e58d4f..e9798da39 100644 --- a/src/OpenCvSharp/Cv2/Cv2_highgui.cs +++ b/src/OpenCvSharp/Cv2/Cv2_highgui.cs @@ -302,7 +302,7 @@ public static int GetMouseWheelDelta(MouseEventFlags flags) /// selection rectangle will correspond to the initial mouse position. /// selected ROI or empty rect if selection canceled. // ReSharper disable once InconsistentNaming - public static Rect SelectROI(string windowName, InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) + public static Rect SelectROI(string windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false) { if (string.IsNullOrEmpty(windowName)) throw new ArgumentNullException(nameof(windowName)); @@ -325,7 +325,7 @@ public static Rect SelectROI(string windowName, InputArrayRef img, bool showCros /// selection rectangle will correspond to the initial mouse position. /// selected ROI or empty rect if selection canceled. // ReSharper disable once InconsistentNaming - public static Rect SelectROI(InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) + public static Rect SelectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false) { NativeMethods.HandleException( NativeMethods.highgui_selectROI2(img.Proxy, showCrosshair ? 1 : 0, fromCenter ? 1 : 0, out var ret)); @@ -347,7 +347,7 @@ public static Rect SelectROI(InputArrayRef img, bool showCrosshair = true, bool /// selection rectangle will correspond to the initial mouse position. /// selected ROIs. // ReSharper disable once InconsistentNaming - public static Rect[] SelectROIs(string windowName, InputArrayRef img, bool showCrosshair = true, bool fromCenter = false) + public static Rect[] SelectROIs(string windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false) { if (string.IsNullOrEmpty(windowName)) throw new ArgumentNullException(nameof(windowName)); diff --git a/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs b/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs index b83506e84..ede52fb0c 100644 --- a/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs +++ b/src/OpenCvSharp/Cv2/Cv2_imgcodecs.cs @@ -155,7 +155,7 @@ public static Mat ImDecode(Mat buf, ImreadModes flags) /// The input array of vector of bytes. /// The same flags as in imread /// - public static Mat ImDecode(InputArrayRef buf, ImreadModes flags) + public static Mat ImDecode(InputArray buf, ImreadModes flags) { NativeMethods.HandleException( NativeMethods.imgcodecs_imdecode_InputArray(buf.Proxy, (int) flags, out var ret)); @@ -207,7 +207,7 @@ public static Mat ImDecode(ReadOnlySpan span, ImreadModes flags) /// The image to be written /// Output buffer resized to fit the compressed image. /// Format-specific parameters. - public static bool ImEncode(string ext, InputArrayRef img, out byte[] buf, int[]? prms = null) + public static bool ImEncode(string ext, InputArray img, out byte[] buf, int[]? prms = null) { if (string.IsNullOrEmpty(ext)) throw new ArgumentNullException(nameof(ext)); @@ -228,7 +228,7 @@ public static bool ImEncode(string ext, InputArrayRef img, out byte[] buf, int[] /// The image to be written /// Output buffer resized to fit the compressed image. /// Format-specific parameters. - public static void ImEncode(string ext, InputArrayRef img, out byte[] buf, params ImageEncodingParam[] prms) + public static void ImEncode(string ext, InputArray img, out byte[] buf, params ImageEncodingParam[] prms) { if (prms is null) throw new ArgumentNullException(nameof(prms)); diff --git a/src/OpenCvSharp/Cv2/Cv2_imgproc.cs b/src/OpenCvSharp/Cv2/Cv2_imgproc.cs index 0202faec5..c95f2b6c8 100644 --- a/src/OpenCvSharp/Cv2/Cv2_imgproc.cs +++ b/src/OpenCvSharp/Cv2/Cv2_imgproc.cs @@ -45,7 +45,7 @@ static partial class Cv2 /// and wish to preserve all the fractional bits, you may want to set normalize = false. /// Type of filter coefficients. It can be CV_32f or CV_64F. public static void GetDerivKernels( - OutputArrayRef kx, OutputArrayRef ky, int dx, int dy, int ksize, + OutputArray kx, OutputArray ky, int dx, int dy, int ksize, bool normalize = false, MatType? ktype = null) { var ktype0 = ktype.GetValueOrDefault(MatType.CV_32F); @@ -116,7 +116,7 @@ public static Mat GetStructuringElement(MorphShapes shape, Size ksize, Point anc /// For larger aperture sizes it can only be CV_8U /// The destination array; will have the same size and the same type as src /// The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ... - public static void MedianBlur(InputArrayRef src, OutputArrayRef dst, int ksize) + public static void MedianBlur(InputArray src, OutputArray dst, int ksize) { NativeMethods.HandleException( NativeMethods.imgproc_medianBlur(src.Proxy, dst.Proxy, ksize)); @@ -140,7 +140,7 @@ public static void MedianBlur(InputArrayRef src, OutputArrayRef dst, int ksize) /// regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. /// pixel extrapolation method /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void GaussianBlur(InputArrayRef src, OutputArrayRef dst, Size ksize, double sigmaX, + public static void GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY = 0, BorderTypes borderType = BorderTypes.Default, AlgorithmHint hint = AlgorithmHint.Default) { NativeMethods.HandleException( @@ -165,7 +165,7 @@ public static void GaussianBlur(InputArrayRef src, OutputArrayRef dst, Size ksiz /// (as long as their colors are close enough; see sigmaColor). Then d>0 , it specifies /// the neighborhood size regardless of sigmaSpace, otherwise d is proportional to sigmaSpace /// - public static void BilateralFilter(InputArrayRef src, OutputArrayRef dst, int d, double sigmaColor, + public static void BilateralFilter(InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( @@ -186,7 +186,7 @@ public static void BilateralFilter(InputArrayRef src, OutputArrayRef dst, int d, /// Indicates, whether the kernel is normalized by its area or not /// The border mode used to extrapolate pixels outside of the image public static void BoxFilter( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, + InputArray src, OutputArray dst, MatType ddepth, Size ksize, Point? anchor = null, bool normalize = true, BorderTypes borderType = BorderTypes.Default) { @@ -215,7 +215,7 @@ public static void BoxFilter( /// /// public static void SqrBoxFilter( - InputArrayRef src, OutputArrayRef dst, int ddepth, + InputArray src, OutputArray dst, int ddepth, Size ksize, Point? anchor = null, bool normalize = true, BorderTypes borderType = BorderTypes.Default) { @@ -236,7 +236,7 @@ public static void SqrBoxFilter( /// The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center /// The border mode used to extrapolate pixels outside of the image public static void Blur( - InputArrayRef src, OutputArrayRef dst, Size ksize, + InputArray src, OutputArray dst, Size ksize, Point? anchor = null, BorderTypes borderType = BorderTypes.Default) { var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); @@ -262,8 +262,8 @@ public static void Blur( /// The optional value added to the filtered pixels before storing them in dst /// The pixel extrapolation method public static void Filter2D( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, - InputArrayRef kernel, Point? anchor = null, double delta = 0, + InputArray src, OutputArray dst, MatType ddepth, + InputArray kernel, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default) { var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); @@ -282,7 +282,7 @@ public static void Filter2D( /// output image of the same size and the same number of channels as src. /// convolution kernel (or rather a correlation kernel), a single-channel floating point matrix. /// filtering parameters (anchor, border, depth, scale, shift). Null uses the defaults. - public static void Filter2D(InputArrayRef src, OutputArrayRef dst, InputArrayRef kernel, Filter2DParams? @params = null) + public static void Filter2D(InputArray src, OutputArray dst, InputArray kernel, Filter2DParams? @params = null) { var p = @params ?? new Filter2DParams(); NativeMethods.HandleException( @@ -307,7 +307,7 @@ public static void Filter2D(InputArrayRef src, OutputArrayRef dst, InputArrayRef /// The value added to the filtered results before storing them /// The pixel extrapolation method public static void SepFilter2D( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, InputArrayRef kernelX, InputArrayRef kernelY, + InputArray src, OutputArray dst, MatType ddepth, InputArray kernelX, InputArray kernelY, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default) { @@ -335,7 +335,7 @@ public static void SepFilter2D( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Sobel( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, int xorder, int yorder, + InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, int ksize = 3, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { @@ -356,7 +356,7 @@ public static void Sobel( /// size of Sobel kernel. It must be 3. /// pixel extrapolation method public static void SpatialGradient( - InputArrayRef src, OutputArrayRef dx, OutputArrayRef dy, int ksize = 3, BorderTypes borderType = BorderTypes.Default) + InputArray src, OutputArray dx, OutputArray dy, int ksize = 3, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( NativeMethods.imgproc_spatialGradient(src.Proxy, dx.Proxy, dy.Proxy, ksize, (int)borderType)); @@ -376,7 +376,7 @@ public static void SpatialGradient( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Scharr( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, int xorder, int yorder, + InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( @@ -398,7 +398,7 @@ public static void Scharr( /// The optional delta value, added to the results prior to storing them in dst /// The pixel extrapolation method public static void Laplacian( - InputArrayRef src, OutputArrayRef dst, MatType ddepth, + InputArray src, OutputArray dst, MatType ddepth, int ksize = 1, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) { @@ -418,7 +418,7 @@ public static void Laplacian( /// The second threshold for the hysteresis procedure /// Aperture size for the Sobel operator [By default this is ApertureSize.Size3] /// Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false] - public static void Canny(InputArrayRef src, OutputArrayRef edges, + public static void Canny(InputArray src, OutputArray edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) { NativeMethods.HandleException( @@ -438,7 +438,7 @@ public static void Canny(InputArrayRef src, OutputArrayRef edges, /// second threshold for the hysteresis procedure. /// Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false] public static void Canny( - InputArrayRef dx, InputArrayRef dy, OutputArrayRef edges, + InputArray dx, InputArray dy, OutputArray edges, double threshold1, double threshold2, bool L2gradient = false) { @@ -459,8 +459,8 @@ public static void Canny( /// Aperture parameter for the Sobel operator. /// Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. public static void CornerMinEigenVal( - InputArrayRef src, - OutputArrayRef dst, + InputArray src, + OutputArray dst, int blockSize, int ksize = 3, BorderTypes borderType = BorderTypes.Default) @@ -483,8 +483,8 @@ public static void CornerMinEigenVal( /// Harris detector free parameter. See the formula above. /// Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. public static void CornerHarris( - InputArrayRef src, - OutputArrayRef dst, + InputArray src, + OutputArray dst, int blockSize, int ksize, double k, @@ -506,7 +506,7 @@ public static void CornerHarris( /// /// public static void CornerEigenValsAndVecs( - InputArrayRef src, OutputArrayRef dst, int blockSize, int ksize, + InputArray src, OutputArray dst, int blockSize, int ksize, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( @@ -524,7 +524,7 @@ public static void CornerEigenValsAndVecs( /// /// public static void PreCornerDetect( - InputArrayRef src, OutputArrayRef dst, int ksize, BorderTypes borderType = BorderTypes.Default) + InputArray src, OutputArray dst, int ksize, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( NativeMethods.imgproc_preCornerDetect(src.Proxy, dst.Proxy, ksize, (int) borderType)); @@ -546,7 +546,7 @@ public static void PreCornerDetect( /// That is, the process of corner position refinement stops either after criteria.maxCount iterations /// or when the corner position moves by less than criteria.epsilon on some iteration. /// - public static Point2f[] CornerSubPix(InputArrayRef image, IEnumerable inputCorners, + public static Point2f[] CornerSubPix(InputArray image, IEnumerable inputCorners, Size winSize, Size zeroZone, TermCriteria criteria) { if (inputCorners is null) @@ -582,9 +582,9 @@ public static Point2f[] CornerSubPix(InputArrayRef image, IEnumerable i /// Parameter indicating whether to use a Harris detector /// Free parameter of the Harris detector. /// Output vector of detected corners. - public static Point2f[] GoodFeaturesToTrack(InputArrayRef src, + public static Point2f[] GoodFeaturesToTrack(InputArray src, int maxCorners, double qualityLevel, double minDistance, - InputArrayRef mask, int blockSize, bool useHarrisDetector, double k) + InputArray mask, int blockSize, bool useHarrisDetector, double k) { using var vector = new StdVector(); var maskPtr = mask.Proxy; @@ -608,7 +608,7 @@ public static Point2f[] GoodFeaturesToTrack(InputArrayRef src, /// The output vector of lines. Each line is represented by a two-element vector (rho, theta) . /// rho is the distance from the coordinate origin (0,0) (top-left corner of the image) and theta is the line rotation angle in radians public static LineSegmentPolar[] HoughLines( - InputArrayRef image, double rho, double theta, int threshold, + InputArray image, double rho, double theta, int threshold, double srn = 0, double stn = 0) { using var vec = new StdVector(); @@ -629,7 +629,7 @@ public static LineSegmentPolar[] HoughLines( /// The maximum allowed gap between points on the same line to link them. [By default this is 0] /// The output lines. Each line is represented by a 4-element vector (x1, y1, x2, y2) public static LineSegmentPoint[] HoughLinesP( - InputArrayRef image, double rho, double theta, int threshold, + InputArray image, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0) { using var vec = new StdVector(); @@ -654,7 +654,7 @@ public static LineSegmentPoint[] HoughLinesP( /// Maximum angle value of the accumulator in radians. /// Angle resolution of the accumulator in radians. public static void HoughLinesPointSet( - InputArrayRef point, OutputArrayRef lines, int linesMax, int threshold, + InputArray point, OutputArray lines, int linesMax, int threshold, double minRho, double maxRho, double rhoStep, double minTheta, double maxTheta, double thetaStep) { @@ -678,7 +678,7 @@ public static void HoughLinesPointSet( /// Maximum circle radius. [By default this is 0] /// The output vector found circles. Each vector is encoded as 3-element floating-point vector (x, y, radius) public static CircleSegment[] HoughCircles( - InputArrayRef image, HoughModes method, double dp, double minDist, + InputArray image, HoughModes method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) { using var vec = new StdVector(); @@ -709,7 +709,7 @@ public static Scalar MorphologyDefaultBorderValue() /// The pixel extrapolation method. [By default this is BorderType.Constant] /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void Dilate( - InputArrayRef src, OutputArrayRef dst, InputArrayRef element, + InputArray src, OutputArray dst, InputArray element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { @@ -735,7 +735,7 @@ public static void Dilate( /// The pixel extrapolation method /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void Erode( - InputArrayRef src, OutputArrayRef dst, InputArrayRef element, + InputArray src, OutputArray dst, InputArray element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { @@ -762,7 +762,7 @@ public static void Erode( /// The pixel extrapolation method. [By default this is BorderType.Constant] /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] public static void MorphologyEx( - InputArrayRef src, OutputArrayRef dst, MorphTypes op, InputArrayRef element, + InputArray src, OutputArray dst, MorphTypes op, InputArray element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) { @@ -792,7 +792,7 @@ public static void MorphologyEx( /// scale factor along the vertical axis; when it equals 0, /// it is computed as: (double)dsize.height/src.rows /// interpolation method - public static void Resize(InputArrayRef src, OutputArrayRef dst, Size dsize, + public static void Resize(InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, InterpolationFlags interpolation = InterpolationFlags.Linear) { NativeMethods.HandleException( @@ -817,7 +817,7 @@ public static void Resize(InputArrayRef src, OutputArrayRef dst, Size dsize, /// value used in case of a constant border; by default, it is 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpAffine( - InputArrayRef src, OutputArrayRef dst, InputArrayRef m, Size dsize, + InputArray src, OutputArray dst, InputArray m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) @@ -844,7 +844,7 @@ public static void WarpAffine( /// value used in case of a constant border; by default, it equals 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpPerspective( - InputArrayRef src, OutputArrayRef dst, InputArrayRef m, Size dsize, + InputArray src, OutputArray dst, InputArray m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, @@ -873,7 +873,7 @@ public static void WarpPerspective( /// value used in case of a constant border; by default, it equals 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void WarpPerspective( - InputArrayRef src, OutputArrayRef dst, float[,] m, Size dsize, + InputArray src, OutputArray dst, float[,] m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, @@ -908,7 +908,7 @@ public static void WarpPerspective( /// Value used in case of a constant border. By default, it is 0. /// Hint that selects between alternative algorithm implementations (OpenCV 5). public static void Remap( - InputArrayRef src, OutputArrayRef dst, InputArrayRef map1, InputArrayRef map2, + InputArray src, OutputArray dst, InputArray map1, InputArray map2, InterpolationFlags interpolation = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null, AlgorithmHint hint = AlgorithmHint.Default) @@ -933,7 +933,7 @@ public static void Remap( /// The second output map. /// Type of the first output map that should be CV_16SC2 , CV_32FC1 , or CV_32FC2 . /// Flag indicating whether the fixed-point maps are used for the nearest-neighbor or for a more complex interpolation. - public static void ConvertMaps(InputArrayRef map1, InputArrayRef map2, OutputArrayRef dstmap1, OutputArrayRef dstmap2, MatType dstmap1Type, bool nnInterpolation = false) + public static void ConvertMaps(InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, MatType dstmap1Type, bool nnInterpolation = false) { NativeMethods.HandleException( NativeMethods.imgproc_convertMaps(map1.Proxy, map2.Proxy, dstmap1.Proxy, dstmap2.Proxy, dstmap1Type, @@ -964,7 +964,7 @@ public static Mat GetRotationMatrix2D(Point2f center, double angle, double scale /// /// Original affine transformation. /// Output reverse affine transformation. - public static void InvertAffineTransform(InputArrayRef m, OutputArrayRef im) + public static void InvertAffineTransform(InputArray m, OutputArray im) { NativeMethods.HandleException( NativeMethods.imgproc_invertAffineTransform(m.Proxy, im.Proxy)); @@ -1000,7 +1000,7 @@ public static Mat GetPerspectiveTransform(IEnumerable src, IEnumerable< /// Coordinates of quadrangle vertices in the source image. /// Coordinates of the corresponding quadrangle vertices in the destination image. /// - public static Mat GetPerspectiveTransform(InputArrayRef src, InputArrayRef dst) + public static Mat GetPerspectiveTransform(InputArray src, InputArray dst) { NativeMethods.HandleException( NativeMethods.imgproc_getPerspectiveTransform2(src.Proxy, dst.Proxy, out var retMat)); @@ -1037,7 +1037,7 @@ public static Mat GetAffineTransform(IEnumerable src, IEnumerableCoordinates of triangle vertices in the source image. /// Coordinates of the corresponding triangle vertices in the destination image. /// - public static Mat GetAffineTransform(InputArrayRef src, InputArrayRef dst) + public static Mat GetAffineTransform(InputArray src, InputArray dst) { NativeMethods.HandleException( NativeMethods.imgproc_getAffineTransform2(src.Proxy, dst.Proxy, out var retMat)); @@ -1056,8 +1056,8 @@ public static Mat GetAffineTransform(InputArrayRef src, InputArrayRef dst) /// within the source image. The center must be inside the image. /// Extracted patch that has the size patchSize and the same number of channels as src . /// Depth of the extracted pixels. By default, they have the same depth as src. - public static void GetRectSubPix(InputArrayRef image, Size patchSize, Point2f center, - OutputArrayRef patch, int patchType = -1) + public static void GetRectSubPix(InputArray image, Size patchSize, Point2f center, + OutputArray patch, int patchType = -1) { NativeMethods.HandleException( NativeMethods.imgproc_getRectSubPix(image.Proxy, patchSize, center, patch.Proxy, patchType)); @@ -1082,7 +1082,7 @@ public static void GetRectSubPix(InputArrayRef image, Size patchSize, Point2f ce /// interpolation methods. /// interpolation methods. public static void WarpPolar( - InputArrayRef src, OutputArrayRef dst, Size dsize, + InputArray src, OutputArray dst, Size dsize, Point2f center, double maxRadius, InterpolationFlags interpolationFlags, WarpPolarMode warpPolarMode) { int flags = (int)interpolationFlags | (int)warpPolarMode; @@ -1100,7 +1100,7 @@ public static void WarpPolar( /// /// /// - public static void Integral(InputArrayRef src, OutputArrayRef sum, MatType? sdepth = null) + public static void Integral(InputArray src, OutputArray sum, MatType? sdepth = null) { NativeMethods.HandleException( NativeMethods.imgproc_integral1(src.Proxy, sum.Proxy, sdepth?.Value ?? -1)); @@ -1117,7 +1117,7 @@ public static void Integral(InputArrayRef src, OutputArrayRef sum, MatType? sdep /// /// /// - public static void Integral(InputArrayRef src, OutputArrayRef sum, OutputArrayRef sqsum, MatType? sdepth = null) + public static void Integral(InputArray src, OutputArray sum, OutputArray sqsum, MatType? sdepth = null) { NativeMethods.HandleException( NativeMethods.imgproc_integral2(src.Proxy, sum.Proxy, sqsum.Proxy, sdepth?.Value ?? -1)); @@ -1138,7 +1138,7 @@ public static void Integral(InputArrayRef src, OutputArrayRef sum, OutputArrayRe /// desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or CV_64F. /// desired depth of the integral image of squared pixel values, CV_32F or CV_64F. public static void Integral( - InputArrayRef src, OutputArrayRef sum, OutputArrayRef sqsum, OutputArrayRef tilted, + InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, MatType? sdepth = null, MatType? sqdepth = null) { NativeMethods.HandleException( @@ -1156,7 +1156,7 @@ public static void Integral( /// Input image as 1- or 3-channel, 8-bit or 32-bit floating point. /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void Accumulate(InputArrayRef src, InputOutputArrayRef dst, InputArrayRef mask) + public static void Accumulate(InputArray src, InputOutputArray dst, InputArray mask) { NativeMethods.HandleException( NativeMethods.imgproc_accumulate(src.Proxy, dst.Proxy, mask.Proxy)); @@ -1172,7 +1172,7 @@ public static void Accumulate(InputArrayRef src, InputOutputArrayRef dst, InputA /// Input image as 1- or 3-channel, 8-bit or 32-bit floating point. /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void AccumulateSquare(InputArrayRef src, InputOutputArrayRef dst, InputArrayRef mask) + public static void AccumulateSquare(InputArray src, InputOutputArray dst, InputArray mask) { NativeMethods.HandleException( NativeMethods.imgproc_accumulateSquare(src.Proxy, dst.Proxy, mask.Proxy)); @@ -1189,7 +1189,7 @@ public static void AccumulateSquare(InputArrayRef src, InputOutputArrayRef dst, /// Second input image of the same type and the same size as src1 /// Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point. /// Optional operation mask. - public static void AccumulateProduct(InputArrayRef src1, InputArrayRef src2, InputOutputArrayRef dst, InputArrayRef mask) + public static void AccumulateProduct(InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask) { NativeMethods.HandleException( NativeMethods.imgproc_accumulateProduct(src1.Proxy, src2.Proxy, dst.Proxy, mask.Proxy)); @@ -1207,7 +1207,7 @@ public static void AccumulateProduct(InputArrayRef src1, InputArrayRef src2, Inp /// Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. /// Weight of the input image. /// Optional operation mask. - public static void AccumulateWeighted(InputArrayRef src, InputOutputArrayRef dst, double alpha, InputArrayRef mask) + public static void AccumulateWeighted(InputArray src, InputOutputArray dst, double alpha, InputArray mask) { NativeMethods.HandleException( NativeMethods.imgproc_accumulateWeighted(src.Proxy, dst.Proxy, alpha, mask.Proxy)); @@ -1231,8 +1231,8 @@ public static void AccumulateWeighted(InputArrayRef src, InputOutputArrayRef dst /// Floating point array with windowing coefficients to reduce edge effects (optional). /// Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). /// detected phase shift(sub-pixel) between the two arrays. - public static Point2d PhaseCorrelate(InputArrayRef src1, InputArrayRef src2, - InputArrayRef window, out double response) + public static Point2d PhaseCorrelate(InputArray src1, InputArray src2, + InputArray window, out double response) { NativeMethods.HandleException( NativeMethods.imgproc_phaseCorrelate(src1.Proxy, src2.Proxy, window.Proxy, out response, out var ret)); @@ -1249,7 +1249,7 @@ public static Point2d PhaseCorrelate(InputArrayRef src1, InputArrayRef src2, /// Destination array to place Hann coefficients in /// The window size specifications /// Created array type - public static void CreateHanningWindow(OutputArrayRef dst, Size winSize, MatType type) + public static void CreateHanningWindow(OutputArray dst, Size winSize, MatType type) { NativeMethods.HandleException( NativeMethods.imgproc_createHanningWindow(dst.Proxy, winSize, type)); @@ -1266,7 +1266,7 @@ public static void CreateHanningWindow(OutputArrayRef dst, Size winSize, MatType /// maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. /// thresholding type (see the details below). /// the computed threshold value when type == OTSU - public static double Threshold(InputArrayRef src, OutputArrayRef dst, double thresh, double maxval, ThresholdTypes type) + public static double Threshold(InputArray src, OutputArray dst, double thresh, double maxval, ThresholdTypes type) { NativeMethods.HandleException( NativeMethods.imgproc_threshold(src.Proxy, dst.Proxy, thresh, maxval, (int)type, out var ret)); @@ -1287,7 +1287,7 @@ public static double Threshold(InputArrayRef src, OutputArrayRef dst, double thr /// Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. /// Constant subtracted from the mean or weighted mean (see the details below). /// Normally, it is positive but may be zero or negative as well. - public static void AdaptiveThreshold(InputArrayRef src, OutputArrayRef dst, + public static void AdaptiveThreshold(InputArray src, OutputArray dst, double maxValue, AdaptiveThresholdTypes adaptiveMethod, ThresholdTypes thresholdType, int blockSize, double c) { NativeMethods.HandleException( @@ -1304,7 +1304,7 @@ public static void AdaptiveThreshold(InputArrayRef src, OutputArrayRef dst, /// output image; it has the specified size and the same type as src. /// size of the output image; by default, it is computed as Size((src.cols+1)/2 /// - public static void PyrDown(InputArrayRef src, OutputArrayRef dst, + public static void PyrDown(InputArray src, OutputArray dst, Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) { var dstSize0 = dstSize.GetValueOrDefault(new Size()); @@ -1322,7 +1322,7 @@ public static void PyrDown(InputArrayRef src, OutputArrayRef dst, /// /// /// - public static void BuildPyramid(InputArrayRef src, VectorOfMat dst,int maxlevel, + public static void BuildPyramid(InputArray src, VectorOfMat dst,int maxlevel, BorderTypes borderType = BorderTypes.Default) { if (dst is null) @@ -1342,7 +1342,7 @@ public static void BuildPyramid(InputArrayRef src, VectorOfMat dst,int maxlevel, /// output image. It has the specified size and the same type as src. /// size of the output image; by default, it is computed as Size(src.cols*2, (src.rows*2) /// - public static void PyrUp(InputArrayRef src, OutputArrayRef dst, + public static void PyrUp(InputArray src, OutputArray dst, Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) { var dstSize0 = dstSize.GetValueOrDefault(new Size()); @@ -1366,8 +1366,8 @@ public static void PyrUp(InputArrayRef src, OutputArrayRef dst, /// /// public static void CalcHist(Mat[] images, - int[] channels, InputArrayRef mask, - OutputArrayRef hist, int dims, int[] histSize, + int[] channels, InputArray mask, + OutputArray hist, int dims, int[] histSize, Rangef[] ranges, bool uniform = true, bool accumulate = false) { if (ranges is null) @@ -1390,8 +1390,8 @@ public static void CalcHist(Mat[] images, /// /// public static void CalcHist(Mat[] images, - int[] channels, InputArrayRef mask, - OutputArrayRef hist, int dims, int[] histSize, + int[] channels, InputArray mask, + OutputArray hist, int dims, int[] histSize, float[][] ranges, bool uniform = true, bool accumulate = false) { if (images is null) @@ -1426,7 +1426,7 @@ public static void CalcHist(Mat[] images, /// /// public static void CalcBackProject(Mat[] images, - int[] channels, InputArrayRef hist, OutputArrayRef backProject, + int[] channels, InputArray hist, OutputArray backProject, Rangef[] ranges, bool uniform = true) { if (images is null) @@ -1456,7 +1456,7 @@ public static void CalcBackProject(Mat[] images, /// The second compared histogram of the same size as h1 /// The comparison method /// - public static double CompareHist(InputArrayRef h1, InputArrayRef h2, HistCompMethods method) + public static double CompareHist(InputArray h1, InputArray h2, HistCompMethods method) { NativeMethods.HandleException( NativeMethods.imgproc_compareHist(h1.Proxy, h2.Proxy, (int)method, out var ret)); @@ -1471,7 +1471,7 @@ public static double CompareHist(InputArrayRef h1, InputArrayRef h2, HistCompMet /// /// The source 8-bit single channel image /// The destination image; will have the same size and the same type as src - public static void EqualizeHist(InputArrayRef src, OutputArrayRef dst) + public static void EqualizeHist(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.imgproc_equalizeHist(src.Proxy, dst.Proxy)); @@ -1511,7 +1511,7 @@ public static CLAHE CreateCLAHE(double clipLimit = 40.0, Size? tileGridSize = nu /// to either signature1 or signature2. The weights must be non-negative and have at least one non-zero value. /// Used metric. /// - public static float EMD(InputArrayRef signature1, InputArrayRef signature2, DistanceTypes distType) + public static float EMD(InputArray signature1, InputArray signature2, DistanceTypes distType) { return EMD(signature1, signature2, distType, default, out _); } @@ -1538,8 +1538,8 @@ public static float EMD(InputArrayRef signature1, InputArrayRef signature2, Dist /// User-defined size1 x size2 cost matrix. Also, if a cost matrix /// is used, lower boundary lowerBound cannot be calculated because it needs a metric function. /// - public static float EMD(InputArrayRef signature1, InputArrayRef signature2, - DistanceTypes distType, InputArrayRef cost) + public static float EMD(InputArray signature1, InputArray signature2, + DistanceTypes distType, InputArray cost) { return EMD(signature1, signature2, distType, cost, out _); } @@ -1576,8 +1576,8 @@ public static float EMD(InputArrayRef signature1, InputArrayRef signature2, /// Resultant size1 x size2 flow matrix: flow[i,j] is a flow from i-th point of signature1 /// to j-th point of signature2. /// - public static float EMD(InputArrayRef signature1, InputArrayRef signature2, - DistanceTypes distType, InputArrayRef cost, out float lowerBound, OutputArrayRef flow = default) + public static float EMD(InputArray signature1, InputArray signature2, + DistanceTypes distType, InputArray cost, out float lowerBound, OutputArray flow = default) { NativeMethods.HandleException( NativeMethods.imgproc_EMD( @@ -1597,7 +1597,7 @@ public static float EMD(InputArrayRef signature1, InputArrayRef signature2, /// Input 8-bit 3-channel image. /// Input/output 32-bit single-channel image (map) of markers. /// It should have the same size as image. - public static void Watershed(InputArrayRef image, InputOutputArrayRef markers) + public static void Watershed(InputArray image, InputOutputArray markers) { NativeMethods.HandleException( NativeMethods.imgproc_watershed(image.Proxy, markers.Proxy)); @@ -1615,7 +1615,7 @@ public static void Watershed(InputArrayRef image, InputOutputArrayRef markers) /// The color window radius. /// Maximum level of the pyramid for the segmentation. /// Termination criteria: when to stop meanshift iterations. - public static void PyrMeanShiftFiltering(InputArrayRef src, OutputArrayRef dst, + public static void PyrMeanShiftFiltering(InputArray src, OutputArray dst, double sp, double sr, int maxLevel = 1, TermCriteria? termcrit = null) { var termcrit0 = termcrit.GetValueOrDefault( @@ -1641,8 +1641,8 @@ public static void PyrMeanShiftFiltering(InputArrayRef src, OutputArrayRef dst, /// Number of iterations the algorithm should make before returning the result. /// Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL . /// Operation mode that could be one of GrabCutFlag value. - public static void GrabCut(InputArrayRef img, InputOutputArrayRef mask, Rect rect, - InputOutputArrayRef bgdModel, InputOutputArrayRef fgdModel, + public static void GrabCut(InputArray img, InputOutputArray mask, Rect rect, + InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, GrabCutModes mode) { NativeMethods.HandleException( @@ -1669,9 +1669,9 @@ public static void GrabCut(InputArrayRef img, InputOutputArrayRef mask, Rect rec /// #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, /// the parameter is forced to 3 because a 3x3 mask gives the same result as 5x5 or any larger aperture. /// Type of the label array to build - public static void DistanceTransformWithLabels(InputArrayRef src, - OutputArrayRef dst, - OutputArrayRef labels, + public static void DistanceTransformWithLabels(InputArray src, + OutputArray dst, + OutputArray labels, DistanceTypes distanceType, DistanceTransformMasks maskSize, DistanceTransformLabelTypes labelType = DistanceTransformLabelTypes.CComp) @@ -1697,8 +1697,8 @@ public static void DistanceTransformWithLabels(InputArrayRef src, /// the same result as 5x5 or any larger aperture. /// Type of output image. It can be MatType.CV_8U or MatType.CV_32F. /// Type CV_8U can be used only for the first variant of the function and distanceType == #DIST_L1. - public static void DistanceTransform(InputArrayRef src, - OutputArrayRef dst, + public static void DistanceTransform(InputArray src, + OutputArray dst, DistanceTypes distanceType, DistanceTransformMasks maskSize, int dstType = MatType.CV_32S) @@ -1719,7 +1719,7 @@ public static void DistanceTransform(InputArrayRef src, /// Starting point. /// New value of the repainted domain pixels. /// - public static int FloodFill(InputOutputArrayRef image, Point seedPoint, Scalar newVal) + public static int FloodFill(InputOutputArray image, Point seedPoint, Scalar newVal) { return FloodFill(image, seedPoint, newVal, out _); } @@ -1745,7 +1745,7 @@ public static int FloodFill(InputOutputArrayRef image, Point seedPoint, Scalar n /// neighbors of a pixel are considered. Using FloodFillFlags.MaskOnly will /// fill in the mask using the grey value 255 (white). /// - public static int FloodFill(InputOutputArrayRef image, + public static int FloodFill(InputOutputArray image, Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4) @@ -1781,7 +1781,7 @@ public static int FloodFill(InputOutputArrayRef image, /// Starting point. /// New value of the repainted domain pixels. /// - public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, + public static int FloodFill(InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal) { return FloodFill(image, mask, seedPoint, newVal, out _); @@ -1813,7 +1813,7 @@ public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, /// neighbors of a pixel are considered. Using FloodFillFlags.MaskOnly will /// fill in the mask using the grey value 255 (white). /// - public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, + public static int FloodFill(InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4) @@ -1845,8 +1845,8 @@ public static int FloodFill(InputOutputArrayRef image, InputOutputArrayRef mask, /// It has a type of CV_32FC1 and the same size with src1. /// It has a type of CV_32FC1 and the same size with src1. /// It is created if it does not have the same size and type with src1. - public static void BlendLinear(InputArrayRef src1, InputArrayRef src2, InputArrayRef weights1, InputArrayRef weights2, - OutputArrayRef dst) + public static void BlendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, + OutputArray dst) { NativeMethods.HandleException( NativeMethods.imgproc_blendLinear(src1.Proxy, src2.Proxy, weights1.Proxy, weights2.Proxy, dst.Proxy)); @@ -1865,7 +1865,7 @@ public static void BlendLinear(InputArrayRef src1, InputArrayRef src2, InputArra /// The color space conversion code /// The number of channels in the destination image; if the parameter is 0, the number of the channels will be derived automatically from src and the code /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void CvtColor(InputArrayRef src, OutputArrayRef dst, ColorConversionCodes code, int dstCn = 0, + public static void CvtColor(InputArray src, OutputArray dst, ColorConversionCodes code, int dstCn = 0, AlgorithmHint hint = AlgorithmHint.Default) { NativeMethods.HandleException( @@ -1892,7 +1892,7 @@ public static void CvtColor(InputArrayRef src, OutputArrayRef dst, ColorConversi /// - #COLOR_YUV2BGRA_NV21 /// - #COLOR_YUV2RGBA_NV21 /// Hint that selects between alternative algorithm implementations (OpenCV 5). - public static void CvtColorTwoPlane(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst, ColorConversionCodes code, + public static void CvtColorTwoPlane(InputArray src1, InputArray src2, OutputArray dst, ColorConversionCodes code, AlgorithmHint hint = AlgorithmHint.Default) { NativeMethods.HandleException( @@ -1931,7 +1931,7 @@ public static void CvtColorTwoPlane(InputArrayRef src1, InputArrayRef src2, Outp /// /// # COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA /// - public static void Demosaicing(InputArrayRef src, OutputArrayRef dst, ColorConversionCodes code, int dstCn = 0) + public static void Demosaicing(InputArray src, OutputArray dst, ColorConversionCodes code, int dstCn = 0) { NativeMethods.HandleException( NativeMethods.imgproc_demosaicing(src.Proxy, dst.Proxy, (int)code, dstCn)); @@ -1948,7 +1948,7 @@ public static void Demosaicing(InputArrayRef src, OutputArrayRef dst, ColorConve /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - public static Moments Moments(InputArrayRef array, bool binaryImage = false) + public static Moments Moments(InputArray array, bool binaryImage = false) { return new (array, binaryImage); } @@ -2011,11 +2011,11 @@ public static Moments Moments(IEnumerable array, bool binaryImage = fal /// Specifies the comparison method /// Mask of searched template. It must have the same datatype and size with templ. It is not set by default. public static void MatchTemplate( - InputArrayRef image, - InputArrayRef templ, - OutputArrayRef result, + InputArray image, + InputArray templ, + OutputArray result, TemplateMatchModes method, - InputArrayRef mask = default) + InputArray mask = default) { NativeMethods.HandleException( NativeMethods.imgproc_matchTemplate(image.Proxy, templ.Proxy, result.Proxy, (int) method, mask.Proxy)); @@ -2045,7 +2045,7 @@ public static void MatchTemplate( /// connected components algorithm type. /// public static int ConnectedComponentsWithAlgorithm( - InputArrayRef image, OutputArrayRef labels, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) + InputArray image, OutputArray labels, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) { NativeMethods.HandleException( NativeMethods.imgproc_connectedComponentsWithAlgorithm( @@ -2067,7 +2067,7 @@ public static int ConnectedComponentsWithAlgorithm( /// destination labeled image /// 8 or 4 for 8-way or 4-way connectivity respectively /// The number of labels - public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels, + public static int ConnectedComponents(InputArray image, OutputArray labels, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) { return ConnectedComponents(image, labels, connectivity, MatType.CV_32S); @@ -2085,7 +2085,7 @@ public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels /// 8 or 4 for 8-way or 4-way connectivity respectively /// output image label type. Currently CV_32S and CV_16U are supported. /// The number of labels - public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels, + public static int ConnectedComponents(InputArray image, OutputArray labels, PixelConnectivity connectivity, MatType ltype) { @@ -2109,7 +2109,7 @@ public static int ConnectedComponents(InputArrayRef image, OutputArrayRef labels /// destination labeled rectangular array /// 8 or 4 for 8-way or 4-way connectivity respectively /// The number of labels - public static int ConnectedComponents(InputArrayRef image, out int[,] labels, PixelConnectivity connectivity) + public static int ConnectedComponents(InputArray image, out int[,] labels, PixelConnectivity connectivity) { using var labelsMat = new Mat(); var result = ConnectedComponents(image, labelsMat, connectivity, MatType.CV_32S); @@ -2140,10 +2140,10 @@ public static int ConnectedComponents(InputArrayRef image, out int[,] labels, Pi /// connected components algorithm type. /// public static int ConnectedComponentsWithStatsWithAlgorithm( - InputArrayRef image, - OutputArrayRef labels, - OutputArrayRef stats, - OutputArrayRef centroids, + InputArray image, + OutputArray labels, + OutputArray stats, + OutputArray centroids, PixelConnectivity connectivity, MatType ltype, ConnectedComponentsAlgorithmsTypes ccltype) @@ -2176,8 +2176,8 @@ public static int ConnectedComponentsWithStatsWithAlgorithm( /// 8 or 4 for 8-way or 4-way connectivity respectively /// public static int ConnectedComponentsWithStats( - InputArrayRef image, OutputArrayRef labels, - OutputArrayRef stats, OutputArrayRef centroids, + InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) { return ConnectedComponentsWithStats(image, labels, stats, centroids, connectivity, MatType.CV_32S); @@ -2201,8 +2201,8 @@ public static int ConnectedComponentsWithStats( /// output image label type. Currently CV_32S and CV_16U are supported. /// public static int ConnectedComponentsWithStats( - InputArrayRef image, OutputArrayRef labels, - OutputArrayRef stats, OutputArrayRef centroids, + InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, PixelConnectivity connectivity, MatType ltype) { @@ -2229,7 +2229,7 @@ public static int ConnectedComponentsWithStats( /// /// public static ConnectedComponents ConnectedComponentsEx( - InputArrayRef image, + InputArray image, PixelConnectivity connectivity = PixelConnectivity.Connectivity8, ConnectedComponentsAlgorithmsTypes ccltype = ConnectedComponentsAlgorithmsTypes.Default) { @@ -2275,7 +2275,7 @@ public static ConnectedComponents ConnectedComponentsEx( /// Contour approximation method /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public static void FindContours(InputArrayRef image, out Point[][] contours, + public static void FindContours(InputArray image, out Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { var offset0 = offset.GetValueOrDefault(new Point()); @@ -2308,8 +2308,8 @@ public static void FindContours(InputArrayRef image, out Point[][] contours, /// Contour approximation method /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. - public static void FindContours(InputArrayRef image, out Mat[] contours, - OutputArrayRef hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + public static void FindContours(InputArray image, out Mat[] contours, + OutputArray hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { var offset0 = offset.GetValueOrDefault(new Point()); using var contoursVec = new VectorOfMat(); @@ -2333,7 +2333,7 @@ public static void FindContours(InputArrayRef image, out Mat[] contours, /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. /// Detected contours. Each contour is stored as a vector of points. - public static Point[][] FindContoursAsArray(InputArrayRef image, + public static Point[][] FindContoursAsArray(InputArray image, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { var offset0 = offset.GetValueOrDefault(new Point()); @@ -2347,14 +2347,14 @@ public static Point[][] FindContoursAsArray(InputArrayRef image, /// /// Finds contours in a binary image using the link-runs algorithm (OpenCV 5). This is an - /// alternative to + /// alternative to /// with reduced memory consumption; it always uses the equivalent of RETR_CCOMP retrieval. /// /// Source, an 8-bit single-channel binary image. /// Detected contours. Each contour is stored as a vector of points. /// Output vector containing information about the image topology /// (next/previous/first-child/parent indices for each contour). - public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] contours, out HierarchyIndex[] hierarchy) + public static void FindContoursLinkRuns(InputArray image, out Point[][] contours, out HierarchyIndex[] hierarchy) { using var contoursVec = new VectorOfVectorPoint(); using var hierarchyVec = new StdVector(); @@ -2371,7 +2371,7 @@ public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] conto /// /// Source, an 8-bit single-channel binary image. /// Detected contours. Each contour is stored as a vector of points. - public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] contours) + public static void FindContoursLinkRuns(InputArray image, out Point[][] contours) { using var contoursVec = new VectorOfVectorPoint(); NativeMethods.HandleException( @@ -2392,7 +2392,7 @@ public static void FindContoursLinkRuns(InputArrayRef image, out Point[][] conto /// Optional offset by which every contour point is shifted. /// This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. /// Detected contours. Each contour is stored as a vector of points. - public static Mat[] FindContoursAsMat(InputArrayRef image, + public static Mat[] FindContoursAsMat(InputArray image, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) { var offset0 = offset.GetValueOrDefault(new Point()); @@ -2415,7 +2415,7 @@ public static Mat[] FindContoursAsMat(InputArrayRef image, /// This is the maximum distance between the original curve and its approximation. /// The result of the approximation; /// The type should match the type of the input curve - public static void ApproxPolyDP(InputArrayRef curve, OutputArrayRef approxCurve, double epsilon, bool closed) + public static void ApproxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed) { NativeMethods.HandleException( NativeMethods.imgproc_approxPolyDP_InputArray(curve.Proxy, approxCurve.Proxy, epsilon, closed ? 1 : 0)); @@ -2476,7 +2476,7 @@ public static Point2f[] ApproxPolyDP(IEnumerable curve, double epsilon, /// The input vector of 2D points, represented by CV_32SC2 or CV_32FC2 matrix. /// Indicates, whether the curve is closed or not. /// - public static double ArcLength(InputArrayRef curve, bool closed) + public static double ArcLength(InputArray curve, bool closed) { NativeMethods.HandleException( NativeMethods.imgproc_arcLength_InputArray(curve.Proxy, closed ? 1 : 0, out var ret)); @@ -2523,7 +2523,7 @@ public static double ArcLength(IEnumerable curve, bool closed) /// /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// Minimal up-right bounding rectangle for the specified point set. - public static Rect BoundingRect(InputArrayRef curve) + public static Rect BoundingRect(InputArray curve) { NativeMethods.HandleException( NativeMethods.imgproc_boundingRect_InputArray(curve.Proxy, out var ret)); @@ -2569,7 +2569,7 @@ public static Rect BoundingRect(IEnumerable curve) /// The contour vertices, represented by CV_32SC2 or CV_32FC2 matrix /// /// - public static double ContourArea(InputArrayRef contour, bool oriented = false) + public static double ContourArea(InputArray contour, bool oriented = false) { NativeMethods.HandleException( NativeMethods.imgproc_contourArea_InputArray(contour.Proxy, oriented ? 1 : 0, out var ret)); @@ -2616,7 +2616,7 @@ public static double ContourArea(IEnumerable contour, bool oriented = f /// /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// - public static RotatedRect MinAreaRect(InputArrayRef points) + public static RotatedRect MinAreaRect(InputArray points) { NativeMethods.HandleException( NativeMethods.imgproc_minAreaRect_InputArray(points.Proxy, out var ret)); @@ -2666,7 +2666,7 @@ public static RotatedRect MinAreaRect(IEnumerable points) /// The input rotated rectangle. It may be the output of /// The output array of four vertices of rectangles. /// - public static void BoxPoints(RotatedRect box, OutputArrayRef points) + public static void BoxPoints(RotatedRect box, OutputArray points) { NativeMethods.HandleException( NativeMethods.imgproc_boxPoints_OutputArray(box, points.Proxy)); @@ -2695,7 +2695,7 @@ public static Point2f[] BoxPoints(RotatedRect box) /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. /// The output center of the circle /// The output radius of the circle - public static void MinEnclosingCircle(InputArrayRef points, out Point2f center, out float radius) + public static void MinEnclosingCircle(InputArray points, out Point2f center, out float radius) { NativeMethods.HandleException( NativeMethods.imgproc_minEnclosingCircle_InputArray(points.Proxy, out center, out radius)); @@ -2738,7 +2738,7 @@ public static void MinEnclosingCircle(IEnumerable points, out Point2f c /// Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector or Mat /// Output vector of three 2D points defining the vertices of the triangle. The depth /// Triangle area - public static double MinEnclosingTriangle(InputArrayRef points, OutputArrayRef triangle) + public static double MinEnclosingTriangle(InputArray points, OutputArray triangle) { NativeMethods.HandleException( NativeMethods.imgproc_minEnclosingTriangle_InputOutputArray(points.Proxy, triangle.Proxy, out var ret)); @@ -2799,7 +2799,7 @@ public static double MinEnclosingTriangle(IEnumerable points, out Point /// Comparison method /// Method-specific parameter (not supported now) /// - public static double MatchShapes(InputArrayRef contour1, InputArrayRef contour2, ShapeMatchModes method, double parameter = 0) + public static double MatchShapes(InputArray contour1, InputArray contour2, ShapeMatchModes method, double parameter = 0) { NativeMethods.HandleException( NativeMethods.imgproc_matchShapes_InputArray(contour1.Proxy, contour2.Proxy, (int)method, parameter, out var ret)); @@ -2848,7 +2848,7 @@ public static double MatchShapes(IEnumerable contour1, IEnumerable /// system is assumed - the origin is at the top-left corner, x axis is oriented to the right, /// and y axis is oriented downwards. /// - public static void ConvexHull(InputArrayRef points, OutputArrayRef hull, bool clockwise = false, bool returnPoints = true) + public static void ConvexHull(InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true) { NativeMethods.HandleException( NativeMethods.imgproc_convexHull_InputArray(points.Proxy, hull.Proxy, clockwise ? 1 : 0, returnPoints ? 1 : 0)); @@ -2965,7 +2965,7 @@ public static int[] ConvexHullIndices(IEnumerable points, bool clockwis /// (with 8 fractional bits) of the distance between the farthest contour point and the hull. /// That is, to get the floating-point value of the depth will be fixpt_depth/256.0. /// - public static void ConvexityDefects(InputArrayRef contour, InputArrayRef convexHull, OutputArrayRef convexityDefects) + public static void ConvexityDefects(InputArray contour, InputArray convexHull, OutputArray convexityDefects) { NativeMethods.HandleException( NativeMethods.imgproc_convexityDefects_InputArray(contour.Proxy, convexHull.Proxy, convexityDefects.Proxy)); @@ -3042,7 +3042,7 @@ public static Vec4i[] ConvexityDefects(IEnumerable contour, IEnumerable /// /// Input vector of 2D points /// - public static bool IsContourConvex(InputArrayRef contour) + public static bool IsContourConvex(InputArray contour) { NativeMethods.HandleException( NativeMethods.imgproc_isContourConvex_InputArray(contour.Proxy, out var ret)); @@ -3093,7 +3093,7 @@ public static bool IsContourConvex(IEnumerable contour) /// /// /// - public static float IntersectConvexConvex(InputArrayRef p1, InputArrayRef p2, OutputArrayRef p12, bool handleNested = true) + public static float IntersectConvexConvex(InputArray p1, InputArray p2, OutputArray p12, bool handleNested = true) { NativeMethods.HandleException( NativeMethods.imgproc_intersectConvexConvex_InputArray( @@ -3167,7 +3167,7 @@ public static float IntersectConvexConvex(IEnumerable p1, IEnumerable

/// Input 2D point set /// - public static RotatedRect FitEllipse(InputArrayRef points) + public static RotatedRect FitEllipse(InputArray points) { NativeMethods.HandleException( NativeMethods.imgproc_fitEllipse_InputArray(points.Proxy, out var ret)); @@ -3217,7 +3217,7 @@ public static RotatedRect FitEllipse(IEnumerable points) ///

/// Input 2D point set /// - public static RotatedRect FitEllipseAMS(InputArrayRef points) + public static RotatedRect FitEllipseAMS(InputArray points) { NativeMethods.HandleException( NativeMethods.imgproc_fitEllipseAMS_InputArray(points.Proxy, out var ret)); @@ -3275,7 +3275,7 @@ public static RotatedRect FitEllipseAMS(IEnumerable points) ///
/// Input 2D point set /// - public static RotatedRect FitEllipseDirect(InputArrayRef points) + public static RotatedRect FitEllipseDirect(InputArray points) { NativeMethods.HandleException( NativeMethods.imgproc_fitEllipseDirect_InputArray(points.Proxy, out var ret)); @@ -3342,7 +3342,7 @@ public static RotatedRect FitEllipseDirect(IEnumerable points) /// (distance between the coordinate origin and the line). /// Sufficient accuracy for the angle. /// 0.01 would be a good default value for reps and aeps. - public static void FitLine(InputArrayRef points, OutputArrayRef line, DistanceTypes distType, + public static void FitLine(InputArray points, OutputArray line, DistanceTypes distType, double param, double reps, double aeps) { NativeMethods.HandleException( @@ -3460,7 +3460,7 @@ public static Line3D FitLine(IEnumerable points, DistanceTypes distType /// /// /// - public static double PointPolygonTest(InputArrayRef contour, Point2f pt, bool measureDist) + public static double PointPolygonTest(InputArray contour, Point2f pt, bool measureDist) { NativeMethods.HandleException( NativeMethods.imgproc_pointPolygonTest_InputArray( @@ -3523,7 +3523,7 @@ public static double PointPolygonTest(IEnumerable contour, Point2f pt, /// Stored as std::vector<cv::Point2f> or cv::Mat as Mx1 of type CV_32FC2. /// public static RectanglesIntersectTypes RotatedRectangleIntersection( - RotatedRect rect1, RotatedRect rect2, OutputArrayRef intersectingRegion) + RotatedRect rect1, RotatedRect rect2, OutputArray intersectingRegion) { NativeMethods.HandleException( NativeMethods.imgproc_rotatedRectangleIntersection_OutputArray( @@ -3565,7 +3565,7 @@ public static RectanglesIntersectTypes RotatedRectangleIntersection( /// The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. /// The result is the colormapped source image. Note: Mat::create is called on dst. /// colormap The colormap to apply - public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, ColormapTypes colormap) + public static void ApplyColorMap(InputArray src, OutputArray dst, ColormapTypes colormap) { NativeMethods.HandleException( NativeMethods.imgproc_applyColorMap1(src.Proxy, dst.Proxy, (int) colormap)); @@ -3580,7 +3580,7 @@ public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, Colormap /// The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. /// The result is the colormapped source image. Note: Mat::create is called on dst. /// The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 - public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, InputArrayRef userColor) + public static void ApplyColorMap(InputArray src, OutputArray dst, InputArray userColor) { NativeMethods.HandleException( NativeMethods.imgproc_applyColorMap2(src.Proxy, dst.Proxy, userColor.Proxy)); @@ -3603,7 +3603,7 @@ public static void ApplyColorMap(InputArrayRef src, OutputArrayRef dst, InputArr /// Line thickness. [By default this is 1] /// Type of the line. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] - public static void Line(InputOutputArrayRef img, int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, + public static void Line(InputOutputArray img, int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { Line(img, new Point(pt1X, pt1Y), new Point(pt2X, pt2Y), color, thickness, lineType, shift); @@ -3620,7 +3620,7 @@ public static void Line(InputOutputArrayRef img, int pt1X, int pt1Y, int pt2X, i /// Type of the line. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Line( - InputOutputArrayRef img, Point pt1, Point pt2, Scalar color, int thickness = 1, + InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -3643,7 +3643,7 @@ public static void Line( /// Number of fractional bits in the point coordinates. /// The length of the arrow tip in relation to the arrow length public static void ArrowedLine( - InputOutputArrayRef img, + InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, @@ -3669,7 +3669,7 @@ public static void ArrowedLine( /// Type of the line, see cvLine description. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Rectangle( - InputOutputArrayRef img, Point pt1, Point pt2, Scalar color, int thickness = 1, + InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -3690,7 +3690,7 @@ public static void Rectangle( /// Type of the line, see cvLine description. [By default this is LineType.Link8] /// Number of fractional bits in the point coordinates. [By default this is 0] public static void Rectangle( - InputOutputArrayRef img, Rect rect, Scalar color, int thickness = 1, + InputOutputArray img, Rect rect, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -3754,7 +3754,7 @@ public static void Rectangle( /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] /// Type of the circle boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public static void Circle(InputOutputArrayRef img, int centerX, int centerY, int radius, Scalar color, + public static void Circle(InputOutputArray img, int centerX, int centerY, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { Circle(img, new Point(centerX, centerY), radius, color, thickness, lineType, shift); @@ -3770,7 +3770,7 @@ public static void Circle(InputOutputArrayRef img, int centerX, int centerY, int /// Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1] /// Type of the circle boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and radius value. [By default this is 0] - public static void Circle(InputOutputArrayRef img, Point center, int radius, Scalar color, + public static void Circle(InputOutputArray img, Point center, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -3792,7 +3792,7 @@ public static void Circle(InputOutputArrayRef img, Point center, int radius, Sca /// Type of the ellipse boundary. [By default this is LineType.Link8] /// Number of fractional bits in the center coordinates and axes' values. [By default this is 0] public static void Ellipse( - InputOutputArrayRef img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, + InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -3810,7 +3810,7 @@ public static void Ellipse( /// Ellipse color. /// Thickness of the ellipse boundary. [By default this is 1] /// Type of the ellipse boundary. [By default this is LineType.Link8] - public static void Ellipse(InputOutputArrayRef img, RotatedRect box, Scalar color, + public static void Ellipse(InputOutputArray img, RotatedRect box, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8) { NativeMethods.HandleException( @@ -3832,7 +3832,7 @@ public static void Ellipse(InputOutputArrayRef img, RotatedRect box, Scalar colo /// Line thickness. /// Type of the line. public static void DrawMarker( - InputOutputArrayRef img, Point position, Scalar color, + InputOutputArray img, Point position, Scalar color, MarkerTypes markerType = MarkerTypes.Cross, int markerSize = 20, int thickness = 1, LineTypes lineType = LineTypes.Link8) { NativeMethods.HandleException( @@ -3872,7 +3872,7 @@ public static void FillConvexPoly(Mat img, IEnumerable pts, Scalar color, /// Polygon color /// Type of the polygon boundaries /// The number of fractional bits in the vertex coordinates - public static void FillConvexPoly(InputOutputArrayRef img, InputArrayRef pts, Scalar color, + public static void FillConvexPoly(InputOutputArray img, InputArray pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0) { @@ -3932,7 +3932,7 @@ public static void FillPoly( /// The number of fractional bits in the vertex coordinates /// public static void FillPoly( - InputOutputArrayRef img, InputArrayRef pts, Scalar color, + InputOutputArray img, InputArray pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null) { var offset0 = offset.GetValueOrDefault(new Point()); @@ -3997,7 +3997,7 @@ public static void Polylines( /// /// public static void Polylines( - InputOutputArrayRef img, InputArrayRef pts, bool isClosed, Scalar color, + InputOutputArray img, InputArray pts, bool isClosed, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) { NativeMethods.HandleException( @@ -4024,7 +4024,7 @@ public static void Polylines( /// when there is hierarchy available. /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) public static void DrawContours( - InputOutputArrayRef image, + InputOutputArray image, IEnumerable> contours, int contourIdx, Scalar color, @@ -4078,13 +4078,13 @@ public static void DrawContours( /// when there is hierarchy available. /// Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy) public static void DrawContours( - InputOutputArrayRef image, + InputOutputArray image, IEnumerable contours, int contourIdx, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, - InputArrayRef hierarchy = default, + InputArray hierarchy = default, int maxLevel = int.MaxValue, Point? offset = null) { @@ -4186,7 +4186,7 @@ public static Point2d[] Ellipse2Poly(Point2d center, Size2d axes, int angle, /// Line type. See #LineTypes /// When true, the image data origin is at the bottom-left corner. /// Otherwise, it is at the top-left corner. - public static void PutText(InputOutputArrayRef img, string text, Point org, + public static void PutText(InputOutputArray img, string text, Point org, HersheyFonts fontFace, double fontScale, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, bool bottomLeftOrigin = false) { @@ -4249,7 +4249,7 @@ public static double GetFontScaleFromHeight(HersheyFonts fontFace, int pixelHeig /// Optional text wrapping range. Null uses the default behavior. /// The coordinates in pixels from where the text can be continued. public static Point PutText( - InputOutputArrayRef img, string text, Point org, Scalar color, FontFace fontFace, int size, + InputOutputArray img, string text, Point org, Scalar color, FontFace fontFace, int size, int weight = 0, PutTextFlags flags = PutTextFlags.AlignLeft, Range? wrap = null) { if (text is null) @@ -4317,8 +4317,8 @@ public static Rect GetTextSize( /// This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. /// OX is drawn in red, OY in green and OZ in blue. public static void DrawFrameAxes( - InputOutputArrayRef image, InputArrayRef cameraMatrix, InputArrayRef distCoeffs, - InputArrayRef rvec, InputArrayRef tvec, float length, int thickness = 3) + InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, + InputArray rvec, InputArray tvec, float length, int thickness = 3) { NativeMethods.HandleException( NativeMethods.imgproc_drawFrameAxes( @@ -4342,10 +4342,10 @@ public static void DrawFrameAxes( /// Camera matrix of the distorted image. /// By default, it is the same as cameraMatrix but you may additionally scale /// and shift the result by using a different matrix. - public static void Undistort(InputArrayRef src, OutputArrayRef dst, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, - InputArrayRef newCameraMatrix = default) + public static void Undistort(InputArray src, OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray newCameraMatrix = default) { NativeMethods.HandleException( NativeMethods.imgproc_undistort(src.Proxy, dst.Proxy, cameraMatrix.Proxy, @@ -4370,9 +4370,9 @@ public static void Undistort(InputArrayRef src, OutputArrayRef dst, /// /// public static void InitUndistortRectifyMap( - InputArrayRef cameraMatrix, InputArrayRef distCoeffs, - InputArrayRef r, InputArrayRef newCameraMatrix, - Size size, MatType m1Type, OutputArrayRef map1, OutputArrayRef map2) + InputArray cameraMatrix, InputArray distCoeffs, + InputArray r, InputArray newCameraMatrix, + Size size, MatType m1Type, OutputArray map1, OutputArray map2) { NativeMethods.HandleException( NativeMethods.imgproc_initUndistortRectifyMap( @@ -4400,9 +4400,9 @@ public static void InitUndistortRectifyMap( /// /// public static float InitWideAngleProjMap( - InputArrayRef cameraMatrix, InputArrayRef distCoeffs, + InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, int destImageWidth, MatType m1Type, - OutputArrayRef map1, OutputArrayRef map2, + OutputArray map1, OutputArray map2, ProjectionType projType, double alpha = 0) { NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Cv2/Cv2_objdetect.cs b/src/OpenCvSharp/Cv2/Cv2_objdetect.cs index 3d0bb5331..a1078d1ff 100644 --- a/src/OpenCvSharp/Cv2/Cv2_objdetect.cs +++ b/src/OpenCvSharp/Cv2/Cv2_objdetect.cs @@ -143,7 +143,7 @@ private static void ClearAndAddRange(ICollection list, IEnumerable valu /// /// /// - public static bool CheckChessboard(InputArrayRef img, Size size) + public static bool CheckChessboard(InputArray img, Size size) { NativeMethods.HandleException( NativeMethods.objdetect_checkChessboard(img.Proxy, size, out var ret)); @@ -161,7 +161,7 @@ public static bool CheckChessboard(InputArrayRef img, Size size) /// flags Various operation flags that can be zero or a combination of the ChessboardFlags values. /// public static bool FindChessboardCornersSB( - InputArrayRef image, Size patternSize, OutputArrayRef corners, ChessboardFlags flags = 0) + InputArray image, Size patternSize, OutputArray corners, ChessboardFlags flags = 0) { NativeMethods.HandleException( NativeMethods.objdetect_findChessboardCornersSB_OutputArray( @@ -182,7 +182,7 @@ public static bool FindChessboardCornersSB( /// flags Various operation flags that can be zero or a combination of the ChessboardFlags values. /// public static bool FindChessboardCornersSB( - InputArrayRef image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = 0) + InputArray image, Size patternSize, out Point2f[] corners, ChessboardFlags flags = 0) { using var cornersVec = new StdVector(); NativeMethods.HandleException( @@ -201,7 +201,7 @@ public static bool FindChessboardCornersSB( /// /// /// - public static bool Find4QuadCornerSubpix(InputArrayRef img, InputOutputArrayRef corners, Size regionSize) + public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size regionSize) { NativeMethods.HandleException( NativeMethods.objdetect_find4QuadCornerSubpix_InputArray( @@ -216,7 +216,7 @@ public static bool Find4QuadCornerSubpix(InputArrayRef img, InputOutputArrayRef /// /// /// - public static bool Find4QuadCornerSubpix(InputArrayRef img, Point2f[] corners, Size regionSize) + public static bool Find4QuadCornerSubpix(InputArray img, Point2f[] corners, Size regionSize) { if (corners is null) throw new ArgumentNullException(nameof(corners)); @@ -243,8 +243,8 @@ public static bool Find4QuadCornerSubpix(InputArrayRef img, Point2f[] corners, S /// Number of inner corners per a chessboard row and column (patternSize = cv::Size(points_per_row,points_per_column)). /// Array of detected corners, the output of findChessboardCorners. /// Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here. - public static void DrawChessboardCorners(InputOutputArrayRef image, Size patternSize, - InputArrayRef corners, bool patternWasFound) + public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, + InputArray corners, bool patternWasFound) { NativeMethods.HandleException( NativeMethods.objdetect_drawChessboardCorners_InputArray( @@ -260,7 +260,7 @@ public static void DrawChessboardCorners(InputOutputArrayRef image, Size pattern /// Array of detected corners, the output of findChessboardCorners. /// Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here. [SuppressMessage("Maintainability", "CA1508: Avoid dead conditional code")] - public static void DrawChessboardCorners(InputOutputArrayRef image, Size patternSize, + public static void DrawChessboardCorners(InputOutputArray image, Size patternSize, IEnumerable corners, bool patternWasFound) { if (corners is null) diff --git a/src/OpenCvSharp/Cv2/Cv2_photo.cs b/src/OpenCvSharp/Cv2/Cv2_photo.cs index 3a4349efa..63a690a0d 100644 --- a/src/OpenCvSharp/Cv2/Cv2_photo.cs +++ b/src/OpenCvSharp/Cv2/Cv2_photo.cs @@ -12,8 +12,8 @@ static partial class Cv2 /// Output image with the same size and type as src. /// Radius of a circular neighborhood of each point inpainted that is considered by the algorithm. /// Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA - public static void Inpaint(InputArrayRef src, InputArrayRef inpaintMask, - OutputArrayRef dst, double inpaintRadius, InpaintTypes flags) + public static void Inpaint(InputArray src, InputArray inpaintMask, + OutputArray dst, double inpaintRadius, InpaintTypes flags) { NativeMethods.HandleException( NativeMethods.photo_inpaint(src.Proxy, inpaintMask.Proxy, dst.Proxy, inpaintRadius, (int)flags)); @@ -36,7 +36,7 @@ public static void Inpaint(InputArrayRef src, InputArrayRef inpaintMask, /// /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels - public static void FastNlMeansDenoising(InputArrayRef src, OutputArrayRef dst, float h = 3, + public static void FastNlMeansDenoising(InputArray src, OutputArray dst, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) { NativeMethods.HandleException( @@ -59,7 +59,7 @@ public static void FastNlMeansDenoising(InputArrayRef src, OutputArrayRef dst, f /// /// Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. /// Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels - public static void FastNlMeansDenoisingColored(InputArrayRef src, OutputArrayRef dst, + public static void FastNlMeansDenoisingColored(InputArray src, OutputArray dst, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) { @@ -85,7 +85,7 @@ public static void FastNlMeansDenoisingColored(InputArrayRef src, OutputArrayRef /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels public static void FastNlMeansDenoisingMulti( - IEnumerable srcImgs, OutputArrayRef dst, + IEnumerable srcImgs, OutputArray dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, int templateWindowSize = 7, int searchWindowSize = 21) { @@ -119,7 +119,7 @@ public static void FastNlMeansDenoisingMulti( /// Size in pixels of the window that is used to compute weighted average for given pixel. /// Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels public static void FastNlMeansDenoisingColoredMulti( - IEnumerable srcImgs, OutputArrayRef dst, + IEnumerable srcImgs, OutputArray dst, int imgToDenoiseIndex, int temporalWindowSize, float h = 3, float hColor = 3, int templateWindowSize = 7, int searchWindowSize = 21) { @@ -177,7 +177,7 @@ public static void DenoiseTVL1( /// Output 8-bit 1-channel image. /// Output 8-bit 3-channel image. public static void Decolor( - InputArrayRef src, OutputArrayRef grayscale, OutputArrayRef colorBoost) + InputArray src, OutputArray grayscale, OutputArray colorBoost) { NativeMethods.HandleException( NativeMethods.photo_decolor(src.Proxy, grayscale.Proxy, colorBoost.Proxy)); @@ -200,8 +200,8 @@ public static void Decolor( /// Output image with the same size and type as dst. /// Cloning method public static void SeamlessClone( - InputArrayRef src, InputArrayRef dst, InputArrayRef mask, Point p, - OutputArrayRef blend, SeamlessCloneFlags flags) + InputArray src, InputArray dst, InputArray mask, Point p, + OutputArray blend, SeamlessCloneFlags flags) { NativeMethods.HandleException( NativeMethods.photo_seamlessClone( @@ -223,7 +223,7 @@ public static void SeamlessClone( /// G-channel multiply factor. /// B-channel multiply factor. public static void ColorChange( - InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, + InputArray src, InputArray mask, OutputArray dst, float redMul = 1.0f, float greenMul = 1.0f, float blueMul = 1.0f) { NativeMethods.HandleException( @@ -248,7 +248,7 @@ public static void ColorChange( /// This is useful to highlight under-exposed foreground objects or to reduce specular reflections. /// public static void IlluminationChange( - InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, + InputArray src, InputArray mask, OutputArray dst, float alpha = 0.2f, float beta = 0.4f) { NativeMethods.HandleException( @@ -271,7 +271,7 @@ public static void IlluminationChange( /// Value > 100. /// The size of the Sobel kernel to be used. public static void TextureFlattening( - InputArrayRef src, InputArrayRef mask, OutputArrayRef dst, + InputArray src, InputArray mask, OutputArray dst, float lowThreshold = 30, float highThreshold = 45, int kernelSize = 3) { @@ -293,7 +293,7 @@ public static void TextureFlattening( /// Range between 0 to 200. /// Range between 0 to 1. public static void EdgePreservingFilter( - InputArrayRef src, OutputArrayRef dst, + InputArray src, OutputArray dst, EdgePreservingMethods flags = EdgePreservingMethods.RecursFilter, float sigmaS = 60, float sigmaR = 0.4f) { @@ -312,7 +312,7 @@ public static void EdgePreservingFilter( /// Range between 0 to 200. /// Range between 0 to 1. public static void DetailEnhance( - InputArrayRef src, OutputArrayRef dst, + InputArray src, OutputArray dst, float sigmaS = 10, float sigmaR = 0.15f) { NativeMethods.HandleException( @@ -332,7 +332,7 @@ public static void DetailEnhance( /// Range between 0 to 1. /// Range between 0 to 0.1. public static void PencilSketch( - InputArrayRef src, OutputArrayRef dst1, OutputArrayRef dst2, + InputArray src, OutputArray dst1, OutputArray dst2, float sigmaS = 60, float sigmaR = 0.07f, float shadeFactor = 0.02f) { NativeMethods.HandleException( @@ -353,7 +353,7 @@ public static void PencilSketch( /// Range between 0 to 200. /// Range between 0 to 1. public static void Stylization( - InputArrayRef src, OutputArrayRef dst, + InputArray src, OutputArray dst, float sigmaS = 60, float sigmaR = 0.45f) { NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs b/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs index e73d2807b..3022815be 100644 --- a/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs +++ b/src/OpenCvSharp/Cv2/Cv2_ptcloud.cs @@ -20,9 +20,9 @@ static partial class Cv2 /// the result of transforming the depth into the external camera. /// whether or not the depth is dilated to avoid holes and occlusion errors (optional). public static void RegisterDepth( - InputArrayRef unregisteredCameraMatrix, InputArrayRef registeredCameraMatrix, InputArrayRef registeredDistCoeffs, - InputArrayRef Rt, InputArrayRef unregisteredDepth, Size outputImagePlaneSize, - OutputArrayRef registeredDepth, bool depthDilation = false) + InputArray unregisteredCameraMatrix, InputArray registeredCameraMatrix, InputArray registeredDistCoeffs, + InputArray Rt, InputArray unregisteredDepth, Size outputImagePlaneSize, + OutputArray registeredDepth, bool depthDilation = false) { NativeMethods.HandleException( NativeMethods.ptcloud_registerDepth( @@ -44,7 +44,7 @@ public static void RegisterDepth( /// the calibration matrix. /// the list of xy coordinates. /// the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). - public static void DepthTo3dSparse(InputArrayRef depth, InputArrayRef inK, InputArrayRef inPoints, OutputArrayRef points3d) + public static void DepthTo3dSparse(InputArray depth, InputArray inK, InputArray inPoints, OutputArray points3d) { NativeMethods.HandleException( NativeMethods.ptcloud_depthTo3dSparse(depth.Proxy, inK.Proxy, inPoints.Proxy, points3d.Proxy)); @@ -61,7 +61,7 @@ public static void DepthTo3dSparse(InputArrayRef depth, InputArrayRef inK, Input /// the calibration matrix. /// the resulting 3d points (point is represented by 4 channels value [x, y, z, 0]). /// the mask of the points to consider (can be empty). - public static void DepthTo3d(InputArrayRef depth, InputArrayRef K, OutputArrayRef points3d, InputArrayRef mask = default) + public static void DepthTo3d(InputArray depth, InputArray K, OutputArray points3d, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.ptcloud_depthTo3d(depth.Proxy, K.Proxy, points3d.Proxy, mask.Proxy)); @@ -79,7 +79,7 @@ public static void DepthTo3d(InputArrayRef depth, InputArrayRef K, OutputArrayRe /// the desired output depth (CV_32F or CV_64F). /// the rescaled float depth image. /// factor by which depth is converted to distance (by default = 1000.0 for Kinect sensor). - public static void RescaleDepth(InputArrayRef src, int type, OutputArrayRef dst, double depthFactor = 1000.0) + public static void RescaleDepth(InputArray src, int type, OutputArray dst, double depthFactor = 1000.0) { NativeMethods.HandleException( NativeMethods.ptcloud_rescaleDepth(src.Proxy, type, dst.Proxy, depthFactor)); @@ -100,8 +100,8 @@ public static void RescaleDepth(InputArrayRef src, int type, OutputArrayRef dst, /// The warped RGB image (optional). /// The mask of valid pixels in warped image (optional). public static void WarpFrame( - InputArrayRef depth, InputArrayRef image, InputArrayRef mask, InputArrayRef Rt, InputArrayRef cameraMatrix, - OutputArrayRef warpedDepth = default, OutputArrayRef warpedImage = default, OutputArrayRef warpedMask = default) + InputArray depth, InputArray image, InputArray mask, InputArray Rt, InputArray cameraMatrix, + OutputArray warpedDepth = default, OutputArray warpedImage = default, OutputArray warpedMask = default) { NativeMethods.HandleException( NativeMethods.ptcloud_warpFrame( @@ -130,7 +130,7 @@ public static void WarpFrame( /// coefficient of the sensor error (0 by default). /// the method to use to compute the planes. public static void FindPlanes( - InputArrayRef points3d, InputArrayRef normals, OutputArrayRef mask, OutputArrayRef planeCoefficients, + InputArray points3d, InputArray normals, OutputArray mask, OutputArray planeCoefficients, int blockSize = 40, int minSize = 1600, double threshold = 0.01, double sensorErrorA = 0, double sensorErrorB = 0, double sensorErrorC = 0, RgbdPlaneMethod method = RgbdPlaneMethod.Default) @@ -152,7 +152,7 @@ public static void FindPlanes( /// Output vertex coordinates, each value contains 3 floats. /// Output per-vertex normals, each value contains 3 floats (optional). /// Output per-vertex colors, each value contains 3 floats (optional). - public static void LoadPointCloud(string filename, OutputArrayRef vertices, OutputArrayRef normals = default, OutputArrayRef rgb = default) + public static void LoadPointCloud(string filename, OutputArray vertices, OutputArray normals = default, OutputArray rgb = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); @@ -169,7 +169,7 @@ public static void LoadPointCloud(string filename, OutputArrayRef vertices, Outp /// Vertex coordinates, each value contains 3 floats. /// Per-vertex normals, each value contains 3 floats (optional). /// Per-vertex colors, each value contains 3 floats (optional). - public static void SavePointCloud(string filename, InputArrayRef vertices, InputArrayRef normals = default, InputArrayRef rgb = default) + public static void SavePointCloud(string filename, InputArray vertices, InputArray normals = default, InputArray rgb = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); @@ -192,8 +192,8 @@ public static void SavePointCloud(string filename, InputArrayRef vertices, Input /// Output per-vertex colors, each value contains 3 floats (optional). /// Output per-vertex texture coordinates, each value contains 2 or 3 floats (optional). public static void LoadMesh( - string filename, OutputArrayRef vertices, out Mat[] indices, - OutputArrayRef normals = default, OutputArrayRef colors = default, OutputArrayRef texCoords = default) + string filename, OutputArray vertices, out Mat[] indices, + OutputArray normals = default, OutputArray colors = default, OutputArray texCoords = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); @@ -216,8 +216,8 @@ public static void LoadMesh( /// Per-vertex colors, each value contains 3 floats (optional). /// Per-vertex texture coordinates, each value contains 2 or 3 floats (optional). public static void SaveMesh( - string filename, InputArrayRef vertices, IEnumerable indices, - InputArrayRef normals = default, InputArrayRef colors = default, InputArrayRef texCoords = default) + string filename, InputArray vertices, IEnumerable indices, + InputArray normals = default, InputArray colors = default, InputArray texCoords = default) { if (filename is null) throw new ArgumentNullException(nameof(filename)); diff --git a/src/OpenCvSharp/Cv2/Cv2_stereo.cs b/src/OpenCvSharp/Cv2/Cv2_stereo.cs index 28b96ba4d..168fee85f 100644 --- a/src/OpenCvSharp/Cv2/Cv2_stereo.cs +++ b/src/OpenCvSharp/Cv2/Cv2_stereo.cs @@ -38,12 +38,12 @@ static partial class Cv2 /// in the rectified images (no source image pixels are lost). Obviously, any intermediate value yields an intermediate result between those two extreme cases. /// New image resolution after rectification. The same size should be passed to initUndistortRectifyMap(). When (0,0) is passed (default), it is set to the original imageSize . /// Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion. - public static void StereoRectify(InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, - InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, - Size imageSize, InputArrayRef R, InputArrayRef T, - OutputArrayRef R1, OutputArrayRef R2, - OutputArrayRef P1, OutputArrayRef P2, - OutputArrayRef Q, + public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + Size imageSize, InputArray R, InputArray T, + OutputArray R1, OutputArray R2, + OutputArray P1, OutputArray P2, + OutputArray Q, StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, double alpha = -1, Size? newImageSize = null) { @@ -82,12 +82,12 @@ public static void StereoRectify(InputArrayRef cameraMatrix1, InputArrayRef dist /// Otherwise, they are likely to be smaller. /// Optional output rectangles inside the rectified images where all the pixels are valid. If alpha=0 , the ROIs cover the whole images. /// Otherwise, they are likely to be smaller. - public static void StereoRectify(InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, - InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, - Size imageSize, InputArrayRef R, InputArrayRef T, - OutputArrayRef R1, OutputArrayRef R2, - OutputArrayRef P1, OutputArrayRef P2, - OutputArrayRef Q, StereoRectificationFlags flags, + public static void StereoRectify(InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + Size imageSize, InputArray R, InputArray T, + OutputArray R1, OutputArray R2, + OutputArray P1, OutputArray P2, + OutputArray Q, StereoRectificationFlags flags, double alpha, Size newImageSize, out Rect validPixROI1, out Rect validPixROI2) { @@ -251,9 +251,9 @@ public static void StereoRectify(double[,] cameraMatrix1, double[] distCoeffs1, /// with the epipolar geometry (that is, the points for which |points2[i]^T * F * points1[i]| > threshold ) /// are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. /// - public static bool StereoRectifyUncalibrated(InputArrayRef points1, InputArrayRef points2, - InputArrayRef F, Size imgSize, - OutputArrayRef H1, OutputArrayRef H2, + public static bool StereoRectifyUncalibrated(InputArray points1, InputArray points2, + InputArray F, Size imgSize, + OutputArray H1, OutputArray H2, double threshold = 5) { NativeMethods.HandleException( @@ -353,15 +353,15 @@ public static bool StereoRectifyUncalibrated( /// /// public static float Rectify3Collinear( - InputArrayRef cameraMatrix1, InputArrayRef distCoeffs1, - InputArrayRef cameraMatrix2, InputArrayRef distCoeffs2, - InputArrayRef cameraMatrix3, InputArrayRef distCoeffs3, + InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + InputArray cameraMatrix3, InputArray distCoeffs3, IReadOnlyList imgpt1, IReadOnlyList imgpt3, - Size imageSize, InputArrayRef R12, InputArrayRef T12, - InputArrayRef R13, InputArrayRef T13, - OutputArrayRef R1, OutputArrayRef R2, OutputArrayRef R3, - OutputArrayRef P1, OutputArrayRef P2, OutputArrayRef P3, - OutputArrayRef Q, double alpha, Size newImgSize, + Size imageSize, InputArray R12, InputArray T12, + InputArray R13, InputArray T13, + OutputArray R1, OutputArray R2, OutputArray R3, + OutputArray P1, OutputArray P2, OutputArray P3, + OutputArray Q, double alpha, Size newImgSize, out Rect roi1, out Rect roi2, StereoRectificationFlags flags) { if (imgpt1 is null) @@ -413,8 +413,8 @@ public static float Rectify3Collinear( /// Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point disparity map, where disparity values /// are multiplied by 16, this scale factor should be taken into account when specifying this parameter value. /// The optional temporary buffer to avoid memory allocation within the function. - public static void FilterSpeckles(InputOutputArrayRef img, double newVal, int maxSpeckleSize, double maxDiff, - InputOutputArrayRef buf = default) + public static void FilterSpeckles(InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff, + InputOutputArray buf = default) { NativeMethods.HandleException( NativeMethods.stereo_filterSpeckles(img.Proxy, newVal, maxSpeckleSize, maxDiff, buf.Proxy)); @@ -448,7 +448,7 @@ public static Rect GetValidDisparityROI(Rect roi1, Rect roi2, /// /// /// - public static void ValidateDisparity(InputOutputArrayRef disparity, InputArrayRef cost, + public static void ValidateDisparity(InputOutputArray disparity, InputArray cost, int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1) { NativeMethods.HandleException( @@ -471,8 +471,8 @@ public static void ValidateDisparity(InputOutputArrayRef disparity, InputArrayRe /// transformed to 3D points with a very large Z value (currently set to 10000). /// he optional output array depth. If it is -1, the output image will have CV_32F depth. /// ddepth can also be set to CV_16S, CV_32S or CV_32F. - public static void ReprojectImageTo3D(InputArrayRef disparity, - OutputArrayRef _3dImage, InputArrayRef Q, + public static void ReprojectImageTo3D(InputArray disparity, + OutputArray _3dImage, InputArray Q, bool handleMissingValues = false, int ddepth = -1) { NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Cv2/Cv2_video.cs b/src/OpenCvSharp/Cv2/Cv2_video.cs index 45b644b70..21d4be661 100644 --- a/src/OpenCvSharp/Cv2/Cv2_video.cs +++ b/src/OpenCvSharp/Cv2/Cv2_video.cs @@ -14,7 +14,7 @@ static partial class Cv2 /// Stop criteria for the underlying MeanShift() . /// public static RotatedRect CamShift( - InputArrayRef probImage, ref Rect window, TermCriteria criteria) + InputArray probImage, ref Rect window, TermCriteria criteria) { NativeMethods.HandleException( NativeMethods.video_CamShift(probImage.Proxy, ref window, criteria, out var ret)); @@ -30,7 +30,7 @@ public static RotatedRect CamShift( /// Stop criteria for the iterative search algorithm. /// Number of iterations CAMSHIFT took to converge. public static int MeanShift( - InputArrayRef probImage, ref Rect window, TermCriteria criteria) + InputArray probImage, ref Rect window, TermCriteria criteria) { NativeMethods.HandleException( NativeMethods.video_meanShift(probImage.Proxy, ref window, criteria, out var ret)); @@ -56,7 +56,7 @@ public static int MeanShift( /// You can pass false to force data copying. /// number of levels in constructed pyramid. Can be less than maxLevel. public static int BuildOpticalFlowPyramid( - InputArrayRef img, OutputArrayRef pyramid, + InputArray img, OutputArray pyramid, Size winSize, int maxLevel, bool withDerivatives = true, BorderTypes pyrBorder = BorderTypes.Reflect101, @@ -87,7 +87,7 @@ public static int BuildOpticalFlowPyramid( /// You can pass false to force data copying. /// number of levels in constructed pyramid. Can be less than maxLevel. public static int BuildOpticalFlowPyramid( - InputArrayRef img, out Mat[] pyramid, + InputArray img, out Mat[] pyramid, Size winSize, int maxLevel, bool withDerivatives = true, BorderTypes pyrBorder = BorderTypes.Reflect101, @@ -117,9 +117,9 @@ public static int BuildOpticalFlowPyramid( /// /// public static void CalcOpticalFlowPyrLK( - InputArrayRef prevImg, InputArrayRef nextImg, - InputArrayRef prevPts, InputOutputArrayRef nextPts, - OutputArrayRef status, OutputArrayRef err, + InputArray prevImg, InputArray nextImg, + InputArray prevPts, InputOutputArray nextPts, + OutputArray status, OutputArray err, Size? winSize = null, int maxLevel = 3, TermCriteria? criteria = null, @@ -151,8 +151,8 @@ public static void CalcOpticalFlowPyrLK( /// /// public static void CalcOpticalFlowPyrLK( - InputArrayRef prevImg, - InputArrayRef nextImg, + InputArray prevImg, + InputArray nextImg, Point2f[] prevPts, ref Point2f[] nextPts, out byte[] status, @@ -204,8 +204,8 @@ public static void CalcOpticalFlowPyrLK( /// a basis for the polynomial expansion; for polyN=5, you can set polySigma=1.1, /// for polyN=7, a good value would be polySigma=1.5. /// operation flags that can be a combination of OPTFLOW_USE_INITIAL_FLOW and/or OPTFLOW_FARNEBACK_GAUSSIAN - public static void CalcOpticalFlowFarneback(InputArrayRef prev, InputArrayRef next, - InputOutputArrayRef flow, double pyrScale, int levels, int winsize, + public static void CalcOpticalFlowFarneback(InputArray prev, InputArray next, + InputOutputArray flow, double pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, OpticalFlowFlags flags) { NativeMethods.HandleException( @@ -221,7 +221,7 @@ public static void CalcOpticalFlowFarneback(InputArrayRef prev, InputArrayRef ne /// single-channel input image to be warped to provide an image similar to templateImage, same type as templateImage. /// An optional mask to indicate valid values of inputImage. /// - public static double ComputeECC(InputArrayRef templateImage, InputArrayRef inputImage, InputArrayRef inputMask = default) + public static double ComputeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = default) { NativeMethods.HandleException( NativeMethods.video_computeECC(templateImage.Proxy, inputImage.Proxy, inputMask.Proxy, out var ret)); @@ -248,12 +248,12 @@ public static double ComputeECC(InputArrayRef templateImage, InputArrayRef input /// An optional value indicating size of gaussian blur filter; (DEFAULT: 5) /// public static double FindTransformECC( - InputArrayRef templateImage, - InputArrayRef inputImage, - InputOutputArrayRef warpMatrix, + InputArray templateImage, + InputArray inputImage, + InputOutputArray warpMatrix, MotionTypes motionType, TermCriteria criteria, - InputArrayRef inputMask = default, + InputArray inputMask = default, int gaussFiltSize = 5) { NativeMethods.HandleException( @@ -281,12 +281,12 @@ public static double FindTransformECC( /// An optional mask to indicate valid values of inputImage. /// public static double FindTransformECC( - InputArrayRef templateImage, - InputArrayRef inputImage, - InputOutputArrayRef warpMatrix, + InputArray templateImage, + InputArray inputImage, + InputOutputArray warpMatrix, MotionTypes motionType = MotionTypes.Affine, TermCriteria? criteria = null, - InputArrayRef inputMask = default) + InputArray inputMask = default) { var criteriaValue = criteria.GetValueOrDefault(new TermCriteria(CriteriaTypes.Count | CriteriaTypes.Eps, 50, 0.001)); diff --git a/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs b/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs index fcbf2c52a..35fa6b1fd 100644 --- a/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs +++ b/src/OpenCvSharp/Modules/aruco/ArucoDetector.cs @@ -36,7 +36,7 @@ public ArucoDetector(Dictionary dictionary, DetectorParameters detectorParams, R /// Basic marker detection. ///
public void DetectMarkers( - InputArrayRef image, + InputArray image, out Point2f[][] corners, out int[] ids, out Point2f[][] rejectedImgPoints) diff --git a/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs b/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs index 3b52ec6ff..d9ed1ffe2 100644 --- a/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs +++ b/src/OpenCvSharp/Modules/aruco/CharucoBoard.cs @@ -99,7 +99,7 @@ public bool LegacyPattern /// /// Generate the board image. /// - public void GenerateImage(Size outSize, OutputArrayRef img, int marginSize = 0, int borderBits = 1) + public void GenerateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) { ThrowIfDisposed(); @@ -110,7 +110,7 @@ public void GenerateImage(Size outSize, OutputArrayRef img, int marginSize = 0, /// /// Check whether the ChArUco markers are collinear. /// - public bool CheckCharucoCornersCollinear(InputArrayRef charucoIds) + public bool CheckCharucoCornersCollinear(InputArray charucoIds) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs b/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs index c6f8f1e4c..58e23d903 100644 --- a/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs +++ b/src/OpenCvSharp/Modules/aruco/CharucoDetector.cs @@ -21,8 +21,8 @@ public CharucoDetector(CharucoBoard board) ///
public CharucoDetector( CharucoBoard board, - InputArrayRef cameraMatrix, - InputArrayRef distCoeffs, + InputArray cameraMatrix, + InputArray distCoeffs, int minMarkers = 2, bool tryRefineMarkers = false, bool checkMarkers = true, @@ -59,7 +59,7 @@ public CharucoDetector( /// Detect aruco markers and interpolate position of ChArUco board corners. ///
public void DetectBoard( - InputArrayRef image, + InputArray image, out Point2f[] charucoCorners, out int[] charucoIds, out Point2f[][] markerCorners, @@ -90,7 +90,7 @@ public void DetectBoard( /// Detect ChArUco Diamond markers. ///
public void DetectDiamonds( - InputArrayRef image, + InputArray image, out Point2f[][] diamondCorners, out Vec4i[] diamondIds, out Point2f[][] markerCorners, diff --git a/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs b/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs index 8ec02a11f..4ff5b563b 100644 --- a/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs +++ b/src/OpenCvSharp/Modules/aruco/Cv2.Aruco.cs @@ -19,7 +19,7 @@ public static partial class Aruco /// positions of marker corners on input image. /// For N detected markers, the dimensions of this array should be Nx4.The order of the corners should be clockwise. /// vector of identifiers for markers in markersCorners. Optional, if not provided, ids are not painted. - public static void DrawDetectedMarkers(InputOutputArrayRef image, Point2f[][] corners, IEnumerable ids) + public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corners, IEnumerable ids) { DrawDetectedMarkers(image, corners, ids, new Scalar(0, 255, 0)); } @@ -33,7 +33,7 @@ public static void DrawDetectedMarkers(InputOutputArrayRef image, Point2f[][] co /// vector of identifiers for markers in markersCorners. Optional, if not provided, ids are not painted. /// color of marker borders. Rest of colors (text color and first corner color) /// are calculated based on this one to improve visualization. - public static void DrawDetectedMarkers(InputOutputArrayRef image, Point2f[][] corners, IEnumerable? ids, Scalar borderColor) + public static void DrawDetectedMarkers(InputOutputArray image, Point2f[][] corners, IEnumerable? ids, Scalar borderColor) { if (corners is null) throw new ArgumentNullException(nameof(corners)); @@ -98,7 +98,7 @@ public static Dictionary ReadDictionary(string dictionaryFile) /// input/output image. It must have 1 or 3 channels. The number of channels is not altered. /// positions of diamond corners in the same format returned by detectCharucoDiamond(). (e.g std::vector<std::vector<cv::Point2f>>). For N detected markers, the dimensions of this array should be Nx4. The order of the corners should be clockwise. /// vector of identifiers for diamonds in diamondCorners, in the same format returned by detectCharucoDiamond() (e.g. std::vector<Vec4i>). Optional, if not provided, ids are not painted. - public static void DrawDetectedDiamonds(InputOutputArrayRef image, Point2f[][] diamondCorners, IEnumerable? diamondIds = null) + public static void DrawDetectedDiamonds(InputOutputArray image, Point2f[][] diamondCorners, IEnumerable? diamondIds = null) { DrawDetectedDiamonds(image, diamondCorners, diamondIds, new Scalar(0, 0, 255)); } @@ -110,7 +110,7 @@ public static void DrawDetectedDiamonds(InputOutputArrayRef image, Point2f[][] d /// positions of diamond corners in the same format returned by detectCharucoDiamond(). (e.g std::vector<std::vector<cv::Point2f>>). For N detected markers, the dimensions of this array should be Nx4. The order of the corners should be clockwise. /// vector of identifiers for diamonds in diamondCorners, in the same format returned by detectCharucoDiamond() (e.g. std::vector<Vec4i>). Optional, if not provided, ids are not painted. /// color of marker borders. Rest of colors (text color and first corner color) are calculated based on this one. - public static void DrawDetectedDiamonds(InputOutputArrayRef image, + public static void DrawDetectedDiamonds(InputOutputArray image, Point2f[][] diamondCorners, IEnumerable? diamondIds, Scalar borderColor) { if (diamondCorners is null) @@ -144,7 +144,7 @@ public static void DrawDetectedDiamonds(InputOutputArrayRef image, /// input/output image. It must have 1 or 3 channels. The number of channels is not altered. /// vector of detected charuco corners. /// list of identifiers for each corner in charucoCorners. - public static void DrawDetectedCornersCharuco(InputOutputArrayRef image, Point2f[] charucoCorners, IEnumerable? charucoIds = null) + public static void DrawDetectedCornersCharuco(InputOutputArray image, Point2f[] charucoCorners, IEnumerable? charucoIds = null) { DrawDetectedCornersCharuco(image, charucoCorners, charucoIds, new Scalar(0, 0, 255)); } @@ -156,7 +156,7 @@ public static void DrawDetectedCornersCharuco(InputOutputArrayRef image, Point2f /// vector of detected charuco corners. /// list of identifiers for each corner in charucoCorners. /// color of the square surrounding each corner. - public static void DrawDetectedCornersCharuco(InputOutputArrayRef image, + public static void DrawDetectedCornersCharuco(InputOutputArray image, Point2f[] charucoCorners, IEnumerable? charucoIds, Scalar cornerColor) { if (charucoCorners is null) diff --git a/src/OpenCvSharp/Modules/aruco/Dictionary.cs b/src/OpenCvSharp/Modules/aruco/Dictionary.cs index 031c4be0e..4608fd67c 100644 --- a/src/OpenCvSharp/Modules/aruco/Dictionary.cs +++ b/src/OpenCvSharp/Modules/aruco/Dictionary.cs @@ -117,7 +117,7 @@ public bool Identify(Mat onlyBits, out int idx, out int rotation, double maxCorr /// /// /// - public int GetDistanceToId(InputArrayRef bits, int id, bool allRotations = true) + public int GetDistanceToId(InputArray bits, int id, bool allRotations = true) { ThrowIfDisposed(); @@ -134,7 +134,7 @@ public int GetDistanceToId(InputArrayRef bits, int id, bool allRotations = true) /// /// /// - public void GenerateImageMarker(int id, int sidePixels, OutputArrayRef img, int borderBits = 1) + public void GenerateImageMarker(int id, int sidePixels, OutputArray img, int borderBits = 1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs b/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs index 84c47f81c..b3dd07406 100644 --- a/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs +++ b/src/OpenCvSharp/Modules/barcode/BarcodeDetector.cs @@ -79,7 +79,7 @@ public void SetDetectorScales(IEnumerable sizes) /// optional output vector of vertices of the found barcode rectangle. Will be empty if not found. /// list of decoded string. /// list of decoded types. - public void DetectAndDecode(InputArrayRef inputImage, out Point2f[] points, out string[] results, out string[] types) + public void DetectAndDecode(InputArray inputImage, out Point2f[] points, out string[] results, out string[] types) { using var pointsVec = new StdVector(); using var infos = new VectorOfString(); diff --git a/src/OpenCvSharp/Modules/core/InputArrayRef.cs b/src/OpenCvSharp/Modules/core/InputArray.cs similarity index 65% rename from src/OpenCvSharp/Modules/core/InputArrayRef.cs rename to src/OpenCvSharp/Modules/core/InputArray.cs index 193b1a2aa..4ab9818e2 100644 --- a/src/OpenCvSharp/Modules/core/InputArrayRef.cs +++ b/src/OpenCvSharp/Modules/core/InputArray.cs @@ -2,21 +2,19 @@ namespace OpenCvSharp; -// FOUNDATION for the InputArray/OutputArray ref-struct redesign (issue: allocation-free arrays). -// -// A handle-less, stack-only proxy that mirrors OpenCV's cv::_InputArray: it carries just a native -// handle + a kind tag (and an inline payload for scalar/vector operands). No native _InputArray is -// allocated on the managed side; the extern boundary receives the proxy BY VALUE and rebuilds a +// InputArray/OutputArray/InputOutputArray: handle-less, stack-only proxies that mirror OpenCV's +// cv::_InputArray/_OutputArray/_InputOutputArray. Each carries just a native handle + a kind tag +// (and an inline payload for scalar/vector operands). No native _InputArray is allocated on the +// managed side; the extern boundary receives the proxy BY VALUE and rebuilds a // cv::_InputArray/_OutputArray on its own stack (see fromInputProxy/fromOutputProxy in my_types.h). -// This makes implicit-conversion temporaries (e.g. Cv2.Foo(mat, dst)) allocation-free and removes -// the non-deterministic finalizer cleanup of the current class-based InputArray. +// This makes implicit-conversion temporaries (e.g. Cv2.Foo(mat, dst)) allocation-free and avoids the +// non-deterministic finalizer cleanup a heap-allocated proxy class would need. // -// Named *Ref while the class-based InputArray/OutputArray still exist; the big-bang migration -// renames these over them. Scope (owner decision, "Option 1"): handle kinds (Mat/UMat/MatExpr) and -// inline value kinds (Scalar/double/Vec). Array / Span / vector-of-Mat inputs are NOT carried here -// (they get dedicated ReadOnlySpan / out Mat[] signatures), so a proxy never owns pinned memory. +// Scope (owner decision, "Option 1"): handle kinds (Mat/UMat/MatExpr) and inline value kinds +// (Scalar/double/Vec). Array / Span / vector-of-Mat inputs are NOT carried here (they get dedicated +// ReadOnlySpan / out Mat[] signatures), so a proxy never owns pinned memory. -/// Kind of array a ref-struct proxy refers to. Must match the switch in my_types.h. +/// Kind of array a proxy refers to. Must match the switch in my_types.h. public enum ArrayProxyKind { /// No array (cv::noArray()). @@ -33,18 +31,6 @@ public enum ArrayProxyKind Double = 5, /// A small fixed-length vector value (inline). Vec = 6, - - // Migration scaffold: a proxy that wraps an existing native cv::_InputArray*/_OutputArray*/ - // _InputOutputArray* (the handle of a class-based InputArray/OutputArray/InputOutputArray). - // Lets externs move to the ArrayProxy ABI one module at a time while the class types still - // exist; the native side just dereferences the handle. Removed once the type flip is complete. - - /// An existing native cv::_InputArray* (class-based ). - RawInputArray = 7, - /// An existing native cv::_OutputArray* (class-based ). - RawOutputArray = 8, - /// An existing native cv::_InputOutputArray* (class-based ). - RawInputOutputArray = 9, } /// @@ -103,33 +89,33 @@ internal struct InputOutputArrayProxy /// Stack-only input proxy (see file header). Carries a native handle or an inline value; building /// one allocates nothing on the managed heap. /// -public readonly ref struct InputArrayRef +public readonly ref struct InputArray { // Keeps the source Mat/UMat/NativeMatExpr alive across the native call (the proxy stores only // its raw handle). internal readonly object? Source; internal readonly InputArrayProxy Proxy; - private InputArrayRef(object? source, InputArrayProxy proxy) + private InputArray(object? source, InputArrayProxy proxy) { Source = source; Proxy = proxy; } /// Wraps a (no allocation). - public static implicit operator InputArrayRef(Mat mat) + public static implicit operator InputArray(Mat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new InputArrayRef(mat, new InputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); + return new InputArray(mat, new InputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); } /// Wraps a (no allocation). - public static implicit operator InputArrayRef(UMat mat) + public static implicit operator InputArray(UMat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new InputArrayRef(mat, new InputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); + return new InputArray(mat, new InputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); } /// @@ -137,19 +123,19 @@ public static implicit operator InputArrayRef(UMat mat) /// (kept alive via ), so this path is not allocation-free — matching the /// inherent cost of feeding a lazy expression into an OpenCV call. /// - public static implicit operator InputArrayRef(MatExpr expr) + public static implicit operator InputArray(MatExpr expr) { ArgumentNullException.ThrowIfNull(expr); var native = expr.Eval(); - return new InputArrayRef(native, new InputArrayProxy { Handle = native.CvPtr, Kind = (int)ArrayProxyKind.MatExpr }); + return new InputArray(native, new InputArrayProxy { Handle = native.CvPtr, Kind = (int)ArrayProxyKind.MatExpr }); } /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Scalar s) => + public static implicit operator InputArray(Scalar s) => new(null, InputArrayProxy.FromScalar(s)); /// Wraps a value (no allocation; travels inline as Scalar(d,0,0,0)). - public static implicit operator InputArrayRef(double d) => + public static implicit operator InputArray(double d) => new(null, new InputArrayProxy { Kind = (int)ArrayProxyKind.Double, Payload0 = d }); // cv depth constants for the inline Vec payload (cv::CV_8U .. CV_64F). @@ -157,110 +143,110 @@ public static implicit operator InputArrayRef(double d) => // Copies a fixed-length vector value into the inline payload (no allocation). The native side // reads it back as (const T*)payload with VecLength elements; see fromInputProxy in my_types.h. - private static InputArrayRef FromVec(T vec, int depth, int length) where T : unmanaged + private static InputArray FromVec(T vec, int depth, int length) where T : unmanaged { var proxy = new InputArrayProxy { Kind = (int)ArrayProxyKind.Vec, VecDepth = depth, VecLength = length }; var payload = MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref proxy.Payload0, 6)); MemoryMarshal.Write(payload, in vec); - return new InputArrayRef(null, proxy); + return new InputArray(null, proxy); } /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2b v) => FromVec(v, DepthU8, 2); + public static implicit operator InputArray(Vec2b v) => FromVec(v, DepthU8, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3b v) => FromVec(v, DepthU8, 3); + public static implicit operator InputArray(Vec3b v) => FromVec(v, DepthU8, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4b v) => FromVec(v, DepthU8, 4); + public static implicit operator InputArray(Vec4b v) => FromVec(v, DepthU8, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6b v) => FromVec(v, DepthU8, 6); + public static implicit operator InputArray(Vec6b v) => FromVec(v, DepthU8, 6); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2s v) => FromVec(v, DepthS16, 2); + public static implicit operator InputArray(Vec2s v) => FromVec(v, DepthS16, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3s v) => FromVec(v, DepthS16, 3); + public static implicit operator InputArray(Vec3s v) => FromVec(v, DepthS16, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4s v) => FromVec(v, DepthS16, 4); + public static implicit operator InputArray(Vec4s v) => FromVec(v, DepthS16, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6s v) => FromVec(v, DepthS16, 6); + public static implicit operator InputArray(Vec6s v) => FromVec(v, DepthS16, 6); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2w v) => FromVec(v, DepthU16, 2); + public static implicit operator InputArray(Vec2w v) => FromVec(v, DepthU16, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3w v) => FromVec(v, DepthU16, 3); + public static implicit operator InputArray(Vec3w v) => FromVec(v, DepthU16, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4w v) => FromVec(v, DepthU16, 4); + public static implicit operator InputArray(Vec4w v) => FromVec(v, DepthU16, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6w v) => FromVec(v, DepthU16, 6); + public static implicit operator InputArray(Vec6w v) => FromVec(v, DepthU16, 6); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2i v) => FromVec(v, DepthS32, 2); + public static implicit operator InputArray(Vec2i v) => FromVec(v, DepthS32, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3i v) => FromVec(v, DepthS32, 3); + public static implicit operator InputArray(Vec3i v) => FromVec(v, DepthS32, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4i v) => FromVec(v, DepthS32, 4); + public static implicit operator InputArray(Vec4i v) => FromVec(v, DepthS32, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6i v) => FromVec(v, DepthS32, 6); + public static implicit operator InputArray(Vec6i v) => FromVec(v, DepthS32, 6); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2f v) => FromVec(v, DepthF32, 2); + public static implicit operator InputArray(Vec2f v) => FromVec(v, DepthF32, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3f v) => FromVec(v, DepthF32, 3); + public static implicit operator InputArray(Vec3f v) => FromVec(v, DepthF32, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4f v) => FromVec(v, DepthF32, 4); + public static implicit operator InputArray(Vec4f v) => FromVec(v, DepthF32, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6f v) => FromVec(v, DepthF32, 6); + public static implicit operator InputArray(Vec6f v) => FromVec(v, DepthF32, 6); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec2d v) => FromVec(v, DepthF64, 2); + public static implicit operator InputArray(Vec2d v) => FromVec(v, DepthF64, 2); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec3d v) => FromVec(v, DepthF64, 3); + public static implicit operator InputArray(Vec3d v) => FromVec(v, DepthF64, 3); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec4d v) => FromVec(v, DepthF64, 4); + public static implicit operator InputArray(Vec4d v) => FromVec(v, DepthF64, 4); /// Wraps a value (no allocation; travels inline). - public static implicit operator InputArrayRef(Vec6d v) => FromVec(v, DepthF64, 6); + public static implicit operator InputArray(Vec6d v) => FromVec(v, DepthF64, 6); #region Create (explicit-call parity with the implicit operators above) /// Wraps a (no allocation). - public static InputArrayRef Create(Mat? mat) => mat!; + public static InputArray Create(Mat? mat) => mat!; /// Wraps a (no allocation). - public static InputArrayRef Create(UMat mat) => mat; + public static InputArray Create(UMat mat) => mat; /// Wraps a (materializes it to a native cv::MatExpr). - public static InputArrayRef Create(MatExpr node) => node; + public static InputArray Create(MatExpr node) => node; /// Wraps a value (no allocation; travels inline). - public static InputArrayRef Create(Scalar val) => val; + public static InputArray Create(Scalar val) => val; /// Wraps a value (no allocation; travels inline). - public static InputArrayRef Create(double val) => val; + public static InputArray Create(double val) => val; /// Wraps a fixed-length value (no allocation; travels inline). - public static InputArrayRef Create(IVec vec) + public static InputArray Create(IVec vec) { ArgumentNullException.ThrowIfNull(vec); return vec switch { - Vec2b v => (InputArrayRef)v, - Vec3b v => (InputArrayRef)v, - Vec4b v => (InputArrayRef)v, - Vec6b v => (InputArrayRef)v, - Vec2s v => (InputArrayRef)v, - Vec3s v => (InputArrayRef)v, - Vec4s v => (InputArrayRef)v, - Vec6s v => (InputArrayRef)v, - Vec2w v => (InputArrayRef)v, - Vec3w v => (InputArrayRef)v, - Vec4w v => (InputArrayRef)v, - Vec6w v => (InputArrayRef)v, - Vec2i v => (InputArrayRef)v, - Vec3i v => (InputArrayRef)v, - Vec4i v => (InputArrayRef)v, - Vec6i v => (InputArrayRef)v, - Vec2f v => (InputArrayRef)v, - Vec3f v => (InputArrayRef)v, - Vec4f v => (InputArrayRef)v, - Vec6f v => (InputArrayRef)v, - Vec2d v => (InputArrayRef)v, - Vec3d v => (InputArrayRef)v, - Vec4d v => (InputArrayRef)v, - Vec6d v => (InputArrayRef)v, + Vec2b v => (InputArray)v, + Vec3b v => (InputArray)v, + Vec4b v => (InputArray)v, + Vec6b v => (InputArray)v, + Vec2s v => (InputArray)v, + Vec3s v => (InputArray)v, + Vec4s v => (InputArray)v, + Vec6s v => (InputArray)v, + Vec2w v => (InputArray)v, + Vec3w v => (InputArray)v, + Vec4w v => (InputArray)v, + Vec6w v => (InputArray)v, + Vec2i v => (InputArray)v, + Vec3i v => (InputArray)v, + Vec4i v => (InputArray)v, + Vec6i v => (InputArray)v, + Vec2f v => (InputArray)v, + Vec3f v => (InputArray)v, + Vec4f v => (InputArray)v, + Vec6f v => (InputArray)v, + Vec2d v => (InputArray)v, + Vec3d v => (InputArray)v, + Vec4d v => (InputArray)v, + Vec6d v => (InputArray)v, _ => throw new ArgumentException($"Not supported type: '{vec.GetType().Name}'", nameof(vec)), }; } @@ -270,7 +256,7 @@ public static InputArrayRef Create(IVec vec) /// (not allocation-free: this materializes a real Mat, same as the /// class-based InputArray.Create<T> it replaces). ///
- public static InputArrayRef Create(T[] array, MatType type) where T : unmanaged + public static InputArray Create(T[] array, MatType type) where T : unmanaged { ArgumentNullException.ThrowIfNull(array); if (array.Length == 0) @@ -279,14 +265,14 @@ public static InputArrayRef Create(T[] array, MatType type) where T : unmanag } /// Wraps a 1-D array, inferring the from . - public static InputArrayRef Create(T[] array) where T : unmanaged => + public static InputArray Create(T[] array) where T : unmanaged => Create(array, EstimateType(typeof(T))); /// /// Wraps a 2-D array by copying it into a freshly-created of the given /// . /// - public static InputArrayRef Create(T[,] array, MatType type) where T : unmanaged + public static InputArray Create(T[,] array, MatType type) where T : unmanaged { ArgumentNullException.ThrowIfNull(array); var rows = array.GetLength(0); @@ -299,11 +285,11 @@ public static InputArrayRef Create(T[,] array, MatType type) where T : unmana } /// Wraps a 2-D array, inferring the from . - public static InputArrayRef Create(T[,] array) where T : unmanaged => + public static InputArray Create(T[,] array) where T : unmanaged => Create(array, EstimateType(typeof(T))); /// Wraps a sequence, inferring the from . - public static InputArrayRef Create(IEnumerable enumerable) where T : unmanaged + public static InputArray Create(IEnumerable enumerable) where T : unmanaged { ArgumentNullException.ThrowIfNull(enumerable); return Create(new List(enumerable).ToArray()); @@ -311,7 +297,7 @@ public static InputArrayRef Create(IEnumerable enumerable) where T : unman /// Wraps a sequence by copying it into a freshly-created of the given /// . - public static InputArrayRef Create(IEnumerable enumerable, MatType type) where T : unmanaged + public static InputArray Create(IEnumerable enumerable, MatType type) where T : unmanaged { ArgumentNullException.ThrowIfNull(enumerable); return Create(new List(enumerable).ToArray(), type); @@ -372,7 +358,7 @@ private static MatType EstimateType(Type t) if (t == typeof(Vec4d)) return MatType.CV_64FC4; if (t == typeof(Vec6d)) return MatType.CV_64FC(6); - throw new ArgumentException("Not supported value type for InputArrayRef"); + throw new ArgumentException("Not supported value type for InputArray"); } #endregion @@ -382,74 +368,74 @@ private static MatType EstimateType(Type t) /// Stack-only output proxy (see file header). Single Mat/UMat output only — native writes through /// the referenced matrix directly, so no write-back (Fix/AssignResult) is needed. ///
-public readonly ref struct OutputArrayRef +public readonly ref struct OutputArray { internal readonly object? Source; internal readonly OutputArrayProxy Proxy; - private OutputArrayRef(object? source, OutputArrayProxy proxy) + private OutputArray(object? source, OutputArrayProxy proxy) { Source = source; Proxy = proxy; } /// Wraps a output (no allocation). - public static implicit operator OutputArrayRef(Mat mat) + public static implicit operator OutputArray(Mat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new OutputArrayRef(mat, new OutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); + return new OutputArray(mat, new OutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); } /// Wraps a output (no allocation). - public static implicit operator OutputArrayRef(UMat mat) + public static implicit operator OutputArray(UMat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new OutputArrayRef(mat, new OutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); + return new OutputArray(mat, new OutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); } /// Wraps a output (no allocation). - public static OutputArrayRef Create(Mat mat) => mat; + public static OutputArray Create(Mat mat) => mat; /// Wraps a output (no allocation). - public static OutputArrayRef Create(UMat mat) => mat; + public static OutputArray Create(UMat mat) => mat; } /// /// Stack-only input/output proxy (see file header). Single Mat/UMat only; its read/write role is /// flag-dependent in OpenCV, so it is kept as one type (not split into in/out variants). /// -public readonly ref struct InputOutputArrayRef +public readonly ref struct InputOutputArray { internal readonly object? Source; internal readonly InputOutputArrayProxy Proxy; - private InputOutputArrayRef(object? source, InputOutputArrayProxy proxy) + private InputOutputArray(object? source, InputOutputArrayProxy proxy) { Source = source; Proxy = proxy; } /// Wraps a in/out target (no allocation). - public static implicit operator InputOutputArrayRef(Mat mat) + public static implicit operator InputOutputArray(Mat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new InputOutputArrayRef(mat, new InputOutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); + return new InputOutputArray(mat, new InputOutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.Mat }); } /// Wraps a in/out target (no allocation). - public static implicit operator InputOutputArrayRef(UMat mat) + public static implicit operator InputOutputArray(UMat mat) { ArgumentNullException.ThrowIfNull(mat); mat.ThrowIfDisposed(); - return new InputOutputArrayRef(mat, new InputOutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); + return new InputOutputArray(mat, new InputOutputArrayProxy { Handle = mat.CvPtr, Kind = (int)ArrayProxyKind.UMat }); } /// Wraps a in/out target (no allocation). - public static InputOutputArrayRef Create(Mat mat) => mat; + public static InputOutputArray Create(Mat mat) => mat; /// Wraps a in/out target (no allocation). - public static InputOutputArrayRef Create(UMat mat) => mat; + public static InputOutputArray Create(UMat mat) => mat; } diff --git a/src/OpenCvSharp/Modules/core/LDA.cs b/src/OpenCvSharp/Modules/core/LDA.cs index d6350c986..f49e2ba04 100644 --- a/src/OpenCvSharp/Modules/core/LDA.cs +++ b/src/OpenCvSharp/Modules/core/LDA.cs @@ -31,7 +31,7 @@ public LDA(int numComponents = 0) /// /// /// - public LDA(InputArrayRef src, InputArrayRef labels, int numComponents = 0) + public LDA(InputArray src, InputArray labels, int numComponents = 0) { NativeMethods.HandleException( NativeMethods.core_LDA_new2(src.Proxy, labels.Proxy, numComponents, out var p)); @@ -133,7 +133,7 @@ public void Load(FileStorage node) ///
/// /// - public void Compute(InputArrayRef src, InputArrayRef labels) + public void Compute(InputArray src, InputArray labels) { ThrowIfDisposed(); @@ -150,7 +150,7 @@ public void Compute(InputArrayRef src, InputArrayRef labels) ///
/// /// - public Mat Project(InputArrayRef src) + public Mat Project(InputArray src) { ThrowIfDisposed(); @@ -168,7 +168,7 @@ public Mat Project(InputArrayRef src) ///
/// /// - public Mat Reconstruct(InputArrayRef src) + public Mat Reconstruct(InputArray src) { ThrowIfDisposed(); @@ -187,7 +187,7 @@ public Mat Reconstruct(InputArrayRef src) /// /// /// - public static Mat SubspaceProject(InputArrayRef w, InputArrayRef mean, InputArrayRef src) + public static Mat SubspaceProject(InputArray w, InputArray mean, InputArray src) { NativeMethods.HandleException( NativeMethods.core_LDA_subspaceProject(w.Proxy, mean.Proxy, src.Proxy, out var ret)); @@ -206,7 +206,7 @@ public static Mat SubspaceProject(InputArrayRef w, InputArrayRef mean, InputArra /// /// /// - public static Mat SubspaceReconstruct(InputArrayRef w, InputArrayRef mean, InputArrayRef src) + public static Mat SubspaceReconstruct(InputArray w, InputArray mean, InputArray src) { NativeMethods.HandleException( NativeMethods.core_LDA_subspaceReconstruct(w.Proxy, mean.Proxy, src.Proxy, out var ret)); diff --git a/src/OpenCvSharp/Modules/core/Mat/Mat.cs b/src/OpenCvSharp/Modules/core/Mat/Mat.cs index 532ebd955..1ef47cc7e 100644 --- a/src/OpenCvSharp/Modules/core/Mat/Mat.cs +++ b/src/OpenCvSharp/Modules/core/Mat/Mat.cs @@ -1275,7 +1275,7 @@ public Mat Clone(Rect roi) ///
/// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) + public void CopyTo(OutputArray m, InputArray mask = default) { ThrowIfDisposed(); @@ -1291,7 +1291,7 @@ public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) ///
/// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(Mat m, InputArrayRef mask = default) + public void CopyTo(Mat m, InputArray mask = default) { ThrowIfDisposed(); if (m is null) @@ -1313,7 +1313,7 @@ public void CopyTo(Mat m, InputArrayRef mask = default) /// if rtype is negative, the output matrix will have the same type as the input. /// optional scale factor. /// optional delta added to the scaled values. - public void ConvertTo(OutputArrayRef m, MatType rtype, double alpha = 1, double beta = 0) + public void ConvertTo(OutputArray m, MatType rtype, double alpha = 1, double beta = 0) { ThrowIfDisposed(); @@ -1364,7 +1364,7 @@ public Mat SetTo(Scalar value, Mat? mask = null) /// /// /// - public Mat SetTo(InputArrayRef value, Mat? mask = null) + public Mat SetTo(InputArray value, Mat? mask = null) { ThrowIfDisposed(); @@ -1449,7 +1449,7 @@ public Mat Reshape(int cn, MatShape newShape) /// /// /// - public MatExpr Mul(InputArrayRef m, double scale = 1) + public MatExpr Mul(InputArray m, double scale = 1) { // MatExpr.FromExpr defers evaluation via a captured delegate, and ref structs cannot be // captured by a closure — so the proxy and its keepalive source are captured by value instead. @@ -1472,7 +1472,7 @@ public MatExpr Mul(InputArrayRef m, double scale = 1) ///
/// Another cross-product operand. /// - public Mat Cross(InputArrayRef m) + public Mat Cross(InputArray m) { ThrowIfDisposed(); @@ -1489,7 +1489,7 @@ public Mat Cross(InputArrayRef m) ///
/// another dot-product operand. /// - public double Dot(InputArrayRef m) + public double Dot(InputArray m) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/core/Mat/UMat.cs b/src/OpenCvSharp/Modules/core/Mat/UMat.cs index 70792999a..cc5193c3f 100644 --- a/src/OpenCvSharp/Modules/core/Mat/UMat.cs +++ b/src/OpenCvSharp/Modules/core/Mat/UMat.cs @@ -694,7 +694,7 @@ public UMat Clone(Rect roi) ///
/// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) + public void CopyTo(OutputArray m, InputArray mask = default) { ThrowIfDisposed(); @@ -710,7 +710,7 @@ public void CopyTo(OutputArrayRef m, InputArrayRef mask = default) ///
/// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. /// Operation mask. Its non-zero elements indicate which matrix elements need to be copied. - public void CopyTo(UMat m, InputArrayRef mask = default) + public void CopyTo(UMat m, InputArray mask = default) { ThrowIfDisposed(); if (m is null) @@ -732,7 +732,7 @@ public void CopyTo(UMat m, InputArrayRef mask = default) /// if rtype is negative, the output matrix will have the same type as the input. /// optional scale factor. /// optional delta added to the scaled values. - public void ConvertTo(OutputArrayRef m, MatType rtype, double alpha = 1, double beta = 0) + public void ConvertTo(OutputArray m, MatType rtype, double alpha = 1, double beta = 0) { ThrowIfDisposed(); @@ -783,7 +783,7 @@ public UMat SetTo(Scalar value, UMat? mask = null) /// /// /// - public UMat SetTo(InputArrayRef value, UMat? mask = null) + public UMat SetTo(InputArray value, UMat? mask = null) { ThrowIfDisposed(); @@ -870,7 +870,7 @@ public UMat Inv(DecompTypes method = DecompTypes.LU) /// /// /// - public UMat Mul(InputArrayRef m, double scale = 1) + public UMat Mul(InputArray m, double scale = 1) { ThrowIfDisposed(); @@ -887,7 +887,7 @@ public UMat Mul(InputArrayRef m, double scale = 1) ///
/// another dot-product operand. /// - public double Dot(InputArrayRef m) + public double Dot(InputArray m) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/core/PCA.cs b/src/OpenCvSharp/Modules/core/PCA.cs index 30567f490..ffb501b12 100644 --- a/src/OpenCvSharp/Modules/core/PCA.cs +++ b/src/OpenCvSharp/Modules/core/PCA.cs @@ -28,7 +28,7 @@ public PCA() /// optional mean value; if the matrix is empty (@c noArray()), the mean is computed from the data. /// operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) /// maximum number of components that PCA should retain; by default, all the components are retained. - public PCA(InputArrayRef data, InputArrayRef mean, Flags flags, int maxComponents = 0) + public PCA(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) { NativeMethods.HandleException( NativeMethods.core_PCA_new2(data.Proxy, mean.Proxy, (int)flags, maxComponents, out var p)); @@ -45,7 +45,7 @@ public PCA(InputArrayRef data, InputArrayRef mean, Flags flags, int maxComponent /// operation flags; currently the parameter is only used to specify the data layout (PCA::Flags) /// Percentage of variance that PCA should retain. /// Using this parameter will let the PCA decided how many components to retain but it will always keep at least 2. - public PCA(InputArrayRef data, InputArrayRef mean, Flags flags, double retainedVariance) + public PCA(InputArray data, InputArray mean, Flags flags, double retainedVariance) { NativeMethods.HandleException( NativeMethods.core_PCA_new3(data.Proxy, mean.Proxy, (int)flags, retainedVariance, out var p)); @@ -124,7 +124,7 @@ public Mat Mean /// maximum number of components that PCA should retain; /// by default, all the components are retained. /// - public PCA Compute(InputArrayRef data, InputArrayRef mean, Flags flags, int maxComponents = 0) + public PCA Compute(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -155,7 +155,7 @@ public PCA Compute(InputArrayRef data, InputArrayRef mean, Flags flags, int maxC /// Using this parameter will let the %PCA decided how many components to /// retain but it will always keep at least 2. /// - public PCA ComputeVar(InputArrayRef data, InputArrayRef mean, Flags flags, double retainedVariance) + public PCA ComputeVar(InputArray data, InputArray mean, Flags flags, double retainedVariance) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -181,7 +181,7 @@ public PCA ComputeVar(InputArrayRef data, InputArrayRef mean, Flags flags, doubl /// (vector dimensionality) and `vec.rows` is the number of vectors to /// project, and the same is true for the PCA::DATA_AS_COL case. /// - public Mat Project(InputArrayRef vec) + public Mat Project(InputArray vec) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -202,7 +202,7 @@ public Mat Project(InputArrayRef vec) /// means that `result.cols==vec.cols` and the number of rows match the /// number of principal components (for example, `maxComponents` parameter /// passed to the constructor). - public void Project(InputArrayRef vec, OutputArrayRef result) + public void Project(InputArray vec, OutputArray result) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -224,7 +224,7 @@ public void Project(InputArrayRef vec, OutputArrayRef result) /// coordinates of the vectors in the principal component subspace, /// the layout and size are the same as of PCA::project output vectors. /// - public Mat BackProject(InputArrayRef vec) + public Mat BackProject(InputArray vec) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -247,7 +247,7 @@ public Mat BackProject(InputArrayRef vec) /// the layout and size are the same as of PCA::project output vectors. /// reconstructed vectors; the layout and size are the same as /// of PCA::project input vectors. - public void BackProject(InputArrayRef vec, OutputArrayRef result) + public void BackProject(InputArray vec, OutputArray result) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/core/RNG.cs b/src/OpenCvSharp/Modules/core/RNG.cs index 436a1ea75..fd30799e3 100644 --- a/src/OpenCvSharp/Modules/core/RNG.cs +++ b/src/OpenCvSharp/Modules/core/RNG.cs @@ -270,10 +270,10 @@ public double Uniform(double a, double b) /// theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely produce array mostly filled /// with 0's and 255's, since the range (0, 255) is significantly smaller than [-DBL_MAX, DBL_MAX). public void Fill( - InputOutputArrayRef mat, + InputOutputArray mat, DistributionType distType, - InputArrayRef a, - InputArrayRef b, + InputArray a, + InputArray b, bool saturateRange = false) { NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/core/SVD.cs b/src/OpenCvSharp/Modules/core/SVD.cs index ccce5d0fc..cbcda7f10 100644 --- a/src/OpenCvSharp/Modules/core/SVD.cs +++ b/src/OpenCvSharp/Modules/core/SVD.cs @@ -22,7 +22,7 @@ public SVD() ///
/// /// - public SVD(InputArrayRef src, Flags flags = 0) + public SVD(InputArray src, Flags flags = 0) { NativeMethods.HandleException( NativeMethods.core_SVD_new2(src.Proxy, (int)flags, out var p)); @@ -80,7 +80,7 @@ public Mat Vt() /// /// /// - public SVD Run(InputArrayRef src, Flags flags = 0) + public SVD Run(InputArray src, Flags flags = 0) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -95,7 +95,7 @@ public SVD Run(InputArrayRef src, Flags flags = 0) /// /// /// - public void BackSubst(InputArrayRef rhs, OutputArrayRef dst) + public void BackSubst(InputArray rhs, OutputArray dst) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -112,8 +112,8 @@ public void BackSubst(InputArrayRef rhs, OutputArrayRef dst) /// /// /// - public static void Compute(InputArrayRef src, OutputArrayRef w, - OutputArrayRef u, OutputArrayRef vt, Flags flags = 0) + public static void Compute(InputArray src, OutputArray w, + OutputArray u, OutputArray vt, Flags flags = 0) { NativeMethods.HandleException( NativeMethods.core_SVD_static_compute1(src.Proxy, w.Proxy, u.Proxy, vt.Proxy, (int)flags)); @@ -129,7 +129,7 @@ public static void Compute(InputArrayRef src, OutputArrayRef w, /// /// /// - public static void Compute(InputArrayRef src, OutputArrayRef w, Flags flags = 0) + public static void Compute(InputArray src, OutputArray w, Flags flags = 0) { NativeMethods.HandleException( NativeMethods.core_SVD_static_compute2(src.Proxy, w.Proxy, (int)flags)); @@ -145,8 +145,8 @@ public static void Compute(InputArrayRef src, OutputArrayRef w, Flags flags = 0) /// /// /// - public static void BackSubst(InputArrayRef w, InputArrayRef u, - InputArrayRef vt, InputArrayRef rhs, OutputArrayRef dst) + public static void BackSubst(InputArray w, InputArray u, + InputArray vt, InputArray rhs, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_SVD_static_backSubst(w.Proxy, u.Proxy, vt.Proxy, rhs.Proxy, dst.Proxy)); @@ -162,7 +162,7 @@ public static void BackSubst(InputArrayRef w, InputArrayRef u, ///
/// /// - public static void SolveZ(InputArrayRef src, OutputArrayRef dst) + public static void SolveZ(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.core_SVD_static_solveZ(src.Proxy, dst.Proxy)); diff --git a/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs b/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs index ad080a646..3d18efc78 100644 --- a/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs +++ b/src/OpenCvSharp/Modules/dnn/ClassificationModel.cs @@ -75,7 +75,7 @@ public bool GetEnableSoftmaxPostProcessing() /// The input image. /// Top-1 predicted class id. /// Top-1 prediction confidence. - public void Classify(InputArrayRef frame, out int classId, out float conf) + public void Classify(InputArray frame, out int classId, out float conf) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs b/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs index c3e0e6c8d..75a3f86d9 100644 --- a/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs +++ b/src/OpenCvSharp/Modules/dnn/Cv2.Dnn.cs @@ -264,7 +264,7 @@ public static Mat BlobFromImages( /// input image (all with 1-, 3- or 4-channels). /// params with preprocessing parameters. If null, default params are used. /// 4-dimensional Mat. - public static Mat BlobFromImageWithParams(InputArrayRef image, Image2BlobParams? param = null) + public static Mat BlobFromImageWithParams(InputArray image, Image2BlobParams? param = null) { param ??= new Image2BlobParams(); diff --git a/src/OpenCvSharp/Modules/dnn/DetectionModel.cs b/src/OpenCvSharp/Modules/dnn/DetectionModel.cs index 0a4e6d0c8..932ca5e34 100644 --- a/src/OpenCvSharp/Modules/dnn/DetectionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/DetectionModel.cs @@ -83,7 +83,7 @@ public bool GetNmsAcrossClasses() /// A threshold used to filter boxes by confidences. /// A threshold used in non maximum suppression. public void Detect( - InputArrayRef frame, out int[] classIds, out float[] confidences, out Rect[] boxes, + InputArray frame, out int[] classIds, out float[] confidences, out Rect[] boxes, float confThreshold = 0.5f, float nmsThreshold = 0.0f) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs b/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs index d7ff51c15..ad4304cbd 100644 --- a/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs +++ b/src/OpenCvSharp/Modules/dnn/Image2BlobParams.cs @@ -8,7 +8,7 @@ namespace OpenCvSharp.Dnn; /// Processing params of image to blob. /// It includes all possible image processing operations and corresponding parameters. ///
-/// +/// public class Image2BlobParams { /// diff --git a/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs b/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs index d36a9f85f..0a7c3e5c4 100644 --- a/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs +++ b/src/OpenCvSharp/Modules/dnn/KeypointsModel.cs @@ -53,7 +53,7 @@ public KeypointsModel(Net network) /// The input image. /// minimum confidence threshold to select a keypoint. /// a vector holding the x and y coordinates of each detected keypoint. - public Point2f[] Estimate(InputArrayRef frame, float thresh = 0.5f) + public Point2f[] Estimate(InputArray frame, float thresh = 0.5f) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/Model.cs b/src/OpenCvSharp/Modules/dnn/Model.cs index c8fcd7609..a491db6de 100644 --- a/src/OpenCvSharp/Modules/dnn/Model.cs +++ b/src/OpenCvSharp/Modules/dnn/Model.cs @@ -169,7 +169,7 @@ public void SetInputParams(double scale = 1.0, Size? size = null, Scalar? mean = /// /// The input image. /// Allocated output blobs, which will store results of the computation. - public Mat[] Predict(InputArrayRef frame) + public Mat[] Predict(InputArray frame) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs b/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs index c7c5ee5e9..7a56b0c7f 100644 --- a/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs +++ b/src/OpenCvSharp/Modules/dnn/SegmentationModel.cs @@ -51,7 +51,7 @@ public SegmentationModel(Net network) ///
/// The input image. /// Allocated class prediction for each pixel. - public void Segment(InputArrayRef frame, OutputArrayRef mask) + public void Segment(InputArray frame, OutputArray mask) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs b/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs index 022b7981a..b0790c1c1 100644 --- a/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/TextDetectionModel.cs @@ -30,7 +30,7 @@ protected TextDetectionModel() /// The input image. /// array with detections' quadrangles (4 points per result). /// array with detection confidences. - public void Detect(InputArrayRef frame, out Point[][] detections, out float[] confidences) + public void Detect(InputArray frame, out Point[][] detections, out float[] confidences) { ThrowIfDisposed(); @@ -51,7 +51,7 @@ public void Detect(InputArrayRef frame, out Point[][] detections, out float[] co /// The input image. /// array with detections' RotatedRect results. /// array with detection confidences. - public void DetectTextRectangles(InputArrayRef frame, out RotatedRect[] detections, out float[] confidences) + public void DetectTextRectangles(InputArray frame, out RotatedRect[] detections, out float[] confidences) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs b/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs index 1bd574961..553c21089 100644 --- a/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs +++ b/src/OpenCvSharp/Modules/dnn/TextRecognitionModel.cs @@ -122,7 +122,7 @@ public void SetVocabulary(IEnumerable vocabulary) ///
/// The input image. /// The text recognition result. - public string Recognize(InputArrayRef frame) + public string Recognize(InputArray frame) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs b/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs index e0c3dbfda..f3b1637a7 100644 --- a/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs +++ b/src/OpenCvSharp/Modules/dnn_superres/DnnSuperResImpl.cs @@ -135,7 +135,7 @@ public void SetPreferableTarget(Target targetId) ///
/// Image to upscale /// Destination upscaled image - public void Upsample(InputArrayRef img, OutputArrayRef result) + public void Upsample(InputArray img, OutputArray result) { ThrowIfDisposed(); @@ -154,7 +154,7 @@ public void Upsample(InputArrayRef img, OutputArrayRef result) /// Names of the output nodes in the neural network [SuppressMessage("Maintainability", "CA1508: Avoid dead conditional code")] public void UpsampleMultioutput( - InputArrayRef img, out Mat[] imgsNew, IEnumerable scaleFactors, IEnumerable nodeNames) + InputArray img, out Mat[] imgsNew, IEnumerable scaleFactors, IEnumerable nodeNames) { ThrowIfDisposed(); if (scaleFactors is null) diff --git a/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs b/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs index f07b78144..5f9e944c7 100644 --- a/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs +++ b/src/OpenCvSharp/Modules/face/FaceRecognizer/FaceRecognizer.cs @@ -64,7 +64,7 @@ public void Update(IEnumerable src, IEnumerable labels) ///
/// /// - public virtual int Predict(InputArrayRef src) + public virtual int Predict(InputArray src) { ThrowIfDisposed(); @@ -80,7 +80,7 @@ public virtual int Predict(InputArrayRef src) /// /// /// - public virtual void Predict(InputArrayRef src, out int label, out double confidence) + public virtual void Predict(InputArray src, out int label, out double confidence) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs b/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs index d1fa5d5e1..9d3de904c 100644 --- a/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs +++ b/src/OpenCvSharp/Modules/face/Facemark/Facemark.cs @@ -39,8 +39,8 @@ public virtual void LoadModel(string model) /// The detected landmark points for each faces. /// public virtual bool Fit( - InputArrayRef image, - InputArrayRef faces, + InputArray image, + InputArray faces, out Point2f[][] landmarks) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/features/ANNIndex.cs b/src/OpenCvSharp/Modules/features/ANNIndex.cs index a0d936310..e74204666 100644 --- a/src/OpenCvSharp/Modules/features/ANNIndex.cs +++ b/src/OpenCvSharp/Modules/features/ANNIndex.cs @@ -34,7 +34,7 @@ public static ANNIndex Create(int dim, ANNIndexDistance distType = ANNIndexDista /// Adds feature vectors to the index. ///
/// Matrix containing the feature vectors to index (num_features x feature_dimension). - public void AddItems(InputArrayRef features) + public void AddItems(InputArray features) { ThrowIfDisposed(); @@ -60,7 +60,7 @@ public void Build(int trees = -1) /// Output matrix that will contain the distances to the K-nearest neighbors found. /// Number of nearest neighbors to search for. /// The maximum number of nodes to inspect; defaults to trees x knn when -1. - public void KnnSearch(InputArrayRef query, OutputArrayRef indices, OutputArrayRef dists, int knn, int searchK = -1) + public void KnnSearch(InputArray query, OutputArray indices, OutputArray dists, int knn, int searchK = -1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/features/Feature2D.cs b/src/OpenCvSharp/Modules/features/Feature2D.cs index 69e21594d..3fba9de4f 100644 --- a/src/OpenCvSharp/Modules/features/Feature2D.cs +++ b/src/OpenCvSharp/Modules/features/Feature2D.cs @@ -116,7 +116,7 @@ public KeyPoint[] Detect(Mat image, Mat? mask = null) /// Mask specifying where to look for keypoints (optional). /// Must be a char matrix with non-zero values in the region of interest. /// The detected keypoints. - public KeyPoint[] Detect(InputArrayRef image, InputArrayRef mask = default) + public KeyPoint[] Detect(InputArray image, InputArray mask = default) { ThrowIfDisposed(); @@ -175,7 +175,7 @@ public KeyPoint[][] Detect(IEnumerable images, IEnumerable? masks = nu /// The image. /// The input keypoints. Keypoints for which a descriptor cannot be computed are removed. /// Computed descriptors. Row i is the descriptor for KeyPoint i.param> - public virtual void Compute(InputArrayRef image, ref KeyPoint[] keypoints, OutputArrayRef descriptors) + public virtual void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray descriptors) { ThrowIfDisposed(); @@ -227,10 +227,10 @@ public virtual void Compute(IEnumerable images, ref KeyPoint[][] keypoints, /// /// public virtual void DetectAndCompute( - InputArrayRef image, - InputArrayRef mask, + InputArray image, + InputArray mask, out KeyPoint[] keypoints, - OutputArrayRef descriptors, + OutputArray descriptors, bool useProvidedKeypoints = false) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs b/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs index fe62f46ac..2fa9b1371 100644 --- a/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs +++ b/src/OpenCvSharp/Modules/features/LightGlueMatcher.cs @@ -63,7 +63,7 @@ public static LightGlueMatcher CreateFromMemory(byte[] modelData, float scoreThr /// Train image keypoints (Nx2 float matrix with x,y coordinates). /// Size of the query image (width, height). /// Size of the train image (width, height). - public void SetPairInfo(InputArrayRef queryKpts, InputArrayRef trainKpts, Size queryImageSize = default, Size trainImageSize = default) + public void SetPairInfo(InputArray queryKpts, InputArray trainKpts, Size queryImageSize = default, Size trainImageSize = default) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/features/MSER.cs b/src/OpenCvSharp/Modules/features/MSER.cs index 19f8cd8b6..1c7d62e35 100644 --- a/src/OpenCvSharp/Modules/features/MSER.cs +++ b/src/OpenCvSharp/Modules/features/MSER.cs @@ -142,7 +142,7 @@ public bool Pass2Only /// resulting list of point sets /// resulting bounding boxes public virtual void DetectRegions( - InputArrayRef image, out Point[][] msers, out Rect[] bboxes) + InputArray image, out Point[][] msers, out Rect[] bboxes) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/flann/Index.cs b/src/OpenCvSharp/Modules/flann/Index.cs index 33f373575..60aca0138 100644 --- a/src/OpenCvSharp/Modules/flann/Index.cs +++ b/src/OpenCvSharp/Modules/flann/Index.cs @@ -13,7 +13,7 @@ public class Index : CvObject /// features – Matrix of type CV _ 32F containing the features(points) to index. The size of the matrix is num _ features x feature _ dimensionality. /// Structure containing the index parameters. The type of index that will be constructed depends on the type of this parameter. /// - public Index(InputArrayRef features, IndexParams @params, FlannDistance distType = FlannDistance.L2) + public Index(InputArray features, IndexParams @params, FlannDistance distType = FlannDistance.L2) { if (@params is null) throw new ArgumentNullException(nameof(@params)); diff --git a/src/OpenCvSharp/Modules/img_hash/AverageHash.cs b/src/OpenCvSharp/Modules/img_hash/AverageHash.cs index 684a4aedb..1b4231d12 100644 --- a/src/OpenCvSharp/Modules/img_hash/AverageHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/AverageHash.cs @@ -36,7 +36,7 @@ public static AverageHash Create() /// input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. /// Hash value of input, it will contain 16 hex decimal number, return type is CV_8U /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); }*/ diff --git a/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs b/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs index c9f428bd2..b5b807edb 100644 --- a/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/BlockMeanHash.cs @@ -63,7 +63,7 @@ public double[] GetMean() /// input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. /// Hash value of input, it will contain 16 hex decimal number, return type is CV_8U /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); }*/ diff --git a/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs b/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs index a01010ee6..75f86b08e 100644 --- a/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/ColorMomentHash.cs @@ -31,7 +31,7 @@ public static ColorMomentHash Create() // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs b/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs index ba76df8fe..3d7c36d42 100644 --- a/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs +++ b/src/OpenCvSharp/Modules/img_hash/ImgHashBase.cs @@ -18,7 +18,7 @@ protected ImgHashBase(IntPtr smartPtr, IntPtr rawPtr, Action release) /// input image want to compute hash value /// hash of the image /// - public virtual void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public virtual void Compute(InputArray inputArr, OutputArray outputArr) { ThrowIfDisposed(); @@ -34,7 +34,7 @@ public virtual void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) /// Hash value one /// Hash value two /// value indicate similarity between inOne and inTwo, the meaning of the value vary from algorithms to algorithms - public virtual double Compare(InputArrayRef hashOne, InputArrayRef hashTwo) + public virtual double Compare(InputArray hashOne, InputArray hashTwo) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs b/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs index d1415f3f9..41b8bb66a 100644 --- a/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/MarrHildrethHash.cs @@ -89,7 +89,7 @@ public float Scale // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/PHash.cs b/src/OpenCvSharp/Modules/img_hash/PHash.cs index 1393a91c0..24a9fe160 100644 --- a/src/OpenCvSharp/Modules/img_hash/PHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/PHash.cs @@ -31,7 +31,7 @@ public static PHash Create() // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs b/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs index 9d5c68598..7c2614a9e 100644 --- a/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs +++ b/src/OpenCvSharp/Modules/img_hash/RadialVarianceHash.cs @@ -75,7 +75,7 @@ public int NumOfAngleLine // ReSharper disable once RedundantOverriddenMember /// - public override void Compute(InputArrayRef inputArr, OutputArrayRef outputArr) + public override void Compute(InputArray inputArr, OutputArray outputArr) { base.Compute(inputArr, outputArr); } diff --git a/src/OpenCvSharp/Modules/imgproc/CLAHE.cs b/src/OpenCvSharp/Modules/imgproc/CLAHE.cs index 92e639b10..afaa40882 100644 --- a/src/OpenCvSharp/Modules/imgproc/CLAHE.cs +++ b/src/OpenCvSharp/Modules/imgproc/CLAHE.cs @@ -42,7 +42,7 @@ public static CLAHE Create(double clipLimit = 40.0, Size? tileGridSize = null) ///
/// Source image of type CV_8UC1 or CV_16UC1. /// Destination image. - public void Apply(InputArrayRef src, OutputArrayRef dst) + public void Apply(InputArray src, OutputArray dst) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs b/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs index 89178de66..082820510 100644 --- a/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs +++ b/src/OpenCvSharp/Modules/imgproc/Enum/PutTextFlags.cs @@ -1,7 +1,7 @@ namespace OpenCvSharp; /// -/// Flags for the FontFace-based +/// Flags for the FontFace-based /// and (OpenCV 5). /// [Flags] diff --git a/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs b/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs index ca2e50be7..a8a6d7787 100644 --- a/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs +++ b/src/OpenCvSharp/Modules/imgproc/Filter2DParams.cs @@ -1,7 +1,7 @@ namespace OpenCvSharp; /// -/// Parameters for the OpenCV 5 overload. +/// Parameters for the OpenCV 5 overload. /// Mirrors cv::Filter2DParams; all fields are optional and default to the OpenCV defaults. /// public class Filter2DParams diff --git a/src/OpenCvSharp/Modules/imgproc/FontFace.cs b/src/OpenCvSharp/Modules/imgproc/FontFace.cs index 9f7b45b40..3619381b2 100644 --- a/src/OpenCvSharp/Modules/imgproc/FontFace.cs +++ b/src/OpenCvSharp/Modules/imgproc/FontFace.cs @@ -4,7 +4,7 @@ namespace OpenCvSharp; /// -/// TrueType font face used by the FontFace-based +/// TrueType font face used by the FontFace-based /// and (OpenCV 5). /// public class FontFace : CvObject diff --git a/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs b/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs index 05383c535..85fef9c00 100644 --- a/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs +++ b/src/OpenCvSharp/Modules/imgproc/GeneralizedHough.cs @@ -123,7 +123,7 @@ public int MaxBufferSize ///
/// /// - public void SetTemplate(InputArrayRef templ, Point? templCenter = null) + public void SetTemplate(InputArray templ, Point? templCenter = null) { ThrowIfDisposed(); var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); @@ -140,7 +140,7 @@ public void SetTemplate(InputArrayRef templ, Point? templCenter = null) /// /// /// - public virtual void SetTemplate(InputArrayRef edges, InputArrayRef dx, InputArrayRef dy, Point? templCenter = null) + public virtual void SetTemplate(InputArray edges, InputArray dx, InputArray dy, Point? templCenter = null) { ThrowIfDisposed(); var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); @@ -161,7 +161,7 @@ public virtual void SetTemplate(InputArrayRef edges, InputArrayRef dx, InputArra /// /// public virtual void Detect( - InputArrayRef image, OutputArrayRef positions, OutputArrayRef votes = default) + InputArray image, OutputArray positions, OutputArray votes = default) { NativeMethods.HandleException( NativeMethods.imgproc_GeneralizedHough_detect1( @@ -181,7 +181,7 @@ public virtual void Detect( /// /// public virtual void Detect( - InputArrayRef edges, InputArrayRef dx, InputArrayRef dy, OutputArrayRef positions, OutputArrayRef votes = default) + InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = default) { NativeMethods.HandleException( NativeMethods.imgproc_GeneralizedHough_detect2( diff --git a/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs b/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs index bbc458df2..cc344e01f 100644 --- a/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs +++ b/src/OpenCvSharp/Modules/imgproc/IntelligentScissorsMB.cs @@ -134,7 +134,7 @@ public IntelligentScissorsMB SetEdgeFeatureCannyParameters( ///
/// input image. Type is #CV_8UC1 / #CV_8UC3 /// - public IntelligentScissorsMB ApplyImage(InputArrayRef image) + public IntelligentScissorsMB ApplyImage(InputArray image) { ThrowIfDisposed(); @@ -155,8 +155,8 @@ public IntelligentScissorsMB ApplyImage(InputArrayRef image) /// Optional parameter. Must be specified if subset of features is specified (non-specified features are calculated internally) /// public IntelligentScissorsMB ApplyImageFeatures( - InputArrayRef nonEdge, InputArrayRef gradientDirection, InputArrayRef gradientMagnitude, - InputArrayRef image = default) + InputArray nonEdge, InputArray gradientDirection, InputArray gradientMagnitude, + InputArray image = default) { ThrowIfDisposed(); @@ -189,7 +189,7 @@ public void BuildMap(Point sourcePt) /// contour The list of pixels which contains optimal path between the source and the target points of the image. /// Type is CV_32SC2 (compatible with `std::vector<Point>`) /// Flag to indicate reverse order of retrived pixels (use "true" value to fetch points from the target to the source point) - public void GetContour(Point targetPt, OutputArrayRef contour, bool backward = false) + public void GetContour(Point targetPt, OutputArray contour, bool backward = false) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs b/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs index 6a36a1dee..a4cde03d7 100644 --- a/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs +++ b/src/OpenCvSharp/Modules/imgproc/LineSegmentDetector.cs @@ -49,8 +49,8 @@ public static LineSegmentDetector Create( /// Vector of precisions with which the lines are found. /// Vector containing number of false alarms in the line region, /// with precision of 10%. The bigger the value, logarithmically better the detection. - public virtual void Detect(InputArrayRef image, OutputArrayRef lines, - OutputArrayRef width = default, OutputArrayRef prec = default, OutputArrayRef nfa = default) + public virtual void Detect(InputArray image, OutputArray lines, + OutputArray width = default, OutputArray prec = default, OutputArray nfa = default) { NativeMethods.imgproc_LineSegmentDetector_detect_OutputArray(Handle, image.Proxy, lines.Proxy, width.Proxy, prec.Proxy, nfa.Proxy); @@ -72,7 +72,7 @@ public virtual void Detect(InputArrayRef image, OutputArrayRef lines, /// Vector of precisions with which the lines are found. /// Vector containing number of false alarms in the line region, /// with precision of 10%. The bigger the value, logarithmically better the detection. - public virtual void Detect(InputArrayRef image, out Vec4f[] lines, + public virtual void Detect(InputArray image, out Vec4f[] lines, out double[] width, out double[] prec, out double[] nfa) { using (var linesVec = new StdVector()) @@ -97,7 +97,7 @@ public virtual void Detect(InputArrayRef image, out Vec4f[] lines, /// The image, where the liens will be drawn. /// Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. - public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines) + public virtual void DrawSegments(InputOutputArray image, InputArray lines) { NativeMethods.imgproc_LineSegmentDetector_drawSegments(Handle, image.Proxy, lines.Proxy); GC.KeepAlive(image.Source); @@ -115,7 +115,7 @@ public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines) /// in the above mentioned colors. /// public virtual int CompareSegments( - Size size, InputArrayRef lines1, InputArrayRef lines2, InputOutputArrayRef image = default) + Size size, InputArray lines1, InputArray lines2, InputOutputArray image = default) { var ret = NativeMethods.imgproc_LineSegmentDetector_compareSegments( Handle, size, lines1.Proxy, lines2.Proxy, image.Proxy); diff --git a/src/OpenCvSharp/Modules/imgproc/Moments.cs b/src/OpenCvSharp/Modules/imgproc/Moments.cs index 3a3cbc212..4763d269d 100644 --- a/src/OpenCvSharp/Modules/imgproc/Moments.cs +++ b/src/OpenCvSharp/Modules/imgproc/Moments.cs @@ -65,7 +65,7 @@ public Moments(double m00, double m10, double m01, double m20, double m11, /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - public Moments(InputArrayRef array, bool binaryImage = false) + public Moments(InputArray array, bool binaryImage = false) { InitializeFromInputArray(array, binaryImage); } @@ -144,7 +144,7 @@ public Moments(IEnumerable array, bool binaryImage = false) /// 2D array) or an array ( 1xN or Nx1 ) of 2D points ( Point or Point2f ) /// If it is true, then all the non-zero image pixels are treated as 1’s /// - private void InitializeFromInputArray(InputArrayRef array, bool binaryImage) + private void InitializeFromInputArray(InputArray array, bool binaryImage) { NativeMethods.HandleException( NativeMethods.imgproc_moments(array.Proxy, binaryImage ? 1 : 0, out var m)); diff --git a/src/OpenCvSharp/Modules/ml/ANN_MLP.cs b/src/OpenCvSharp/Modules/ml/ANN_MLP.cs index 03ce7b38a..ef8ee3274 100644 --- a/src/OpenCvSharp/Modules/ml/ANN_MLP.cs +++ b/src/OpenCvSharp/Modules/ml/ANN_MLP.cs @@ -284,7 +284,7 @@ public virtual void SetActivationFunction(ActivationFunctions type, double param /// The last element - number of elements in the output layer.Default value is empty Mat. ///
/// - public virtual void SetLayerSizes(InputArrayRef layerSizes) + public virtual void SetLayerSizes(InputArray layerSizes) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/EM.cs b/src/OpenCvSharp/Modules/ml/EM.cs index 93984da4e..e24557bb6 100644 --- a/src/OpenCvSharp/Modules/ml/EM.cs +++ b/src/OpenCvSharp/Modules/ml/EM.cs @@ -197,10 +197,10 @@ public Mat[] GetCovs() /// // ReSharper disable once InconsistentNaming public virtual bool TrainEM( - InputArrayRef samples, - OutputArrayRef logLikelihoods = default, - OutputArrayRef labels = default, - OutputArrayRef probs = default) + InputArray samples, + OutputArray logLikelihoods = default, + OutputArray labels = default, + OutputArray probs = default) { ThrowIfDisposed(); @@ -242,13 +242,13 @@ public virtual bool TrainEM( /// The optional output matrix that contains posterior probabilities of each Gaussian /// mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. public virtual bool TrainE( - InputArrayRef samples, - InputArrayRef means0, - InputArrayRef covs0 = default, - InputArrayRef weights0 = default, - OutputArrayRef logLikelihoods = default, - OutputArrayRef labels = default, - OutputArrayRef probs = default) + InputArray samples, + InputArray means0, + InputArray covs0 = default, + InputArray weights0 = default, + OutputArray logLikelihoods = default, + OutputArray labels = default, + OutputArray probs = default) { ThrowIfDisposed(); @@ -289,11 +289,11 @@ public virtual bool TrainE( /// The optional output matrix that contains posterior probabilities of each Gaussian /// mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and CV_64FC1 type. public virtual bool TrainM( - InputArrayRef samples, - InputArrayRef probs0, - OutputArrayRef logLikelihoods = default, - OutputArrayRef labels = default, - OutputArrayRef probs = default) + InputArray samples, + InputArray probs0, + OutputArray logLikelihoods = default, + OutputArray labels = default, + OutputArray probs = default) { ThrowIfDisposed(); @@ -323,7 +323,7 @@ public virtual bool TrainM( /// \f$1 \times dims\f$ or \f$dims \times 1\f$ size. /// Optional output matrix that contains posterior probabilities of each component /// given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. - public virtual Vec2d Predict2(InputArrayRef sample, OutputArrayRef probs = default) + public virtual Vec2d Predict2(InputArray sample, OutputArray probs = default) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/KNearest.cs b/src/OpenCvSharp/Modules/ml/KNearest.cs index 9549bdb03..a1d76b965 100644 --- a/src/OpenCvSharp/Modules/ml/KNearest.cs +++ b/src/OpenCvSharp/Modules/ml/KNearest.cs @@ -152,8 +152,8 @@ public Types AlgorithmType /// Optional output distances from the input vectors to the corresponding neighbors. /// It is a single-precision floating-point matrix of `[number_of_samples] * k` size. /// - public float FindNearest(InputArrayRef samples, int k, OutputArrayRef results, - OutputArrayRef neighborResponses = default, OutputArrayRef dist = default) + public float FindNearest(InputArray samples, int k, OutputArray results, + OutputArray neighborResponses = default, OutputArray dist = default) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/LogisticRegression.cs b/src/OpenCvSharp/Modules/ml/LogisticRegression.cs index 0f021cd15..454753ee4 100644 --- a/src/OpenCvSharp/Modules/ml/LogisticRegression.cs +++ b/src/OpenCvSharp/Modules/ml/LogisticRegression.cs @@ -184,7 +184,7 @@ public TermCriteria TermCriteria /// Predicted labels as a column matrix of type CV_32S. /// Not used. /// - public float Predict(InputArrayRef samples, OutputArrayRef results = default, int flags = 0) + public float Predict(InputArray samples, OutputArray results = default, int flags = 0) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs b/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs index 9e739515d..991366b68 100644 --- a/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs +++ b/src/OpenCvSharp/Modules/ml/NormalBayesClassifier.cs @@ -70,8 +70,8 @@ public static NormalBayesClassifier LoadFromString(string strModel) /// output vector outputs. The predicted class for a single input vector is returned by the method. /// The vector outputProbs contains the output probabilities corresponding to each element of result. /// - public float PredictProb(InputArrayRef inputs, OutputArrayRef outputs, - OutputArrayRef outputProbs, int flags = 0) + public float PredictProb(InputArray inputs, OutputArray outputs, + OutputArray outputProbs, int flags = 0) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/SVM.cs b/src/OpenCvSharp/Modules/ml/SVM.cs index 8467fb556..33bff6a75 100644 --- a/src/OpenCvSharp/Modules/ml/SVM.cs +++ b/src/OpenCvSharp/Modules/ml/SVM.cs @@ -337,7 +337,7 @@ public Mat GetSupportVectors() /// within the matrix of support vectors (which can be retrieved by SVM::getSupportVectors). /// In the case of linear %SVM each decision function consists of a single "compressed" support vector. /// - public double GetDecisionFunction(int i, OutputArrayRef alpha, OutputArrayRef svidx) + public double GetDecisionFunction(int i, OutputArray alpha, OutputArray svidx) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ml/StatModel.cs b/src/OpenCvSharp/Modules/ml/StatModel.cs index 0b2e28f4b..d154841e6 100644 --- a/src/OpenCvSharp/Modules/ml/StatModel.cs +++ b/src/OpenCvSharp/Modules/ml/StatModel.cs @@ -80,7 +80,7 @@ public virtual bool Train(TrainData trainData, int flags = 0) /// SampleTypes value /// vector of responses associated with the training samples. /// - public virtual bool Train(InputArrayRef samples, SampleTypes layout, InputArrayRef responses) + public virtual bool Train(InputArray samples, SampleTypes layout, InputArray responses) { ThrowIfDisposed(); @@ -103,7 +103,7 @@ public virtual bool Train(InputArrayRef samples, SampleTypes layout, InputArrayR /// sounds a bit confusing. /// the optional output responses. /// - public virtual float CalcError(TrainData data, bool test, OutputArrayRef resp) + public virtual float CalcError(TrainData data, bool test, OutputArray resp) { throw new NotImplementedException(); } @@ -115,7 +115,7 @@ public virtual float CalcError(TrainData data, bool test, OutputArrayRef resp) /// The optional output matrix of results. /// The optional flags, model-dependent. /// - public virtual float Predict(InputArrayRef samples, OutputArrayRef results = default, Flags flags = 0) + public virtual float Predict(InputArray samples, OutputArray results = default, Flags flags = 0) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs b/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs index 78fb836e5..bdc1eb47c 100644 --- a/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs +++ b/src/OpenCvSharp/Modules/objdetect/FaceDetectorYN.cs @@ -65,8 +65,8 @@ public static FaceDetectorYN Create( public int Detect(Mat image, Mat faces) { ThrowIfDisposed(); - InputArrayRef iaImage = image; - OutputArrayRef oaFaces = faces; + InputArray iaImage = image; + OutputArray oaFaces = faces; NativeMethods.HandleException( NativeMethods.objdetect_FaceDetectorYN_detect(Handle, iaImage.Proxy, oaFaces.Proxy, out var result)); return result; diff --git a/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs b/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs index 950bba848..56c8b28a2 100644 --- a/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs +++ b/src/OpenCvSharp/Modules/objdetect/QRCodeDetector.cs @@ -58,7 +58,7 @@ public void SetEpsY(double epsY) /// grayscale or color (BGR) image containing (or not) QR code. /// Output vector of vertices of the minimum-area quadrangle containing the code. /// - public bool Detect(InputArrayRef img, out Point2f[] points) + public bool Detect(InputArray img, out Point2f[] points) { using var pointsVec = new StdVector(); @@ -79,7 +79,7 @@ public bool Detect(InputArrayRef img, out Point2f[] points) /// Quadrangle vertices found by detect() method (or some other algorithm). /// The optional output image containing rectified and binarized QR code /// - public string Decode(InputArrayRef img, IEnumerable points, OutputArrayRef straightQrCode = default) + public string Decode(InputArray img, IEnumerable points, OutputArray straightQrCode = default) { if (points is null) throw new ArgumentNullException(nameof(points)); @@ -104,7 +104,7 @@ public string Decode(InputArrayRef img, IEnumerable points, OutputArray /// optional output array of vertices of the found QR code quadrangle. Will be empty if not found. /// The optional output image containing rectified and binarized QR code /// - public string DetectAndDecode(InputArrayRef img, out Point2f[] points, OutputArrayRef straightQrCode = default) + public string DetectAndDecode(InputArray img, out Point2f[] points, OutputArray straightQrCode = default) { using var pointsVec = new StdVector(); using var resultString = new StdString(); @@ -125,7 +125,7 @@ public string DetectAndDecode(InputArrayRef img, out Point2f[] points, OutputArr /// grayscale or color (BGR) image containing (or not) QR code. /// Output vector of vertices of the minimum-area quadrangle containing the codes. /// - public bool DetectMulti(InputArrayRef img, out Point2f[] points) + public bool DetectMulti(InputArray img, out Point2f[] points) { using var pointsVec = new StdVector(); @@ -146,7 +146,7 @@ public bool DetectMulti(InputArrayRef img, out Point2f[] points) /// Quadrangle vertices found by detect() method (or some other algorithm). /// UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. /// - public bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo) + public bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo) { return DecodeMulti(img, points, out decodedInfo, out _, false); } @@ -160,7 +160,7 @@ public bool DecodeMulti(InputArrayRef img, IEnumerable points, out stri /// UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. /// The optional output image containing rectified and binarized QR code /// - public bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode) + public bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode) { return DecodeMulti(img, points, out decodedInfo, out straightQrCode, true); } @@ -176,7 +176,7 @@ public bool DecodeMulti(InputArrayRef img, IEnumerable points, out stri /// The optional output image containing rectified and binarized QR code /// to output /// - protected bool DecodeMulti(InputArrayRef img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode, bool isOutputStraightQrCode) + protected bool DecodeMulti(InputArray img, IEnumerable points, out string?[] decodedInfo, out Mat[] straightQrCode, bool isOutputStraightQrCode) { if (points is null) throw new ArgumentNullException(nameof(points)); diff --git a/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs b/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs index 4d496bcfc..312c31fcd 100644 --- a/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs +++ b/src/OpenCvSharp/Modules/optflow/Cv2.OptFlow.cs @@ -19,7 +19,7 @@ public static partial class OptFlow /// Current time in milliseconds or other units. /// Maximal duration of the motion track in the same units as timestamp . public static void UpdateMotionHistory( - InputArrayRef silhouette, InputOutputArrayRef mhi, + InputArray silhouette, InputOutputArray mhi, double timestamp, double duration) { NativeMethods.HandleException( @@ -45,7 +45,7 @@ public static void UpdateMotionHistory( /// min(delta1, delta2) <= M(x,y)-m(x,y) <= max(delta1, delta2). /// public static void CalcMotionGradient( - InputArrayRef mhi, OutputArrayRef mask, OutputArrayRef orientation, + InputArray mhi, OutputArray mask, OutputArray orientation, double delta1, double delta2, int apertureSize = 3) { NativeMethods.HandleException( @@ -68,7 +68,7 @@ public static void CalcMotionGradient( /// Maximum duration of a motion track in milliseconds, passed to UpdateMotionHistory() . /// public static double CalcGlobalOrientation( - InputArrayRef orientation, InputArrayRef mask, InputArrayRef mhi, + InputArray orientation, InputArray mask, InputArray mhi, double timestamp, double duration) { NativeMethods.HandleException( @@ -91,7 +91,7 @@ public static double CalcGlobalOrientation( /// Current time in milliseconds or other units. /// Segmentation threshold that is recommended to be equal to the interval between motion history “steps” or greater. public static void SegmentMotion( - InputArrayRef mhi, OutputArrayRef segmask, + InputArray mhi, OutputArray segmask, out Rect[] boundingRects, double timestamp, double segThresh) { @@ -115,9 +115,9 @@ public static void SegmentMotion( /// Size of block through which we sum up when calculate cost function for pixel /// maximal flow that we search at each level public static void CalcOpticalFlowSF( - InputArrayRef from, - InputArrayRef to, - OutputArrayRef flow, + InputArray from, + InputArray to, + OutputArray flow, int layers, int averagingBlockSize, int maxFlow) @@ -152,9 +152,9 @@ public static void CalcOpticalFlowSF( /// color sigma for bilateral upscale operation /// threshold to detect point with irregular flow - where flow should be recalculated after upscale public static void CalcOpticalFlowSF( - InputArrayRef from, - InputArrayRef to, - OutputArrayRef flow, + InputArray from, + InputArray to, + OutputArray flow, int layers, int averagingBlockSize, int maxFlow, @@ -198,9 +198,9 @@ public static void CalcOpticalFlowSF( /// see the respective parameter of the ximgproc::fastGlobalSmootherFilter() /// see the respective parameter of the ximgproc::fastGlobalSmootherFilter() public static void CalcOpticalFlowSparseToDense( - InputArrayRef from, - InputArrayRef to, - OutputArrayRef flow, + InputArray from, + InputArray to, + OutputArray flow, int gridStep = 8, int k = 128, float sigma = 0.05f, diff --git a/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs b/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs index 1a258270a..46891bfe9 100644 --- a/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs +++ b/src/OpenCvSharp/Modules/photo/CalibrateCRF.cs @@ -18,7 +18,7 @@ protected CalibrateCRF(IntPtr smartPtr, IntPtr rawPtr, Action release) /// vector of input images /// 256x1 matrix with inverse camera response function /// vector of exposure time values for each image - public virtual void Process(IEnumerable src, OutputArrayRef dst, IEnumerable times) + public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable times) { if (src is null) throw new ArgumentNullException(nameof(src)); diff --git a/src/OpenCvSharp/Modules/photo/MergeExposures.cs b/src/OpenCvSharp/Modules/photo/MergeExposures.cs index 1ae7df0ca..a35051add 100644 --- a/src/OpenCvSharp/Modules/photo/MergeExposures.cs +++ b/src/OpenCvSharp/Modules/photo/MergeExposures.cs @@ -18,7 +18,7 @@ protected MergeExposures(IntPtr smartPtr, IntPtr rawPtr, Action release) /// result image /// vector of exposure time values for each image /// 256x1 matrix with inverse camera response function for each pixel value, it should have the same number of channels as images. - public virtual void Process(IEnumerable src, OutputArrayRef dst, IEnumerable times, InputArrayRef response) + public virtual void Process(IEnumerable src, OutputArray dst, IEnumerable times, InputArray response) { if (src is null) throw new ArgumentNullException(nameof(src)); diff --git a/src/OpenCvSharp/Modules/photo/MergeMertens.cs b/src/OpenCvSharp/Modules/photo/MergeMertens.cs index 396d046b0..1c7b5d85e 100644 --- a/src/OpenCvSharp/Modules/photo/MergeMertens.cs +++ b/src/OpenCvSharp/Modules/photo/MergeMertens.cs @@ -37,7 +37,7 @@ public static MergeMertens Create() ///
/// vector of input images /// result image - public void Process(IEnumerable src, OutputArrayRef dst) + public void Process(IEnumerable src, OutputArray dst) { if (src is null) throw new ArgumentNullException(nameof(src)); diff --git a/src/OpenCvSharp/Modules/photo/Tonemap.cs b/src/OpenCvSharp/Modules/photo/Tonemap.cs index 4c0e0f773..8cd1c289f 100644 --- a/src/OpenCvSharp/Modules/photo/Tonemap.cs +++ b/src/OpenCvSharp/Modules/photo/Tonemap.cs @@ -40,7 +40,7 @@ public static Tonemap Create(float gamma = 1f) ///
/// source image - CV_32FC3 Mat (float 32 bits 3 channels) /// destination image - CV_32FC3 Mat with values in [0, 1] range - public virtual void Process(InputArrayRef src, OutputArrayRef dst) + public virtual void Process(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.photo_Tonemap_process(Handle, src.Proxy, dst.Proxy)); diff --git a/src/OpenCvSharp/Modules/ptcloud/Odometry.cs b/src/OpenCvSharp/Modules/ptcloud/Odometry.cs index a38a0c646..08804ed50 100644 --- a/src/OpenCvSharp/Modules/ptcloud/Odometry.cs +++ b/src/OpenCvSharp/Modules/ptcloud/Odometry.cs @@ -116,7 +116,7 @@ public void PrepareFrames(OdometryFrame srcFrame, OdometryFrame dstFrame) /// dst frame ("rotated" image). /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArrayRef Rt) + public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArray Rt) { ThrowIfDisposed(); if (srcFrame is null) @@ -139,7 +139,7 @@ public bool Compute(OdometryFrame srcFrame, OdometryFrame dstFrame, OutputArrayR /// destination depth ("rotated" image). /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(InputArrayRef srcDepth, InputArrayRef dstDepth, OutputArrayRef Rt) + public bool Compute(InputArray srcDepth, InputArray dstDepth, OutputArray Rt) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -158,7 +158,7 @@ public bool Compute(InputArrayRef srcDepth, InputArrayRef dstDepth, OutputArrayR /// destination RGB. /// Rigid transformation output (4x4). /// true on success, false if failed to find the transformation. - public bool Compute(InputArrayRef srcDepth, InputArrayRef srcRGB, InputArrayRef dstDepth, InputArrayRef dstRGB, OutputArrayRef Rt) + public bool Compute(InputArray srcDepth, InputArray srcRGB, InputArray dstDepth, InputArray dstRGB, OutputArray Rt) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs b/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs index 98bdf46ba..9f187e26b 100644 --- a/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs +++ b/src/OpenCvSharp/Modules/ptcloud/OdometryFrame.cs @@ -19,7 +19,7 @@ public class OdometryFrame : CvObject /// An BGR or grayscale image (or null if it's not required for the used ICP algorithm). /// A user-provided mask of valid pixels, should be CV_8UC1. /// A user-provided normals to the depth surface, should be CV_32FC4. - public OdometryFrame(InputArrayRef depth = default, InputArrayRef image = default, InputArrayRef mask = default, InputArrayRef normals = default) + public OdometryFrame(InputArray depth = default, InputArray image = default, InputArray mask = default, InputArray normals = default) { NativeMethods.HandleException( NativeMethods.ptcloud_OdometryFrame_new( @@ -59,7 +59,7 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) /// /// Gets the original user-provided BGR/Gray image. /// - public void GetImage(OutputArrayRef image) + public void GetImage(OutputArray image) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -69,7 +69,7 @@ public void GetImage(OutputArrayRef image) /// /// Gets the gray image generated from the user-provided BGR/Gray image. /// - public void GetGrayImage(OutputArrayRef image) + public void GetGrayImage(OutputArray image) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -79,7 +79,7 @@ public void GetGrayImage(OutputArrayRef image) /// /// Gets the original user-provided depth image. /// - public void GetDepth(OutputArrayRef depth) + public void GetDepth(OutputArray depth) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -89,7 +89,7 @@ public void GetDepth(OutputArrayRef depth) /// /// Gets the depth image generated for ICP algorithm needs. /// - public void GetProcessedDepth(OutputArrayRef depth) + public void GetProcessedDepth(OutputArray depth) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -99,7 +99,7 @@ public void GetProcessedDepth(OutputArrayRef depth) /// /// Gets the valid pixels mask generated for the ICP calculations intersected with the user-provided mask. /// - public void GetMask(OutputArrayRef mask) + public void GetMask(OutputArray mask) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -109,7 +109,7 @@ public void GetMask(OutputArrayRef mask) /// /// Gets the normals image either generated for the ICP calculations or user-provided. /// - public void GetNormals(OutputArrayRef normals) + public void GetNormals(OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -133,7 +133,7 @@ public int GetPyramidLevels() /// Output image. /// Type of pyramid. /// Level in the pyramid. - public void GetPyramidAt(OutputArrayRef img, OdometryFramePyramidType pyrType, long level) + public void GetPyramidAt(OutputArray img, OdometryFramePyramidType pyrType, long level) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs b/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs index 7ff2f33aa..199693019 100644 --- a/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs +++ b/src/OpenCvSharp/Modules/ptcloud/OdometrySettings.cs @@ -45,7 +45,7 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) /// /// Sets the camera matrix. /// - public void SetCameraMatrix(InputArrayRef val) + public void SetCameraMatrix(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -56,7 +56,7 @@ public void SetCameraMatrix(InputArrayRef val) /// /// Gets the camera matrix. /// - public void GetCameraMatrix(OutputArrayRef val) + public void GetCameraMatrix(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -66,7 +66,7 @@ public void GetCameraMatrix(OutputArrayRef val) /// /// Sets the iteration counts. /// - public void SetIterCounts(InputArrayRef val) + public void SetIterCounts(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -77,7 +77,7 @@ public void SetIterCounts(InputArrayRef val) /// /// Gets the iteration counts. /// - public void GetIterCounts(OutputArrayRef val) + public void GetIterCounts(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -87,7 +87,7 @@ public void GetIterCounts(OutputArrayRef val) /// /// Sets the minimum gradient magnitudes. /// - public void SetMinGradientMagnitudes(InputArrayRef val) + public void SetMinGradientMagnitudes(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -98,7 +98,7 @@ public void SetMinGradientMagnitudes(InputArrayRef val) /// /// Gets the minimum gradient magnitudes. /// - public void GetMinGradientMagnitudes(OutputArrayRef val) + public void GetMinGradientMagnitudes(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs b/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs index d0338dc0d..228046e96 100644 --- a/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs +++ b/src/OpenCvSharp/Modules/ptcloud/RgbdNormals.cs @@ -45,7 +45,7 @@ private static IntPtr GetRawPtr(IntPtr smartPtr) /// threshold in depth difference, used in LINEMOD algorithm. /// one of the methods to use. public static RgbdNormals Create( - int rows = 0, int cols = 0, int depth = 0, InputArrayRef K = default, int windowSize = 5, + int rows = 0, int cols = 0, int depth = 0, InputArray K = default, int windowSize = 5, float diffThreshold = 50f, RgbdNormalsMethod method = RgbdNormalsMethod.RGBD_NORMALS_METHOD_FALS) { NativeMethods.HandleException( @@ -72,7 +72,7 @@ public void Release() ///
/// a rows x cols x 3 matrix of CV_32F/CV_64F or a rows x cols x 1 CV_16U. /// a rows x cols x 3 matrix. - public void Apply(InputArrayRef points, OutputArrayRef normals) + public void Apply(InputArray points, OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -169,7 +169,7 @@ public int Depth /// Gets the calibration matrix. ///
/// the output calibration matrix. - public void GetK(OutputArrayRef val) + public void GetK(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -180,7 +180,7 @@ public void GetK(OutputArrayRef val) /// Sets the calibration matrix. ///
/// the calibration matrix to use. - public void SetK(InputArrayRef val) + public void SetK(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ptcloud/Volume.cs b/src/OpenCvSharp/Modules/ptcloud/Volume.cs index 39f610e8f..d66f27ac7 100644 --- a/src/OpenCvSharp/Modules/ptcloud/Volume.cs +++ b/src/OpenCvSharp/Modules/ptcloud/Volume.cs @@ -66,7 +66,7 @@ private void InitSafeHandle(IntPtr p, bool ownsHandle = true) ///
/// the object from which to take depth and image data. /// the pose of camera in global coordinates. - public void IntegrateFrame(OdometryFrame frame, InputArrayRef pose) + public void IntegrateFrame(OdometryFrame frame, InputArray pose) { ThrowIfDisposed(); if (frame is null) @@ -83,7 +83,7 @@ public void IntegrateFrame(OdometryFrame frame, InputArrayRef pose) ///
/// the depth image. /// the pose of camera in global coordinates. - public void Integrate(InputArrayRef depth, InputArrayRef pose) + public void Integrate(InputArray depth, InputArray pose) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -98,7 +98,7 @@ public void Integrate(InputArrayRef depth, InputArrayRef pose) /// the depth image. /// the color image (only for ColorTSDF). /// the pose of camera in global coordinates. - public void IntegrateColor(InputArrayRef depth, InputArrayRef image, InputArrayRef pose) + public void IntegrateColor(InputArray depth, InputArray image, InputArray pose) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -118,7 +118,7 @@ public void IntegrateColor(InputArrayRef depth, InputArrayRef image, InputArrayR /// the pose of camera in global coordinates. /// image to store rendered points. /// image to store rendered normals corresponding to points. - public void Raycast(InputArrayRef cameraPose, OutputArrayRef points, OutputArrayRef normals) + public void Raycast(InputArray cameraPose, OutputArray points, OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -133,7 +133,7 @@ public void Raycast(InputArrayRef cameraPose, OutputArrayRef points, OutputArray /// image to store rendered points. /// image to store rendered normals corresponding to points. /// image to store rendered colors corresponding to points (only for ColorTSDF). - public void RaycastColor(InputArrayRef cameraPose, OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) + public void RaycastColor(InputArray cameraPose, OutputArray points, OutputArray normals, OutputArray colors) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -150,7 +150,7 @@ public void RaycastColor(InputArrayRef cameraPose, OutputArrayRef points, Output /// camera raycast intrinsics. /// image to store rendered points. /// image to store rendered normals corresponding to points. - public void RaycastEx(InputArrayRef cameraPose, int height, int width, InputArrayRef K, OutputArrayRef points, OutputArrayRef normals) + public void RaycastEx(InputArray cameraPose, int height, int width, InputArray K, OutputArray points, OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -169,7 +169,7 @@ public void RaycastEx(InputArrayRef cameraPose, int height, int width, InputArra /// image to store rendered points. /// image to store rendered normals corresponding to points. /// image to store rendered colors corresponding to points (only for ColorTSDF). - public void RaycastExColor(InputArrayRef cameraPose, int height, int width, InputArrayRef K, OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) + public void RaycastExColor(InputArray cameraPose, int height, int width, InputArray K, OutputArray points, OutputArray normals, OutputArray colors) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -187,7 +187,7 @@ public void RaycastExColor(InputArrayRef cameraPose, int height, int width, Inpu ///
/// the input existing points. /// the storage of normals (corresponding to input points). - public void FetchNormals(InputArrayRef points, OutputArrayRef normals) + public void FetchNormals(InputArray points, OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -200,7 +200,7 @@ public void FetchNormals(InputArrayRef points, OutputArrayRef normals) ///
/// the storage of all points. /// the storage of all normals, corresponding to points. - public void FetchPointsNormals(OutputArrayRef points, OutputArrayRef normals) + public void FetchPointsNormals(OutputArray points, OutputArray normals) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -213,7 +213,7 @@ public void FetchPointsNormals(OutputArrayRef points, OutputArrayRef normals) /// the storage of all points. /// the storage of all normals, corresponding to points. /// the storage of all colors, corresponding to points (only for ColorTSDF). - public void FetchPointsNormalsColors(OutputArrayRef points, OutputArrayRef normals, OutputArrayRef colors) + public void FetchPointsNormalsColors(OutputArray points, OutputArray normals, OutputArray colors) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -261,7 +261,7 @@ public long GetTotalVolumeUnits() ///
/// 6-float 1d array containing (min_x, min_y, min_z, max_x, max_y, max_z) in volume coordinates. /// bounding box calculation precision. - public void GetBoundingBox(OutputArrayRef bb, VolumeBoundingBoxPrecision precision) + public void GetBoundingBox(OutputArray bb, VolumeBoundingBoxPrecision precision) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs b/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs index 8a86cda13..3ae127b0c 100644 --- a/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs +++ b/src/OpenCvSharp/Modules/ptcloud/VolumeSettings.cs @@ -251,7 +251,7 @@ public float RaycastStepFactor /// Sets volume pose. ///
/// input value. - public void SetVolumePose(InputArrayRef val) + public void SetVolumePose(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -263,7 +263,7 @@ public void SetVolumePose(InputArrayRef val) /// Gets volume pose. ///
/// output value. - public void GetVolumePose(OutputArrayRef val) + public void GetVolumePose(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -274,7 +274,7 @@ public void GetVolumePose(OutputArrayRef val) /// Sets resolution of voxel space. ///
/// input value. - public void SetVolumeResolution(InputArrayRef val) + public void SetVolumeResolution(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -286,7 +286,7 @@ public void SetVolumeResolution(InputArrayRef val) /// Gets resolution of voxel space. ///
/// output value. - public void GetVolumeResolution(OutputArrayRef val) + public void GetVolumeResolution(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -297,7 +297,7 @@ public void GetVolumeResolution(OutputArrayRef val) /// Returns 3 integers representing strides by x, y and z dimension. ///
/// output value. - public void GetVolumeStrides(OutputArrayRef val) + public void GetVolumeStrides(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -308,7 +308,7 @@ public void GetVolumeStrides(OutputArrayRef val) /// Sets intrinsics of camera for integrations. ///
/// input value. - public void SetCameraIntegrateIntrinsics(InputArrayRef val) + public void SetCameraIntegrateIntrinsics(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -320,7 +320,7 @@ public void SetCameraIntegrateIntrinsics(InputArrayRef val) /// Returns intrinsics of camera for integrations. ///
/// output value. - public void GetCameraIntegrateIntrinsics(OutputArrayRef val) + public void GetCameraIntegrateIntrinsics(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -331,7 +331,7 @@ public void GetCameraIntegrateIntrinsics(OutputArrayRef val) /// Sets camera intrinsics for raycast image. ///
/// input value. - public void SetCameraRaycastIntrinsics(InputArrayRef val) + public void SetCameraRaycastIntrinsics(InputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( @@ -343,7 +343,7 @@ public void SetCameraRaycastIntrinsics(InputArrayRef val) /// Returns camera intrinsics for raycast image. ///
/// output value. - public void GetCameraRaycastIntrinsics(OutputArrayRef val) + public void GetCameraRaycastIntrinsics(OutputArray val) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs b/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs index 0e35dca81..36fc2f258 100644 --- a/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs +++ b/src/OpenCvSharp/Modules/quality/QualityBRISQUE.cs @@ -72,7 +72,7 @@ public static QualityBRISQUE Create(SVM model, Mat range) /// String which contains a path to the BRISQUE model data, eg. /path/to/brisque_model_live.yml /// cv::String which contains a path to the BRISQUE range data, eg. /path/to/brisque_range_live.yml /// cv::Scalar with the score in the first element. The score ranges from 0 (best quality) to 100 (worst quality) - public static Scalar Compute(InputArrayRef img, string modelFilePath, string rangeFilePath) + public static Scalar Compute(InputArray img, string modelFilePath, string rangeFilePath) { if (string.IsNullOrEmpty(modelFilePath)) throw new ArgumentNullException(nameof(modelFilePath)); @@ -91,7 +91,7 @@ public static Scalar Compute(InputArrayRef img, string modelFilePath, string ran ///
/// image (BGR(A) or grayscale) for which to compute features /// output row vector of features to cv::Mat or cv::UMat - public static void ComputeFeatures(InputArrayRef img, OutputArrayRef features) + public static void ComputeFeatures(InputArray img, OutputArray features) { NativeMethods.HandleException( NativeMethods.quality_QualityBRISQUE_computeFeatures(img.Proxy, features.Proxy)); diff --git a/src/OpenCvSharp/Modules/quality/QualityBase.cs b/src/OpenCvSharp/Modules/quality/QualityBase.cs index 673606a95..76da5de88 100644 --- a/src/OpenCvSharp/Modules/quality/QualityBase.cs +++ b/src/OpenCvSharp/Modules/quality/QualityBase.cs @@ -31,7 +31,7 @@ public override bool Empty /// Returns output quality map that was generated during computation, if supported by the algorithm ///
/// - public virtual void GetQualityMap(OutputArrayRef dst) + public virtual void GetQualityMap(OutputArray dst) { NativeMethods.HandleException( NativeMethods.quality_QualityBase_getQualityMap(Handle, dst.Proxy)); @@ -43,7 +43,7 @@ public virtual void GetQualityMap(OutputArrayRef dst) /// See specific algorithm for interpreting result scores ///
/// comparison image, or image to evaluate for no-reference quality algorithms - public virtual Scalar Compute(InputArrayRef img) + public virtual Scalar Compute(InputArray img) { NativeMethods.HandleException( NativeMethods.quality_QualityBase_compute(Handle, img.Proxy, out var ret)); diff --git a/src/OpenCvSharp/Modules/quality/QualityGMSD.cs b/src/OpenCvSharp/Modules/quality/QualityGMSD.cs index 08c7bc5a9..ea33fb1c6 100644 --- a/src/OpenCvSharp/Modules/quality/QualityGMSD.cs +++ b/src/OpenCvSharp/Modules/quality/QualityGMSD.cs @@ -22,7 +22,7 @@ private QualityGMSD(IntPtr smartPtr, IntPtr rawPtr) ///
/// input image to use as the source for comparison /// - public static QualityGMSD Create(InputArrayRef @ref) + public static QualityGMSD Create(InputArray @ref) { NativeMethods.HandleException( NativeMethods.quality_createQualityGMSD(@ref.Proxy, out var smartPtr)); @@ -38,7 +38,7 @@ public static QualityGMSD Create(InputArrayRef @ref) /// /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) + public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray qualityMap = default) { NativeMethods.HandleException( NativeMethods.quality_QualityGMSD_staticCompute( diff --git a/src/OpenCvSharp/Modules/quality/QualityMSE.cs b/src/OpenCvSharp/Modules/quality/QualityMSE.cs index 077bd6dea..8dc706023 100644 --- a/src/OpenCvSharp/Modules/quality/QualityMSE.cs +++ b/src/OpenCvSharp/Modules/quality/QualityMSE.cs @@ -19,7 +19,7 @@ private QualityMSE(IntPtr smartPtr, IntPtr rawPtr) ///
/// input image to use as the source for comparison /// - public static QualityMSE Create(InputArrayRef @ref) + public static QualityMSE Create(InputArray @ref) { NativeMethods.HandleException( NativeMethods.quality_createQualityMSE(@ref.Proxy, out var smartPtr)); @@ -39,7 +39,7 @@ public static QualityMSE Create(InputArrayRef @ref) /// /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) + public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray qualityMap = default) { NativeMethods.HandleException( NativeMethods.quality_QualityMSE_staticCompute( diff --git a/src/OpenCvSharp/Modules/quality/QualityPSNR.cs b/src/OpenCvSharp/Modules/quality/QualityPSNR.cs index 14abc6965..9ae6c0135 100644 --- a/src/OpenCvSharp/Modules/quality/QualityPSNR.cs +++ b/src/OpenCvSharp/Modules/quality/QualityPSNR.cs @@ -44,7 +44,7 @@ public double MaxPixelValue /// input image to use as the source for comparison /// maximum per-channel value for any individual pixel; eg 255 for uint8 image /// - public static QualityPSNR Create(InputArrayRef @ref, double maxPixelValue = MaxPixelValueDefault) + public static QualityPSNR Create(InputArray @ref, double maxPixelValue = MaxPixelValueDefault) { NativeMethods.HandleException( NativeMethods.quality_createQualityPSNR(@ref.Proxy, maxPixelValue, out var smartPtr)); @@ -61,7 +61,7 @@ public static QualityPSNR Create(InputArrayRef @ref, double maxPixelValue = MaxP /// output quality map, or default to skip it /// maximum per-channel value for any individual pixel; eg 255 for uint8 image /// PSNR value, or double.PositiveInfinity if the MSE between the two images == 0 - public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default, double maxPixelValue = MaxPixelValueDefault) + public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray qualityMap = default, double maxPixelValue = MaxPixelValueDefault) { NativeMethods.HandleException( NativeMethods.quality_QualityPSNR_staticCompute( diff --git a/src/OpenCvSharp/Modules/quality/QualitySSIM.cs b/src/OpenCvSharp/Modules/quality/QualitySSIM.cs index 35b31c554..5bb7ee265 100644 --- a/src/OpenCvSharp/Modules/quality/QualitySSIM.cs +++ b/src/OpenCvSharp/Modules/quality/QualitySSIM.cs @@ -21,7 +21,7 @@ private QualitySSIM(IntPtr smartPtr, IntPtr rawPtr) ///
/// input image to use as the source for comparison /// - public static QualitySSIM Create(InputArrayRef @ref) + public static QualitySSIM Create(InputArray @ref) { NativeMethods.HandleException( NativeMethods.quality_createQualitySSIM(@ref.Proxy, out var smartPtr)); @@ -37,7 +37,7 @@ public static QualitySSIM Create(InputArrayRef @ref) /// /// output quality map, or default to skip it /// cv::Scalar with per-channel quality values. Values range from 0 (worst) to 1 (best) - public static Scalar Compute(InputArrayRef @ref, InputArrayRef cmp, OutputArrayRef qualityMap = default) + public static Scalar Compute(InputArray @ref, InputArray cmp, OutputArray qualityMap = default) { NativeMethods.HandleException( NativeMethods.quality_QualitySSIM_staticCompute( diff --git a/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs b/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs index 4306f5d44..cff43c833 100644 --- a/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs +++ b/src/OpenCvSharp/Modules/saliency/MotionSaliencyBinWangApr2014.cs @@ -32,7 +32,7 @@ public static MotionSaliencyBinWangApr2014 Create() /// Input image frame (grayscale, CV_8UC1). /// The computed binary saliency map. /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) + public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs b/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs index d36e960f5..16d9dd532 100644 --- a/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs +++ b/src/OpenCvSharp/Modules/saliency/ObjectnessBING.cs @@ -37,7 +37,7 @@ public static ObjectnessBING Create() /// Sorted by descending objectness score. /// /// true if the computation succeeded. - public virtual bool ComputeSaliency(InputArrayRef image, out Vec4i[] objectnessBoundingBox) + public virtual bool ComputeSaliency(InputArray image, out Vec4i[] objectnessBoundingBox) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs b/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs index 3969d19ba..4cf653b96 100644 --- a/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs +++ b/src/OpenCvSharp/Modules/saliency/StaticSaliencyFineGrained.cs @@ -32,7 +32,7 @@ public static StaticSaliencyFineGrained Create() /// The input image. /// The computed saliency map. /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) + public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) { ThrowIfDisposed(); @@ -49,7 +49,7 @@ public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliency /// The input saliency map. /// The computed binary map. /// true if the binary map was computed successfully. - public virtual bool ComputeBinaryMap(InputArrayRef saliencyMap, OutputArrayRef binaryMap) + public virtual bool ComputeBinaryMap(InputArray saliencyMap, OutputArray binaryMap) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs b/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs index 56e1516ca..127e55779 100644 --- a/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs +++ b/src/OpenCvSharp/Modules/saliency/StaticSaliencySpectralResidual.cs @@ -32,7 +32,7 @@ public static StaticSaliencySpectralResidual Create() /// The input image. /// The computed saliency map (CV_32FC1). /// true if the saliency map was computed successfully. - public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliencyMap) + public virtual bool ComputeSaliency(InputArray image, OutputArray saliencyMap) { ThrowIfDisposed(); @@ -49,7 +49,7 @@ public virtual bool ComputeSaliency(InputArrayRef image, OutputArrayRef saliency /// The input saliency map (CV_32FC1). /// The computed binary map. /// true if the binary map was computed successfully. - public virtual bool ComputeBinaryMap(InputArrayRef saliencyMap, OutputArrayRef binaryMap) + public virtual bool ComputeBinaryMap(InputArray saliencyMap, OutputArray binaryMap) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs b/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs index cdb8d9961..aff57b0b6 100644 --- a/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs +++ b/src/OpenCvSharp/Modules/shape/Cv2.Shape.cs @@ -81,7 +81,7 @@ public static EMDL1HistogramCostExtractor CreateEMDL1HistogramCostExtractor( /// First signature: a single-column float matrix where each row is a histogram bin value. /// Second signature, same format and size as signature1. /// The EMDL1 distance. - public static float EMDL1(InputArrayRef signature1, InputArrayRef signature2) + public static float EMDL1(InputArray signature1, InputArray signature2) { NativeMethods.HandleException( NativeMethods.shape_EMDL1(signature1.Proxy, signature2.Proxy, out var ret)); diff --git a/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs b/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs index acf680ea2..5d9f21f9a 100644 --- a/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/HistogramCostExtractor.cs @@ -18,7 +18,7 @@ protected HistogramCostExtractor(IntPtr smartPtr, IntPtr rawPtr, Action /// Second set of descriptors. /// Output cost matrix. public virtual void BuildCostMatrix( - InputArrayRef descriptors1, InputArrayRef descriptors2, OutputArrayRef costMatrix) + InputArray descriptors1, InputArray descriptors2, OutputArray costMatrix) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs b/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs index d2dfd40cb..80862b2d1 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeContextDistanceExtractor.cs @@ -255,7 +255,7 @@ public float StdDev ///
/// Image corresponding to the shape defined by contours1. /// Image corresponding to the shape defined by contours2. - public void SetImages(InputArrayRef image1, InputArrayRef image2) + public void SetImages(InputArray image1, InputArray image2) { ThrowIfDisposed(); @@ -272,7 +272,7 @@ public void SetImages(InputArrayRef image1, InputArrayRef image2) ///
/// Image corresponding to the shape defined by contours1. /// Image corresponding to the shape defined by contours2. - public void GetImages(OutputArrayRef image1, OutputArrayRef image2) + public void GetImages(OutputArray image1, OutputArray image2) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs b/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs index b69b715cf..752755034 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs @@ -19,7 +19,7 @@ protected ShapeDistanceExtractor(IntPtr smartPtr, IntPtr rawPtr, Action /// Contour defining second shape. /// /// - public virtual float ComputeDistance(InputArrayRef contour1, InputArrayRef contour2) + public virtual float ComputeDistance(InputArray contour1, InputArray contour2) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs b/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs index ee804a9fa..c2b164cbd 100644 --- a/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs +++ b/src/OpenCvSharp/Modules/shape/ShapeTransformer.cs @@ -27,8 +27,8 @@ protected ShapeTransformer(IntPtr smartPtr, IntPtr rawPtr, Action releas /// Contour defining second shape (to which the first will be transformed). /// Vector of matching points between the two contours. public virtual void EstimateTransformation( - InputArrayRef transformingShape, - InputArrayRef targetShape, + InputArray transformingShape, + InputArray targetShape, IEnumerable matches) { ThrowIfDisposed(); @@ -50,7 +50,7 @@ public virtual void EstimateTransformation( /// Contour (set of points) to apply the transformation to. /// Output contour. If null, only the cost is returned without writing the output. /// The transformation cost. - public virtual float ApplyTransformation(InputArrayRef input, OutputArrayRef output = default) + public virtual float ApplyTransformation(InputArray input, OutputArray output = default) { ThrowIfDisposed(); @@ -72,8 +72,8 @@ public virtual float ApplyTransformation(InputArrayRef input, OutputArrayRef out /// Border extrapolation method. Default: BorderTypes.Constant. /// Value used for BorderTypes.Constant borders. Default: black. public virtual void WarpImage( - InputArrayRef transformingImage, - OutputArrayRef output, + InputArray transformingImage, + OutputArray output, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) diff --git a/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs b/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs index e6dfef25b..567816e8e 100644 --- a/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs +++ b/src/OpenCvSharp/Modules/stereo/StereoMatcher.cs @@ -23,7 +23,7 @@ protected StereoMatcher(IntPtr smartPtr, IntPtr rawPtr, Action release) /// Output disparity map. It has the same size as the input images. Some algorithms, /// like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map(where each disparity value has 4 fractional bits), /// whereas other algorithms output 32 - bit floating - point disparity map. - public virtual void Compute(InputArrayRef left, InputArrayRef right, OutputArrayRef disparity) + public virtual void Compute(InputArray left, InputArray right, OutputArray disparity) { NativeMethods.HandleException( NativeMethods.stereo_StereoMatcher_compute(Handle, left.Proxy, right.Proxy, disparity.Proxy)); diff --git a/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs b/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs index e715aa6a0..14eaee31b 100644 --- a/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs +++ b/src/OpenCvSharp/Modules/stitching/Cv2.Detail.cs @@ -64,8 +64,8 @@ public static ImageFeatures[] ComputeImageFeatures( /// public static ImageFeatures ComputeImageFeatures( Feature2D featuresFinder, - InputArrayRef image, - InputArrayRef mask = default) + InputArray image, + InputArray mask = default) { if (featuresFinder is null) throw new ArgumentNullException(nameof(featuresFinder)); diff --git a/src/OpenCvSharp/Modules/stitching/Stitcher.cs b/src/OpenCvSharp/Modules/stitching/Stitcher.cs index f9bc40011..ddc945011 100644 --- a/src/OpenCvSharp/Modules/stitching/Stitcher.cs +++ b/src/OpenCvSharp/Modules/stitching/Stitcher.cs @@ -269,7 +269,7 @@ public double WorkScale #region Methods - public Status EstimateTransform(InputArrayRef images) + public Status EstimateTransform(InputArray images) { NativeMethods.HandleException( NativeMethods.stitching_Stitcher_estimateTransform_InputArray1(Handle, images.Proxy, out var ret)); @@ -278,7 +278,7 @@ public Status EstimateTransform(InputArrayRef images) return (Status)ret; } - public Status EstimateTransform(InputArrayRef images, Rect[][] rois) + public Status EstimateTransform(InputArray images, Rect[][] rois) { if (rois is null) throw new ArgumentNullException(nameof(rois)); @@ -325,7 +325,7 @@ public Status EstimateTransform(IEnumerable images, Rect[][] rois) return (Status)ret; } - public Status ComposePanorama(OutputArrayRef pano) + public Status ComposePanorama(OutputArray pano) { NativeMethods.HandleException( NativeMethods.stitching_Stitcher_composePanorama1(Handle, pano.Proxy, out var ret)); @@ -334,7 +334,7 @@ public Status ComposePanorama(OutputArrayRef pano) return (Status)ret; } - public Status ComposePanorama(InputArrayRef images, OutputArrayRef pano) + public Status ComposePanorama(InputArray images, OutputArray pano) { NativeMethods.HandleException( NativeMethods.stitching_Stitcher_composePanorama2_InputArray(Handle, images.Proxy, pano.Proxy, out var ret)); @@ -344,7 +344,7 @@ public Status ComposePanorama(InputArrayRef images, OutputArrayRef pano) return (Status)ret; } - public Status ComposePanorama(IEnumerable images, OutputArrayRef pano) + public Status ComposePanorama(IEnumerable images, OutputArray pano) { if (images is null) throw new ArgumentNullException(nameof(images)); @@ -364,7 +364,7 @@ public Status ComposePanorama(IEnumerable images, OutputArrayRef pano) /// Input images. /// Final pano. /// Status code. - public Status Stitch(InputArrayRef images, OutputArrayRef pano) + public Status Stitch(InputArray images, OutputArray pano) { NativeMethods.HandleException( NativeMethods.stitching_Stitcher_stitch1_InputArray(Handle, images.Proxy, pano.Proxy, out var ret)); @@ -381,7 +381,7 @@ public Status Stitch(InputArrayRef images, OutputArrayRef pano) /// Input images. /// Final pano. /// Status code. - public Status Stitch(IEnumerable images, OutputArrayRef pano) + public Status Stitch(IEnumerable images, OutputArray pano) { if (images is null) throw new ArgumentNullException(nameof(images)); @@ -404,7 +404,7 @@ public Status Stitch(IEnumerable images, OutputArrayRef pano) /// Region of interest rectangles. /// Final pano. /// Status code. - public Status Stitch(InputArrayRef images, Rect[][] rois, OutputArrayRef pano) + public Status Stitch(InputArray images, Rect[][] rois, OutputArray pano) { if (rois is null) throw new ArgumentNullException(nameof(rois)); @@ -425,7 +425,7 @@ public Status Stitch(InputArrayRef images, Rect[][] rois, OutputArrayRef pano) /// Region of interest rectangles. /// Final pano. /// Status code. - public Status Stitch(IEnumerable images, Rect[][] rois, OutputArrayRef pano) + public Status Stitch(IEnumerable images, Rect[][] rois, OutputArray pano) { if (images is null) throw new ArgumentNullException(nameof(images)); diff --git a/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs b/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs index a6c923457..9dc3fd9de 100644 --- a/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs +++ b/src/OpenCvSharp/Modules/superres/DenseOpticalFlowExt.cs @@ -100,7 +100,7 @@ public virtual void CollectGarbage() /// /// /// - public virtual void Calc(InputArrayRef frame0, InputArrayRef frame1, OutputArrayRef flow1, OutputArrayRef flow2 = default) + public virtual void Calc(InputArray frame0, InputArray frame1, OutputArray flow1, OutputArray flow2 = default) { NativeMethods.HandleException( NativeMethods.superres_DenseOpticalFlowExt_calc( diff --git a/src/OpenCvSharp/Modules/superres/FrameSource.cs b/src/OpenCvSharp/Modules/superres/FrameSource.cs index c070f65ed..0d2b26a43 100644 --- a/src/OpenCvSharp/Modules/superres/FrameSource.cs +++ b/src/OpenCvSharp/Modules/superres/FrameSource.cs @@ -88,7 +88,7 @@ public static FrameSource CreateFrameSource_Camera(int deviceId) /// ///
/// - public virtual void NextFrame(OutputArrayRef frame) + public virtual void NextFrame(OutputArray frame) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/superres/SuperResolution.cs b/src/OpenCvSharp/Modules/superres/SuperResolution.cs index a02b9a62c..f5cf547c6 100644 --- a/src/OpenCvSharp/Modules/superres/SuperResolution.cs +++ b/src/OpenCvSharp/Modules/superres/SuperResolution.cs @@ -77,7 +77,7 @@ public virtual void SetInput(FrameSource fs) /// Process next frame from input and return output result. ///
/// Output result - public virtual void NextFrame(OutputArrayRef frame) + public virtual void NextFrame(OutputArray frame) { ThrowIfDisposed(); @@ -116,7 +116,7 @@ protected virtual void InitImpl(FrameSource fs) ///
/// /// - protected virtual void ProcessImpl(FrameSource fs, OutputArrayRef output) + protected virtual void ProcessImpl(FrameSource fs, OutputArray output) { } diff --git a/src/OpenCvSharp/Modules/text/Cv2.Text.cs b/src/OpenCvSharp/Modules/text/Cv2.Text.cs index 4ed6eade9..98b50d350 100644 --- a/src/OpenCvSharp/Modules/text/Cv2.Text.cs +++ b/src/OpenCvSharp/Modules/text/Cv2.Text.cs @@ -27,7 +27,7 @@ public static partial class Text /// paper and returns all possible regions where text is likely to occur. /// a vector of resulting bounding boxes where probability of finding text is high public static Rect[] DetectTextSWT( - InputArrayRef input, bool darkOnLight, OutputArrayRef draw = default, OutputArrayRef chainBBs = default) + InputArray input, bool darkOnLight, OutputArray draw = default, OutputArray chainBBs = default) { using var result = new StdVector(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/text/TextDetector.cs b/src/OpenCvSharp/Modules/text/TextDetector.cs index a06d9108f..f475bfcc9 100644 --- a/src/OpenCvSharp/Modules/text/TextDetector.cs +++ b/src/OpenCvSharp/Modules/text/TextDetector.cs @@ -14,7 +14,7 @@ public abstract class TextDetector : CvObject /// an image to process /// a vector of Rect that will store the detected word bounding box /// a vector of float that will be updated with the confidence the classifier has for the selected bounding box - public virtual void Detect(InputArrayRef inputImage, out Rect[] bbox, out float[] confidence) + public virtual void Detect(InputArray inputImage, out Rect[] bbox, out float[] confidence) { using (var bboxVec = new StdVector()) using (var confidenceVec = new StdVector()) diff --git a/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs b/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs index c9ce72d59..6ffdb0e03 100644 --- a/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs +++ b/src/OpenCvSharp/Modules/text/TextDetectorCNN.cs @@ -70,7 +70,7 @@ internal TextDetectorCNN(IntPtr p) /// an image to process /// a vector of Rect that will store the detected word bounding box /// a vector of float that will be updated with the confidence the classifier has for the selected bounding box - public override void Detect(InputArrayRef inputImage, out Rect[] bbox, out float[] confidence) + public override void Detect(InputArray inputImage, out Rect[] bbox, out float[] confidence) { using var bboxVec = new StdVector(); using var confidenceVec = new StdVector(); diff --git a/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs b/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs index e44965812..4b9714e09 100644 --- a/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs +++ b/src/OpenCvSharp/Modules/tracking/TrackerCSRT.cs @@ -60,7 +60,7 @@ public static TrackerCSRT Create(Params parameters) /// ///
/// - public virtual void SetInitialMask(InputArrayRef mask) + public virtual void SetInitialMask(InputArray mask) { NativeMethods.HandleException( NativeMethods.tracking_TrackerCSRT_setInitialMask(RawPtr, mask.Proxy)); diff --git a/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs b/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs index c2a760d80..9dfcca38b 100644 --- a/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs +++ b/src/OpenCvSharp/Modules/video/BackgroundSubtractor.cs @@ -19,7 +19,7 @@ protected BackgroundSubtractor(IntPtr smartPtr, IntPtr rawPtr, Action re /// /// /// - public virtual void Apply(InputArrayRef image, OutputArrayRef fgmask, double learningRate = -1) + public virtual void Apply(InputArray image, OutputArray fgmask, double learningRate = -1) { NativeMethods.HandleException( NativeMethods.video_BackgroundSubtractor_apply(Handle, image.Proxy, fgmask.Proxy, learningRate)); @@ -32,7 +32,7 @@ public virtual void Apply(InputArrayRef image, OutputArrayRef fgmask, double lea /// computes a background image ///
/// - public virtual void GetBackgroundImage(OutputArrayRef backgroundImage) + public virtual void GetBackgroundImage(OutputArray backgroundImage) { NativeMethods.HandleException( NativeMethods.video_BackgroundSubtractor_getBackgroundImage(Handle, backgroundImage.Proxy)); diff --git a/src/OpenCvSharp/Modules/videoio/VideoCapture.cs b/src/OpenCvSharp/Modules/videoio/VideoCapture.cs index b150d5d82..c18c0a4eb 100644 --- a/src/OpenCvSharp/Modules/videoio/VideoCapture.cs +++ b/src/OpenCvSharp/Modules/videoio/VideoCapture.cs @@ -1146,7 +1146,7 @@ public bool Grab() /// the video frame is returned here. If no frames has been grabbed the image will be empty. /// it could be a frame index or a driver specific flag /// - public bool Retrieve(OutputArrayRef image, int flag = 0) + public bool Retrieve(OutputArray image, int flag = 0) { ThrowIfDisposed(); @@ -1166,7 +1166,7 @@ public bool Retrieve(OutputArrayRef image, int flag = 0) /// the video frame is returned here. If no frames has been grabbed the image will be empty. /// non-zero streamIdx is only valid for multi-head camera live streams /// - public bool Retrieve(OutputArrayRef image, CameraChannels streamIdx) + public bool Retrieve(OutputArray image, CameraChannels streamIdx) { ThrowIfDisposed(); @@ -1251,7 +1251,7 @@ public Mat RetrieveMat() /// frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). ///
/// `false` if no frames has been grabbed - public bool Read(OutputArrayRef image) + public bool Read(OutputArray image) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/videoio/VideoWriter.cs b/src/OpenCvSharp/Modules/videoio/VideoWriter.cs index 1a7c0c53a..8945cf449 100644 --- a/src/OpenCvSharp/Modules/videoio/VideoWriter.cs +++ b/src/OpenCvSharp/Modules/videoio/VideoWriter.cs @@ -308,7 +308,7 @@ public void Release() ///
/// the written frame. /// - public void Write(InputArrayRef image) + public void Write(InputArray image) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs b/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs index 9fa44d6c4..40b37fd96 100644 --- a/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs +++ b/src/OpenCvSharp/Modules/wechat_qrcode/WeChatQRCode.cs @@ -47,7 +47,7 @@ public WeChatQRCode( /// Will be empty if not found. /// /// list of decoded string. - public string[] DetectAndDecode(InputArrayRef inputImage, out Point2f[][] points) + public string[] DetectAndDecode(InputArray inputImage, out Point2f[][] points) { using var pointsVec = new VectorOfVectorPoint2f(); using var texts = new VectorOfString(); @@ -71,7 +71,7 @@ public string[] DetectAndDecode(InputArrayRef inputImage, out Point2f[][] points /// Will be empty if not found. /// /// list of decoded string. - public string[] DetectAndDecodeRaw(InputArrayRef inputImage, out Mat[] bbox) + public string[] DetectAndDecodeRaw(InputArray inputImage, out Mat[] bbox) { using var bboxVec = new VectorOfMat(); using var texts = new VectorOfString(); diff --git a/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs b/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs index 8be5756ce..c43407cf3 100644 --- a/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs +++ b/src/OpenCvSharp/Modules/xfeatures2d/BOWImgDescriptorExtractor.cs @@ -91,7 +91,7 @@ public Mat GetVocabulary() /// pointIdxsOfClusters Indices of keypoints that belong to the cluster. /// This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster(word of vocabulary) returned if it is non-zero. /// Descriptors of the image keypoints that are returned if they are non-zero. - public void Compute(InputArrayRef image, ref KeyPoint[] keypoints, OutputArrayRef imgDescriptor, + public void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray imgDescriptor, out int[][] pointIdxsOfClusters, Mat? descriptors = null) { ThrowIfDisposed(); @@ -117,7 +117,7 @@ public void Compute(InputArrayRef image, ref KeyPoint[] keypoints, OutputArrayRe /// Computed output image descriptor. /// Indices of keypoints that belong to the cluster. /// This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster(word of vocabulary) returned if it is non-zero. - public void Compute(InputArrayRef keypointDescriptors, OutputArrayRef imgDescriptor, out int[][] pointIdxsOfClusters) + public void Compute(InputArray keypointDescriptors, OutputArray imgDescriptor, out int[][] pointIdxsOfClusters) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs b/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs index aaaa9a80b..83892e4c6 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Cv2.XImgProc.cs @@ -132,7 +132,7 @@ public static class RL /// resulting run length encoded image. /// threshold value. /// thresholding type (only cv::THRESH_BINARY and cv::THRESH_BINARY_INV are supported) - public static void Threshold(InputArrayRef src, OutputArrayRef rlDest, double thresh, ThresholdTypes type) + public static void Threshold(InputArray src, OutputArray rlDest, double thresh, ThresholdTypes type) { NativeMethods.HandleException( NativeMethods.ximgproc_rl_threshold(src.Proxy, rlDest.Proxy, thresh, (int)type)); @@ -148,7 +148,7 @@ public static void Threshold(InputArrayRef src, OutputArrayRef rlDest, double th /// kernel /// position of the anchor within the element; default value (0, 0) is usually the element center. public static void Dilate( - InputArrayRef rlSrc, OutputArrayRef rlDest, InputArrayRef rlKernel, Point? anchor = null) + InputArray rlSrc, OutputArray rlDest, InputArray rlKernel, Point? anchor = null) { var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); @@ -170,7 +170,7 @@ public static void Dilate( /// position of the anchor within the element; default value (0, 0) /// is usually the element center. public static void Erode( - InputArrayRef rlSrc, OutputArrayRef rlDest, InputArrayRef rlKernel, bool bBoundaryOn = true, Point? anchor = null) + InputArray rlSrc, OutputArray rlDest, InputArray rlKernel, bool bBoundaryOn = true, Point? anchor = null) { var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); @@ -201,7 +201,7 @@ public static Mat GetStructuringElement(MorphShapes shape, Size ksize) /// image to paint into (currently only single channel images). /// run length encoded image /// all foreground pixel of the binary image are set to this value - public static void Paint(InputOutputArrayRef image, InputArrayRef rlSrc, Scalar value) + public static void Paint(InputOutputArray image, InputArray rlSrc, Scalar value) { NativeMethods.HandleException( NativeMethods.ximgproc_rl_paint(image.Proxy, rlSrc.Proxy, value)); @@ -215,7 +215,7 @@ public static void Paint(InputOutputArrayRef image, InputArrayRef rlSrc, Scalar ///
/// /// - public static bool IsRLMorphologyPossible(InputArrayRef rlStructuringElement) + public static bool IsRLMorphologyPossible(InputArray rlStructuringElement) { NativeMethods.HandleException( NativeMethods.ximgproc_rl_isRLMorphologyPossible(rlStructuringElement.Proxy, out var ret)); @@ -232,7 +232,7 @@ public static bool IsRLMorphologyPossible(InputArrayRef rlStructuringElement) /// result /// image size (to be used if an "on" boundary should be used in erosion, using the default /// means that the size is computed from the extension of the input) - public static void CreateRLEImage(IEnumerable runs, OutputArrayRef res, Size? size = null) + public static void CreateRLEImage(IEnumerable runs, OutputArray res, Size? size = null) { var runsArray = runs as Point3i[] ?? runs.ToArray(); var sizeValue = size.GetValueOrDefault(new Size(0, 0)); @@ -253,7 +253,7 @@ public static void CreateRLEImage(IEnumerable runs, OutputArrayRef res, /// to be on for erosion operations (True: works in the same way as the default of cv::erode, False: is a little faster) /// position of the anchor within the element; default value (0, 0) is usually the element center. public static void MorphologyEx( - InputArrayRef rlSrc, OutputArrayRef rlDest, MorphTypes op, InputArrayRef rlKernel, + InputArray rlSrc, OutputArray rlDest, MorphTypes op, InputArray rlKernel, bool bBoundaryOnForErosion = true, Point? anchor = null) { var anchorValue = anchor.GetValueOrDefault(new Point(0, 0)); @@ -293,8 +293,8 @@ public static void MorphologyEx( /// Other techniques can be specified, see cv::ximgproc::LocalBinarizationMethods. /// The user-adjustable parameter used by Sauvola's technique. This is the dynamic range of standard deviation. public static void NiblackThreshold( - InputArrayRef src, - OutputArrayRef dst, + InputArray src, + OutputArray dst, double maxValue, ThresholdTypes type, int blockSize, @@ -317,7 +317,7 @@ public static void NiblackThreshold( /// Destination image of the same size and the same type as src. The function can work in-place. /// Value that defines which thinning algorithm should be used. public static void Thinning( - InputArrayRef src, OutputArrayRef dst, + InputArray src, OutputArray dst, ThinningTypes thinningType = ThinningTypes.ZHANGSUEN) { NativeMethods.HandleException( @@ -335,7 +335,7 @@ public static void Thinning( /// The amount of time to step forward by on each iteration (normally, it's between 0 and 1). /// sensitivity to the edges /// The number of iterations - public static void AnisotropicDiffusion(InputArrayRef src, OutputArrayRef dst, float alpha, float k, int niters) + public static void AnisotropicDiffusion(InputArray src, OutputArray dst, float alpha, float k, int niters) { NativeMethods.HandleException( NativeMethods.ximgproc_anisotropicDiffusion(src.Proxy, dst.Proxy, alpha, k, niters)); @@ -378,7 +378,7 @@ public static void BrightEdges(Mat original, Mat edgeView, int contrast = 1, int ///
/// Source 8-bit, 32-bit or 64-bit image, with 3-channel image. /// result CV_64FC4 a quaternion image( 4 chanels zero channel and B,G,R). - public static void CreateQuaternionImage(InputArrayRef img, OutputArrayRef qimg) + public static void CreateQuaternionImage(InputArray img, OutputArray qimg) { NativeMethods.HandleException( NativeMethods.ximgproc_createQuaternionImage(img.Proxy, qimg.Proxy)); @@ -391,7 +391,7 @@ public static void CreateQuaternionImage(InputArrayRef img, OutputArrayRef qimg) ///
/// quaternion image. /// conjugate of qimg - public static void QConj(InputArrayRef qimg, OutputArrayRef qcimg) + public static void QConj(InputArray qimg, OutputArray qcimg) { NativeMethods.HandleException( NativeMethods.ximgproc_qconj(qimg.Proxy, qcimg.Proxy)); @@ -404,7 +404,7 @@ public static void QConj(InputArrayRef qimg, OutputArrayRef qcimg) ///
/// quaternion image. /// conjugate of qimg - public static void QUnitary(InputArrayRef qimg, OutputArrayRef qnimg) + public static void QUnitary(InputArray qimg, OutputArray qnimg) { NativeMethods.HandleException( NativeMethods.ximgproc_qunitary(qimg.Proxy, qnimg.Proxy)); @@ -418,7 +418,7 @@ public static void QUnitary(InputArrayRef qimg, OutputArrayRef qnimg) /// quaternion image. /// quaternion image. /// product dst(I)=src1(I) . src2(I) - public static void QMultiply(InputArrayRef src1, InputArrayRef src2, OutputArrayRef dst) + public static void QMultiply(InputArray src1, InputArray src2, OutputArray dst) { NativeMethods.HandleException( NativeMethods.ximgproc_qmultiply(src1.Proxy, src2.Proxy, dst.Proxy)); @@ -434,7 +434,7 @@ public static void QMultiply(InputArrayRef src1, InputArrayRef src2, OutputArray /// quaternion image in dual space. /// quaternion image in dual space. only DFT_INVERSE flags is supported /// true the hypercomplex exponential is to be multiplied on the left (false on the right ). - public static void QDft(InputArrayRef img, OutputArrayRef qimg, DftFlags flags, bool sideLeft) + public static void QDft(InputArray img, OutputArray qimg, DftFlags flags, bool sideLeft) { NativeMethods.HandleException( NativeMethods.ximgproc_qdft(img.Proxy, qimg.Proxy, (int)flags, sideLeft ? 1 : 0)); @@ -448,7 +448,7 @@ public static void QDft(InputArrayRef img, OutputArrayRef qimg, DftFlags flags, /// Image where the search is running. It must be 3 channels image /// Searched template. It must be not greater than the source image and have 3 channels /// Map of comparison results. It must be single-channel 64-bit floating-point - public static void ColorMatchTemplate(InputArrayRef img, InputArrayRef templ, OutputArrayRef result) + public static void ColorMatchTemplate(InputArray img, InputArray templ, OutputArray result) { NativeMethods.HandleException( NativeMethods.ximgproc_colorMatchTemplate(img.Proxy, templ.Proxy, result.Proxy)); @@ -468,7 +468,7 @@ public static void ColorMatchTemplate(InputArrayRef img, InputArrayRef templ, Ou /// result CV_32FC image with same number of channel than _op. /// double see paper /// double see paper - public static void GradientDericheY(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) + public static void GradientDericheY(InputArray op, OutputArray dst, double alpha, double omega) { NativeMethods.HandleException( NativeMethods.ximgproc_GradientDericheY(op.Proxy, dst.Proxy, alpha, omega)); @@ -483,7 +483,7 @@ public static void GradientDericheY(InputArrayRef op, OutputArrayRef dst, double /// result CV_32FC image with same number of channel than _op. /// double see paper /// double see paper - public static void GradientDericheX(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) + public static void GradientDericheX(InputArray op, OutputArray dst, double alpha, double omega) { NativeMethods.HandleException( NativeMethods.ximgproc_GradientDericheX(op.Proxy, dst.Proxy, alpha, omega)); @@ -562,7 +562,7 @@ public static EdgeBoxes CreateEdgeBoxes( /// // ReSharper disable once InconsistentNaming public static DTFilter CreateDTFilter( - InputArrayRef guide, double sigmaSpatial, double sigmaColor, + InputArray guide, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { return OpenCvSharp.XImgProc.DTFilter.Create(guide, sigmaSpatial, sigmaColor, mode, numIters); @@ -584,7 +584,7 @@ public static DTFilter CreateDTFilter( /// filtering 2D signals in the article. /// optional number of iterations used for filtering, 3 is quite enough. // ReSharper disable once InconsistentNaming - public static void DTFilter(InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, double sigmaSpatial, + public static void DTFilter(InputArray guide, InputArray src, OutputArray dst, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { NativeMethods.HandleException( @@ -604,7 +604,7 @@ public static void DTFilter(InputArrayRef guide, InputArrayRef src, OutputArrayR /// space into bilateralFilter. /// public static GuidedFilter CreateGuidedFilter( - InputArrayRef guide, int radius, double eps) + InputArray guide, int radius, double eps) { return OpenCvSharp.XImgProc.GuidedFilter.Create(guide, radius, eps); } @@ -624,7 +624,7 @@ public static GuidedFilter CreateGuidedFilter( /// space into bilateralFilter. /// optional depth of the output image. public static void GuidedFilter( - InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, + InputArray guide, InputArray src, OutputArray dst, int radius, double eps, int dDepth = -1) { NativeMethods.HandleException( @@ -663,7 +663,7 @@ public static AdaptiveManifoldFilter CreateAMFilter( /// original paper. // ReSharper disable once InconsistentNaming public static void AMFilter( - InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, double sigmaS, double sigmaR, + InputArray joint, InputArray src, OutputArray dst, double sigmaS, double sigmaR, bool adjustOutliers = false) { NativeMethods.HandleException( @@ -690,7 +690,7 @@ public static void AMFilter( /// proportional to sigmaSpace. /// public static void JointBilateralFilter( - InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, int d, + InputArray joint, InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( @@ -714,7 +714,7 @@ public static void JointBilateralFilter( /// Range blur parameter for texture blurring. Larger value makes result to be more blurred. When the /// value is negative, it is automatically calculated as described in the paper. public static void BilateralTextureFilter( - InputArrayRef src, OutputArrayRef dst, int fr = 3, int numIter = 1, double sigmaAlpha = -1.0, double sigmaAvg = -1.0) + InputArray src, OutputArray dst, int fr = 3, int numIter = 1, double sigmaAlpha = -1.0, double sigmaAvg = -1.0) { NativeMethods.HandleException( NativeMethods.ximgproc_bilateralTextureFilter( @@ -740,7 +740,7 @@ public static void BilateralTextureFilter( /// Number of iterations of joint edge-preserving filtering applied on the source image. /// public static void RollingGuidanceFilter( - InputArrayRef src, OutputArrayRef dst, int d = -1, double sigmaColor = 25, + InputArray src, OutputArray dst, int d = -1, double sigmaColor = 25, double sigmaSpace = 3, int numOfIter = 4, BorderTypes borderType = BorderTypes.Default) { NativeMethods.HandleException( @@ -765,8 +765,8 @@ public static void RollingGuidanceFilter( /// number of iterations used for solver, 25 is usually enough. /// convergence tolerance used for solver. public static void FastBilateralSolverFilter( - InputArrayRef guide, InputArrayRef src, InputArrayRef confidence, - OutputArrayRef dst, double sigmaSpatial = 8, double sigmaLuma = 8, double sigmaChroma = 8, + InputArray guide, InputArray src, InputArray confidence, + OutputArray dst, double sigmaSpatial = 8, double sigmaLuma = 8, double sigmaChroma = 8, double lambda = 128.0, int numIter = 25, double maxTol = 1e-5) { NativeMethods.HandleException( @@ -789,7 +789,7 @@ public static void FastBilateralSolverFilter( /// number of iterations used for filtering, 3 is usually enough. /// public static FastGlobalSmootherFilter CreateFastGlobalSmootherFilter( - InputArrayRef guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) + InputArray guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { return OpenCvSharp.XImgProc.FastGlobalSmootherFilter.Create(guide, lambda, sigmaColor, lambdaAttenuation, numIter); } @@ -807,7 +807,7 @@ public static FastGlobalSmootherFilter CreateFastGlobalSmootherFilter( /// it should be 0.25. Setting it to 1.0 may lead to streaking artifacts. /// number of iterations used for filtering, 3 is usually enough. public static void FastGlobalSmootherFilter( - InputArrayRef guide, InputArrayRef src, OutputArrayRef dst, double lambda, double sigmaColor, + InputArray guide, InputArray src, OutputArray dst, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { NativeMethods.HandleException( @@ -825,7 +825,7 @@ public static void FastGlobalSmootherFilter( /// destination image. /// parameter defining the smooth term weight. /// parameter defining the increasing factor of the weight of the gradient data term. - public static void L0Smooth(InputArrayRef src, OutputArrayRef dst, double lambda = 0.02, double kappa = 2.0) + public static void L0Smooth(InputArray src, OutputArray dst, double lambda = 0.02, double kappa = 2.0) { NativeMethods.HandleException( NativeMethods.ximgproc_l0Smooth( @@ -845,7 +845,7 @@ public static void L0Smooth(InputArrayRef src, OutputArrayRef dst, double lambda /// Destination image of the same size and type as src. /// Diameter of each pixel neighborhood that is used during filtering. Must be greater or equal 3. /// Threshold, which distinguishes between noise, outliers, and data. - public static void EdgePreservingFilter(InputArrayRef src, OutputArrayRef dst, int d, double threshold) + public static void EdgePreservingFilter(InputArray src, OutputArray dst, int d, double threshold) { NativeMethods.HandleException( NativeMethods.ximgproc_edgePreservingFilter(src.Proxy, dst.Proxy, d, threshold)); @@ -872,7 +872,7 @@ public static void EdgePreservingFilter(InputArrayRef src, OutputArrayRef dst, i /// The destination estimated covariance matrix. Output matrix will be size (windowRows*windowCols, windowRows*windowCols). /// The number of rows in the window. /// The number of cols in the window. - public static void CovarianceEstimation(InputArrayRef src, OutputArrayRef dst, int windowRows, int windowCols) + public static void CovarianceEstimation(InputArray src, OutputArray dst, int windowRows, int windowCols) { NativeMethods.HandleException( NativeMethods.ximgproc_covarianceEstimation(src.Proxy, dst.Proxy, windowRows, windowCols)); @@ -895,8 +895,8 @@ public static void CovarianceEstimation(InputArrayRef src, OutputArrayRef dst, i /// The operation to be applied, see cv::HoughOp /// Specifies to do or not to do image skewing, see cv::HoughDeskewOption public static void FastHoughTransform( - InputArrayRef src, - OutputArrayRef dst, + InputArray src, + OutputArray dst, MatType dstMatDepth, AngleRangeOption angleRange = AngleRangeOption.ARO_315_135, HoughOP op = HoughOP.FHT_ADD, @@ -925,7 +925,7 @@ public static void FastHoughTransform( /// Coordinates of line segment corresponded by point in Hough space. public static Vec4i HoughPoint2Line( Point houghPoint, - InputArrayRef srcImgInfo, + InputArray srcImgInfo, AngleRangeOption angleRange = AngleRangeOption.ARO_315_135, HoughDeskewOption makeSkew = HoughDeskewOption.DESKEW, RulesOption rules = RulesOption.IGNORE_BORDERS) @@ -977,7 +977,7 @@ public static FastLineDetector CreateFastLineDetector( /// Chooses the enforcement of superpixel compactness factor of superpixel /// // ReSharper disable once InconsistentNaming - public static SuperpixelLSC CreateSuperpixelLSC(InputArrayRef image, int regionSize = 10, float ratio = 0.075f) + public static SuperpixelLSC CreateSuperpixelLSC(InputArray image, int regionSize = 10, float ratio = 0.075f) { return SuperpixelLSC.Create(image, regionSize, ratio); } @@ -993,7 +993,7 @@ public static SuperpixelLSC CreateSuperpixelLSC(InputArrayRef image, int regionS /// Result CV_32F image with same number of channel than op. /// double see paper /// double see paper - public static void GradientPaillouY(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) + public static void GradientPaillouY(InputArray op, OutputArray dst, double alpha, double omega) { NativeMethods.HandleException( NativeMethods.ximgproc_GradientPaillouY(op.Proxy, dst.Proxy, alpha, omega)); @@ -1009,7 +1009,7 @@ public static void GradientPaillouY(InputArrayRef op, OutputArrayRef dst, double /// Result CV_32F image with same number of channel than op. /// double see paper /// double see paper - public static void GradientPaillouX(InputArrayRef op, OutputArrayRef dst, double alpha, double omega) + public static void GradientPaillouX(InputArray op, OutputArray dst, double alpha, double omega) { NativeMethods.HandleException( NativeMethods.ximgproc_GradientPaillouX(op.Proxy, dst.Proxy, alpha, omega)); @@ -1027,7 +1027,7 @@ public static void GradientPaillouX(InputArrayRef op, OutputArrayRef dst, double ///
/// Given transformed image. /// Transformation matrix corresponding to inversed image transformation - public static double[,] PeiLinNormalization(InputArrayRef i) + public static double[,] PeiLinNormalization(InputArray i) { double[,] ret = new double[2, 3]; unsafe @@ -1048,7 +1048,7 @@ public static void GradientPaillouX(InputArrayRef op, OutputArrayRef dst, double ///
/// Given transformed image. /// Inversed image transformation. - public static void PeiLinNormalization(InputArrayRef i, OutputArrayRef t) + public static void PeiLinNormalization(InputArray i, OutputArray t) { NativeMethods.HandleException( NativeMethods.ximgproc_PeiLinNormalization_OutputArray(i.Proxy, t.Proxy)); @@ -1143,8 +1143,8 @@ public static StructuredEdgeDetection CreateStructuredEdgeDetection(string model /// A 0-1 mask that has the same size with I. This mask is used to ignore the effect of some pixels. If the pixel value on mask is 0, /// the pixel will be ignored when maintaining the joint-histogram.This is useful for applications like optical flow occlusion handling. public static void WeightedMedianFilter( - InputArrayRef joint, InputArrayRef src, OutputArrayRef dst, int r, - double sigma = 25.5, WMFWeightType weightType = WMFWeightType.EXP, InputArrayRef mask = default) + InputArray joint, InputArray src, OutputArray dst, int r, + double sigma = 25.5, WMFWeightType weightType = WMFWeightType.EXP, InputArray mask = default) { NativeMethods.HandleException( NativeMethods.ximgproc_weightedMedianFilter( diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs index fbef4aa39..37dab9c0e 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeBoxes.cs @@ -300,7 +300,7 @@ public virtual float Kappa /// edge image. /// orientation map. /// proposal boxes. - public virtual void GetBoundingBoxes(InputArrayRef edgeMap, InputArrayRef orientationMap, out Rect[] boxes) + public virtual void GetBoundingBoxes(InputArray edgeMap, InputArray orientationMap, out Rect[] boxes) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs index 374ae81be..af6cd88d3 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeDrawing.cs @@ -127,7 +127,7 @@ public static EdgeDrawing Create() /// Detects edges in a grayscale or color image and prepares them to detect lines and ellipses. ///
/// 8-bit, single-channel (CV_8UC1) or color (CV_8UC3, CV_8UC4) input image. - public virtual void DetectEdges(InputArrayRef src) + public virtual void DetectEdges(InputArray src) { ThrowIfDisposed(); @@ -140,7 +140,7 @@ public virtual void DetectEdges(InputArrayRef src) /// Returns the edge image prepared by . ///
/// 8-bit, single-channel output image. - public virtual void GetEdgeImage(OutputArrayRef dst) + public virtual void GetEdgeImage(OutputArray dst) { ThrowIfDisposed(); @@ -152,7 +152,7 @@ public virtual void GetEdgeImage(OutputArrayRef dst) /// Returns the gradient image prepared by . ///
/// 16-bit, single-channel output image. - public virtual void GetGradientImage(OutputArrayRef dst) + public virtual void GetGradientImage(OutputArray dst) { ThrowIfDisposed(); @@ -175,7 +175,7 @@ public virtual Point[][] GetSegments() } /// - /// Returns for each line found in its edge segment index in + /// Returns for each line found in its edge segment index in /// . /// /// Edge segment indices of detected lines. @@ -194,7 +194,7 @@ public virtual int[] GetSegmentIndicesOfLines() /// Call before calling this function. ///
/// Output Vec4f array: start point (x1,y1) and end point (x2,y2) of each line. - public virtual void DetectLines(OutputArrayRef lines) + public virtual void DetectLines(OutputArray lines) { ThrowIfDisposed(); @@ -225,7 +225,7 @@ public virtual Vec4f[] DetectLines() /// Output Vec6d array: center point and perimeter for circles; /// center point, axes and angle for ellipses. /// - public virtual void DetectEllipses(OutputArrayRef ellipses) + public virtual void DetectEllipses(OutputArray ellipses) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs index 76c59a8f4..7267ecadd 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/AdaptiveManifoldFilter.cs @@ -181,7 +181,7 @@ public bool UseRNG /// filtering image with any numbers of channels. /// output image. /// optional joint (also called as guided) image with any numbers of channels. - public virtual void Filter(InputArrayRef src, OutputArrayRef dst, InputArrayRef joint = default) + public virtual void Filter(InputArray src, OutputArray dst, InputArray joint = default) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs index 079df14e5..3334b9f7a 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/DTFilter.cs @@ -31,7 +31,7 @@ private DTFilter(IntPtr smartPtr, IntPtr rawPtr) /// optional number of iterations used for filtering, 3 is quite enough. /// public static DTFilter Create( - InputArrayRef guide, double sigmaSpatial, double sigmaColor, + InputArray guide, double sigmaSpatial, double sigmaColor, EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3) { NativeMethods.HandleException( @@ -50,7 +50,7 @@ public static DTFilter Create( /// /// /// - public virtual void Filter(InputArrayRef src, OutputArrayRef dst, int dDepth = -1) + public virtual void Filter(InputArray src, OutputArray dst, int dDepth = -1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs index b22e187b4..2afb3b790 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastBilateralSolverFilter.cs @@ -29,7 +29,7 @@ private FastBilateralSolverFilter(IntPtr smartPtr, IntPtr rawPtr) /// convergence tolerance used for solver. /// public static FastBilateralSolverFilter Create( - InputArrayRef guide, double sigmaSpatial, double sigmaLuma, double sigmaChroma, + InputArray guide, double sigmaSpatial, double sigmaLuma, double sigmaChroma, double lambda = 128.0, int numIter = 25, double maxTol = 1e-5) { NativeMethods.HandleException( @@ -47,7 +47,7 @@ public static FastBilateralSolverFilter Create( /// source image for filtering with unsigned 8-bit or signed 16-bit or floating-point 32-bit depth and up to 3 channels. /// confidence image with unsigned 8-bit or floating-point 32-bit confidence and 1 channel. /// destination image. - public virtual void Filter(InputArrayRef src, InputArrayRef confidence, OutputArrayRef dst) + public virtual void Filter(InputArray src, InputArray confidence, OutputArray dst) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs index e8d983f42..1c3549934 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/FastGlobalSmootherFilter.cs @@ -28,7 +28,7 @@ private FastGlobalSmootherFilter(IntPtr smartPtr, IntPtr rawPtr) /// number of iterations used for filtering, 3 is usually enough. /// public static FastGlobalSmootherFilter Create( - InputArrayRef guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) + InputArray guide, double lambda, double sigmaColor, double lambdaAttenuation = 0.25, int numIter = 3) { NativeMethods.HandleException( NativeMethods.ximgproc_createFastGlobalSmootherFilter( @@ -44,7 +44,7 @@ public static FastGlobalSmootherFilter Create( ///
/// source image for filtering with unsigned 8-bit or signed 16-bit or floating-point 32-bit depth and up to 4 channels. /// destination image. - public virtual void Filter(InputArrayRef src, OutputArrayRef dst) + public virtual void Filter(InputArray src, OutputArray dst) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs index a42cff955..9a6867e86 100644 --- a/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/EdgeFilter/GuidedFilter.cs @@ -27,7 +27,7 @@ private GuidedFilter(IntPtr smartPtr, IntPtr rawPtr) /// space into bilateralFilter. /// public static GuidedFilter Create( - InputArrayRef guide, int radius, double eps) + InputArray guide, int radius, double eps) { NativeMethods.HandleException( NativeMethods.ximgproc_createGuidedFilter( @@ -44,7 +44,7 @@ public static GuidedFilter Create( /// filtering image with any numbers of channels. /// output image. /// optional depth of the output image. dDepth can be set to -1, which will be equivalent to src.depth(). - public virtual void Filter(InputArrayRef src, OutputArrayRef dst, int dDepth = -1) + public virtual void Filter(InputArray src, OutputArray dst, int dDepth = -1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs b/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs index 8e9f8a910..ba4285702 100644 --- a/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs +++ b/src/OpenCvSharp/Modules/ximgproc/FastLineDetector.cs @@ -48,7 +48,7 @@ public static FastLineDetector Create( /// and ending point of a line. Where Vec4f is (x1, y1, x2, y2), /// point 1 is the start, point 2 - end.Returned lines are directed so that the /// brighter side is on their left. - public virtual void Detect(InputArrayRef image, OutputArrayRef lines) + public virtual void Detect(InputArray image, OutputArray lines) { ThrowIfDisposed(); @@ -69,7 +69,7 @@ public virtual void Detect(InputArrayRef image, OutputArrayRef lines) /// and ending point of a line. Where Vec4f is (x1, y1, x2, y2), /// point 1 is the start, point 2 - end.Returned lines are directed so that the /// brighter side is on their left. - public virtual Vec4f[] Detect(InputArrayRef image) + public virtual Vec4f[] Detect(InputArray image) { ThrowIfDisposed(); @@ -86,7 +86,7 @@ public virtual Vec4f[] Detect(InputArrayRef image) /// The image, where the lines will be drawn. Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. /// If true, arrow heads will be drawn. - public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines, + public virtual void DrawSegments(InputOutputArray image, InputArray lines, bool drawArrow = false) { ThrowIfDisposed(); @@ -103,7 +103,7 @@ public virtual void DrawSegments(InputOutputArrayRef image, InputArrayRef lines, /// The image, where the lines will be drawn. Should be bigger or equal to the image, where the lines were found. /// A vector of the lines that needed to be drawn. /// If true, arrow heads will be drawn. - public virtual void DrawSegments(InputOutputArrayRef image, IEnumerable lines, bool drawArrow = false) + public virtual void DrawSegments(InputOutputArray image, IEnumerable lines, bool drawArrow = false) { ThrowIfDisposed(); if (lines is null) diff --git a/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs b/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs index 4d25516c3..088d00b12 100644 --- a/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs +++ b/src/OpenCvSharp/Modules/ximgproc/RidgeDetectionFilter.cs @@ -57,7 +57,7 @@ public static RidgeDetectionFilter Create( ///
/// InputArray as supported by Sobel. img can be 1-Channel or 3-Channels. /// OutputAray of structure as RidgeDetectionFilter::ddepth. Output image with ridges. - public virtual void GetRidgeFilteredImage(InputArrayRef src, OutputArrayRef dst) + public virtual void GetRidgeFilteredImage(InputArray src, OutputArray dst) { ThrowIfDisposed(); NativeMethods.HandleException( diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs index 693b160bd..2754a23c8 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/GraphSegmentation.cs @@ -99,7 +99,7 @@ public virtual int MinSize ///
/// The input image. Any number of channel (1 (Eg: Gray), 3 (Eg: RGB), 4 (Eg: RGB-D)) can be provided /// The output segmentation. It's a CV_32SC1 Mat with the same number of cols and rows as input image, with an unique, sequential, id for each pixel. - public virtual void ProcessImage(InputArrayRef src, OutputArrayRef dst) + public virtual void ProcessImage(InputArray src, OutputArray dst) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs index af2f9a42f..6677086cd 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentation.cs @@ -33,7 +33,7 @@ public static SelectiveSearchSegmentation Create() /// Set a image used by switch* functions to initialize the class ///
/// The image - public virtual void SetBaseImage(InputArrayRef img) + public virtual void SetBaseImage(InputArray img) { ThrowIfDisposed(); @@ -85,7 +85,7 @@ public virtual void SwitchToSelectiveSearchQuality(int baseK = 150, int incK = 1 /// Add a new image in the list of images to process. ///
/// The image - public virtual void AddImage(InputArrayRef img) + public virtual void AddImage(InputArray img) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs index cbe6e1d40..958d09cab 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategy.cs @@ -31,7 +31,7 @@ protected SelectiveSearchSegmentationStrategy(IntPtr smartPtr, IntPtr rawPtr, Ac /// A segementation of the image. The parameter must be the same size of img. /// The sizes of different regions /// If not set to -1, try to cache pre-computations. If the same set og (img, regions, size) is used, the image_id need to be the same. - public virtual void SetImage(InputArrayRef img, InputArrayRef regions, InputArrayRef sizes, int imageId = -1) + public virtual void SetImage(InputArray img, InputArray regions, InputArray sizes, int imageId = -1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs index f44492699..6768c6a09 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Segmentation/SelectiveSearchSegmentationStrategyMultiple.cs @@ -23,7 +23,7 @@ private SelectiveSearchSegmentationStrategyMultiple(IntPtr smartPtr, IntPtr rawP /// A segementation of the image. The parameter must be the same size of img. /// The sizes of different regions /// If not set to -1, try to cache pre-computations. If the same set og (img, regions, size) is used, the image_id need to be the same. - public new virtual void SetImage(InputArrayRef img, InputArrayRef regions, InputArrayRef sizes, int imageId = -1) + public new virtual void SetImage(InputArray img, InputArray regions, InputArray sizes, int imageId = -1) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs b/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs index 95b8a6c9b..a5de403bc 100644 --- a/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs +++ b/src/OpenCvSharp/Modules/ximgproc/StructuredEdgeDetection.cs @@ -39,7 +39,7 @@ public static StructuredEdgeDetection Create(string model, RFFeatureGetter? howT /// edge image. /// orientation map. /// proposal boxes. - public virtual void GetBoundingBoxes(InputArrayRef edgeMap, InputArrayRef orientationMap, out Rect[] boxes) + public virtual void GetBoundingBoxes(InputArray edgeMap, InputArray orientationMap, out Rect[] boxes) { ThrowIfDisposed(); @@ -58,7 +58,7 @@ public virtual void GetBoundingBoxes(InputArrayRef edgeMap, InputArrayRef orient ///
/// source image (RGB, float, in [0;1]) to detect edges /// destination image (grayscale, float, in [0;1]) where edges are drawn - public virtual void DetectEdges(InputArrayRef src, OutputArrayRef dst) + public virtual void DetectEdges(InputArray src, OutputArray dst) { ThrowIfDisposed(); @@ -73,7 +73,7 @@ public virtual void DetectEdges(InputArrayRef src, OutputArrayRef dst) ///
/// edge image. /// orientation image. - public virtual void ComputeOrientation(InputArrayRef src, OutputArrayRef dst) + public virtual void ComputeOrientation(InputArray src, OutputArray dst) { ThrowIfDisposed(); @@ -93,7 +93,7 @@ public virtual void ComputeOrientation(InputArrayRef src, OutputArrayRef dst) /// radius for boundary suppression. /// multiplier for conservative suppression. /// enables/disables parallel computing. - public virtual void EdgesNms(InputArrayRef edgeImage, InputArrayRef orientationImage, OutputArrayRef dst, + public virtual void EdgesNms(InputArray edgeImage, InputArray orientationImage, OutputArray dst, int r = 2, int s = 0, float m = 1, bool isParallel = true) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs index 1aa65fda3..108c75443 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelLSC.cs @@ -37,7 +37,7 @@ private SuperpixelLSC(IntPtr smartPtr, IntPtr rawPtr) /// Chooses the enforcement of superpixel compactness factor of superpixel /// public static SuperpixelLSC Create( - InputArrayRef image, int regionSize = 10, float ratio = 0.075f) + InputArray image, int regionSize = 10, float ratio = 0.075f) { NativeMethods.HandleException( NativeMethods.ximgproc_createSuperpixelLSC( @@ -91,7 +91,7 @@ public virtual void Iterate(int numIterations = 10) ///
/// Return: A CV_32SC1 integer array containing the labels of the superpixel /// segmentation.The labels are in the range[0, getNumberOfSuperpixels()]. - public virtual void GetLabels(OutputArrayRef labelsOut) + public virtual void GetLabels(OutputArray labelsOut) { ThrowIfDisposed(); @@ -106,7 +106,7 @@ public virtual void GetLabels(OutputArrayRef labelsOut) ///
/// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs index d4ffdaa28..8f68952b4 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSEEDS.cs @@ -90,7 +90,7 @@ public virtual int GetNumberOfSuperpixels() /// channels must match with the initialized image size & channels with the function /// createSuperpixelSEEDS(). It should be in HSV or Lab color space.Lab is a bit better, but also slower. /// Number of pixel level iterations. Higher number improves the result. - public virtual void Iterate(InputArrayRef img, int numIterations = 10) + public virtual void Iterate(InputArray img, int numIterations = 10) { ThrowIfDisposed(); @@ -110,7 +110,7 @@ public virtual void Iterate(InputArrayRef img, int numIterations = 10) ///
/// Return: A CV_32UC1 integer array containing the labels of the superpixel /// segmentation.The labels are in the range[0, getNumberOfSuperpixels()]. - public virtual void GetLabels(OutputArrayRef labelsOut) + public virtual void GetLabels(OutputArray labelsOut) { ThrowIfDisposed(); @@ -125,7 +125,7 @@ public virtual void GetLabels(OutputArrayRef labelsOut) ///
/// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs index e81cbb423..66fe8c43d 100644 --- a/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs +++ b/src/OpenCvSharp/Modules/ximgproc/Superpixel/SuperpixelSLIC.cs @@ -34,7 +34,7 @@ private SuperpixelSLIC(IntPtr smartPtr, IntPtr rawPtr) /// Chooses the enforcement of superpixel smoothness factor of superpixel /// public static SuperpixelSLIC Create( - InputArrayRef image, + InputArray image, SLICType algorithm = SLICType.SLICO, int regionSize = 10, float ruler = 10.0f) @@ -91,7 +91,7 @@ public virtual void Iterate(int numIterations = 10) /// the range[0, getNumberOfSuperpixels()]. ///
/// - public virtual void GetLabels(OutputArrayRef labelsOut) + public virtual void GetLabels(OutputArray labelsOut) { ThrowIfDisposed(); @@ -106,7 +106,7 @@ public virtual void GetLabels(OutputArrayRef labelsOut) ///
/// Return: CV_8U1 image mask where -1 indicates that the pixel is a superpixel border, and 0 otherwise. /// If false, the border is only one pixel wide, otherwise all pixels at the border are masked. - public virtual void GetLabelContourMask(OutputArrayRef image, bool thickLine = true) + public virtual void GetLabelContourMask(OutputArray image, bool thickLine = true) { ThrowIfDisposed(); diff --git a/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs b/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs index 43d403354..6e462f2dc 100644 --- a/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs +++ b/src/OpenCvSharp/Modules/xphoto/Cv2.XPhoto.cs @@ -42,9 +42,9 @@ public static partial class XPhoto /// Type of the orthogonal transform used in collaborative filtering step. /// Currently only Haar transform is supported. public static void Bm3dDenoising( - InputArrayRef src, - InputOutputArrayRef dstStep1, - OutputArrayRef dstStep2, + InputArray src, + InputOutputArray dstStep1, + OutputArray dstStep2, float h = 1, int templateWindowSize = 4, int searchWindowSize = 16, @@ -88,8 +88,8 @@ public static void Bm3dDenoising( /// Type of the orthogonal transform used in collaborative filtering step. /// Currently only Haar transform is supported. public static void Bm3dDenoising( - InputArrayRef src, - OutputArrayRef dst, + InputArray src, + OutputArray dst, float h = 1, int templateWindowSize = 4, int searchWindowSize = 16, @@ -183,7 +183,7 @@ public static void Inpaint(Mat src, Mat mask, Mat dst, OpenCvSharp.XPhoto.Inpain /// image is divided by dynRatio before histogram processing /// color space conversion code(see ColorConversionCodes). Histogram will used only first plane public static void OilPainting( - InputArrayRef src, OutputArrayRef dst, int size, int dynRatio, + InputArray src, OutputArray dst, int size, int dynRatio, ColorConversionCodes? code = null) { NativeMethods.HandleException( @@ -206,7 +206,7 @@ public static void OilPainting( /// gain for the B channel /// gain for the G channel /// gain for the R channel - public static void ApplyChannelGains(InputArrayRef src, OutputArrayRef dst, float gainB, float gainG, float gainR) + public static void ApplyChannelGains(InputArray src, OutputArray dst, float gainB, float gainG, float gainR) { NativeMethods.HandleException( NativeMethods.xphoto_applyChannelGains(src.Proxy, dst.Proxy, gainB, gainG, gainR)); diff --git a/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs b/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs index 232bca894..8f073af25 100644 --- a/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/GrayworldWB.cs @@ -54,7 +54,7 @@ public float SaturationThreshold ///
/// Input image /// White balancing result - public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) + public override void BalanceWhite(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.xphoto_GrayworldWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); diff --git a/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs b/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs index a7facb0b2..6a08b5372 100644 --- a/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/LearningBasedWB.cs @@ -92,7 +92,7 @@ public float SaturationThreshold ///
/// Input image /// White balancing result - public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) + public override void BalanceWhite(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.xphoto_LearningBasedWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); @@ -106,7 +106,7 @@ public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) ///
/// Input three-channel image (BGR color space is assumed). /// An array of four (r,g) chromaticity tuples corresponding to the features listed above. - public void ExtractSimpleFeatures(InputArrayRef src, OutputArrayRef dst) + public void ExtractSimpleFeatures(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.xphoto_LearningBasedWB_extractSimpleFeatures(Handle, src.Proxy, dst.Proxy)); diff --git a/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs b/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs index a41386097..e6f4d5fbf 100644 --- a/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs +++ b/src/OpenCvSharp/Modules/xphoto/SimpleWB.cs @@ -132,7 +132,7 @@ public float P ///
/// Input image /// White balancing result - public override void BalanceWhite(InputArrayRef src, OutputArrayRef dst) + public override void BalanceWhite(InputArray src, OutputArray dst) { NativeMethods.HandleException( NativeMethods.xphoto_SimpleWB_balanceWhite(Handle, src.Proxy, dst.Proxy)); diff --git a/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs b/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs index c0b1183ea..b36f0b290 100644 --- a/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs +++ b/src/OpenCvSharp/Modules/xphoto/WhiteBalancer.cs @@ -14,5 +14,5 @@ protected WhiteBalancer(IntPtr smartPtr, IntPtr rawPtr, Action release) ///
/// Input image /// White balancing result - public abstract void BalanceWhite(InputArrayRef src, OutputArrayRef dst); + public abstract void BalanceWhite(InputArray src, OutputArray dst); } diff --git a/test/OpenCvSharp.Tests/core/CoreTest.cs b/test/OpenCvSharp.Tests/core/CoreTest.cs index 5cc78984b..c54c8777e 100644 --- a/test/OpenCvSharp.Tests/core/CoreTest.cs +++ b/test/OpenCvSharp.Tests/core/CoreTest.cs @@ -51,7 +51,7 @@ public void AddScalar() Assert.Equal(13, dst.At(1, 0)); Assert.Equal(14, dst.At(1, 1)); - var inputArray = InputArrayRef.Create(10.0); + var inputArray = InputArray.Create(10.0); Cv2.Add(src, inputArray, dst); Assert.Equal(11, dst.At(0, 0)); Assert.Equal(12, dst.At(0, 1)); @@ -414,7 +414,7 @@ public void Norm() public void NormVecb() { var vec = new Vec3b(10, 20, 30); - var ia = InputArrayRef.Create(vec); + var ia = InputArray.Create(vec); var norm = Cv2.Norm(ia, NormTypes.L1); Assert.Equal(60, norm); } diff --git a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs b/test/OpenCvSharp.Tests/core/InputArrayTest.cs similarity index 93% rename from test/OpenCvSharp.Tests/core/InputArrayRefTest.cs rename to test/OpenCvSharp.Tests/core/InputArrayTest.cs index a0aa02f7c..74f6971cf 100644 --- a/test/OpenCvSharp.Tests/core/InputArrayRefTest.cs +++ b/test/OpenCvSharp.Tests/core/InputArrayTest.cs @@ -8,7 +8,7 @@ namespace OpenCvSharp.Tests.Core; /// Mat/UMat/MatExpr/Scalar/double/Vec are allocation-free, and the explicit Create(...) factory /// methods behave the same as their implicit-conversion equivalents. ///
-public class InputArrayRefTest : TestBase +public class InputArrayTest : TestBase { private static Mat Float3x3(params float[] v) { @@ -91,7 +91,7 @@ public void Create_FromVec_MatchesImplicitConversion() var v = new Vec3d(1, 2, 3); using var actual = new Mat(); - Cv2.Transpose(InputArrayRef.Create(v), actual); + Cv2.Transpose(InputArray.Create(v), actual); using var expected = new Mat(); Cv2.Transpose(v, expected); @@ -110,7 +110,7 @@ public void Create_From2DArray_MatchesManuallyBuiltMat() }; using var actual = new Mat(); - Cv2.Transpose(InputArrayRef.Create(a), actual); + Cv2.Transpose(InputArray.Create(a), actual); using var src = Mat.FromPixelData(3, 3, MatType.CV_64FC1, a); using var expected = new Mat(); @@ -125,7 +125,7 @@ public void Create_From1DArray_MatchesManuallyBuiltMat() double[] a = [1, 2, 3, 4, 5, 6]; using var actual = new Mat(); - Cv2.Transpose(InputArrayRef.Create(a), actual); + Cv2.Transpose(InputArray.Create(a), actual); using var src = Mat.FromPixelData(6, 1, MatType.CV_64FC1, a); using var expected = new Mat(); @@ -140,7 +140,7 @@ public void Create_FromMat_MatchesImplicitConversion() using var src = Float3x3(1, 2, 3, 4, 5, 6, 7, 8, 9); using var actual = new Mat(); - Cv2.Transpose(InputArrayRef.Create(src), actual); + Cv2.Transpose(InputArray.Create(src), actual); using var expected = new Mat(); Cv2.Transpose(src, expected); diff --git a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs index 183a0b87d..ff8a8d90c 100644 --- a/test/OpenCvSharp.Tests/core/SolveEquationTest.cs +++ b/test/OpenCvSharp.Tests/core/SolveEquationTest.cs @@ -50,9 +50,9 @@ public void ByNormalArray() using var x = new Mat(); - var ia = InputArrayRef.Create(a); - var iy = InputArrayRef.Create(y); - var ox = OutputArrayRef.Create(x); + var ia = InputArray.Create(a); + var iy = InputArray.Create(y); + var ox = OutputArray.Create(x); Cv2.Solve(ia, iy, ox, DecompTypes.LU); testOutputHelper.WriteLine("X1 = {0}, X2 = {1}", x.At(0), x.At(1)); diff --git a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs index efea40b5d..f352d2fef 100644 --- a/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs +++ b/test/OpenCvSharp.Tests/imgproc/ImgProcTest.cs @@ -471,8 +471,8 @@ public void Rectangle() Cv2.Rectangle(img1, new Rect(10, 10, 80, 80), color, 1); Cv2.Rectangle(img2, new Point(10, 10), new Point(89, 89), color, 1); - Cv2.Rectangle(InputOutputArrayRef.Create(img3), new Rect(10, 10, 80, 80), color, 1); - Cv2.Rectangle(InputOutputArrayRef.Create(img4), new Point(10, 10), new Point(89, 89), color, 1); + Cv2.Rectangle(InputOutputArray.Create(img3), new Rect(10, 10, 80, 80), color, 1); + Cv2.Rectangle(InputOutputArray.Create(img4), new Point(10, 10), new Point(89, 89), color, 1); ShowImagesWhenDebugMode(img1, img2);