diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..176b8ff --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +Docker +.git +obj +bin +build +.vs +build*.ps1 +build*.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8425f17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.vs +build/ +bin/ +obj/ +*.lib +*.so +*.dll diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..1e8161c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.0) +project(OpenCvSharpAutogen) +SET(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "limited configs" FORCE) +SET (CMAKE_CXX_STANDARD 11) + +add_subdirectory(OpenVinoOpenCvSharpExtern) diff --git a/Docker/debian-buster-arm32v7-opencv/Dockerfile b/Docker/debian-buster-arm32v7-opencv/Dockerfile new file mode 100644 index 0000000..1389507 --- /dev/null +++ b/Docker/debian-buster-arm32v7-opencv/Dockerfile @@ -0,0 +1,130 @@ +FROM mcr.microsoft.com/dotnet/core/runtime:3.1.0-buster-slim-arm32v7 AS dotnet-runtime + +ARG DOWNLOAD_LINK=https://download.01.org/opencv/2019/openvinotoolkit/R3/l_openvino_toolkit_runtime_raspbian_p_2019.3.334.tgz +ARG INSTALL_DIR=/opt/intel/openvino +ARG TEMP_DIR=/tmp/openvino_installer + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ffmpeg \ + libgdiplus \ + libgdk3.0-cil \ + wget && \ + rm -rf /var/lib/apt/lists/* + + +RUN mkdir -p $TEMP_DIR && \ + mkdir -p $INSTALL_DIR && \ + cd $TEMP_DIR && \ + wget -c $DOWNLOAD_LINK && \ + tar -xf l_openvino_toolkit_runtime_raspbian_p_*.tgz --strip 1 -C $INSTALL_DIR && \ + rm -rf ${INSTALL_DIR}/opencv + +FROM dotnet-runtime as opencv-build +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + unzip \ + cmake && \ + rm -rf /var/lib/apt/lists/* + +ARG OPENCV_VERSION=4.1.2 +WORKDIR /opencvbuild + +RUN wget https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip && \ + unzip ${OPENCV_VERSION}.zip && \ + rm ${OPENCV_VERSION}.zip && \ + mv opencv-${OPENCV_VERSION} opencv && \ + wget https://github.com/opencv/opencv_contrib/archive/${OPENCV_VERSION}.zip && \ + unzip ${OPENCV_VERSION}.zip && \ + rm ${OPENCV_VERSION}.zip && \ + mv opencv_contrib-${OPENCV_VERSION} opencv_contrib + +# Build OpenCV +WORKDIR /opencvbuild/build +RUN cmake \ + -D OPENCV_EXTRA_MODULES_PATH=/opencvbuild/opencv_contrib/modules \ + -D InferenceEngine_DIR=/opt/intel/openvino/deployment_tools/inference_engine/share \ + -D CMAKE_INSTALL_PREFIX=/opencv/install \ + -D CMAKE_BUILD_TYPE=RELEASE \ + -D ENABLE_NEON=ON \ + -D ENABLE_VFPV3=ON \ + -D WITH_OPENMP=ON \ + -D WITH_TBB=ON \ + -D BUILD_TBB=ON \ + -D WITH_VTK=OFF \ + -D WITH_INF_ENGINE=ON \ + -D BUILD_EXAMPLES=OFF \ + -D BUILD_DOCS=OFF \ + -D BUILD_PERF_TESTS=OFF \ + -D BUILD_TESTS=OFF \ + -D BUILD_JAVA=OFF \ + -D BUILD_opencv_app=OFF \ + -D BUILD_opencv_java=OFF \ + -D BUILD_opencv_python=OFF \ + -D BUILD_opencv_ts=OFF \ + -D BUILD_opencv_js=OFF \ + -D WITH_GSTREAMER=OFF \ + -D OPENCV_ENABLE_NONFREE=ON \ + ../opencv + +RUN make && \ + make install + + +# Build OpenVinoOpenCvSharp +WORKDIR /OpenVinoOpenCvSharp +COPY CMakeLists.txt . +COPY OpenVinoOpenCvSharpExtern/ OpenVinoOpenCvSharpExtern/ + +WORKDIR /OpenVinoOpenCvSharp/build/ +RUN cmake \ + -D OpenCV_DIR=/opencvbuild/install/cmake \ + -D InferenceEngine_DIR=/opt/intel/openvino/deployment_tools/inference_engine/share \ + -D CMAKE_INSTALL_PREFIX=../install \ + .. + +RUN make -j4 && \ + make install + + +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/core/sdk:3.1.100-buster AS build +WORKDIR /build + +COPY OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj PeopleDetectionOpenCV/ +COPY Shared/Shared.csproj Shared/ +COPY FaceDetectionOpenVino/FaceDetectionOpenVino.csproj FaceDetectionOpenVino/ + +RUN dotnet restore PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj +RUN dotnet restore FaceDetectionOpenVino/FaceDetectionOpenVino.csproj + +COPY OpenVinoOpenCvSharp/ OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/ PeopleDetectionOpenCV/ +COPY Shared/ Shared/ +COPY FaceDetectionOpenVino/ FaceDetectionOpenVino/ + +WORKDIR /build/PeopleDetectionOpenCV +RUN dotnet build -c Release + +WORKDIR /build/FaceDetectionOpenVino +RUN dotnet build -c Release + +FROM build AS publish +WORKDIR /build/PeopleDetectionOpenCV +RUN dotnet publish --no-build -c Release -o /app/PeopleDetectionOpenCV/publish + +WORKDIR /build/FaceDetectionOpenVino +RUN dotnet publish --no-build -c Release -o /app/FaceDetectionOpenVino/publish + +FROM dotnet-runtime as final +WORKDIR /app +COPY --from=opencv-build /opencvsharp/install/ /opt/opencv/ +COPY --from=opencv-build /OpenVinoOpenCvSharp/install/lib/libOpenVinoOpenCvSharpExtern.so /opt/ + +ENV LD_LIBRARY_PATH=/opt:/opt/opencv/lib:/opt/intel/openvino/deployment_tools/inference_engine/lib/armv7l + +COPY --from=publish /app/ . + +# COPY PeopleDetectionOpenCV/run.sh . +# RUN chmod a+x run.sh + +# ENTRYPOINT [ "./run.sh" ] diff --git a/Docker/debian-buster-arm32v7-opencv/build.ps1 b/Docker/debian-buster-arm32v7-opencv/build.ps1 new file mode 100644 index 0000000..1a24ef9 --- /dev/null +++ b/Docker/debian-buster-arm32v7-opencv/build.ps1 @@ -0,0 +1,5 @@ +$VERSION="1.0.0" + +docker buildx build --platform linux/arm/v7 -t "nrandell/arm-opencv-nick-builder:$VERSION" -f Dockerfile --push ../.. + + diff --git a/Docker/debian-buster-arm32v7/Dockerfile b/Docker/debian-buster-arm32v7/Dockerfile new file mode 100644 index 0000000..18efdbe --- /dev/null +++ b/Docker/debian-buster-arm32v7/Dockerfile @@ -0,0 +1,82 @@ +FROM mcr.microsoft.com/dotnet/core/runtime:3.1.0-buster-slim-arm32v7 AS dotnet-runtime + +ARG DOWNLOAD_LINK=https://download.01.org/opencv/2019/openvinotoolkit/R3/l_openvino_toolkit_runtime_raspbian_p_2019.3.334.tgz +ARG INSTALL_DIR=/opt/intel/openvino +ARG TEMP_DIR=/tmp/openvino_installer + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ffmpeg \ + libgdiplus \ + libgdk3.0-cil \ + wget && \ + rm -rf /var/lib/apt/lists/* + + +RUN mkdir -p $TEMP_DIR && \ + mkdir -p $INSTALL_DIR && \ + cd $TEMP_DIR && \ + wget -c $DOWNLOAD_LINK && \ + tar -xf l_openvino_toolkit_runtime_raspbian_p_*.tgz --strip 1 -C $INSTALL_DIR + + +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/core/sdk:3.1.100-buster AS build +WORKDIR /build + +COPY OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj PeopleDetectionOpenCV/ +COPY Shared/Shared.csproj Shared/ +COPY FaceDetectionOpenVino/FaceDetectionOpenVino.csproj FaceDetectionOpenVino/ + +RUN dotnet restore PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj +RUN dotnet restore FaceDetectionOpenVino/FaceDetectionOpenVino.csproj + +COPY OpenVinoOpenCvSharp/ OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/ PeopleDetectionOpenCV/ +COPY Shared/ Shared/ +COPY FaceDetectionOpenVino/ FaceDetectionOpenVino/ + +WORKDIR /build/PeopleDetectionOpenCV +RUN dotnet build -c Release + +WORKDIR /build/FaceDetectionOpenVino +RUN dotnet build -c Release + +FROM mcr.microsoft.com/dotnet/core/sdk:3.1.100-buster-arm32v7 as build-native-env + +COPY --from=dotnet-runtime /opt/intel/ /opt/intel/ + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + cmake && \ + rm -rf /var/lib/apt/lists/* + +WORKDIR /OpenVinoOpenCvSharp +COPY CMakeLists.txt . +COPY OpenVinoOpenCvSharpExtern/ OpenVinoOpenCvSharpExtern/ + +WORKDIR /OpenVinoOpenCvSharp/build/ +RUN cmake \ + -D OpenCV_DIR=/opt/intel/openvino/opencv/cmake \ + -D CMAKE_INSTALL_PREFIX=../install \ + .. + +RUN cmake --build . --target install --config Release + + +FROM build AS publish +WORKDIR /build/PeopleDetectionOpenCV +RUN dotnet publish --no-build -c Release -o /app/PeopleDetectionOpenCV/publish + +WORKDIR /build/FaceDetectionOpenVino +RUN dotnet publish --no-build -c Release -o /app/FaceDetectionOpenVino/publish + +FROM dotnet-runtime as final +WORKDIR /app +COPY --from=build-native-env /OpenVinoOpenCvSharp/install/lib/libOpenVinoOpenCvSharpExtern.so . + +COPY --from=publish /app/ . + +COPY PeopleDetectionOpenCV/run.sh . +RUN chmod a+x run.sh + +ENTRYPOINT [ "./run.sh" ] diff --git a/Docker/debian-buster-arm32v7/build.ps1 b/Docker/debian-buster-arm32v7/build.ps1 new file mode 100644 index 0000000..2538679 --- /dev/null +++ b/Docker/debian-buster-arm32v7/build.ps1 @@ -0,0 +1,5 @@ +$VERSION="1.0.3" + +docker buildx build --platform linux/arm/v7 -t "nrandell/arm-nick-builder:$VERSION" -f Dockerfile --push ../.. + + diff --git a/Docker/ubuntu-18.04/Dockerfile b/Docker/ubuntu-18.04/Dockerfile new file mode 100644 index 0000000..a82010a --- /dev/null +++ b/Docker/ubuntu-18.04/Dockerfile @@ -0,0 +1,80 @@ +FROM ubuntu:18.04 as build-native-env + +ARG DOWNLOAD_LINK=http://registrationcenter-download.intel.com/akdlm/irc_nas/16057/l_openvino_toolkit_p_2019.3.376.tgz +ARG INSTALL_DIR=/opt/intel/openvino +ARG TEMP_DIR=/tmp/openvino_installer +RUN apt-get update && apt-get install -y --no-install-recommends \ + wget \ + cpio \ + sudo \ + lsb-release && \ + rm -rf /var/lib/apt/lists/* +RUN mkdir -p $TEMP_DIR && cd $TEMP_DIR && \ + wget -c $DOWNLOAD_LINK && \ + tar xf l_openvino_toolkit*.tgz && \ + cd l_openvino_toolkit* + +RUN cd $TEMP_DIR && \ + cd l_openvino_toolkit* && \ + sed -i 's/decline/accept/g' silent.cfg && \ + ./install.sh -s silent.cfg && \ + rm -rf $TEMP_DIR + +RUN $INSTALL_DIR/install_dependencies/install_openvino_dependencies.sh + +WORKDIR /OpenVinoOpenCvSharp +COPY CMakeLists.txt . +COPY OpenVinoOpenCvSharpExtern/ OpenVinoOpenCvSharpExtern/ + +WORKDIR /OpenVinoOpenCvSharp/build/ +RUN cmake \ + -D OpenCV_DIR=/opt/intel/openvino/opencv/cmake \ + -D CMAKE_INSTALL_PREFIX=../install \ + .. + +RUN cmake --build . --target install --config Release + +FROM mcr.microsoft.com/dotnet/core/sdk:3.1.100-bionic AS build-dotnet-env +WORKDIR /build + +COPY OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj PeopleDetectionOpenCV/ +COPY Shared/Shared.csproj Shared/ +RUN dotnet restore PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj + +COPY OpenVinoOpenCvSharp/ OpenVinoOpenCvSharp/ +COPY PeopleDetectionOpenCV/ PeopleDetectionOpenCV/ +COPY Shared/ Shared/ + +WORKDIR /build/PeopleDetectionOpenCV +RUN dotnet build -c Release + +FROM build-dotnet-env AS publish +RUN dotnet publish --no-build -c Release -o /app/publish + +FROM mcr.microsoft.com/dotnet/core/runtime:3.1.0-bionic AS dotnet-runtime + +RUN apt update +RUN apt install -y --no-install-recommends software-properties-common +RUN add-apt-repository -y ppa:jonathonf/ffmpeg-4 +RUN apt update +RUN apt install -y --no-install-recommends ffmpeg + +WORKDIR /app +COPY --from=build-native-env /opt/intel/ /opt/intel/ +RUN /opt/intel/openvino/install_dependencies/install_openvino_dependencies.sh + +RUN apt install -y --no-install-recommends libgdiplus +RUN echo "deb http://ppa.launchpad.net/intel-opencl/intel-opencl/ubuntu bionic main" >/etc/apt/sources.list.d/intel-opencl.list +RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B9732172C4830B8F +RUN apt update +RUN apt install -y intel-opencl-icd clinfo +COPY --from=build-native-env /OpenVinoOpenCvSharp/install/lib/libOpenVinoOpenCvSharpExtern.so . + + +COPY --from=publish /app/publish . + +COPY PeopleDetectionOpenCV/run.sh . +RUN chmod a+x run.sh + +ENTRYPOINT [ "./run.sh" ] diff --git a/Docker/ubuntu-18.04/build.ps1 b/Docker/ubuntu-18.04/build.ps1 new file mode 100644 index 0000000..1fe34e7 --- /dev/null +++ b/Docker/ubuntu-18.04/build.ps1 @@ -0,0 +1,6 @@ +$VERSION="1.0.4" + +docker build -t "nrandell/nick-builder:$VERSION" -f Dockerfile ../.. +docker push "nrandell/nick-builder:$VERSION" + + diff --git a/FaceDetectionOpenVino/FaceDetectionOpenVino.csproj b/FaceDetectionOpenVino/FaceDetectionOpenVino.csproj new file mode 100644 index 0000000..6da3e88 --- /dev/null +++ b/FaceDetectionOpenVino/FaceDetectionOpenVino.csproj @@ -0,0 +1,15 @@ + + + + Exe + netcoreapp3.1 + x64 + enable + + + + + + + + diff --git a/FaceDetectionOpenVino/InferenceEngineDetector.cs b/FaceDetectionOpenVino/InferenceEngineDetector.cs new file mode 100644 index 0000000..03c75aa --- /dev/null +++ b/FaceDetectionOpenVino/InferenceEngineDetector.cs @@ -0,0 +1,49 @@ +using OpenCvSharp; +using OpenCvSharp.Dnn; +using Shared; +using System.Collections.Generic; +using System.Drawing; +using System.IO; + +namespace FaceDetectionOpenVino +{ + public class InferenceEngineDetector : IDetector + { + public Net Net { get; } + + public InferenceEngineDetector(string modelFile) + { + Net = CvDnn.ReadNet(modelFile, Path.ChangeExtension(modelFile, ".xml")); + //Net.SetPreferableBackend(Net.Backend.INFERENCE_ENGINE); + //Net.SetPreferableTarget(Net.Target.OPENCL_FP16); + Net.SetPreferableBackend(Net.Backend.OPENCV); + } + + public Rectangle[] Detect(Mat mat, byte[] buffer) + { + var frameWidth = mat.Width; + var frameHeight = mat.Height; + using var blob = CvDnn.BlobFromImage(mat, 1.0, new OpenCvSharp.Size(300, 300), new OpenCvSharp.Scalar(104, 117, 123), false, false); + Net.SetInput(blob); + using var detections = Net.Forward(); + using var detectionMat = new Mat(detections.Size(2), detections.Size(3), MatType.CV_32F, detections.Ptr(0)); + var rectangles = new List(); + for (var i = 0; i < detectionMat.Rows; i++) + { + var confidence = detectionMat.At(i, 2); + if (confidence > 0.7) + { + var left = (int)(detectionMat.At(i, 3) * frameWidth); + var top = (int)(detectionMat.At(i, 4) * frameHeight); + var right = (int)(detectionMat.At(i, 5) * frameWidth); + var bottom = (int)(detectionMat.At(i, 6) * frameHeight); + + rectangles.Add(new Rectangle(left, top, right - left, bottom - top)); + } + } + + return rectangles.ToArray(); + } + + } +} diff --git a/FaceDetectionOpenVino/Program.cs b/FaceDetectionOpenVino/Program.cs new file mode 100644 index 0000000..e646397 --- /dev/null +++ b/FaceDetectionOpenVino/Program.cs @@ -0,0 +1,126 @@ +using OpenCvSharp; +using Shared; +using System; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace FaceDetectionOpenVino +{ + internal static class Program + { + public static async Task Main(string[] args) + { + var path = Environment.GetEnvironmentVariable("PATH"); + Environment.SetEnvironmentVariable("PATH", @"C:\Program Files (x86)\IntelSWTools\openvino\deployment_tools\inference_engine\bin\intel64\Release;C:\Program Files (x86)\IntelSWTools\openvino\opencv\bin;" + path); + WindowsLibraryLoader.Instance.AdditionalPaths.Add(@"C:\Users\nick\Source\Repos\OpenVinoOpenCvSharp\install\bin"); + if (args.Length != 4) + { + Console.WriteLine("Usage: PersonDetection "); + return -1; + } + + try + { + FFmpegHelper.Register(); + + var buildInfo = OpenCvSharp.Cv2.GetBuildInformation(); + Console.WriteLine($"Build info: {buildInfo}"); + + var inputFormat = args[0]; + var inputCamera = args[1]; + var model = args[2]; + var output = args[3]; + + var outputFolder = new DirectoryInfo(output); + if (!outputFolder.Exists) + { + outputFolder.Create(); + } + + var dataTransfer = new DataTransfer(); + var detector = new InferenceEngineDetector(model); + ProcessStream(inputFormat, inputCamera, dataTransfer); + + var counter = 0; + while (true) + { + using var data = await dataTransfer.GetNext(default); + HandleFrame(data.Value.Mat, data.Value.Buffer, ref counter, detector, outputFolder); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error {ex.Message}"); + Console.WriteLine(ex); + return -2; + } + } + + private static void ProcessStream(string inputFormat, string inputCamera, DataTransfer dataTransfer) + { + var thread = new Thread(() => + { + try + { + using var decoder = new Decoder(inputFormat, inputCamera, dataTransfer); + Console.WriteLine($"Codec name: {decoder.CodecName}"); + + var info = decoder.GetContextInfo(); + foreach (var (key, value) in info) + { + Console.WriteLine($"{key} = '{value}'"); + } + decoder.Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Error in thread: {ex.Message}"); + } + }); + + thread.Start(); + } + + private static void HandleFrame(Mat mat, byte[] buffer, ref int counter, IDetector detector, DirectoryInfo outputFolder) + { + var sw = Stopwatch.StartNew(); + + var faces = detector.Detect(mat, buffer); + var predictTime = sw.Elapsed; + if (faces.Length > 0) + { + using var bitmap = mat.ToBitmap(); + + AugmentOutputImage(faces, bitmap); + var outputFileName = Path.Combine(outputFolder.FullName, $"image-{counter:D03}.png"); + bitmap.Save(outputFileName, ImageFormat.Png); + counter = (counter + 1) % 20; + Console.WriteLine($"Processed {counter} in {predictTime} total {sw.Elapsed}"); + } + else + { + Console.WriteLine($"Skipped in {predictTime} total {sw.Elapsed}"); + } + } + + private static void AugmentOutputImage(Rectangle[] output, Bitmap bitmap) + { + Console.WriteLine($"Got {output.Length} detections"); + + using var graphics = Graphics.FromImage(bitmap); + graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; + using var pen = new Pen(Color.Red, 4); + + for (var i = 0; i < output.Length; i++) + { + var rectangle = output[i]; + var rect = new Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height); + graphics.DrawRectangle(pen, rect); + } + } + } +} diff --git a/FaceDetectionOpenVino/Properties/launchSettings.json b/FaceDetectionOpenVino/Properties/launchSettings.json new file mode 100644 index 0000000..1f628dc --- /dev/null +++ b/FaceDetectionOpenVino/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "FaceDetectionOpenVino": { + "commandName": "Project", + "commandLineArgs": "dshow \"video=Razer Kiyo\" \"c:\\users\\nick\\downloads\\models\\face-detection-retail-0005.bin\" \"c:\\temp\\pddumps\\local\"" + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp.sln b/OpenVinoOpenCvSharp.sln new file mode 100644 index 0000000..3e048dc --- /dev/null +++ b/OpenVinoOpenCvSharp.sln @@ -0,0 +1,57 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29519.181 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PeopleDetectionOpenCV", "PeopleDetectionOpenCV\PeopleDetectionOpenCV.csproj", "{70AB41F0-9FC8-459B-A989-0780355812E8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "Shared\Shared.csproj", "{DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenVinoOpenCvSharp", "OpenVinoOpenCvSharp\OpenVinoOpenCvSharp.csproj", "{323B93E1-9EA9-4641-A415-821BBB0D1516}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FaceDetectionOpenVino", "FaceDetectionOpenVino\FaceDetectionOpenVino.csproj", "{486BCF83-C85E-4855-9619-3B902331C36A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {70AB41F0-9FC8-459B-A989-0780355812E8}.Debug|Any CPU.ActiveCfg = Debug|x64 + {70AB41F0-9FC8-459B-A989-0780355812E8}.Debug|x64.ActiveCfg = Debug|x64 + {70AB41F0-9FC8-459B-A989-0780355812E8}.Debug|x64.Build.0 = Debug|x64 + {70AB41F0-9FC8-459B-A989-0780355812E8}.Release|Any CPU.ActiveCfg = Release|x64 + {70AB41F0-9FC8-459B-A989-0780355812E8}.Release|x64.ActiveCfg = Release|x64 + {70AB41F0-9FC8-459B-A989-0780355812E8}.Release|x64.Build.0 = Release|x64 + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Debug|x64.ActiveCfg = Debug|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Debug|x64.Build.0 = Debug|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Release|Any CPU.Build.0 = Release|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Release|x64.ActiveCfg = Release|Any CPU + {DFCB28CA-5D41-4FAD-91EC-7EB8DB4ACC0C}.Release|x64.Build.0 = Release|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Debug|Any CPU.Build.0 = Debug|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Debug|x64.ActiveCfg = Debug|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Debug|x64.Build.0 = Debug|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Release|Any CPU.ActiveCfg = Release|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Release|Any CPU.Build.0 = Release|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Release|x64.ActiveCfg = Release|Any CPU + {323B93E1-9EA9-4641-A415-821BBB0D1516}.Release|x64.Build.0 = Release|Any CPU + {486BCF83-C85E-4855-9619-3B902331C36A}.Debug|Any CPU.ActiveCfg = Debug|x64 + {486BCF83-C85E-4855-9619-3B902331C36A}.Debug|x64.ActiveCfg = Debug|x64 + {486BCF83-C85E-4855-9619-3B902331C36A}.Debug|x64.Build.0 = Debug|x64 + {486BCF83-C85E-4855-9619-3B902331C36A}.Release|Any CPU.ActiveCfg = Release|x64 + {486BCF83-C85E-4855-9619-3B902331C36A}.Release|x64.ActiveCfg = Release|x64 + {486BCF83-C85E-4855-9619-3B902331C36A}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5D62A850-48D2-49BC-86A6-1F94578ACA5F} + EndGlobalSection +EndGlobal diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2.cs b/OpenVinoOpenCvSharp/Cv2/Cv2.cs new file mode 100644 index 0000000..2e7d1be --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2.cs @@ -0,0 +1,46 @@ +using System; + +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp +{ + /// + /// OpenCV Functions of C++ I/F (cv::xxx) + /// + public static partial class Cv2 + { + /// + /// The ratio of a circle's circumference to its diameter + /// + public const double PI = 3.1415926535897932384626433832795; + + /// + /// + /// + public const double LOG2 = 0.69314718055994530941723212145818; + + /// + /// + /// + public const int FILLED = -1; + + /// + /// set up P/Invoke settings only for .NET 2.0/3.0/3.5 + /// + /// + public static void Initialize() + { + NativeMethods.TryPInvoke(); + } + + /// + /// 引数がnullの時はIntPtr.Zeroに変換する + /// + /// + /// + internal static IntPtr ToPtr(ICvPtrHolder? obj) + { + return obj?.CvPtr ?? IntPtr.Zero; + } + } +} diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2_calib3d.cs b/OpenVinoOpenCvSharp/Cv2/Cv2_calib3d.cs new file mode 100644 index 0000000..8b1d71b --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2_calib3d.cs @@ -0,0 +1,4100 @@ +using OpenCvSharp.Util; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + // ReSharper disable IdentifierTypo + // ReSharper disable CommentTypo + // ReSharper disable UnusedMember.Global + + using FeatureDetector = Feature2D; + + static partial class Cv2 + { + #region Rodrigues + + /// + /// converts rotation vector to rotation matrix or vice versa using Rodrigues transformation + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.calib3d_Rodrigues(src.CvPtr, dst.CvPtr, ToPtr(jacobian)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(jacobian); + dst.Fix(); + jacobian?.Fix(); + } + + /// + /// converts rotation vector to rotation matrix using Rodrigues transformation + /// + /// Input rotation vector (3x1). + /// Output rotation matrix (3x3). + /// Optional output Jacobian matrix, 3x9, which is a matrix of partial derivatives of the output array components with respect to the input array components. + public static void Rodrigues(double[] vector, out double[,] matrix, out double[,] jacobian) + { + if (vector == null) + throw new ArgumentNullException(nameof(vector)); + if (vector.Length != 3) + throw new ArgumentException("vector.Length != 3"); + + using (var vectorM = new Mat(3, 1, MatType.CV_64FC1, vector)) + using (var matrixM = new Mat()) + using (var jacobianM = new Mat()) + { + NativeMethods.calib3d_Rodrigues_VecToMat(vectorM.CvPtr, matrixM.CvPtr, jacobianM.CvPtr); + matrix = matrixM.ToRectangularArray(); + jacobian = jacobianM.ToRectangularArray(); + } + } + + /// + /// converts rotation vector to rotation matrix using Rodrigues transformation + /// + /// Input rotation vector (3x1). + /// Output rotation matrix (3x3). + public static void Rodrigues(double[] vector, out double[,] matrix) + { + Rodrigues(vector, out matrix, out _); + } + + /// + /// converts rotation matrix to rotation vector using Rodrigues transformation + /// + /// Input rotation matrix (3x3). + /// Output rotation vector (3x1). + /// Optional output Jacobian matrix, 3x9, which is a matrix of partial derivatives of the output array components with respect to the input array components. + public static void Rodrigues(double[,] matrix, out double[] vector, out double[,] jacobian) + { + if (matrix == null) + throw new ArgumentNullException(nameof(matrix)); + if (matrix.GetLength(0) != 3 || matrix.GetLength(1) != 3) + throw new ArgumentException("matrix must be double[3,3]"); + + using (var matrixM = new Mat(3, 3, MatType.CV_64FC1, matrix)) + using (var vectorM = new Mat()) + using (var jacobianM = new Mat()) + { + NativeMethods.calib3d_Rodrigues_MatToVec(vectorM.CvPtr, matrixM.CvPtr, jacobianM.CvPtr); + vector = vectorM.ToArray(); + jacobian = jacobianM.ToRectangularArray(); + } + } + + /// + /// converts rotation matrix to rotation vector using Rodrigues transformation + /// + /// Input rotation matrix (3x3). + /// Output rotation vector (3x1). + public static void Rodrigues(double[,] matrix, out double[] vector) + { + Rodrigues(matrix, out vector, out _); + } + + #endregion + #region FindHomography + + /// + /// computes the best-fit perspective transformation mapping srcPoints to dstPoints. + /// + /// Coordinates of the points in the original plane, a matrix of the type CV_32FC2 + /// Coordinates of the points in the target plane, a matrix of the type CV_32FC2 + /// Method used to computed a homography matrix. + /// Maximum allowed reprojection error to treat a point pair as an inlier (used in the RANSAC method only) + /// Optional output mask set by a robust method ( CV_RANSAC or CV_LMEDS ). Note that the input mask values are ignored. + /// + public static Mat FindHomography(InputArray srcPoints, InputArray dstPoints, + HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, + OutputArray? mask = null) + { + if (srcPoints == null) + throw new ArgumentNullException(nameof(srcPoints)); + if (dstPoints == null) + throw new ArgumentNullException(nameof(dstPoints)); + srcPoints.ThrowIfDisposed(); + dstPoints.ThrowIfDisposed(); + + var mat = NativeMethods.calib3d_findHomography_InputArray(srcPoints.CvPtr, dstPoints.CvPtr, (int)method, + ransacReprojThreshold, ToPtr(mask)); + GC.KeepAlive(srcPoints); + GC.KeepAlive(dstPoints); + GC.KeepAlive(mask); + + mask?.Fix(); + return new Mat(mat); + } + + /// + /// computes the best-fit perspective transformation mapping srcPoints to dstPoints. + /// + /// Coordinates of the points in the original plane + /// Coordinates of the points in the target plane + /// Method used to computed a homography matrix. + /// Maximum allowed reprojection error to treat a point pair as an inlier (used in the RANSAC method only) + /// Optional output mask set by a robust method ( CV_RANSAC or CV_LMEDS ). Note that the input mask values are ignored. + /// + public static Mat FindHomography(IEnumerable srcPoints, IEnumerable dstPoints, + HomographyMethods method = HomographyMethods.None, double ransacReprojThreshold = 3, + OutputArray? mask = null) + { + if (srcPoints == null) + throw new ArgumentNullException(nameof(srcPoints)); + if (dstPoints == null) + throw new ArgumentNullException(nameof(dstPoints)); + + var srcPointsArray = EnumerableEx.ToArray(srcPoints); + var dstPointsArray = EnumerableEx.ToArray(dstPoints); + + var mat = NativeMethods.calib3d_findHomography_vector(srcPointsArray, srcPointsArray.Length, + dstPointsArray, dstPointsArray.Length, (int)method, ransacReprojThreshold, ToPtr(mask)); + GC.KeepAlive(mask); + + mask?.Fix(); + return new Mat(mat); + } + + #endregion + #region RQDecomp3x3 + + /// + /// Computes RQ decomposition of 3x3 matrix + /// + /// 3x3 input matrix. + /// Output 3x3 upper-triangular matrix. + /// Output 3x3 orthogonal matrix. + /// Optional output 3x3 rotation matrix around x-axis. + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (mtxR == null) + throw new ArgumentNullException(nameof(mtxR)); + if (mtxQ == null) + throw new ArgumentNullException(nameof(mtxQ)); + src.ThrowIfDisposed(); + mtxR.ThrowIfNotReady(); + mtxQ.ThrowIfNotReady(); + NativeMethods.calib3d_RQDecomp3x3_InputArray(src.CvPtr, mtxR.CvPtr, mtxQ.CvPtr, + ToPtr(qx), ToPtr(qy), ToPtr(qz), out var ret); + GC.KeepAlive(src); + GC.KeepAlive(mtxR); + GC.KeepAlive(mtxQ); + qx?.Fix(); + qy?.Fix(); + qz?.Fix(); + return ret; + } + + /// + /// Computes RQ decomposition of 3x3 matrix + /// + /// 3x3 input matrix. + /// Output 3x3 upper-triangular matrix. + /// Output 3x3 orthogonal matrix. + /// + public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] mtxQ) + { + return RQDecomp3x3(src, out mtxR, out mtxQ, out _, out _, out _); + } + + /// + /// Computes RQ decomposition of 3x3 matrix + /// + /// 3x3 input matrix. + /// Output 3x3 upper-triangular matrix. + /// Output 3x3 orthogonal matrix. + /// Optional output 3x3 rotation matrix around x-axis. + /// Optional output 3x3 rotation matrix around y-axis. + /// Optional output 3x3 rotation matrix around z-axis. + /// + public static Vec3d RQDecomp3x3(double[,] src, out double[,] mtxR, out double[,] mtxQ, + out double[,] qx, out double[,] qy, out double[,] qz) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (src.GetLength(0) != 3 || src.GetLength(1) != 3) + throw new ArgumentException("src must be double[3,3]"); + + using (var srcM = new Mat(3, 3, MatType.CV_64FC1, src)) + using (var mtxRM = new Mat()) + using (var mtxQM = new Mat()) + using (var qxM = new Mat()) + using (var qyM = new Mat()) + using (var qzM = new Mat()) + { + NativeMethods.calib3d_RQDecomp3x3_Mat(srcM.CvPtr, + mtxRM.CvPtr, mtxQM.CvPtr, qxM.CvPtr, qyM.CvPtr, qzM.CvPtr, + out var ret); + mtxR = mtxRM.ToRectangularArray(); + mtxQ = mtxQM.ToRectangularArray(); + qx = qxM.ToRectangularArray(); + qy = qyM.ToRectangularArray(); + qz = qzM.ToRectangularArray(); + return ret; + } + } + + #endregion + #region DecomposeProjectionMatrix + + /// + /// Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector + /// + /// 3x4 input projection matrix P. + /// Output 3x3 camera matrix K. + /// Output 3x3 external rotation matrix R. + /// Output 4x1 translation vector T. + /// Optional 3x3 rotation matrix around x-axis. + /// Optional 3x3 rotation matrix around y-axis. + /// 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) + { + if (projMatrix == null) + throw new ArgumentNullException(nameof(projMatrix)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (rotMatrix == null) + throw new ArgumentNullException(nameof(rotMatrix)); + projMatrix.ThrowIfDisposed(); + cameraMatrix.ThrowIfNotReady(); + rotMatrix.ThrowIfNotReady(); + transVect.ThrowIfNotReady(); + + NativeMethods.calib3d_decomposeProjectionMatrix_InputArray( + projMatrix.CvPtr, cameraMatrix.CvPtr, rotMatrix.CvPtr, transVect.CvPtr, + ToPtr(rotMatrixX), ToPtr(rotMatrixY), ToPtr(rotMatrixZ), ToPtr(eulerAngles)); + GC.KeepAlive(projMatrix); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(rotMatrix); + GC.KeepAlive(transVect); + GC.KeepAlive(rotMatrixX); + GC.KeepAlive(rotMatrixY); + GC.KeepAlive(rotMatrixZ); + GC.KeepAlive(eulerAngles); + + cameraMatrix.Fix(); + rotMatrix.Fix(); + transVect.Fix(); + rotMatrixX?.Fix(); + rotMatrixY?.Fix(); + rotMatrixZ?.Fix(); + eulerAngles?.Fix(); + } + + /// + /// Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector + /// + /// 3x4 input projection matrix P. + /// Output 3x3 camera matrix K. + /// Output 3x3 external rotation matrix R. + /// Output 4x1 translation vector T. + /// Optional 3x3 rotation matrix around x-axis. + /// Optional 3x3 rotation matrix around y-axis. + /// Optional 3x3 rotation matrix around z-axis. + /// ptional three-element vector containing three Euler angles of rotation in degrees. + public static void DecomposeProjectionMatrix(double[,] projMatrix, + out double[,] cameraMatrix, + out double[,] rotMatrix, + out double[] transVect, + out double[,] rotMatrixX, + out double[,] rotMatrixY, + out double[,] rotMatrixZ, + out double[] eulerAngles) + { + if (projMatrix == null) + throw new ArgumentNullException(nameof(projMatrix)); + var dim0 = projMatrix.GetLength(0); + var dim1 = projMatrix.GetLength(1); + if (!((dim0 == 3 && dim1 == 4) || (dim0 == 4 && dim1 == 3))) + throw new ArgumentException("projMatrix must be double[3,4] or double[4,3]"); + + using (var projMatrixM = new Mat(3, 4, MatType.CV_64FC1, projMatrix)) + using (var cameraMatrixM = new Mat()) + using (var rotMatrixM = new Mat()) + using (var transVectM = new Mat()) + using (var rotMatrixXM = new Mat()) + using (var rotMatrixYM = new Mat()) + using (var rotMatrixZM = new Mat()) + using (var eulerAnglesM = new Mat()) + { + NativeMethods.calib3d_decomposeProjectionMatrix_Mat( + projMatrixM.CvPtr, + cameraMatrixM.CvPtr, rotMatrixM.CvPtr, transVectM.CvPtr, + rotMatrixXM.CvPtr, rotMatrixYM.CvPtr, rotMatrixZM.CvPtr, + eulerAnglesM.CvPtr); + + cameraMatrix = cameraMatrixM.ToRectangularArray(); + rotMatrix = rotMatrixM.ToRectangularArray(); + transVect = transVectM.ToArray(); + rotMatrixX = rotMatrixXM.ToRectangularArray(); + rotMatrixY = rotMatrixYM.ToRectangularArray(); + rotMatrixZ = rotMatrixZM.ToRectangularArray(); + eulerAngles = eulerAnglesM.ToArray(); + } + } + + /// + /// Decomposes the projection matrix into camera matrix and the rotation martix and the translation vector + /// + /// 3x4 input projection matrix P. + /// Output 3x3 camera matrix K. + /// Output 3x3 external rotation matrix R. + /// Output 4x1 translation vector T. + public static void DecomposeProjectionMatrix(double[,] projMatrix, + out double[,] cameraMatrix, + out double[,] rotMatrix, + out double[] transVect) + { + DecomposeProjectionMatrix(projMatrix, out cameraMatrix, out rotMatrix, out transVect, + out _, out _, out _, out _); + } + + #endregion + #region MatMulDeriv + + /// + /// computes derivatives of the matrix product w.r.t each of the multiplied matrix coefficients + /// + /// First multiplied matrix. + /// Second multiplied matrix. + /// 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 == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + if (dABdA == null) + throw new ArgumentNullException(nameof(dABdA)); + if (dABdB == null) + throw new ArgumentNullException(nameof(dABdB)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + dABdA.ThrowIfNotReady(); + dABdB.ThrowIfNotReady(); + NativeMethods.calib3d_matMulDeriv(a.CvPtr, b.CvPtr, dABdA.CvPtr, dABdB.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + dABdA.Fix(); + dABdB.Fix(); + } + + #endregion + #region ComposeRT + + /// + /// composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments + /// + /// First rotation vector. + /// First translation vector. + /// Second rotation vector. + /// Second translation vector. + /// Output rotation vector of the superposition. + /// Output translation vector of the superposition. + /// 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. + /// 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. + /// 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. + /// 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) + { + if (rvec1 == null) + throw new ArgumentNullException(nameof(rvec1)); + if (tvec1 == null) + throw new ArgumentNullException(nameof(tvec1)); + if (rvec2 == null) + throw new ArgumentNullException(nameof(rvec2)); + if (tvec2 == null) + throw new ArgumentNullException(nameof(tvec2)); + rvec1.ThrowIfDisposed(); + tvec1.ThrowIfDisposed(); + rvec2.ThrowIfDisposed(); + tvec2.ThrowIfDisposed(); + rvec3.ThrowIfNotReady(); + tvec3.ThrowIfNotReady(); + NativeMethods.calib3d_composeRT_InputArray(rvec1.CvPtr, tvec1.CvPtr, rvec2.CvPtr, tvec2.CvPtr, + rvec3.CvPtr, tvec3.CvPtr, + ToPtr(dr3dr1), ToPtr(dr3dt1), ToPtr(dr3dr2), ToPtr(dr3dt2), + ToPtr(dt3dr1), ToPtr(dt3dt1), ToPtr(dt3dr2), ToPtr(dt3dt2)); + 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); + } + + /// + /// composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments + /// + /// First rotation vector. + /// First translation vector. + /// Second rotation vector. + /// Second translation vector. + /// Output rotation vector of the superposition. + /// Output translation vector of the superposition. + /// 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. + /// 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. + /// 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. + /// 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(double[] rvec1, double[] tvec1, + double[] rvec2, double[] tvec2, + out double[] rvec3, out double[] tvec3, + out double[,] dr3dr1, out double[,] dr3dt1, + out double[,] dr3dr2, out double[,] dr3dt2, + out double[,] dt3dr1, out double[,] dt3dt1, + out double[,] dt3dr2, out double[,] dt3dt2) + { + if (rvec1 == null) + throw new ArgumentNullException(nameof(rvec1)); + if (tvec1 == null) + throw new ArgumentNullException(nameof(tvec1)); + if (rvec2 == null) + throw new ArgumentNullException(nameof(rvec2)); + if (tvec2 == null) + throw new ArgumentNullException(nameof(tvec2)); + + using (var rvec1M = new Mat(3, 1, MatType.CV_64FC1, rvec1)) + using (var tvec1M = new Mat(3, 1, MatType.CV_64FC1, tvec1)) + using (var rvec2M = new Mat(3, 1, MatType.CV_64FC1, rvec2)) + using (var tvec2M = new Mat(3, 1, MatType.CV_64FC1, tvec2)) + using (var rvec3M = new Mat()) + using (var tvec3M = new Mat()) + using (var dr3dr1M = new Mat()) + using (var dr3dt1M = new Mat()) + using (var dr3dr2M = new Mat()) + using (var dr3dt2M = new Mat()) + using (var dt3dr1M = new Mat()) + using (var dt3dt1M = new Mat()) + using (var dt3dr2M = new Mat()) + using (var dt3dt2M = new Mat()) + { + NativeMethods.calib3d_composeRT_Mat(rvec1M.CvPtr, tvec1M.CvPtr, rvec2M.CvPtr, tvec2M.CvPtr, + rvec3M.CvPtr, tvec3M.CvPtr, + dr3dr1M.CvPtr, dr3dt1M.CvPtr, dr3dr2M.CvPtr, dr3dt2M.CvPtr, + dt3dr1M.CvPtr, dt3dt1M.CvPtr, dt3dr2M.CvPtr, dt3dt2M.CvPtr); + rvec3 = rvec3M.ToArray(); + tvec3 = tvec3M.ToArray(); + dr3dr1 = dr3dr1M.ToRectangularArray(); + dr3dt1 = dr3dt1M.ToRectangularArray(); + dr3dr2 = dr3dr2M.ToRectangularArray(); + dr3dt2 = dr3dt2M.ToRectangularArray(); + dt3dr1 = dt3dr1M.ToRectangularArray(); + dt3dt1 = dt3dt1M.ToRectangularArray(); + dt3dr2 = dt3dr2M.ToRectangularArray(); + dt3dt2 = dt3dt2M.ToRectangularArray(); + } + } + + /// + /// composes 2 [R|t] transformations together. Also computes the derivatives of the result w.r.t the arguments + /// + /// First rotation vector. + /// First translation vector. + /// Second rotation vector. + /// Second translation vector. + /// Output rotation vector of the superposition. + /// Output translation vector of the superposition. + public static void ComposeRT(double[] rvec1, double[] tvec1, + double[] rvec2, double[] tvec2, + out double[] rvec3, out double[] tvec3) + { + ComposeRT(rvec1, tvec1, rvec2, tvec2, out rvec3, out tvec3, + out _, out _, out _, out _, + out _, out _, out _, out _); + } + + #endregion + #region ProjectPoints + + /// + /// projects points from the model coordinate space to the image coordinates. + /// Also computes derivatives of the image coordinates w.r.t the intrinsic + /// and extrinsic camera parameters + /// + /// Array of object points, 3xN/Nx3 1-channel or + /// 1xN/Nx1 3-channel, where N is the number of points in the view. + /// Rotation vector (3x1). + /// Translation vector (3x1). + /// Camera matrix (3x3) + /// 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. + /// Output array of image points, 2xN/Nx2 1-channel + /// or 1xN/Nx1 2-channel + /// Optional output 2Nx(10 + numDistCoeffs) jacobian matrix + /// of derivatives of image points with respect to components of the rotation vector, + /// translation vector, focal lengths, coordinates of the principal point and + /// the distortion coefficients. In the old interface different components of + /// the jacobian are returned via different output parameters. + /// Optional “fixed aspect ratio” parameter. + /// 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, + double aspectRatio = 0) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + objectPoints.ThrowIfDisposed(); + rvec.ThrowIfDisposed(); + tvec.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + imagePoints.ThrowIfNotReady(); + + if (jacobian == null) + jacobian = new Mat(); + + NativeMethods.calib3d_projectPoints_InputArray( + objectPoints.CvPtr, + rvec.CvPtr, tvec.CvPtr, cameraMatrix.CvPtr, ToPtr(distCoeffs), + imagePoints.CvPtr, ToPtr(jacobian), aspectRatio); + + GC.KeepAlive(objectPoints); + GC.KeepAlive(rvec); + GC.KeepAlive(tvec); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(imagePoints); + GC.KeepAlive(jacobian); + } + + /// + /// projects points from the model coordinate space to the image coordinates. + /// Also computes derivatives of the image coordinates w.r.t the intrinsic + /// and extrinsic camera parameters + /// + /// Array of object points, 3xN/Nx3 1-channel or + /// 1xN/Nx1 3-channel, where N is the number of points in the view. + /// Rotation vector (3x1). + /// Translation vector (3x1). + /// Camera matrix (3x3) + /// 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. + /// Output array of image points, 2xN/Nx2 1-channel + /// or 1xN/Nx1 2-channel + /// Optional output 2Nx(10 + numDistCoeffs) jacobian matrix + /// of derivatives of image points with respect to components of the rotation vector, + /// translation vector, focal lengths, coordinates of the principal point and + /// the distortion coefficients. In the old interface different components of + /// the jacobian are returned via different output parameters. + /// Optional “fixed aspect ratio” parameter. + /// 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(IEnumerable objectPoints, + double[] rvec, double[] tvec, + double[,] cameraMatrix, double[] distCoeffs, + out Point2f[] imagePoints, + out double[,] jacobian, + double aspectRatio = 0) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (rvec.Length != 3) + throw new ArgumentException($"{nameof(rvec)}.Length != 3"); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + if (tvec.Length != 3) + throw new ArgumentException($"{nameof(tvec)}.Length != 3"); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3) + throw new ArgumentException("cameraMatrix must be double[3,3]"); + + var objectPointsArray = EnumerableEx.ToArray(objectPoints); + using (var objectPointsM = new Mat(objectPointsArray.Length, 1, MatType.CV_32FC3, objectPointsArray)) + using (var rvecM = new Mat(3, 1, MatType.CV_64FC1, rvec)) + using (var tvecM = new Mat(3, 1, MatType.CV_64FC1, tvec)) + using (var cameraMatrixM = new Mat(3, 3, MatType.CV_64FC1, cameraMatrix)) + using (var distCoeffsM = (distCoeffs == null) ? new Mat() : new Mat(distCoeffs.Length, 1, MatType.CV_64FC1, distCoeffs)) + using (var imagePointsM = new Mat()) + using (var jacobianM = new Mat()) + { + NativeMethods.calib3d_projectPoints_Mat(objectPointsM.CvPtr, + rvecM.CvPtr, tvecM.CvPtr, cameraMatrixM.CvPtr, distCoeffsM.CvPtr, + imagePointsM.CvPtr, jacobianM.CvPtr, aspectRatio); + + imagePoints = imagePointsM.ToArray(); + jacobian = jacobianM.ToRectangularArray(); + } + } + + #endregion + #region SolvePnP + + /// + /// Finds an object pose from 3D-2D point correspondences. + /// + /// Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, + /// where N is the number of points. vector<Point3f> can be also passed here. + /// Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, + /// where N is the number of points. vector<Point2f> can be also passed here. + /// 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. + /// Output rotation vector that, together with tvec , brings points from the model coordinate system to the + /// camera coordinate system. + /// Output translation vector. + /// If true, the function uses the provided rvec and tvec values as initial approximations of + /// 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, + bool useExtrinsicGuess = false, + SolvePnPFlags flags = SolvePnPFlags.Iterative) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + objectPoints.ThrowIfDisposed(); + imagePoints.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + distCoeffs.ThrowIfDisposed(); + rvec.ThrowIfDisposed(); + tvec.ThrowIfDisposed(); + var distCoeffsPtr = ToPtr(distCoeffs); + NativeMethods.calib3d_solvePnP_InputArray( + objectPoints.CvPtr, imagePoints.CvPtr, cameraMatrix.CvPtr, distCoeffsPtr, + rvec.CvPtr, tvec.CvPtr, useExtrinsicGuess ? 1 : 0, (int)flags); + rvec.Fix(); + tvec.Fix(); + GC.KeepAlive(objectPoints); + GC.KeepAlive(imagePoints); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + } + + /// + /// Finds an object pose from 3D-2D point correspondences. + /// + /// Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, + /// where N is the number of points. vector<Point3f> can be also passed here. + /// Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, + /// where N is the number of points. vector<Point2f> can be also passed here. + /// 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. + /// Output rotation vector that, together with tvec , brings points from the model coordinate system to the + /// camera coordinate system. + /// Output translation vector. + /// If true, the function uses the provided rvec and tvec values as initial approximations of + /// the rotation and translation vectors, respectively, and further optimizes them. + /// Method for solving a PnP problem + public static void SolvePnP( + IEnumerable objectPoints, + IEnumerable imagePoints, + double[,] cameraMatrix, + IEnumerable distCoeffs, + ref double[] rvec, + ref double[] tvec, + bool useExtrinsicGuess = false, + SolvePnPFlags flags = SolvePnPFlags.Iterative) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3) + throw new ArgumentException(""); + + var objectPointsArray = EnumerableEx.ToArray(objectPoints); + var imagePointsArray = EnumerableEx.ToArray(imagePoints); + var distCoeffsArray = EnumerableEx.ToArray(distCoeffs); + var distCoeffsLength = (distCoeffs == null) ? 0 : distCoeffsArray.Length; + + if (!useExtrinsicGuess) + { + rvec = new double[3]; + tvec = new double[3]; + } + + unsafe + { + fixed (double* cameraMatrixPtr = cameraMatrix) + { + NativeMethods.calib3d_solvePnP_vector( + objectPointsArray, objectPointsArray.Length, + imagePointsArray, imagePointsArray.Length, + cameraMatrixPtr, distCoeffsArray, distCoeffsLength, + rvec, tvec, useExtrinsicGuess ? 1 : 0, (int)flags); + } + } + } + + #endregion + #region SolvePnPRansac + /// + /// computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. + /// + /// Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, + /// where N is the number of points. List<Point3f> can be also passed here. + /// Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, where N is the number of points. + /// List<Point2f> can be also passed here. + /// Input 3x3 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. + /// Output rotation vector that, together with tvec , brings points from the model coordinate system + /// to the camera coordinate system. + /// Output translation vector. + /// If true, the function uses the provided rvec and tvec values as initial approximations + /// of the rotation and translation vectors, respectively, and further optimizes them. + /// Number of iterations. + /// Inlier threshold value used by the RANSAC procedure. + /// The parameter value is the maximum allowed distance between the observed and computed point projections to consider it an inlier. + /// The probability that the algorithm produces a useful result. + /// 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, + bool useExtrinsicGuess = false, + int iterationsCount = 100, + float reprojectionError = 8.0f, + double confidence = 0.99, + OutputArray? inliers = null, + SolvePnPFlags flags = SolvePnPFlags.Iterative) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + objectPoints.ThrowIfDisposed(); + imagePoints.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + distCoeffs.ThrowIfDisposed(); + rvec.ThrowIfDisposed(); + tvec.ThrowIfDisposed(); + var distCoeffsPtr = ToPtr(distCoeffs); + + NativeMethods.calib3d_solvePnPRansac_InputArray( + objectPoints.CvPtr, imagePoints.CvPtr, cameraMatrix.CvPtr, distCoeffsPtr, + rvec.CvPtr, tvec.CvPtr, useExtrinsicGuess ? 1 : 0, iterationsCount, + reprojectionError, confidence, ToPtr(inliers), (int)flags); + + GC.KeepAlive(objectPoints); + GC.KeepAlive(imagePoints); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + rvec.Fix(); + tvec.Fix(); + inliers?.Fix(); + } + + /// + /// computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. + /// + /// Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, + /// where N is the number of points. List<Point3f> can be also passed here. + /// Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, where N is the number of points. + /// List<Point2f> can be also passed here. + /// Input 3x3 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. + /// Output rotation vector that, together with tvec , brings points from the model coordinate system + /// to the camera coordinate system. + /// Output translation vector. + public static void SolvePnPRansac( + IEnumerable objectPoints, + IEnumerable imagePoints, + double[,] cameraMatrix, + IEnumerable distCoeffs, + out double[] rvec, out double[] tvec) + { + SolvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs, out rvec, out tvec, out _); + } + + /// + /// computes the camera pose from a few 3D points and the corresponding projections. The outliers are possible. + /// + /// Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, + /// where N is the number of points. List<Point3f> can be also passed here. + /// Array of corresponding image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, where N is the number of points. + /// List<Point2f> can be also passed here. + /// Input 3x3 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. + /// Output rotation vector that, together with tvec , brings points from the model coordinate system + /// to the camera coordinate system. + /// Output translation vector. + /// If true, the function uses the provided rvec and tvec values as initial approximations + /// of the rotation and translation vectors, respectively, and further optimizes them. + /// Number of iterations. + /// Inlier threshold value used by the RANSAC procedure. + /// The parameter value is the maximum allowed distance between the observed and computed point projections to consider it an inlier. + /// The probability that the algorithm produces a useful result. + /// Output vector that contains indices of inliers in objectPoints and imagePoints . + /// Method for solving a PnP problem + public static void SolvePnPRansac( + IEnumerable objectPoints, + IEnumerable imagePoints, + double[,] cameraMatrix, + IEnumerable distCoeffs, + out double[] rvec, out double[] tvec, + out int[] inliers, + bool useExtrinsicGuess = false, + int iterationsCount = 100, + float reprojectionError = 8.0f, + double confidence = 0.99, + SolvePnPFlags flags = SolvePnPFlags.Iterative) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + + if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3) + throw new ArgumentException(""); + + var objectPointsArray = EnumerableEx.ToArray(objectPoints); + var imagePointsArray = EnumerableEx.ToArray(imagePoints); + var distCoeffsArray = EnumerableEx.ToArray(distCoeffs); + var distCoeffsLength = (distCoeffs == null) ? 0 : distCoeffsArray.Length; + rvec = new double[3]; + tvec = new double[3]; + + using (var inliersVec = new VectorOfInt32()) + { + unsafe + { + fixed (double* cameraMatrixPtr = cameraMatrix) + { + NativeMethods.calib3d_solvePnPRansac_vector( + objectPointsArray, objectPointsArray.Length, + imagePointsArray, imagePointsArray.Length, + cameraMatrixPtr, distCoeffsArray, distCoeffsLength, + rvec, tvec, useExtrinsicGuess ? 1 : 0, iterationsCount, + reprojectionError, confidence, inliersVec.CvPtr, (int)flags); + inliers = inliersVec.ToArray(); + } + } + } + } + #endregion + #region InitCameraMatrix2D + /// + /// initializes camera matrix from a few 3D points and the corresponding projections. + /// + /// Vector of vectors (vector<vector<Point3d>>) of the calibration pattern points in the calibration pattern coordinate space. In the old interface all the per-view vectors are concatenated. + /// Vector of vectors (vector<vector<Point2d>>) of the projections of the calibration pattern points. In the old interface all the per-view vectors are concatenated. + /// Image size in pixels used to initialize the principal point. + /// If it is zero or negative, both f_x and f_y are estimated independently. Otherwise, f_x = f_y * aspectRatio . + /// + public static Mat InitCameraMatrix2D( + IEnumerable objectPoints, + IEnumerable imagePoints, + Size imageSize, + double aspectRatio = 1.0) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + + var objectPointsPtrs = EnumerableEx.SelectPtrs(objectPoints); + var imagePointsPtrs = EnumerableEx.SelectPtrs(imagePoints); + + var matPtr = NativeMethods.calib3d_initCameraMatrix2D_Mat(objectPointsPtrs, objectPointsPtrs.Length, + imagePointsPtrs, imagePointsPtrs.Length, imageSize, aspectRatio); + return new Mat(matPtr); + } + /// + /// initializes camera matrix from a few 3D points and the corresponding projections. + /// + /// Vector of vectors of the calibration pattern points in the calibration pattern coordinate space. In the old interface all the per-view vectors are concatenated. + /// Vector of vectors of the projections of the calibration pattern points. In the old interface all the per-view vectors are concatenated. + /// Image size in pixels used to initialize the principal point. + /// If it is zero or negative, both f_x and f_y are estimated independently. Otherwise, f_x = f_y * aspectRatio . + /// + public static Mat InitCameraMatrix2D( + IEnumerable> objectPoints, + IEnumerable> imagePoints, + Size imageSize, + double aspectRatio = 1.0) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + + using (var opArray = new ArrayAddress2(objectPoints)) + using (var ipArray = new ArrayAddress2(imagePoints)) + { + var matPtr = NativeMethods.calib3d_initCameraMatrix2D_array( + opArray, opArray.Dim1Length, opArray.Dim2Lengths, + ipArray, ipArray.Dim1Length, ipArray.Dim2Lengths, + imageSize, aspectRatio); + return new Mat(matPtr); + } + } + #endregion + #region FindChessboardCorners + /// + /// Finds the positions of internal corners of the chessboard. + /// + /// Source chessboard view. It must be an 8-bit grayscale or color image. + /// Number of inner corners per a chessboard row and column + /// ( patternSize = Size(points_per_row,points_per_colum) = Size(columns, rows) ). + /// Output array of detected corners. + /// Various operation flags that can be zero or a combination of the ChessboardFlag values + /// 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, + Size patternSize, + OutputArray corners, + ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + image.ThrowIfDisposed(); + corners.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_findChessboardCorners_InputArray( + image.CvPtr, patternSize, corners.CvPtr, (int)flags); + GC.KeepAlive(image); + corners.Fix(); + return ret != 0; + } + /// + /// Finds the positions of internal corners of the chessboard. + /// + /// Source chessboard view. It must be an 8-bit grayscale or color image. + /// Number of inner corners per a chessboard row and column + /// ( patternSize = Size(points_per_row,points_per_colum) = Size(columns, rows) ). + /// Output array of detected corners. + /// Various operation flags that can be zero or a combination of the ChessboardFlag values + /// 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, + Size patternSize, + out Point2f[] corners, + ChessboardFlags flags = ChessboardFlags.AdaptiveThresh | ChessboardFlags.NormalizeImage) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var cornersVec = new VectorOfPoint2f()) + { + var ret = NativeMethods.calib3d_findChessboardCorners_vector( + image.CvPtr, patternSize, cornersVec.CvPtr, (int)flags); + GC.KeepAlive(image); + corners = cornersVec.ToArray(); + return ret != 0; + } + } + #endregion + #region CheckChessboard + + /// + /// Checks whether the image contains chessboard of the specific size or not. + /// + /// + /// + /// + public static bool CheckChessboard(InputArray img, Size size) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + + var ret = NativeMethods.calib3d_checkChessboard(img.CvPtr, size); + GC.KeepAlive(img); + return ret != 0; + } + + #endregion + #region FindChessboardCornersSB + + /// + /// Finds the positions of internal corners of the chessboard using a sector based approach. + /// + /// image Source chessboard view. It must be an 8-bit grayscale or color image. + /// Number of inner corners per a chessboard row and column + /// (patternSize = Size(points_per_row, points_per_column) = Size(columns, rows) ). + /// Output array of detected corners. + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + image.ThrowIfDisposed(); + corners.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_findChessboardCornersSB_OutputArray( + image.CvPtr, patternSize, corners.CvPtr, (int) flags); + + GC.KeepAlive(image); + GC.KeepAlive(corners); + + return ret != 0; + } + + /// + /// Finds the positions of internal corners of the chessboard using a sector based approach. + /// + /// image Source chessboard view. It must be an 8-bit grayscale or color image. + /// Number of inner corners per a chessboard row and column + /// (patternSize = Size(points_per_row, points_per_column) = Size(columns, rows) ). + /// Output array of detected corners. + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var cornersVec = new VectorOfPoint2f()) + { + var ret = NativeMethods.calib3d_findChessboardCornersSB_vector( + image.CvPtr, patternSize, cornersVec.CvPtr, (int) flags); + corners = cornersVec.ToArray(); + GC.KeepAlive(image); + return ret != 0; + } + } + + #endregion + #region Find4QuadCornerSubpix + /// + /// finds subpixel-accurate positions of the chessboard corners + /// + /// + /// + /// + /// + public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size regionSize) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + img.ThrowIfDisposed(); + corners.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_find4QuadCornerSubpix_InputArray( + img.CvPtr, corners.CvPtr, regionSize); + GC.KeepAlive(img); + corners.Fix(); + return ret != 0; + } + /// + /// finds subpixel-accurate positions of the chessboard corners + /// + /// + /// + /// + /// + public static bool Find4QuadCornerSubpix(InputArray img, [In, Out] Point2f[] corners, Size regionSize) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + img.ThrowIfDisposed(); + + using (var cornersVec = new VectorOfPoint2f(corners)) + { + var ret = NativeMethods.calib3d_find4QuadCornerSubpix_vector( + img.CvPtr, cornersVec.CvPtr, regionSize); + GC.KeepAlive(img); + + var newCorners = cornersVec.ToArray(); + for (var i = 0; i < corners.Length; i++) + { + corners[i] = newCorners[i]; + } + + return ret != 0; + } + } + #endregion + #region DrawChessboardCorners + /// + /// Renders the detected chessboard corners. + /// + /// Destination image. It must be an 8-bit color image. + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + image.ThrowIfNotReady(); + corners.ThrowIfDisposed(); + + NativeMethods.calib3d_drawChessboardCorners_InputArray( + image.CvPtr, patternSize, corners.CvPtr, patternWasFound ? 1 : 0); + GC.KeepAlive(corners); + image.Fix(); + } + /// + /// Renders the detected chessboard corners. + /// + /// Destination image. It must be an 8-bit color image. + /// 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, + IEnumerable corners, bool patternWasFound) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (corners == null) + throw new ArgumentNullException(nameof(corners)); + image.ThrowIfNotReady(); + + var cornersArray = EnumerableEx.ToArray(corners); + NativeMethods.calib3d_drawChessboardCorners_array( + image.CvPtr, patternSize, cornersArray, cornersArray.Length, + patternWasFound ? 1 : 0); + image.Fix(); + } + + #endregion + #region DrawFrameAxes + + /// + /// Draw axes of the world/object coordinate system from pose estimation. + /// + /// Input/output image. It must have 1 or 3 channels. The number of channels is not altered. + /// Input 3x3 floating-point matrix of camera intrinsic parameters. + /// Input vector of distortion coefficients + /// \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of + /// 4, 5, 8, 12 or 14 elements.If the vector is empty, the zero distortion coefficients are assumed. + /// Rotation vector (see @ref Rodrigues ) that, together with tvec , brings points from + /// the model coordinate system to the camera coordinate system. + /// Translation vector. + /// Length of the painted axes in the same unit than tvec (usually in meters). + /// Line thickness of the painted axes. + /// 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 == null) + throw new ArgumentNullException(nameof(image)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (distCoeffs == null) + throw new ArgumentNullException(nameof(distCoeffs)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + image.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + distCoeffs.ThrowIfDisposed(); + rvec.ThrowIfDisposed(); + tvec.ThrowIfDisposed(); + + NativeMethods.calib3d_drawFrameAxes( + image.CvPtr, cameraMatrix.CvPtr, distCoeffs.CvPtr, rvec.CvPtr, tvec.CvPtr, length, thickness); + + GC.KeepAlive(image); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(rvec); + GC.KeepAlive(tvec); + } + + #endregion + #region FindCirclesGrid + /// + /// Finds centers in the grid of circles. + /// + /// grid view of input circles; it must be an 8-bit grayscale or color image. + /// number of circles per row and column ( patternSize = Size(points_per_row, points_per_colum) ). + /// output array of detected centers. + /// various operation flags that can be one of the FindCirclesGridFlag values + /// feature detector that finds blobs like dark circles on light background. + /// + public static bool FindCirclesGrid( + InputArray image, + Size patternSize, + OutputArray centers, + FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, + FeatureDetector? blobDetector = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (centers == null) + throw new ArgumentNullException(nameof(centers)); + image.ThrowIfDisposed(); + centers.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_findCirclesGrid_InputArray( + image.CvPtr, patternSize, centers.CvPtr, (int)flags, ToPtr(blobDetector)); + GC.KeepAlive(image); + GC.KeepAlive(centers); + GC.KeepAlive(blobDetector); + centers.Fix(); + return ret != 0; + } + + /// + /// Finds centers in the grid of circles. + /// + /// grid view of input circles; it must be an 8-bit grayscale or color image. + /// number of circles per row and column ( patternSize = Size(points_per_row, points_per_colum) ). + /// output array of detected centers. + /// various operation flags that can be one of the FindCirclesGridFlag values + /// feature detector that finds blobs like dark circles on light background. + /// + public static bool FindCirclesGrid( + InputArray image, + Size patternSize, + out Point2f[] centers, + FindCirclesGridFlags flags = FindCirclesGridFlags.SymmetricGrid, + FeatureDetector? blobDetector = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var centersVec = new VectorOfPoint2f()) + { + var ret = NativeMethods.calib3d_findCirclesGrid_vector( + image.CvPtr, patternSize, centersVec.CvPtr, (int)flags, ToPtr(blobDetector)); + GC.KeepAlive(image); + GC.KeepAlive(blobDetector); + centers = centersVec.ToArray(); + return ret != 0; + } + } + #endregion + #region CalibrateCamera + /// + /// finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern. + /// + /// In the new interface it is a vector of vectors of calibration pattern points in the calibration pattern coordinate space. + /// The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and + /// it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns + /// in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, + /// if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0. + /// In the old interface all the vectors of object points from different views are concatenated together. + /// In the new interface it is a vector of vectors of the projections of calibration pattern points. + /// imagePoints.Count() and objectPoints.Count() and imagePoints[i].Count() must be equal to objectPoints[i].Count() for each i. + /// Size of the image used only to initialize the intrinsic camera matrix. + /// Output 3x3 floating-point camera matrix. + /// If CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be + /// initialized before calling the function. + /// Output 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. + /// Output vector of rotation vectors (see Rodrigues() ) estimated for each pattern view. That is, each k-th rotation vector + /// together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern + /// from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the + /// calibration pattern in the k-th pattern view (k=0.. M -1) + /// Output vector of translation vectors estimated for each pattern view. + /// Different flags that may be zero or a combination of the CalibrationFlag values + /// Termination criteria for the iterative optimization algorithm. + /// + public static double CalibrateCamera( + IEnumerable objectPoints, + IEnumerable imagePoints, + Size imageSize, + InputOutputArray cameraMatrix, + InputOutputArray distCoeffs, + out Mat[] rvecs, + out Mat[] tvecs, + CalibrationFlags flags = CalibrationFlags.None, + TermCriteria? criteria = null) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (distCoeffs == null) + throw new ArgumentNullException(nameof(distCoeffs)); + cameraMatrix.ThrowIfNotReady(); + distCoeffs.ThrowIfNotReady(); + + var criteria0 = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 30, Double.Epsilon)); + + var objectPointsPtrs = EnumerableEx.SelectPtrs(objectPoints); + var imagePointsPtrs = EnumerableEx.SelectPtrs(imagePoints); + + double ret; + using (var rvecsVec = new VectorOfMat()) + using (var tvecsVec = new VectorOfMat()) + { + ret = NativeMethods.calib3d_calibrateCamera_InputArray( + objectPointsPtrs, objectPointsPtrs.Length, + imagePointsPtrs, objectPointsPtrs.Length, + imageSize, cameraMatrix.CvPtr, distCoeffs.CvPtr, + rvecsVec.CvPtr, tvecsVec.CvPtr, (int)flags, criteria0); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(objectPoints); + GC.KeepAlive(imagePoints); + rvecs = rvecsVec.ToArray(); + tvecs = tvecsVec.ToArray(); + } + + cameraMatrix.Fix(); + distCoeffs.Fix(); + return ret; + } + + /// + /// finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern. + /// + /// In the new interface it is a vector of vectors of calibration pattern points in the calibration pattern coordinate space. + /// The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and + /// it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns + /// in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, + /// if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0. + /// In the old interface all the vectors of object points from different views are concatenated together. + /// In the new interface it is a vector of vectors of the projections of calibration pattern points. + /// imagePoints.Count() and objectPoints.Count() and imagePoints[i].Count() must be equal to objectPoints[i].Count() for each i. + /// Size of the image used only to initialize the intrinsic camera matrix. + /// Output 3x3 floating-point camera matrix. + /// If CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be + /// initialized before calling the function. + /// Output 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. + /// Output vector of rotation vectors (see Rodrigues() ) estimated for each pattern view. That is, each k-th rotation vector + /// together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern + /// from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the + /// calibration pattern in the k-th pattern view (k=0.. M -1) + /// Output vector of translation vectors estimated for each pattern view. + /// Different flags that may be zero or a combination of the CalibrationFlag values + /// Termination criteria for the iterative optimization algorithm. + /// + public static double CalibrateCamera( + IEnumerable> objectPoints, + IEnumerable> imagePoints, + Size imageSize, + double[,] cameraMatrix, + double[] distCoeffs, + out Vec3d[] rvecs, + out Vec3d[] tvecs, + CalibrationFlags flags = CalibrationFlags.None, + TermCriteria? criteria = null) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (distCoeffs == null) + throw new ArgumentNullException(nameof(distCoeffs)); + + var criteria0 = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 30, Double.Epsilon)); + + using (var op = new ArrayAddress2(objectPoints)) + using (var ip = new ArrayAddress2(imagePoints)) + using (var rvecsVec = new VectorOfMat()) + using (var tvecsVec = new VectorOfMat()) + { + unsafe + { + fixed (double* cameraMatrixPtr = cameraMatrix) + { + var ret = NativeMethods.calib3d_calibrateCamera_vector( + op.Pointer, op.Dim1Length, op.Dim2Lengths, + ip.Pointer, ip.Dim1Length, ip.Dim2Lengths, + imageSize, cameraMatrixPtr, distCoeffs, distCoeffs.Length, + rvecsVec.CvPtr, tvecsVec.CvPtr, (int)flags, criteria0); + var rvecsM = rvecsVec.ToArray(); + var tvecsM = tvecsVec.ToArray(); + rvecs = EnumerableEx.SelectToArray(rvecsM, m => m.Get(0)); + tvecs = EnumerableEx.SelectToArray(tvecsM, m => m.Get(0)); + return ret; + } + } + } + } + #endregion + #region CalibrationMatrixValues + /// + /// computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size. + /// + /// Input camera matrix that can be estimated by calibrateCamera() or stereoCalibrate() . + /// Input image size in pixels. + /// Physical width of the sensor. + /// Physical height of the sensor. + /// Output field of view in degrees along the horizontal sensor axis. + /// Output field of view in degrees along the vertical sensor axis. + /// Focal length of the lens in mm. + /// Principal point in pixels. + /// fy / fx + public static void CalibrationMatrixValues( + InputArray cameraMatrix, Size imageSize, + double apertureWidth, double apertureHeight, + out double fovx, out double fovy, out double focalLength, + out Point2d principalPoint, out double aspectRatio) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + cameraMatrix.ThrowIfDisposed(); + + NativeMethods.calib3d_calibrationMatrixValues_InputArray(cameraMatrix.CvPtr, + imageSize, apertureWidth, apertureHeight, out fovx, out fovy, out focalLength, + out principalPoint, out aspectRatio); + GC.KeepAlive(cameraMatrix); + } + /// + /// computes several useful camera characteristics from the camera matrix, camera frame resolution and the physical sensor size. + /// + /// Input camera matrix that can be estimated by calibrateCamera() or stereoCalibrate() . + /// Input image size in pixels. + /// Physical width of the sensor. + /// Physical height of the sensor. + /// Output field of view in degrees along the horizontal sensor axis. + /// Output field of view in degrees along the vertical sensor axis. + /// Focal length of the lens in mm. + /// Principal point in pixels. + /// fy / fx + public static void CalibrationMatrixValues( + double[,] cameraMatrix, Size imageSize, + double apertureWidth, double apertureHeight, + out double fovx, out double fovy, out double focalLength, + out Point2d principalPoint, out double aspectRatio) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (cameraMatrix.GetLength(0) != 3 || cameraMatrix.GetLength(1) != 3) + throw new ArgumentException("cameraMatrix must be 3x3"); + + unsafe + { + fixed (double* cameraMatrixPtr = cameraMatrix) + { + NativeMethods.calib3d_calibrationMatrixValues_array( + cameraMatrixPtr, + imageSize, apertureWidth, apertureHeight, out fovx, out fovy, out focalLength, + out principalPoint, out aspectRatio); + } + } + } + #endregion + #region StereoCalibrate + + /// + /// finds intrinsic and extrinsic parameters of a stereo camera + /// + /// Vector of vectors of the calibration pattern points. + /// Vector of vectors of the projections of the calibration pattern points, observed by the first camera. + /// Vector of vectors of the projections of the calibration pattern points, observed by the second camera. + /// Input/output first camera matrix + /// Input/output 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. + /// The output vector length depends on the flags. + /// Input/output second camera matrix. The parameter is similar to cameraMatrix1 . + /// Input/output lens distortion coefficients for the second camera. The parameter is similar to distCoeffs1 . + /// Size of the image used only to initialize intrinsic camera matrix. + /// Output rotation matrix between the 1st and the 2nd camera coordinate systems. + /// Output translation vector between the coordinate systems of the cameras. + /// Output essential matrix. + /// Output fundamental matrix. + /// Termination criteria for the iterative optimization algorithm. + /// Different flags that may be zero or a combination of the CalibrationFlag values + /// + public static double StereoCalibrate(IEnumerable objectPoints, + IEnumerable imagePoints1, + IEnumerable imagePoints2, + 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) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints1 == null) + throw new ArgumentNullException(nameof(imagePoints1)); + if (imagePoints2 == null) + throw new ArgumentNullException(nameof(imagePoints2)); + if (cameraMatrix1 == null) + throw new ArgumentNullException(nameof(cameraMatrix1)); + if (distCoeffs1 == null) + throw new ArgumentNullException(nameof(distCoeffs1)); + if (cameraMatrix2 == null) + throw new ArgumentNullException(nameof(cameraMatrix2)); + if (distCoeffs2 == null) + throw new ArgumentNullException(nameof(distCoeffs2)); + cameraMatrix1.ThrowIfDisposed(); + distCoeffs1.ThrowIfDisposed(); + cameraMatrix2.ThrowIfDisposed(); + distCoeffs2.ThrowIfDisposed(); + cameraMatrix1.ThrowIfNotReady(); + cameraMatrix2.ThrowIfNotReady(); + distCoeffs1.ThrowIfNotReady(); + distCoeffs2.ThrowIfNotReady(); + + var opPtrs = EnumerableEx.SelectPtrs(objectPoints); + var ip1Ptrs = EnumerableEx.SelectPtrs(imagePoints1); + var ip2Ptrs = EnumerableEx.SelectPtrs(imagePoints2); + + var criteria0 = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 30, 1e-6)); + + var result = + NativeMethods.calib3d_stereoCalibrate_InputArray( + opPtrs, opPtrs.Length, + ip1Ptrs, ip1Ptrs.Length, ip2Ptrs, ip2Ptrs.Length, + cameraMatrix1.CvPtr, distCoeffs1.CvPtr, + cameraMatrix2.CvPtr, distCoeffs2.CvPtr, + imageSize, ToPtr(R), ToPtr(T), ToPtr(E), ToPtr(F), + (int)flags, criteria0); + 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(objectPoints); + GC.KeepAlive(imagePoints1); + GC.KeepAlive(imagePoints2); + cameraMatrix1.Fix(); + distCoeffs1.Fix(); + cameraMatrix2.Fix(); + distCoeffs2.Fix(); + R?.Fix(); + T?.Fix(); + E?.Fix(); + F?.Fix(); + + return result; + } + + /// + /// finds intrinsic and extrinsic parameters of a stereo camera + /// + /// Vector of vectors of the calibration pattern points. + /// Vector of vectors of the projections of the calibration pattern points, observed by the first camera. + /// Vector of vectors of the projections of the calibration pattern points, observed by the second camera. + /// Input/output first camera matrix + /// Input/output 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. + /// The output vector length depends on the flags. + /// Input/output second camera matrix. The parameter is similar to cameraMatrix1 . + /// Input/output lens distortion coefficients for the second camera. The parameter is similar to distCoeffs1 . + /// Size of the image used only to initialize intrinsic camera matrix. + /// Output rotation matrix between the 1st and the 2nd camera coordinate systems. + /// Output translation vector between the coordinate systems of the cameras. + /// Output essential matrix. + /// Output fundamental matrix. + /// Termination criteria for the iterative optimization algorithm. + /// Different flags that may be zero or a combination of the CalibrationFlag values + /// + public static double StereoCalibrate(IEnumerable> objectPoints, + IEnumerable> imagePoints1, + IEnumerable> imagePoints2, + double[,] cameraMatrix1, double[] distCoeffs1, + double[,] cameraMatrix2, double[] distCoeffs2, + Size imageSize, OutputArray R, + OutputArray T, OutputArray E, OutputArray F, + CalibrationFlags flags = CalibrationFlags.FixIntrinsic, + TermCriteria? criteria = null) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints1 == null) + throw new ArgumentNullException(nameof(imagePoints1)); + if (imagePoints2 == null) + throw new ArgumentNullException(nameof(imagePoints2)); + if (cameraMatrix1 == null) + throw new ArgumentNullException(nameof(cameraMatrix1)); + if (distCoeffs1 == null) + throw new ArgumentNullException(nameof(distCoeffs1)); + if (cameraMatrix2 == null) + throw new ArgumentNullException(nameof(cameraMatrix2)); + if (distCoeffs2 == null) + throw new ArgumentNullException(nameof(distCoeffs2)); + + var criteria0 = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 30, 1e-6)); + + using (var op = new ArrayAddress2(objectPoints)) + using (var ip1 = new ArrayAddress2(imagePoints1)) + using (var ip2 = new ArrayAddress2(imagePoints2)) + { + unsafe + { + fixed (double* cameraMatrix1Ptr = cameraMatrix1) + fixed (double* cameraMatrix2Ptr = cameraMatrix2) + { + var res = NativeMethods.calib3d_stereoCalibrate_array( + op.Pointer, op.Dim1Length, op.Dim2Lengths, + ip1.Pointer, ip1.Dim1Length, ip1.Dim2Lengths, + ip2.Pointer, ip2.Dim1Length, ip2.Dim2Lengths, + cameraMatrix1Ptr, distCoeffs1, distCoeffs1.Length, + cameraMatrix2Ptr, distCoeffs2, distCoeffs2.Length, + imageSize, ToPtr(R), ToPtr(T), ToPtr(E), ToPtr(F), + (int)flags, criteria0); + GC.KeepAlive(R); + GC.KeepAlive(T); + GC.KeepAlive(E); + GC.KeepAlive(F); + return res; + } + } + } + } + + #endregion + #region StereoRectify + + /// + /// computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters + /// + /// First camera matrix. + /// First camera distortion parameters. + /// Second camera matrix. + /// Second camera distortion parameters. + /// Size of the image used for stereo calibration. + /// Rotation matrix between the coordinate systems of the first and the second cameras. + /// Translation vector between coordinate systems of the cameras. + /// Output 3x3 rectification transform (rotation matrix) for the first camera. + /// Output 3x3 rectification transform (rotation matrix) for the second camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. + /// Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ). + /// Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY. + /// If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. + /// And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. + /// Free scaling parameter. + /// If it is -1 or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1. + /// alpha=0 means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification). + /// alpha=1 means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained + /// 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, + StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, + double alpha = -1, Size? newImageSize = null) + { + var newImageSize0 = newImageSize.GetValueOrDefault(new Size(0, 0)); + StereoRectify(cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, + imageSize, R, T, R1, R2, P1, P2, Q, flags, alpha, newImageSize0, + out _, out _); + } + + /// + /// computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters + /// + /// First camera matrix. + /// First camera distortion parameters. + /// Second camera matrix. + /// Second camera distortion parameters. + /// Size of the image used for stereo calibration. + /// Rotation matrix between the coordinate systems of the first and the second cameras. + /// Translation vector between coordinate systems of the cameras. + /// Output 3x3 rectification transform (rotation matrix) for the first camera. + /// Output 3x3 rectification transform (rotation matrix) for the second camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. + /// Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ). + /// Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY. + /// If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. + /// And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. + /// Free scaling parameter. + /// If it is -1 or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1. + /// alpha=0 means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification). + /// alpha=1 means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained + /// 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. + /// 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. + /// 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, + double alpha, Size newImageSize, + out Rect validPixROI1, out Rect validPixROI2) + { + if (cameraMatrix1 == null) + throw new ArgumentNullException(nameof(cameraMatrix1)); + if (distCoeffs1 == null) + throw new ArgumentNullException(nameof(distCoeffs1)); + if (cameraMatrix2 == null) + throw new ArgumentNullException(nameof(cameraMatrix2)); + if (distCoeffs2 == null) + throw new ArgumentNullException(nameof(distCoeffs2)); + if (R == null) + throw new ArgumentNullException(nameof(R)); + if (T == null) + throw new ArgumentNullException(nameof(T)); + if (R1 == null) + throw new ArgumentNullException(nameof(R1)); + if (R2 == null) + throw new ArgumentNullException(nameof(R2)); + if (P1 == null) + throw new ArgumentNullException(nameof(P1)); + if (P2 == null) + throw new ArgumentNullException(nameof(P2)); + if (Q == 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.calib3d_stereoRectify_InputArray( + cameraMatrix1.CvPtr, distCoeffs1.CvPtr, + cameraMatrix2.CvPtr, distCoeffs2.CvPtr, + imageSize, R.CvPtr, T.CvPtr, + R1.CvPtr, R2.CvPtr, P1.CvPtr, P2.CvPtr, Q.CvPtr, + (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); + + R1.Fix(); + R2.Fix(); + P1.Fix(); + P2.Fix(); + Q.Fix(); + } + + /// + /// computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters + /// + /// First camera matrix. + /// First camera distortion parameters. + /// Second camera matrix. + /// Second camera distortion parameters. + /// Size of the image used for stereo calibration. + /// Rotation matrix between the coordinate systems of the first and the second cameras. + /// Translation vector between coordinate systems of the cameras. + /// Output 3x3 rectification transform (rotation matrix) for the first camera. + /// Output 3x3 rectification transform (rotation matrix) for the second camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. + /// Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ). + /// Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY. + /// If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. + /// And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. + /// Free scaling parameter. + /// If it is -1 or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1. + /// alpha=0 means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification). + /// alpha=1 means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained + /// 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(double[,] cameraMatrix1, double[] distCoeffs1, + double[,] cameraMatrix2, double[] distCoeffs2, + Size imageSize, double[,] R, double[] T, + out double[,] R1, out double[,] R2, + out double[,] P1, out double[,] P2, + out double[,] Q, + StereoRectificationFlags flags = StereoRectificationFlags.ZeroDisparity, + double alpha = -1, Size? newImageSize = null) + { + var newImageSize0 = newImageSize.GetValueOrDefault(new Size(0, 0)); + StereoRectify( + cameraMatrix1, distCoeffs1, + cameraMatrix2, distCoeffs2, + imageSize, R, T, + out R1, out R2, out P1, out P2, out Q, + flags, alpha, newImageSize0, out _, out _); + } + + /// + /// computes the rectification transformation for a stereo camera from its intrinsic and extrinsic parameters + /// + /// First camera matrix. + /// First camera distortion parameters. + /// Second camera matrix. + /// Second camera distortion parameters. + /// Size of the image used for stereo calibration. + /// Rotation matrix between the coordinate systems of the first and the second cameras. + /// Translation vector between coordinate systems of the cameras. + /// Output 3x3 rectification transform (rotation matrix) for the first camera. + /// Output 3x3 rectification transform (rotation matrix) for the second camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. + /// Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D() ). + /// Operation flags that may be zero or CV_CALIB_ZERO_DISPARITY. + /// If the flag is set, the function makes the principal points of each camera have the same pixel coordinates in the rectified views. + /// And if the flag is not set, the function may still shift the images in the horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the useful image area. + /// Free scaling parameter. + /// If it is -1 or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1. + /// alpha=0 means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification). + /// alpha=1 means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained + /// 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. + /// 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. + /// 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(double[,] cameraMatrix1, double[] distCoeffs1, + double[,] cameraMatrix2, double[] distCoeffs2, + Size imageSize, double[,] R, double[] T, + out double[,] R1, out double[,] R2, + out double[,] P1, out double[,] P2, + out double[,] Q, StereoRectificationFlags flags, + double alpha, Size newImageSize, + out Rect validPixROI1, out Rect validPixROI2) + { + if (cameraMatrix1 == null) + throw new ArgumentNullException(nameof(cameraMatrix1)); + if (distCoeffs1 == null) + throw new ArgumentNullException(nameof(distCoeffs1)); + if (cameraMatrix2 == null) + throw new ArgumentNullException(nameof(cameraMatrix2)); + if (distCoeffs2 == null) + throw new ArgumentNullException(nameof(distCoeffs2)); + if (R == null) + throw new ArgumentNullException(nameof(R)); + if (T == null) + throw new ArgumentNullException(nameof(T)); + + R1 = new double[3, 3]; + R2 = new double[3, 3]; + P1 = new double[3, 4]; + P2 = new double[3, 4]; + Q = new double[4, 4]; + + unsafe + { + fixed (double* cameraMatrix1Ptr = cameraMatrix1) + fixed (double* cameraMatrix2Ptr = cameraMatrix2) + fixed (double* RPtr = R) + fixed (double* R1Ptr = R1) + fixed (double* R2Ptr = R2) + fixed (double* P1Ptr = P1) + fixed (double* P2Ptr = P2) + fixed (double* QPtr = Q) + { + NativeMethods.calib3d_stereoRectify_array( + cameraMatrix1Ptr, distCoeffs1, distCoeffs1.Length, + cameraMatrix2Ptr, distCoeffs2, distCoeffs2.Length, + imageSize, RPtr, T, + R1Ptr, R2Ptr, P1Ptr, P2Ptr, QPtr, + (int)flags, alpha, newImageSize, out validPixROI1, out validPixROI2); + } + } + } + + #endregion + #region StereoRectifyUncalibrated + + /// + /// computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed) + /// + /// Array of feature points in the first image. + /// The corresponding points in the second image. + /// The same formats as in findFundamentalMat() are supported. + /// Input fundamental matrix. It can be computed from the same set + /// of point pairs using findFundamentalMat() . + /// Size of the image. + /// Output rectification homography matrix for the first image. + /// Output rectification homography matrix for the second image. + /// Optional threshold used to filter out the outliers. + /// If the parameter is greater than zero, all the point pairs that do not comply + /// 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, + double threshold = 5) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (H1 == null) + throw new ArgumentNullException(nameof(H1)); + if (H2 == null) + throw new ArgumentNullException(nameof(H2)); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + F.ThrowIfDisposed(); + H1.ThrowIfNotReady(); + H2.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_stereoRectifyUncalibrated_InputArray( + points1.CvPtr, points2.CvPtr, F.CvPtr, imgSize, H1.CvPtr, H2.CvPtr, threshold); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + GC.KeepAlive(F); + GC.KeepAlive(H1); + GC.KeepAlive(H2); + H1.Fix(); + H2.Fix(); + return ret != 0; + } + + /// + /// computes the rectification transformation for an uncalibrated stereo camera (zero distortion is assumed) + /// + /// Array of feature points in the first image. + /// The corresponding points in the second image. + /// The same formats as in findFundamentalMat() are supported. + /// Input fundamental matrix. It can be computed from the same set + /// of point pairs using findFundamentalMat() . + /// Size of the image. + /// Output rectification homography matrix for the first image. + /// Output rectification homography matrix for the second image. + /// Optional threshold used to filter out the outliers. + /// If the parameter is greater than zero, all the point pairs that do not comply + /// 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(IEnumerable points1, + IEnumerable points2, + double[,] F, Size imgSize, + out double[,] H1, out double[,] H2, + double threshold = 5 + ) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (F.GetLength(0) != 3 || F.GetLength(1) != 3) + throw new ArgumentException("F != double[3,3]"); + + var points1Array = EnumerableEx.ToArray(points1); + var points2Array = EnumerableEx.ToArray(points2); + + H1 = new double[3, 3]; + H2 = new double[3, 3]; + + unsafe + { + fixed (double* FPtr = F) + fixed (double* H1Ptr = H1) + fixed (double* H2Ptr = H1) + { + var ret = NativeMethods.calib3d_stereoRectifyUncalibrated_array( + points1Array, points1Array.Length, + points2Array, points2Array.Length, + FPtr, imgSize, H1Ptr, H2Ptr, threshold); + return ret != 0; + } + } + } + + #endregion + #region Rectify3Collinear + /// + /// computes the rectification transformations for 3-head camera, where all the heads are on the same line. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static float Rectify3Collinear(InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + InputArray cameraMatrix3, InputArray distCoeffs3, + IEnumerable imgpt1, IEnumerable 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, + out Rect roi1, out Rect roi2, StereoRectificationFlags flags) + { + if (cameraMatrix1 == null) + throw new ArgumentNullException(nameof(cameraMatrix1)); + if (distCoeffs1 == null) + throw new ArgumentNullException(nameof(distCoeffs1)); + if (cameraMatrix2 == null) + throw new ArgumentNullException(nameof(cameraMatrix2)); + if (distCoeffs2 == null) + throw new ArgumentNullException(nameof(distCoeffs2)); + if (cameraMatrix3 == null) + throw new ArgumentNullException(nameof(cameraMatrix3)); + if (distCoeffs3 == null) + throw new ArgumentNullException(nameof(distCoeffs3)); + if (imgpt1 == null) + throw new ArgumentNullException(nameof(imgpt1)); + if (imgpt3 == null) + throw new ArgumentNullException(nameof(imgpt3)); + if (R12 == null) + throw new ArgumentNullException(nameof(R12)); + if (T12 == null) + throw new ArgumentNullException(nameof(T12)); + if (R13 == null) + throw new ArgumentNullException(nameof(R13)); + if (T13 == null) + throw new ArgumentNullException(nameof(T13)); + if (R1 == null) + throw new ArgumentNullException(nameof(R1)); + if (R2 == null) + throw new ArgumentNullException(nameof(R2)); + if (R3 == null) + throw new ArgumentNullException(nameof(R3)); + if (P1 == null) + throw new ArgumentNullException(nameof(P1)); + if (P2 == null) + throw new ArgumentNullException(nameof(P2)); + if (P3 == null) + throw new ArgumentNullException(nameof(P3)); + if (Q == 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 = EnumerableEx.SelectPtrs(imgpt1); + var imgpt3Ptrs = EnumerableEx.SelectPtrs(imgpt3); + var ret = NativeMethods.calib3d_rectify3Collinear_InputArray( + cameraMatrix1.CvPtr, distCoeffs1.CvPtr, + cameraMatrix2.CvPtr, distCoeffs2.CvPtr, + cameraMatrix3.CvPtr, distCoeffs3.CvPtr, + imgpt1Ptrs, imgpt1Ptrs.Length, imgpt3Ptrs, imgpt3Ptrs.Length, + imageSize, R12.CvPtr, T12.CvPtr, R13.CvPtr, T13.CvPtr, + R1.CvPtr, R2.CvPtr, R3.CvPtr, P1.CvPtr, P2.CvPtr, P3.CvPtr, + Q.CvPtr, alpha, newImgSize, out roi1, out roi2, (int)flags); + GC.KeepAlive(cameraMatrix1); + GC.KeepAlive(distCoeffs1); + GC.KeepAlive(cameraMatrix2); + GC.KeepAlive(distCoeffs2); + GC.KeepAlive(cameraMatrix3); + GC.KeepAlive(distCoeffs3); + 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(); + return ret; + } + #endregion + #region GetOptimalNewCameraMatrix + + /// + /// Returns the new camera matrix based on the free scaling parameter. + /// + /// 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 array is null, the zero distortion coefficients are assumed. + /// Original image size. + /// Free scaling parameter between 0 (when all the pixels in the undistorted image are valid) + /// and 1 (when all the source image pixels are retained in the undistorted image). + /// Image size after rectification. By default,it is set to imageSize . + /// Optional output rectangle that outlines all-good-pixels region in the undistorted image. See roi1, roi2 description in stereoRectify() . + /// Optional flag that indicates whether in the new camera matrix the principal point + /// should be at the image center or not. By default, the principal point is chosen to best fit a + /// subset of the source image (determined by alpha) to the corrected image. + /// optimal new camera matrix + public static Mat GetOptimalNewCameraMatrix(InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, double alpha, Size newImgSize, + out Rect validPixROI, bool centerPrincipalPoint = false) + { + if (cameraMatrix == null) + throw new ArgumentNullException(); + cameraMatrix.ThrowIfDisposed(); + + var mat = NativeMethods.calib3d_getOptimalNewCameraMatrix_InputArray( + cameraMatrix.CvPtr, ToPtr(distCoeffs), imageSize, alpha, newImgSize, + out validPixROI, centerPrincipalPoint ? 1 : 0); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + return new Mat(mat); + } + /// + /// Returns the new camera matrix based on the free scaling parameter. + /// + /// 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 array is null, the zero distortion coefficients are assumed. + /// Original image size. + /// Free scaling parameter between 0 (when all the pixels in the undistorted image are valid) + /// and 1 (when all the source image pixels are retained in the undistorted image). + /// Image size after rectification. By default,it is set to imageSize . + /// Optional output rectangle that outlines all-good-pixels region in the undistorted image. See roi1, roi2 description in stereoRectify() . + /// Optional flag that indicates whether in the new camera matrix the principal point + /// should be at the image center or not. By default, the principal point is chosen to best fit a + /// subset of the source image (determined by alpha) to the corrected image. + /// optimal new camera matrix + public static double[,]? GetOptimalNewCameraMatrix(double[,] cameraMatrix, double[] distCoeffs, + Size imageSize, double alpha, Size newImgSize, + out Rect validPixROI, bool centerPrincipalPoint = false) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + + IntPtr matPtr; + unsafe + { + fixed (double* cameraMatrixPtr = cameraMatrix) + { + matPtr = NativeMethods.calib3d_getOptimalNewCameraMatrix_array( + cameraMatrixPtr, distCoeffs, distCoeffs.Length, + imageSize, alpha, newImgSize, + out validPixROI, centerPrincipalPoint ? 1 : 0); + if (matPtr == IntPtr.Zero) + return null; + } + } + + using var mat = new Mat(matPtr); + return mat.ToRectangularArray(); + } + #endregion + #region ConvertPointsHomogeneous + /// + /// converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N+1-dimensional points. + public static void ConvertPointsToHomogeneous(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.calib3d_convertPointsToHomogeneous_InputArray(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + /// + /// converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N+1-dimensional points. + public static Vec3f[] ConvertPointsToHomogeneous(IEnumerable src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + + var srcA = EnumerableEx.ToArray(src); + var dstA = new Vec3f[srcA.Length]; + NativeMethods.calib3d_convertPointsToHomogeneous_array1(srcA, dstA, srcA.Length); + return dstA; + } + /// + /// converts point coordinates from normal pixel coordinates to homogeneous coordinates ((x,y)->(x,y,1)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N+1-dimensional points. + public static Vec4f[] ConvertPointsToHomogeneous(IEnumerable src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + + var srcA = EnumerableEx.ToArray(src); + var dstA = new Vec4f[srcA.Length]; + NativeMethods.calib3d_convertPointsToHomogeneous_array2(srcA, dstA, srcA.Length); + return dstA; + } + + /// + /// converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N-1-dimensional points. + public static void ConvertPointsFromHomogeneous(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.calib3d_convertPointsFromHomogeneous_InputArray(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + dst.Fix(); + } + /// + /// converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N-1-dimensional points. + public static Vec2f[] ConvertPointsFromHomogeneous(IEnumerable src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + + var srcA = EnumerableEx.ToArray(src); + var dstA = new Vec2f[srcA.Length]; + NativeMethods.calib3d_convertPointsFromHomogeneous_array1(srcA, dstA, srcA.Length); + return dstA; + } + /// + /// converts point coordinates from homogeneous to normal pixel coordinates ((x,y,z)->(x/z, y/z)) + /// + /// Input vector of N-dimensional points. + /// Output vector of N-1-dimensional points. + public static Vec3f[] ConvertPointsFromHomogeneous(IEnumerable src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + + var srcA = EnumerableEx.ToArray(src); + var dstA = new Vec3f[srcA.Length]; + NativeMethods.calib3d_convertPointsFromHomogeneous_array2(srcA, dstA, srcA.Length); + return dstA; + } + + /// + /// Converts points to/from homogeneous coordinates. + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.calib3d_convertPointsHomogeneous(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + dst.Fix(); + } + #endregion + #region FindFundamentalMat + /// + /// Calculates a fundamental matrix from the corresponding points in two images. + /// + /// Array of N points from the first image. + /// The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1 . + /// Method for computing a fundamental matrix. + /// Parameter used for RANSAC. + /// It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is + /// considered an outlier and is not used for computing the final fundamental matrix. It can be set to + /// something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. + /// Parameter used for the RANSAC or LMedS methods only. + /// It specifies a desirable level of confidence (probability) that the estimated matrix is correct. + /// 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. For other methods, it is set to all 1’s. + /// fundamental matrix + public static Mat FindFundamentalMat( + InputArray points1, InputArray points2, + FundamentalMatMethod method = FundamentalMatMethod.Ransac, + double param1 = 3.0, double param2 = 0.99, + OutputArray? mask = null) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + + var mat = NativeMethods.calib3d_findFundamentalMat_InputArray( + points1.CvPtr, points2.CvPtr, (int)method, + param1, param2, ToPtr(mask)); + mask?.Fix(); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + return new Mat(mat); + } + + /// + /// Calculates a fundamental matrix from the corresponding points in two images. + /// + /// Array of N points from the first image. + /// The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1 . + /// Method for computing a fundamental matrix. + /// Parameter used for RANSAC. + /// It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is + /// considered an outlier and is not used for computing the final fundamental matrix. It can be set to + /// something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. + /// Parameter used for the RANSAC or LMedS methods only. + /// It specifies a desirable level of confidence (probability) that the estimated matrix is correct. + /// 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. For other methods, it is set to all 1’s. + /// fundamental matrix + public static Mat FindFundamentalMat( + IEnumerable points1, IEnumerable points2, + FundamentalMatMethod method = FundamentalMatMethod.Ransac, + double param1 = 3.0, double param2 = 0.99, + OutputArray? mask = null) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + + var points1Array = EnumerableEx.ToArray(points1); + var points2Array = EnumerableEx.ToArray(points2); + + var mat = NativeMethods.calib3d_findFundamentalMat_array( + points1Array, points1Array.Length, + points2Array, points2Array.Length, (int)method, + param1, param2, ToPtr(mask)); + mask?.Fix(); + return new Mat(mat); + } + #endregion + #region ComputeCorrespondEpilines + /// + /// For points in an image of a stereo pair, computes the corresponding epilines in the other image. + /// + /// Input points. N \times 1 or 1 x N matrix of type CV_32FC2 or CV_64FC2. + /// Index of the image (1 or 2) that contains the 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(InputArray points, + int whichImage, + InputArray F, + OutputArray lines) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (lines == null) + throw new ArgumentNullException(nameof(lines)); + points.ThrowIfDisposed(); + F.ThrowIfDisposed(); + lines.ThrowIfNotReady(); + + NativeMethods.calib3d_computeCorrespondEpilines_InputArray( + points.CvPtr, whichImage, F.CvPtr, lines.CvPtr); + + GC.KeepAlive(F); + GC.KeepAlive(points); + lines.Fix(); + } + + /// + /// For points in an image of a stereo pair, computes the corresponding epilines in the other image. + /// + /// Input points. N \times 1 or 1 x N matrix of type CV_32FC2 or CV_64FC2. + /// Index of the image (1 or 2) that contains the 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 Point3f[] ComputeCorrespondEpilines(IEnumerable points, + int whichImage, double[,] F) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (F.GetLength(0) != 3 && F.GetLength(1) != 3) + throw new ArgumentException("F != double[3,3]"); + + var pointsArray = EnumerableEx.ToArray(points); + var lines = new Point3f[pointsArray.Length]; + + unsafe + { + fixed (double* FPtr = F) + { + NativeMethods.calib3d_computeCorrespondEpilines_array2d( + pointsArray, pointsArray.Length, + whichImage, FPtr, lines); + } + } + + return lines; + } + /// + /// For points in an image of a stereo pair, computes the corresponding epilines in the other image. + /// + /// Input points. N \times 1 or 1 x N matrix of type CV_32FC2 or CV_64FC2. + /// Index of the image (1 or 2) that contains the 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 Point3f[] ComputeCorrespondEpilines(IEnumerable points, + int whichImage, double[,] F) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (F.GetLength(0) != 3 && F.GetLength(1) != 3) + throw new ArgumentException("F != double[3,3]"); + + var pointsArray = EnumerableEx.ToArray(points); + var lines = new Point3f[pointsArray.Length]; + + unsafe + { + fixed (double* FPtr = F) + { + NativeMethods.calib3d_computeCorrespondEpilines_array3d( + pointsArray, pointsArray.Length, + whichImage, FPtr, lines); + } + } + + return lines; + } + #endregion + #region TriangulatePoints + /// + /// Reconstructs points by triangulation. + /// + /// 3x4 projection matrix of the first camera. + /// 3x4 projection matrix of the second camera. + /// 2xN array of feature points in the first image. In case of c++ version + /// it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. + /// 2xN array of corresponding points in the second image. In case of c++ version + /// 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) + { + if (projMatr1 == null) + throw new ArgumentNullException(nameof(projMatr1)); + if (projMatr2 == null) + throw new ArgumentNullException(nameof(projMatr2)); + if (projPoints1 == null) + throw new ArgumentNullException(nameof(projPoints1)); + if (projPoints2 == null) + throw new ArgumentNullException(nameof(projPoints2)); + if (points4D == null) + throw new ArgumentNullException(nameof(points4D)); + projMatr1.ThrowIfDisposed(); + projMatr2.ThrowIfDisposed(); + projPoints1.ThrowIfDisposed(); + projPoints2.ThrowIfDisposed(); + points4D.ThrowIfNotReady(); + + NativeMethods.calib3d_triangulatePoints_InputArray( + projMatr1.CvPtr, projMatr2.CvPtr, + projPoints1.CvPtr, projPoints2.CvPtr, points4D.CvPtr); + + GC.KeepAlive(projMatr1); + GC.KeepAlive(projMatr2); + GC.KeepAlive(projPoints1); + GC.KeepAlive(projPoints2); + points4D.Fix(); + } + /// + /// Reconstructs points by triangulation. + /// + /// 3x4 projection matrix of the first camera. + /// 3x4 projection matrix of the second camera. + /// 2xN array of feature points in the first image. In case of c++ version + /// it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. + /// 2xN array of corresponding points in the second image. In case of c++ version + /// 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 Vec4d[] TriangulatePoints( + double[,] projMatr1, double[,] projMatr2, + IEnumerable projPoints1, IEnumerable projPoints2) + { + if (projMatr1 == null) + throw new ArgumentNullException(nameof(projMatr1)); + if (projMatr2 == null) + throw new ArgumentNullException(nameof(projMatr2)); + if (projPoints1 == null) + throw new ArgumentNullException(nameof(projPoints1)); + if (projPoints2 == null) + throw new ArgumentNullException(nameof(projPoints2)); + if (projMatr1.GetLength(0) != 3 && projMatr1.GetLength(1) != 4) + throw new ArgumentException($"{nameof(projMatr1)} != double[3,4]"); + if (projMatr2.GetLength(0) != 3 && projMatr2.GetLength(1) != 4) + throw new ArgumentException($"{nameof(projMatr2)} != double[3,4]"); + + var projPoints1Array = EnumerableEx.ToArray(projPoints1); + var projPoints2Array = EnumerableEx.ToArray(projPoints2); + var points4D = new Vec4d[projPoints1Array.Length]; + + unsafe + { + fixed (double* projMatr1Ptr = projMatr1) + fixed (double* projMatr2Ptr = projMatr2) + { + NativeMethods.calib3d_triangulatePoints_array( + projMatr1Ptr, projMatr2Ptr, + projPoints1Array, projPoints1Array.Length, + projPoints2Array, projPoints2Array.Length, + points4D); + } + } + + return points4D; + } + #endregion + #region CorrectMatches + /// + /// Refines coordinates of corresponding points. + /// + /// 3x3 fundamental matrix. + /// 1xN array containing the first set of points. + /// 1xN array containing the second set of points. + /// The optimized points1. + /// The optimized points2. + public static void CorrectMatches( + InputArray F, InputArray points1, InputArray points2, + OutputArray newPoints1, OutputArray newPoints2) + { + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (newPoints1 == null) + throw new ArgumentNullException(nameof(newPoints1)); + if (newPoints2 == null) + throw new ArgumentNullException(nameof(newPoints2)); + F.ThrowIfDisposed(); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + newPoints1.ThrowIfNotReady(); + newPoints2.ThrowIfNotReady(); + + NativeMethods.calib3d_correctMatches_InputArray( + F.CvPtr, points1.CvPtr, points2.CvPtr, + newPoints1.CvPtr, newPoints2.CvPtr); + + GC.KeepAlive(F); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + newPoints1.Fix(); + newPoints2.Fix(); + } + + /// + /// Refines coordinates of corresponding points. + /// + /// 3x3 fundamental matrix. + /// 1xN array containing the first set of points. + /// 1xN array containing the second set of points. + /// The optimized points1. + /// The optimized points2. + public static void CorrectMatches( + double[,] F, IEnumerable points1, IEnumerable points2, + out Point2d[] newPoints1, out Point2d[] newPoints2) + { + if (F == null) + throw new ArgumentNullException(nameof(F)); + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + + var points1Array = EnumerableEx.ToArray(points1); + var points2Array = EnumerableEx.ToArray(points2); + newPoints1 = new Point2d[points1Array.Length]; + newPoints2 = new Point2d[points2Array.Length]; + + unsafe + { + fixed (double* FPtr = F) + { + NativeMethods.calib3d_correctMatches_array( + FPtr, points1Array, points1Array.Length, + points2Array, points2Array.Length, + newPoints1, newPoints2); + } + } + } + #endregion + #region RecoverPose + /// + /// Recover relative camera rotation and translation from an estimated essential matrix and the corresponding points in two images, using cheirality check. + /// Returns the number of inliers which pass the check. + /// + /// The input essential matrix. + /// Array of N 2D points from the first image. The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1. + /// Camera matrix K=⎡⎣⎢fx000fy0cxcy1⎤⎦⎥ . Note that this function assumes that points1 and points2 are feature points from cameras with the same camera matrix. + /// Recovered relative rotation. + /// Recovered relative translation. + /// Input/output mask for inliers in points1 and points2. : + /// If it is not empty, then it marks inliers in points1 and points2 for then given essential matrix E. + /// Only these inliers will be used to recover pose. In the output mask only inliers which pass the cheirality check. + /// 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) + { + if (E == null) + throw new ArgumentNullException(nameof(E)); + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (R == null) + throw new ArgumentNullException(nameof(R)); + if (t == null) + throw new ArgumentNullException(nameof(t)); + E.ThrowIfDisposed(); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + R.ThrowIfNotReady(); + t.ThrowIfNotReady(); + + var result = NativeMethods.calib3d_recoverPose_InputArray1( + E.CvPtr, points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, + R.CvPtr, t.CvPtr, ToPtr(mask)); + + GC.KeepAlive(E); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + GC.KeepAlive(cameraMatrix); + R.Fix(); + t.Fix(); + mask?.Fix(); + + return result; + } + + /// + /// Recover relative camera rotation and translation from an estimated essential matrix and the corresponding points in two images, using cheirality check. + /// Returns the number of inliers which pass the check. + /// + /// The input essential matrix. + /// Array of N 2D points from the first image. The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1. + /// Recovered relative rotation. + /// Recovered relative translation. + /// Focal length of the camera. Note that this function assumes that points1 and points2 are feature points from cameras with same focal length and principal point. + /// principal point of the camera. + /// Input/output mask for inliers in points1 and points2. : + /// If it is not empty, then it marks inliers in points1 and points2 for then given essential matrix E. + /// Only these inliers will be used to recover pose. In the output mask only inliers which pass the cheirality check. + /// 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) + { + if (E == null) + throw new ArgumentNullException(nameof(E)); + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (R == null) + throw new ArgumentNullException(nameof(R)); + if (t == null) + throw new ArgumentNullException(nameof(t)); + E.ThrowIfDisposed(); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + R.ThrowIfNotReady(); + t.ThrowIfNotReady(); + + var result = NativeMethods.calib3d_recoverPose_InputArray2( + E.CvPtr, points1.CvPtr, points2.CvPtr, + R.CvPtr, t.CvPtr, focal, new StructurePointer(pp), ToPtr(mask)); + + GC.KeepAlive(E); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + GC.KeepAlive(pp); + R.Fix(); + t.Fix(); + mask?.Fix(); + + return result; + } + + /// + /// Recover relative camera rotation and translation from an estimated essential matrix and the corresponding points in two images, using cheirality check. + /// Returns the number of inliers which pass the check. + /// + /// The input essential matrix. + /// Array of N 2D points from the first image. The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1. + /// Camera matrix K=⎡⎣⎢fx000fy0cxcy1⎤⎦⎥ . Note that this function assumes that points1 and points2 are feature points from cameras with the same camera matrix. + /// Recovered relative rotation. + /// Recovered relative translation. + /// threshold distance which is used to filter out far away points (i.e. infinite points). + /// Input/output mask for inliers in points1 and points2. : + /// If it is not empty, then it marks inliers in points1 and points2 for then given essential matrix E. + /// Only these inliers will be used to recover pose. In the output mask only inliers which pass the cheirality check. + /// 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. + /// 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) + { + if (E == null) + throw new ArgumentNullException(nameof(E)); + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (R == null) + throw new ArgumentNullException(nameof(R)); + if (t == null) + throw new ArgumentNullException(nameof(t)); + E.ThrowIfDisposed(); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + R.ThrowIfNotReady(); + t.ThrowIfNotReady(); + + var result = NativeMethods.calib3d_recoverPose_InputArray3( + E.CvPtr, points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, + R.CvPtr, t.CvPtr, distanceTresh, ToPtr(mask), ToPtr(triangulatedPoints)); + + GC.KeepAlive(E); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + GC.KeepAlive(cameraMatrix); + R.Fix(); + t.Fix(); + mask?.Fix(); + triangulatedPoints?.Fix(); + + return result; + } + #endregion + #region FindEssentialMat + /// + /// Calculates an essential matrix from the corresponding points in two images. + /// + /// Array of N (N >= 5) 2D points from the first image. + /// The point coordinates should be floating-point (single or double precision). + /// Array of the second image points of the same size and format as points1 . + /// Camera matrix K=⎡⎣⎢fx000fy0cxcy1⎤⎦⎥ . Note that this function assumes that points1 and points2 are feature points from cameras with the same camera matrix. + /// Method for computing an essential matrix. + /// RANSAC for the RANSAC algorithm. + /// LMEDS for the LMedS algorithm. + /// Parameter used for the RANSAC or LMedS methods only. + /// It specifies a desirable level of confidence (probability) that the estimated matrix is correct. + /// Parameter used for RANSAC. + /// It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. + /// It can be set to something like 1-3, depending on the accuracy of the point localization, image resolution, and the image noise. + /// 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, + EssentialMatMethod method = EssentialMatMethod.Ransac, + double prob = 0.999, double threshold = 1.0, + OutputArray? mask = null) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + cameraMatrix.ThrowIfDisposed(); + + var mat = NativeMethods.calib3d_findEssentialMat_InputArray1( + points1.CvPtr, points2.CvPtr, cameraMatrix.CvPtr, + (int)method, prob, threshold, ToPtr(mask)); + mask?.Fix(); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + GC.KeepAlive(cameraMatrix); + return new Mat(mat); + } + + /// + /// Calculates an essential matrix from the corresponding points in two images. + /// + /// Array of N (N >= 5) 2D points from the first image. + /// The point coordinates should be floating-point (single or double precision). + /// Array of the second image por LMedS methods only. + /// It specifies a desirable level of confidence (probability) that the estimated matrix is correct. + /// Parameter used for RANSAC. + /// It is the maximum distance from a point to an epipolar line in pixels, beyond which the point is considered an outlier and is not used for computing the final fundamental matrix. + /// It can be set to something like 1-3, depending on ints of the same size and format as points1 . + /// Focal length of the camera. Note that this function assumes that points1 and points2 are feature points from cameras with same focal length and principal point. + /// principal point of the camera. + /// Method for computing an essential matrix. + /// RANSAC for the RANSAC algorithm. + /// LMEDS for the LMedS algorithm. + /// Parameter used for the RANSAC othe accuracy of the point localization, image resolution, and the image noise. + /// 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, + EssentialMatMethod method = EssentialMatMethod.Ransac, + double prob = 0.999, double threshold = 1.0, + OutputArray? mask = null) + { + if (points1 == null) + throw new ArgumentNullException(nameof(points1)); + if (points2 == null) + throw new ArgumentNullException(nameof(points2)); + points1.ThrowIfDisposed(); + points2.ThrowIfDisposed(); + + var mat = NativeMethods.calib3d_findEssentialMat_InputArray2( + points1.CvPtr, points2.CvPtr, focal, new StructurePointer(pp), + (int)method, prob, threshold, ToPtr(mask)); + mask?.Fix(); + GC.KeepAlive(points1); + GC.KeepAlive(points2); + return new Mat(mat); + } + #endregion + #region FilterSpeckles + + /// + /// filters off speckles (small regions of incorrectly computed disparity) + /// + /// The input 16-bit signed disparity image + /// The disparity value used to paint-off the speckles + /// The maximum speckle size to consider it a speckle. Larger blobs are not affected by the algorithm + /// Maximum difference between neighbor disparity pixels to put them into the same blob. + /// 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) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfNotReady(); + + NativeMethods.calib3d_filterSpeckles(img.CvPtr, newVal, maxSpeckleSize, maxDiff, ToPtr(buf)); + GC.KeepAlive(img); + GC.KeepAlive(buf); + img.Fix(); + } + + #endregion + #region GetValidDisparityROI + + /// + /// computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify()) + /// + /// + /// + /// + /// + /// + /// + public static Rect GetValidDisparityROI(Rect roi1, Rect roi2, + int minDisparity, int numberOfDisparities, int SADWindowSize) + { + return NativeMethods.calib3d_getValidDisparityROI( + roi1, roi2, minDisparity, numberOfDisparities, SADWindowSize); + } + + #endregion + #region ValidateDisparity + + /// + /// validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm + /// + /// + /// + /// + /// + /// + public static void ValidateDisparity(InputOutputArray disparity, InputArray cost, + int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1) + { + if (disparity == null) + throw new ArgumentNullException(nameof(disparity)); + if (cost == null) + throw new ArgumentNullException(nameof(cost)); + disparity.ThrowIfNotReady(); + cost.ThrowIfDisposed(); + + NativeMethods.calib3d_validateDisparity( + disparity.CvPtr, cost.CvPtr, minDisparity, numberOfDisparities, disp12MaxDisp); + disparity.Fix(); + GC.KeepAlive(disparity); + GC.KeepAlive(cost); + } + + #endregion + #region ReprojectImageTo3D + + /// + /// reprojects disparity image to 3D: (x,y,d)->(X,Y,Z) using the matrix Q returned by cv::stereoRectify + /// + /// Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit floating-point disparity image. + /// Output 3-channel floating-point image of the same size as disparity. + /// Each element of _3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. + /// 4 x 4 perspective transformation matrix that can be obtained with stereoRectify(). + /// Indicates, whether the function should handle missing values (i.e. points where the disparity was not computed). + /// If handleMissingValues=true, then pixels with the minimal disparity that corresponds to the outliers (see StereoBM::operator() ) are + /// 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, + bool handleMissingValues = false, int ddepth = -1) + { + if (disparity == null) + throw new ArgumentNullException(nameof(disparity)); + if (_3dImage == null) + throw new ArgumentNullException(nameof(_3dImage)); + if (Q == null) + throw new ArgumentNullException(nameof(Q)); + disparity.ThrowIfDisposed(); + _3dImage.ThrowIfNotReady(); + Q.ThrowIfDisposed(); + + NativeMethods.calib3d_reprojectImageTo3D( + disparity.CvPtr, _3dImage.CvPtr, Q.CvPtr, handleMissingValues ? 1 : 0, ddepth); + + _3dImage.Fix(); + GC.KeepAlive(disparity); + GC.KeepAlive(_3dImage); + GC.KeepAlive(Q); + } + + #endregion + #region EstimateAffine3D + + /// + /// Computes an optimal affine transformation between two 3D point sets. + /// + /// First input 3D point set. + /// Second input 3D point set. + /// Output 3D affine transformation matrix 3 x 4 . + /// Output vector indicating which points are inliers. + /// Maximum reprojection error in the RANSAC algorithm to consider a point as an inlier. + /// Confidence level, between 0 and 1, for the estimated transformation. + /// 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, + double ransacThreshold = 3, double confidence = 0.99) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (outVal == null) + throw new ArgumentNullException(nameof(outVal)); + if (inliers == null) + throw new ArgumentNullException(nameof(inliers)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + outVal.ThrowIfNotReady(); + inliers.ThrowIfNotReady(); + + var ret = NativeMethods.calib3d_estimateAffine3D( + src.CvPtr, dst.CvPtr, outVal.CvPtr, inliers.CvPtr, ransacThreshold, confidence); + + outVal.Fix(); + inliers.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(dst); + return ret; + } + + #endregion + #region SampsonDistance + + /// + /// Calculates the Sampson Distance between two points. + /// + /// first homogeneous 2d point + /// second homogeneous 2d point + /// 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) + { + if (pt1 == null) + throw new ArgumentNullException(nameof(pt1)); + if (pt2 == null) + throw new ArgumentNullException(nameof(pt2)); + if (f == null) + throw new ArgumentNullException(nameof(f)); + pt1.ThrowIfDisposed(); + pt2.ThrowIfDisposed(); + f.ThrowIfDisposed(); + + var ret = NativeMethods.calib3d_sampsonDistance_InputArray(pt1.CvPtr, pt2.CvPtr, f.CvPtr); + + GC.KeepAlive(pt1); + GC.KeepAlive(pt2); + + return ret; + } + + /// + /// Calculates the Sampson Distance between two points. + /// + /// first homogeneous 2d point + /// second homogeneous 2d point + /// F fundamental matrix + /// The computed Sampson distance. + /// https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp#L1109 + public static double SampsonDistance(Point3d pt1, Point3d pt2, double[,] f) + { + if (f == null) + throw new ArgumentNullException(nameof(f)); + if (f.GetLength(0) != 3 || f.GetLength(1) != 3) + throw new ArgumentException("f should be 3x3 matrix", nameof(f)); + + unsafe + { + fixed (double* fPtr = f) + { + var ret = NativeMethods.calib3d_sampsonDistance_Point3d(pt1, pt2, fPtr); + GC.KeepAlive(f); + return ret; + } + } + } + + #endregion + #region EstimateAffine2D + + /// + /// Computes an optimal affine transformation between two 2D point sets. + /// + /// First input 2D point set containing (X,Y). + /// Second input 2D point set containing (x,y). + /// Output vector indicating which points are inliers (1-inlier, 0-outlier). + /// Robust method used to compute transformation. + /// Maximum reprojection error in the RANSAC algorithm to consider a point as an inlier.Applies only to RANSAC. + /// The maximum number of robust method iterations. + /// Confidence level, between 0 and 1, for the estimated transformation. + /// 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. + /// Maximum number of iterations of refining algorithm (Levenberg-Marquardt). + /// 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, + RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, + ulong maxIters = 2000, double confidence = 0.99, + ulong refineIters = 10) + { + if (from == null) + throw new ArgumentNullException(nameof(from)); + if (to == null) + throw new ArgumentNullException(nameof(to)); + from.ThrowIfDisposed(); + to.ThrowIfDisposed(); + inliers?.ThrowIfNotReady(); + + var matPtr = NativeMethods.calib3d_estimateAffine2D(from.CvPtr, to.CvPtr, ToPtr(inliers), + (int) method, ransacReprojThreshold, maxIters, confidence, refineIters); + + GC.KeepAlive(inliers); + GC.KeepAlive(inliers); + GC.KeepAlive(inliers); + + return (matPtr == IntPtr.Zero) ? null : new Mat(matPtr); + } + + #endregion + #region EstimateAffinePartial2D + + /// + /// Computes an optimal limited affine transformation with 4 degrees of freedom between two 2D point sets. + /// + /// First input 2D point set. + /// Second input 2D point set. + /// Output vector indicating which points are inliers. + /// Robust method used to compute transformation. + /// Maximum reprojection error in the RANSAC algorithm to consider a point as an inlier.Applies only to RANSAC. + /// The maximum number of robust method iterations. + /// Confidence level, between 0 and 1, for the estimated transformation. + /// 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. + /// + /// 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, + RobustEstimationAlgorithms method = RobustEstimationAlgorithms.RANSAC, double ransacReprojThreshold = 3, + ulong maxIters = 2000, double confidence = 0.99, + ulong refineIters = 10) + { + if (from == null) + throw new ArgumentNullException(nameof(from)); + if (to == null) + throw new ArgumentNullException(nameof(to)); + from.ThrowIfDisposed(); + to.ThrowIfDisposed(); + inliers?.ThrowIfNotReady(); + + var matPtr = NativeMethods.calib3d_estimateAffinePartial2D(from.CvPtr, to.CvPtr, ToPtr(inliers), + (int)method, ransacReprojThreshold, maxIters, confidence, refineIters); + + GC.KeepAlive(inliers); + GC.KeepAlive(inliers); + GC.KeepAlive(inliers); + + return (matPtr == IntPtr.Zero) ? null : new Mat(matPtr); + } + + #endregion + #region DecomposeHomographyMat + + /// + /// Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). + /// + /// The input homography matrix between two images. + /// The input intrinsic camera calibration matrix. + /// Array of rotation matrices. + /// Array of translation matrices. + /// Array of plane normal matrices. + /// + public static int DecomposeHomographyMat( + InputArray h, + InputArray k, + out Mat[] rotations, + out Mat[] translations, + out Mat[] normals) + { + if (h == null) + throw new ArgumentNullException(nameof(h)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + + h.ThrowIfDisposed(); + k.ThrowIfDisposed(); + + int result; + + using (var rotationsVec = new VectorOfMat()) + using (var translationsVec = new VectorOfMat()) + using (var normalsVec = new VectorOfMat()) + { + result = NativeMethods.calib3d_decomposeHomographyMat( + h.CvPtr, k.CvPtr, rotationsVec.CvPtr, translationsVec.CvPtr, normalsVec.CvPtr); + + rotations = rotationsVec.ToArray(); + translations = translationsVec.ToArray(); + normals = normalsVec.ToArray(); + } + + GC.KeepAlive(h); + GC.KeepAlive(k); + GC.KeepAlive(rotations); + GC.KeepAlive(translations); + GC.KeepAlive(normals); + + return result; + } + + #endregion + #region FilterHomographyDecompByVisibleRefpoints + + /// + /// Filters homography decompositions based on additional information. + /// + /// Vector of rotation matrices. + /// Vector of plane normal matrices. + /// Vector of (rectified) visible reference points before the homography is applied + /// Vector of (rectified) visible reference points after the homography is applied + /// Vector of int indices representing the viable solution set after filtering + /// optional Mat/Vector of 8u type representing the mask for the inliers as given by the findHomography function + public static void FilterHomographyDecompByVisibleRefpoints( + IEnumerable rotations, + IEnumerable normals, + InputArray beforePoints, + InputArray afterPoints, + OutputArray possibleSolutions, + InputArray? pointsMask = null) + { + if (rotations == null) + throw new ArgumentNullException(nameof(rotations)); + if (normals == null) + throw new ArgumentNullException(nameof(normals)); + if (beforePoints == null) + throw new ArgumentNullException(nameof(beforePoints)); + if (afterPoints == null) + throw new ArgumentNullException(nameof(afterPoints)); + if (possibleSolutions == 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.calib3d_filterHomographyDecompByVisibleRefpoints( + rotationsVec.CvPtr, normalsVec.CvPtr, beforePoints.CvPtr, afterPoints.CvPtr, possibleSolutions.CvPtr, ToPtr(pointsMask)); + } + + GC.KeepAlive(rotations); + GC.KeepAlive(normals); + GC.KeepAlive(beforePoints); + GC.KeepAlive(afterPoints); + GC.KeepAlive(possibleSolutions); + GC.KeepAlive(pointsMask); + } + + #endregion + #region Undistort + + /// + /// corrects lens distortion for the given camera matrix and distortion coefficients + /// + /// Input (distorted) image. + /// Output (corrected) image that has the same size and type as src . + /// 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. + public static void Undistort(InputArray src, OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray? newCameraMatrix = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + cameraMatrix.ThrowIfDisposed(); + NativeMethods.calib3d_undistort(src.CvPtr, dst.CvPtr, cameraMatrix.CvPtr, + ToPtr(distCoeffs), ToPtr(newCameraMatrix)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(newCameraMatrix); + dst.Fix(); + } + + #endregion + #region InitUndistortRectifyMap + + /// + /// initializes maps for cv::remap() to correct lens distortion and optionally rectify the image + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void InitUndistortRectifyMap( + InputArray cameraMatrix, InputArray distCoeffs, + InputArray r, InputArray newCameraMatrix, + Size size, MatType m1Type, OutputArray map1, OutputArray map2) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (distCoeffs == null) + throw new ArgumentNullException(nameof(distCoeffs)); + if (r == null) + throw new ArgumentNullException(nameof(r)); + if (newCameraMatrix == null) + throw new ArgumentNullException(nameof(newCameraMatrix)); + if (map1 == null) + throw new ArgumentNullException(nameof(map1)); + if (map2 == null) + throw new ArgumentNullException(nameof(map2)); + cameraMatrix.ThrowIfDisposed(); + distCoeffs.ThrowIfDisposed(); + r.ThrowIfDisposed(); + newCameraMatrix.ThrowIfDisposed(); + map1.ThrowIfNotReady(); + map2.ThrowIfNotReady(); + NativeMethods.calib3d_initUndistortRectifyMap( + cameraMatrix.CvPtr, distCoeffs.CvPtr, r.CvPtr, newCameraMatrix.CvPtr, size, m1Type, map1.CvPtr, map2.CvPtr); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(r); + GC.KeepAlive(newCameraMatrix); + GC.KeepAlive(map1); + GC.KeepAlive(map2); + map1.Fix(); + map2.Fix(); + } + + #endregion + #region InitWideAngleProjMap + + /// + /// initializes maps for cv::remap() for wide-angle + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static float InitWideAngleProjMap( + InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, int destImageWidth, MatType m1Type, + OutputArray map1, OutputArray map2, + ProjectionType projType, double alpha = 0) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + if (distCoeffs == null) + throw new ArgumentNullException(nameof(distCoeffs)); + if (map1 == null) + throw new ArgumentNullException(nameof(map1)); + if (map2 == null) + throw new ArgumentNullException(nameof(map2)); + cameraMatrix.ThrowIfDisposed(); + distCoeffs.ThrowIfDisposed(); + map1.ThrowIfNotReady(); + map2.ThrowIfNotReady(); + var ret = NativeMethods.calib3d_initWideAngleProjMap(cameraMatrix.CvPtr, distCoeffs.CvPtr, imageSize, + destImageWidth, m1Type, map1.CvPtr, map2.CvPtr, (int)projType, alpha); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(map1); + GC.KeepAlive(map2); + map1.Fix(); + map2.Fix(); + return ret; + } + + #endregion + #region GetDefaultNewCameraMatrix + + /// + /// returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true) + /// + /// Input camera matrix. + /// 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 static Mat GetDefaultNewCameraMatrix( + InputArray cameraMatrix, Size? imgSize = null, bool centerPrincipalPoint = false) + { + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + cameraMatrix.ThrowIfDisposed(); + var imgSize0 = imgSize.GetValueOrDefault(new Size()); + var matPtr = NativeMethods.calib3d_getDefaultNewCameraMatrix( + cameraMatrix.CvPtr, imgSize0, centerPrincipalPoint ? 1 : 0); + GC.KeepAlive(cameraMatrix); + return new Mat(matPtr); + } + + #endregion + #region UndistortPoints + + /// + /// Computes the ideal point coordinates from the observed point coordinates. + /// + /// Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2). + /// Output ideal point coordinates after undistortion and reverse perspective transformation. + /// If matrix P is identity or omitted, dst will contain normalized point coordinates. + /// 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. + public static void UndistortPoints( + InputArray src, + OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray? r = null, + InputArray? p = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (cameraMatrix == null) + throw new ArgumentNullException(nameof(cameraMatrix)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + cameraMatrix.ThrowIfDisposed(); + NativeMethods.calib3d_undistortPoints( + src.CvPtr, dst.CvPtr, cameraMatrix.CvPtr, + ToPtr(distCoeffs), ToPtr(r), ToPtr(p)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(cameraMatrix); + GC.KeepAlive(distCoeffs); + GC.KeepAlive(r); + GC.KeepAlive(p); + dst.Fix(); + } + + #endregion + + /// + /// The methods in this class use a so-called fisheye camera model. + /// + public static class FishEye + { + /// + /// Projects points using fisheye model. + /// + /// The function computes projections of 3D points to the image plane given intrinsic and extrinsic + /// camera parameters.Optionally, the function computes Jacobians - matrices of partial derivatives of + /// image points coordinates(as functions of all the input parameters) with respect to the particular + /// parameters, intrinsic and/or extrinsic. + /// + /// Array of object points, 1xN/Nx1 3-channel (or vector<Point3f> ), + /// where N is the number of points in the view. + /// Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, + /// or vector<Point2f>. + /// + /// + /// Camera matrix + /// Input vector of distortion coefficients + /// The skew coefficient. + /// Optional output 2Nx15 jacobian matrix of derivatives of image points with respect + /// to components of the focal lengths, coordinates of the principal point, distortion coefficients, + /// 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) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (rvec == null) + throw new ArgumentNullException(nameof(rvec)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + objectPoints.ThrowIfDisposed(); + rvec.ThrowIfDisposed(); + tvec.ThrowIfDisposed(); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + jacobian?.ThrowIfNotReady(); + + NativeMethods.calib3d_fisheye_projectPoints2( + objectPoints.CvPtr, + imagePoints.CvPtr, + rvec.CvPtr, tvec.CvPtr, + k.CvPtr, d.CvPtr, + alpha, ToPtr(jacobian)); + + GC.KeepAlive(objectPoints); + GC.KeepAlive(rvec); + GC.KeepAlive(tvec); + GC.KeepAlive(k); + GC.KeepAlive(d); + GC.KeepAlive(imagePoints); + GC.KeepAlive(jacobian); + } + + /// + /// Distorts 2D points using fisheye model. + /// + /// Array of object points, 1xN/Nx1 2-channel (or vector<Point2f> ), + /// where N is the number of points in the view. + /// Output array of image points, 1xN/Nx1 2-channel, or vector<Point2f> . + /// Camera matrix + /// Input vector of distortion coefficients + /// The skew coefficient. + public static void DistortPoints(InputArray undistorted, OutputArray distorted, InputArray k, InputArray d, double alpha = 0) + { + if (undistorted == null) + throw new ArgumentNullException(nameof(undistorted)); + if (distorted == null) + throw new ArgumentNullException(nameof(distorted)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + undistorted.ThrowIfDisposed(); + distorted.ThrowIfNotReady(); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + + NativeMethods.calib3d_fisheye_distortPoints(undistorted.CvPtr, distorted.CvPtr, k.CvPtr, d.CvPtr, alpha); + + GC.KeepAlive(undistorted); + GC.KeepAlive(distorted); + GC.KeepAlive(k); + GC.KeepAlive(d); + } + + /// + /// Undistorts 2D points using fisheye model + /// + /// Array of object points, 1xN/Nx1 2-channel (or vector<Point2f> ), + /// where N is the number of points in the view. + /// Output array of image points, 1xN/Nx1 2-channel, or vector>Point2f> . + /// Camera matrix + /// Input vector of distortion coefficients (k_1, k_2, k_3, k_4). + /// Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel + /// 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) + { + if (distorted == null) + throw new ArgumentNullException(nameof(distorted)); + if (undistorted == null) + throw new ArgumentNullException(nameof(undistorted)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + distorted.ThrowIfDisposed(); + undistorted.ThrowIfNotReady(); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + r?.ThrowIfDisposed(); + p?.ThrowIfDisposed(); + + NativeMethods.calib3d_fisheye_undistortPoints(distorted.CvPtr, undistorted.CvPtr, k.CvPtr, d.CvPtr, ToPtr(r), ToPtr(p)); + + GC.KeepAlive(distorted); + GC.KeepAlive(undistorted); + GC.KeepAlive(k); + GC.KeepAlive(d); + GC.KeepAlive(r); + GC.KeepAlive(p); + } + + /// + /// Computes undistortion and rectification maps for image transform by cv::remap(). + /// If D is empty zero distortion is used, if R or P is empty identity matrixes are used. + /// + /// Camera matrix + /// Input vector of distortion coefficients (k_1, k_2, k_3, k_4). + /// Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 1-channel or 1x1 3-channel + /// New camera matrix (3x3) or new projection matrix (3x4) + /// Undistorted image size. + /// Type of the first output map that can be CV_32FC1 or CV_16SC2 . See convertMaps() for details. + /// 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) + { + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + if (r == null) + throw new ArgumentNullException(nameof(r)); + if (p == null) + throw new ArgumentNullException(nameof(p)); + if (map1 == null) + throw new ArgumentNullException(nameof(map1)); + if (map2 == null) + throw new ArgumentNullException(nameof(map2)); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + r.ThrowIfDisposed(); + p.ThrowIfDisposed(); + map1.ThrowIfNotReady(); + map2.ThrowIfNotReady(); + + NativeMethods.calib3d_fisheye_initUndistortRectifyMap(k.CvPtr, d.CvPtr, r.CvPtr, p.CvPtr, size, m1type, map1.CvPtr, map2.CvPtr); + + GC.KeepAlive(k); + GC.KeepAlive(d); + GC.KeepAlive(r); + GC.KeepAlive(p); + GC.KeepAlive(map1); + GC.KeepAlive(map2); + } + + /// + /// Transforms an image to compensate for fisheye lens distortion. + /// + /// image with fisheye lens distortion. + /// Output image with compensated fisheye lens distortion. + /// Camera matrix + /// Input vector of distortion coefficients (k_1, k_2, k_3, k_4). + /// Camera matrix of the distorted image. By default, it is the identity matrix but you + /// 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) + { + if (distorted == null) + throw new ArgumentNullException(nameof(distorted)); + if (undistorted == null) + throw new ArgumentNullException(nameof(undistorted)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + distorted.ThrowIfDisposed(); + undistorted.ThrowIfNotReady(); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + knew?.ThrowIfDisposed(); + + NativeMethods.calib3d_fisheye_undistortImage(distorted.CvPtr, undistorted.CvPtr, k.CvPtr, d.CvPtr, ToPtr(knew), newSize); + + GC.KeepAlive(distorted); + GC.KeepAlive(undistorted); + GC.KeepAlive(k); + GC.KeepAlive(d); + GC.KeepAlive(knew); + } + + /// + /// Estimates new camera matrix for undistortion or rectification. + /// + /// Camera matrix + /// Input vector of distortion coefficients (k_1, k_2, k_3, k_4). + /// + /// Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + /// 1-channel or 1x1 3-channel + /// New camera matrix (3x3) or new projection matrix (3x4) + /// Sets the new focal length in range between the min focal length and the max focal + /// length.Balance is in range of[0, 1]. + /// + /// 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) + { + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + if (r == null) + throw new ArgumentNullException(nameof(r)); + if (p == null) + throw new ArgumentNullException(nameof(p)); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + r.ThrowIfDisposed(); + p.ThrowIfNotReady(); + + NativeMethods.calib3d_fisheye_estimateNewCameraMatrixForUndistortRectify( + k.CvPtr, d.CvPtr, imageSize, r.CvPtr, p.CvPtr, balance, newSize, fovScale); + + GC.KeepAlive(k); + GC.KeepAlive(d); + GC.KeepAlive(r); + GC.KeepAlive(p); + } + + /// + /// Performs camera calibaration + /// + /// vector of vectors of calibration pattern points in the calibration pattern coordinate space. + /// vector of vectors of the projections of calibration pattern points. + /// imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to + /// objectPoints[i].size() for each i. + /// Size of the image used only to initialize the intrinsic camera matrix. + /// Output 3x3 floating-point camera matrix + /// Output vector of distortion coefficients (k_1, k_2, k_3, k_4). + /// Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view. + /// That is, each k-th rotation vector together with the corresponding k-th translation vector(see + /// the next output parameter description) brings the calibration pattern from the model coordinate + /// space(in which object points are specified) to the world coordinate space, that is, a real + /// position of the calibration pattern in the k-th pattern view(k= 0.. * M * -1). + /// Output vector of translation vectors estimated for each pattern view. + /// Different flags that may be zero or a combination of flag values + /// Termination criteria for the iterative optimization algorithm. + /// + public static double Calibrate( + IEnumerable objectPoints, IEnumerable imagePoints, + Size imageSize, InputOutputArray k, InputOutputArray d, + out IEnumerable rvecs, out IEnumerable tvecs, + FishEyeCalibrationFlags flags = 0, TermCriteria? criteria = null) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints == null) + throw new ArgumentNullException(nameof(imagePoints)); + if (k == null) + throw new ArgumentNullException(nameof(k)); + if (d == null) + throw new ArgumentNullException(nameof(d)); + k.ThrowIfDisposed(); + d.ThrowIfDisposed(); + + var criteriaVal = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 100, double.Epsilon)); + + double result; + using (var objectPointsVec = new VectorOfMat(objectPoints)) + using (var imagePointsVec = new VectorOfMat(imagePoints)) + using (var rvecsVec = new VectorOfMat()) + using (var tvecsVec = new VectorOfMat()) + { + result = NativeMethods.calib3d_fisheye_calibrate( + objectPointsVec.CvPtr, imagePointsVec.CvPtr, imageSize, + k.CvPtr, d.CvPtr, rvecsVec.CvPtr, tvecsVec.CvPtr, (int)flags, criteriaVal); + + rvecs = rvecsVec.ToArray(); + tvecs = tvecsVec.ToArray(); + } + + GC.KeepAlive(objectPoints); + GC.KeepAlive(imagePoints); + GC.KeepAlive(k); + GC.KeepAlive(d); + + return result; + } + + /// + /// Stereo rectification for fisheye camera model + /// + /// First camera matrix. + /// First camera distortion parameters. + /// Second camera matrix. + /// Second camera distortion parameters. + /// Size of the image used for stereo calibration. + /// Rotation matrix between the coordinate systems of the first and the second cameras. + /// Translation vector between coordinate systems of the cameras. + /// Output 3x3 rectification transform (rotation matrix) for the first camera. + /// Output 3x3 rectification transform (rotation matrix) for the second camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the first camera. + /// Output 3x4 projection matrix in the new (rectified) coordinate systems for the second camera. + /// Output 4x4 disparity-to-depth mapping matrix (see reprojectImageTo3D ). + /// Operation flags that may be zero or CALIB_ZERO_DISPARITY . If the flag is set, + /// the function makes the principal points of each camera have the same pixel coordinates in the + /// rectified views.And if the flag is not set, the function may still shift the images in the + /// horizontal or vertical direction(depending on the orientation of epipolar lines) to maximize the + /// useful image area. + /// New image resolution after rectification. The same size should be passed to + /// initUndistortRectifyMap(see the stereo_calib.cpp sample in OpenCV samples directory). 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. + /// Sets the new focal length in range between the min focal length and the max focal + /// 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, + double balance = 0.0, double fovScale = 1.0) + { + if (k1 == null) + throw new ArgumentNullException(nameof(k1)); + if (d1 == null) + throw new ArgumentNullException(nameof(d1)); + if (k2 == null) + throw new ArgumentNullException(nameof(k2)); + if (d2 == null) + throw new ArgumentNullException(nameof(d2)); + if (r == null) + throw new ArgumentNullException(nameof(r)); + if (tvec == null) + throw new ArgumentNullException(nameof(tvec)); + if (r1 == null) + throw new ArgumentNullException(nameof(r1)); + if (r2 == null) + throw new ArgumentNullException(nameof(r2)); + if (p1 == null) + throw new ArgumentNullException(nameof(p1)); + if (p2 == null) + throw new ArgumentNullException(nameof(p2)); + if (q == 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.calib3d_fisheye_stereoRectify( + k1.CvPtr, d1.CvPtr, k2.CvPtr, d2.CvPtr, + imageSize, r.CvPtr, tvec.CvPtr, r1.CvPtr, r2.CvPtr, + p1.CvPtr, p2.CvPtr, q.CvPtr, (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); + } + + /// + /// Performs stereo calibration + /// + /// Vector of vectors of the calibration pattern points. + /// Vector of vectors of the projections of the calibration pattern points, + /// observed by the first camera. + /// Vector of vectors of the projections of the calibration pattern points, + /// observed by the second camera. + /// Input/output first camera matrix + /// Input/output vector of distortion coefficients (k_1, k_2, k_3, k_4) of 4 elements. + /// Input/output second camera matrix. The parameter is similar to K1 . + /// Input/output lens distortion coefficients for the second camera. The parameter is + /// similar to D1. + /// Size of the image used only to initialize intrinsic camera matrix. + /// Output rotation matrix between the 1st and the 2nd camera coordinate systems. + /// Output translation vector between the coordinate systems of the cameras. + /// Different flags that may be zero or a combination of the FishEyeCalibrationFlags values + /// Termination criteria for the iterative optimization algorithm. + /// + 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, + TermCriteria? criteria = null) + { + if (objectPoints == null) + throw new ArgumentNullException(nameof(objectPoints)); + if (imagePoints1 == null) + throw new ArgumentNullException(nameof(imagePoints1)); + if (imagePoints2 == null) + throw new ArgumentNullException(nameof(imagePoints2)); + if (k1 == null) + throw new ArgumentNullException(nameof(k1)); + if (d1 == null) + throw new ArgumentNullException(nameof(d1)); + if (k2 == null) + throw new ArgumentNullException(nameof(k2)); + if (d2 == null) + throw new ArgumentNullException(nameof(d2)); + if (r == null) + throw new ArgumentNullException(nameof(r)); + if (t == null) + throw new ArgumentNullException(nameof(t)); + k1.ThrowIfNotReady(); + d1.ThrowIfNotReady(); + k2.ThrowIfNotReady(); + d2.ThrowIfNotReady(); + r.ThrowIfNotReady(); + t.ThrowIfNotReady(); + + var criteriaVal = criteria.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 100, double.Epsilon)); + + double result; + using (var objectPointsVec = new VectorOfMat(objectPoints)) + using (var imagePoints1Vec = new VectorOfMat(imagePoints1)) + using (var imagePoints2Vec = new VectorOfMat(imagePoints2)) + { + result = NativeMethods.calib3d_fisheye_stereoCalibrate( + objectPointsVec.CvPtr, imagePoints1Vec.CvPtr, imagePoints2Vec.CvPtr, + k1.CvPtr, d1.CvPtr, k2.CvPtr, d2.CvPtr, imageSize, + r.CvPtr, t.CvPtr, (int)flags, criteriaVal); + } + + 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); + + return result; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2_core.cs b/OpenVinoOpenCvSharp/Cv2/Cv2_core.cs new file mode 100644 index 0000000..8e014f6 --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2_core.cs @@ -0,0 +1,3782 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenCvSharp.Util; +// ReSharper disable CommentTypo +// ReSharper disable IdentifierTypo +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + static partial class Cv2 + { + #region Miscellaneous + + /// + /// OpenCV will try to set the number of threads for the next parallel region. + /// If threads == 0, OpenCV will disable threading optimizations and run all it's functions + /// sequentially.Passing threads < 0 will reset threads number to system default. This function must + /// be called outside of parallel region. + /// OpenCV will try to run its functions with specified threads number, but some behaviour differs from framework: + /// - `TBB` - User-defined parallel constructions will run with the same threads number, if another is not specified.If later on user creates his own scheduler, OpenCV will use it. + /// - `OpenMP` - No special defined behaviour. + /// - `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its functions sequentially. + /// - `GCD` - Supports only values <= 0. + /// - `C=` - No special defined behaviour. + /// + /// Number of threads used by OpenCV. + public static void SetNumThreads(int nThreads) + { + NativeMethods.core_setNumThreads(nThreads); + } + + /// + /// Returns the number of threads used by OpenCV for parallel regions. + /// + /// Always returns 1 if OpenCV is built without threading support. + /// The exact meaning of return value depends on the threading framework used by OpenCV library: + /// - `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is + /// any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns default + /// number of threads used by TBB library. + /// - `OpenMP` - An upper bound on the number of threads that could be used to form a new team. + /// - `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions. + /// - `GCD` - Unsupported; returns the GCD thread pool limit(512) for compatibility. + /// - `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before + /// called setNumThreads with threads > 0, otherwise returns the number of logical CPUs, + /// available for the process. + /// + /// + public static int GetNumThreads() + { + return NativeMethods.core_getNumThreads(); + } + + /// + /// Returns the index of the currently executed thread within the current parallel region. + /// Always returns 0 if called outside of parallel region. + /// @deprecated Current implementation doesn't corresponding to this documentation. + /// The exact meaning of the return value depends on the threading framework used by OpenCV library: + /// - `TBB` - Unsupported with current 4.1 TBB release.Maybe will be supported in future. + /// - `OpenMP` - The thread number, within the current team, of the calling thread. + /// - `Concurrency` - An ID for the virtual processor that the current context is executing + /// on(0 for master thread and unique number for others, but not necessary 1,2,3,...). + /// - `GCD` - System calling thread's ID. Never returns 0 inside parallel region. + /// - `C=` - The index of the current parallel task. + /// + /// + public static int GetThreadNum() + { + return NativeMethods.core_getThreadNum(); + } + + /// + /// Returns full configuration time cmake output. + /// + /// Returned value is raw cmake output including version control system revision, compiler version, + /// compiler flags, enabled modules and third party libraries, etc.Output format depends on target architecture. + /// + /// + public static string GetBuildInformation() + { + var length = NativeMethods.core_getBuildInformation_length(); + var buf = new StringBuilder(length + 1); + NativeMethods.core_getBuildInformation(buf, buf.Capacity); + return buf.ToString(); + } + + /// + /// Returns library version string. + /// For example "3.4.1-dev". + /// + /// + public static string GetVersionString() + { + const int length = 128; + var buf = new StringBuilder(length + 1); + NativeMethods.core_getVersionString(buf, buf.Capacity); + return buf.ToString(); + } + + /// + /// Returns major library version + /// + /// + public static int GetVersionMajor() + { + return NativeMethods.core_getVersionMajor(); + } + + /// + /// Returns minor library version + /// + /// + public static int GetVersionMinor() + { + return NativeMethods.core_getVersionMinor(); + } + + /// + /// Returns revision field of the library version + /// + /// + public static int GetVersionRevision() + { + return NativeMethods.core_getVersionRevision(); + } + + /// + /// Returns the number of ticks. + /// The function returns the number of ticks after the certain event (for example, when the machine was + /// turned on). It can be used to initialize RNG or to measure a function execution time by reading the + /// tick count before and after the function call. + /// + /// + public static long GetTickCount() + { + return NativeMethods.core_getTickCount(); + } + + /// + /// Returns the number of ticks per second. + /// The function returns the number of ticks per second.That is, the following code computes the execution time in seconds: + /// + /// + public static double GetTickFrequency() + { + return NativeMethods.core_getTickFrequency(); + } + + /// + /// Returns the number of CPU ticks. + /// + /// The function returns the current number of CPU ticks on some architectures(such as x86, x64, PowerPC). + /// On other platforms the function is equivalent to getTickCount.It can also be used for very accurate time + /// measurements, as well as for RNG initialization.Note that in case of multi-CPU systems a thread, from which + /// getCPUTickCount is called, can be suspended and resumed at another CPU with its own counter. So, + /// theoretically (and practically) the subsequent calls to the function do not necessary return the monotonously + /// increasing values. Also, since a modern CPU varies the CPU frequency depending on the load, the number of CPU + /// clocks spent in some code cannot be directly converted to time units.Therefore, getTickCount is generally + /// a preferable solution for measuringexecution time. + /// + /// + public static long GetCpuTickCount() + { + return NativeMethods.core_getCPUTickCount(); + } + + /// + /// Returns true if the specified feature is supported by the host hardware. + /// The function returns true if the host hardware supports the specified feature.When user calls + /// setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until + /// setUseOptimized(true) is called.This way user can dynamically switch on and off the optimized code in OpenCV. + /// + /// The feature of interest, one of cv::CpuFeatures + /// + public static bool CheckHardwareSupport(CpuFeatures feature) + { + return NativeMethods.core_checkHardwareSupport((int) feature) != 0; + } + + /// + /// Returns feature name by ID. + /// Returns empty string if feature is not defined + /// + /// + /// + public static string GetHardwareFeatureName(int feature) + { + const int length = 128; + var buf = new StringBuilder(length + 1); + NativeMethods.core_getHardwareFeatureName(feature, buf, buf.Capacity); + return buf.ToString(); + } + + /// + /// Returns list of CPU features enabled during compilation. + /// Returned value is a string containing space separated list of CPU features with following markers: + /// - no markers - baseline features + /// - prefix `*` - features enabled in dispatcher + /// - suffix `?` - features enabled but not available in HW + /// + /// + /// `SSE SSE2 SSE3* SSE4.1 *SSE4.2 *FP16* AVX *AVX2* AVX512-SKX?` + /// + /// + public static string GetCpuFeaturesLine() + { + const int length = 512; + var buf = new StringBuilder(length + 1); + NativeMethods.core_getCPUFeaturesLine(buf, buf.Capacity); + return buf.ToString(); + } + + /// + /// Returns the number of logical CPUs available for the process. + /// + /// + public static int GetNumberOfCpus() + { + return NativeMethods.core_getNumberOfCPUs(); + } + + /// + /// + /// + /// + /// + public static IntPtr FastMalloc(long bufSize) + { + return NativeMethods.core_fastMalloc(new IntPtr(bufSize)); + } + + /// + /// + /// + /// + public static void FastFree(IntPtr ptr) + { + NativeMethods.core_fastFree(ptr); + } + + /// + /// Turns on/off available optimization. + /// The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled + /// or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way. + /// + /// + public static void SetUseOptimized(bool onoff) + { + NativeMethods.core_setUseOptimized(onoff ? 1 : 0); + } + + /// + /// Returns the current optimization status. + /// The function returns the current optimization status, which is controlled by cv::setUseOptimized(). + /// + /// + public static bool UseOptimized() + { + return NativeMethods.core_useOptimized() != 0; + } + + /// + /// Aligns buffer size by the certain number of bytes + /// This small inline function aligns a buffer size by + /// the certian number of bytes by enlarging it. + /// + /// + /// + /// + public static int AlignSize(int sz, int n) + { + var assert = ((n & (n - 1)) == 0); // n is a power of 2 + if (!assert) + throw new ArgumentException(); + return (sz + n - 1) & -n; + } + + /// + /// + /// + /// + /// + /// + public static string?[] Glob(string pattern, bool recursive = false) + { + if (pattern == null) + throw new ArgumentNullException(nameof(pattern)); + + using (var resultVec = new VectorOfString()) + { + NativeMethods.core_glob(pattern, resultVec.CvPtr, recursive ? 1 : 0); + return resultVec.ToArray(); + } + } + + /// + /// Sets/resets the break-on-error mode. + /// When the break-on-error mode is set, the default error handler issues a hardware exception, + /// which can make debugging more convenient. + /// + /// + /// the previous state + public static bool SetBreakOnError(bool flag) + { + return NativeMethods.core_setBreakOnError(flag ? 1 : 0) != 0; + } + + /// + /// + /// + /// + /// + /// + public static string? Format(InputArray mtx, FormatType format = FormatType.Default) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + + unsafe + { + sbyte* buf = null; + try + { + buf = NativeMethods.core_format(mtx.CvPtr, (int) format); + return StringHelper.PtrToStringAnsi(buf); + } + finally + { + if (buf != null) + NativeMethods.core_char_delete(buf); + GC.KeepAlive(mtx); + } + } + } + + #endregion + + #region Abs + + /// + /// Computes absolute value of each matrix element + /// + /// matrix + /// + public static MatExpr Abs(Mat src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + var retPtr = NativeMethods.core_abs_Mat(src.CvPtr); + GC.KeepAlive(src); + return new MatExpr(retPtr); + } + + /// + /// Computes absolute value of each matrix element + /// + /// matrix expression + /// + public static MatExpr Abs(MatExpr src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + var retPtr = NativeMethods.core_abs_MatExpr(src.CvPtr); + GC.KeepAlive(src); + return new MatExpr(retPtr); + } + + #endregion + + #region Add + +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の和を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src1 と同じサイズ,同じ型の出力配列. + /// 8ビット,シングルチャンネル配列のオプションの処理マスク.出力配列内の変更される要素を表します. [既定値はnull] + /// +#else + /// + /// Computes the per-element sum of two arrays or an array and a scalar. + /// + /// 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] + /// +#endif + public static void Add(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null, + int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_add(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask), dtype); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + + #endregion + + #region Subtract + +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の差を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src1 と同じサイズ,同じ型の出力配列. + /// オプション.8ビット,シングルチャンネル配列の処理マスク.出力配列内の変更される要素を表します. [既定値はnull] + /// +#else + /// + /// Calculates per-element difference between two arrays or array and a scalar + /// + /// 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] + /// +#endif + public static void Subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null, + int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_subtract_InputArray2(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask), dtype); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(mask); + } + +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の差を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src1 と同じサイズ,同じ型の出力配列. + /// オプション.8ビット,シングルチャンネル配列の処理マスク.出力配列内の変更される要素を表します. [既定値はnull] + /// +#else + /// + /// Calculates per-element difference between two arrays or array and a scalar + /// + /// 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] + /// +#endif + public static void Subtract(InputArray src1, Scalar src2, OutputArray dst, InputArray? mask = null, + int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_subtract_InputArrayScalar(src1.CvPtr, src2, dst.CvPtr, ToPtr(mask), dtype); + GC.KeepAlive(src1); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(mask); + } + +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の差を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src1 と同じサイズ,同じ型の出力配列. + /// オプション.8ビット,シングルチャンネル配列の処理マスク.出力配列内の変更される要素を表します. [既定値はnull] + /// +#else + /// + /// Calculates per-element difference between two arrays or array and a scalar + /// + /// 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] + /// +#endif + public static void Subtract(Scalar src1, InputArray src2, OutputArray dst, InputArray? mask = null, + int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_subtract_ScalarInputArray(src1, src2.CvPtr, dst.CvPtr, ToPtr(mask), dtype); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(mask); + } + + #endregion + + #region Multiply + +#if LANG_JP + /// + /// 2つの配列同士の,要素毎のスケーリングされた積を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src1 と同じサイズ,同じ型の出力配列 + /// オプションであるスケールファクタ. [既定値は1] + /// +#else + /// + /// Calculates the per-element scaled product of two arrays + /// + /// The first source array + /// The second source array of the same size and the same type as src1 + /// The destination array; will have the same size and the same type as src1 + /// The optional scale factor. [By default this is 1] + /// +#endif + public static void Multiply(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_multiply(src1.CvPtr, src2.CvPtr, dst.CvPtr, scale, dtype); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Divide + +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の商を求めます. + /// + /// 1番目の入力配列 + /// src1 と同じサイズ,同じ型である2番目の入力配列 + /// src2 と同じサイズ,同じ型である出力配列 + /// スケールファクタ [既定値は1] + /// +#else + /// + /// Performs per-element division of two arrays or a scalar by an array. + /// + /// The first source array + /// The second source array; should have the same size and same type as src1 + /// The destination array; will have the same size and same type as src2 + /// Scale factor [By default this is 1] + /// +#endif + public static void Divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_divide2(src1.CvPtr, src2.CvPtr, dst.CvPtr, scale, dtype); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } +#if LANG_JP + /// + /// 2つの配列同士,あるいは配列とスカラの 要素毎の商を求めます. + /// + /// スケールファクタ + /// 1番目の入力配列 + /// src2 と同じサイズ,同じ型である出力配列 + /// +#else + /// + /// Performs per-element division of two arrays or a scalar by an array. + /// + /// Scale factor + /// The first source array + /// The destination array; will have the same size and same type as src2 + /// +#endif + public static void Divide(double scale, InputArray src2, OutputArray dst, int dtype = -1) + { + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_divide1(scale, src2.CvPtr, dst.CvPtr, dtype); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region ScaleAdd + + /// + /// adds scaled array to another one (dst = alpha*src1 + src2) + /// + /// + /// + /// + /// + public static void ScaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_scaleAdd(src1.CvPtr, alpha, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region AddWeighted + + /// + /// computes weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma) + /// + /// + /// + /// + /// + /// + /// + /// + public static void AddWeighted(InputArray src1, double alpha, InputArray src2, + double beta, double gamma, OutputArray dst, int dtype = -1) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_addWeighted(src1.CvPtr, alpha, src2.CvPtr, beta, gamma, dst.CvPtr, dtype); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + /// + /// Computes the source location of an extrapolated pixel. + /// + /// 0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >= len + /// Length of the array along the corresponding axis. + /// Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and BORDER_ISOLATED. + /// When borderType==BORDER_CONSTANT, the function always returns -1, regardless + /// + public static int BorderInterpolate(int p, int len, BorderTypes borderType) + { + return NativeMethods.core_borderInterpolate(p, len, (int) borderType); + } + + #region CopyMakeBorder + + /// + /// Forms a border around the image + /// + /// The source image + /// The destination image; will have the same type as src and + /// the size Size(src.cols+left+right, src.rows+top+bottom) + /// 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 static void CopyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, + BorderTypes borderType, Scalar? value = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var value0 = value.GetValueOrDefault(new Scalar()); + NativeMethods.core_copyMakeBorder(src.CvPtr, dst.CvPtr, top, bottom, left, right, (int) borderType, value0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region ConvertScaleAbs + +#if LANG_JP + /// + /// スケーリング後,絶対値を計算し,結果を結果を 8 ビットに変換します. + /// + /// 入力配列 + /// 出力配列 + /// オプションのスケールファクタ. [既定値は1] + /// スケーリングされた値に加えられるオプション値. [既定値は0] +#else + /// + /// Scales, computes absolute values and converts the result to 8-bit. + /// + /// The source array + /// 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] +#endif + public static void ConvertScaleAbs(InputArray src, OutputArray dst, double alpha = 1, double beta = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_convertScaleAbs(src.CvPtr, dst.CvPtr, alpha, beta); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region LUT + + /// + /// 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) + /// 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, + /// and the same depth as lut + /// + public static void LUT(InputArray src, InputArray lut, OutputArray dst, int interpolation = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (lut == null) + throw new ArgumentNullException(nameof(lut)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + lut.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_LUT(src.CvPtr, lut.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(lut); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// 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) + /// 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, + /// and the same depth as lut + /// + public static void LUT(InputArray src, byte[] lut, OutputArray dst, int interpolation = 0) + { + if (lut == null) + throw new ArgumentNullException(nameof(lut)); + if (lut.Length != 256) + throw new ArgumentException("lut.Length != 256"); + using (var lutMat = new Mat(256, 1, MatType.CV_8UC1, lut)) + { + LUT(src, lutMat, dst, interpolation); + } + } + + #endregion + + #region Sum + + /// + /// computes sum of array elements + /// + /// The source array; must have 1 to 4 channels + /// + public static Scalar Sum(InputArray src) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + var ret = NativeMethods.core_sum(src.CvPtr); + GC.KeepAlive(src); + return ret; + } + + #endregion + + #region CountNonZero + + /// + /// computes the number of nonzero array elements + /// + /// Single-channel array + /// number of non-zero elements in mtx + public static int CountNonZero(InputArray mtx) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + mtx.ThrowIfDisposed(); + var ret = NativeMethods.core_countNonZero(mtx.CvPtr); + GC.KeepAlive(mtx); + return ret; + } + + #endregion + + #region FindNonZero + + /// + /// returns the list of locations of non-zero pixels + /// + /// + /// + public static void FindNonZero(InputArray src, OutputArray idx) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (idx == null) + throw new ArgumentNullException(nameof(idx)); + src.ThrowIfDisposed(); + idx.ThrowIfNotReady(); + NativeMethods.core_findNonZero(src.CvPtr, idx.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(idx); + idx.Fix(); + } + + #endregion + + #region Mean + + /// + /// computes mean value of selected array elements + /// + /// The source array; it should have 1 to 4 channels + /// (so that the result can be stored in Scalar) + /// The optional operation mask + /// + public static Scalar Mean(InputArray src, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + var ret = NativeMethods.core_mean(src.CvPtr, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(mask); + return ret; + } + + #endregion + + #region MeanStdDev + + /// + /// computes mean value and standard deviation of all or selected array elements + /// + /// 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, OutputArray mean, OutputArray stddev, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (stddev == null) + throw new ArgumentNullException(nameof(stddev)); + src.ThrowIfDisposed(); + mean.ThrowIfNotReady(); + stddev.ThrowIfNotReady(); + + NativeMethods.core_meanStdDev_OutputArray(src.CvPtr, mean.CvPtr, stddev.CvPtr, ToPtr(mask)); + + mean.Fix(); + stddev.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(mean); + GC.KeepAlive(stddev); + GC.KeepAlive(mask); + } + + /// + /// computes mean value and standard deviation of all or selected array elements + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + + src.ThrowIfDisposed(); + + NativeMethods.core_meanStdDev_Scalar(src.CvPtr, out mean, out stddev, ToPtr(mask)); + + GC.KeepAlive(src); + GC.KeepAlive(mask); + } + + #endregion + + #region Norm + + /// + /// Calculates absolute array norm, absolute difference norm, or relative difference norm. + /// + /// The first source array + /// Type of the norm + /// The optional operation mask + /// + public static double Norm(InputArray src1, + NormTypes normType = NormTypes.L2, InputArray? mask = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + src1.ThrowIfDisposed(); + var ret = NativeMethods.core_norm1(src1.CvPtr, (int) normType, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(mask); + return ret; + } + + /// + /// computes norm of selected part of the difference between two arrays + /// + /// The first source array + /// The second source array of the same size and the same type as src1 + /// Type of the norm + /// The optional operation mask + /// + public static double Norm(InputArray src1, InputArray src2, + NormTypes normType = NormTypes.L2, InputArray? mask = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + var ret = NativeMethods.core_norm2(src1.CvPtr, src2.CvPtr, (int) normType, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(mask); + return ret; + } + + #endregion + + #region BatchDistance + + /// + /// naive nearest neighbor finder + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void BatchDistance(InputArray src1, InputArray src2, + // ReSharper disable once IdentifierTypo + OutputArray dist, int dtype, OutputArray nidx, + NormTypes normType = NormTypes.L2, + int k = 0, InputArray? mask = null, + int update = 0, bool crosscheck = false) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dist == null) + throw new ArgumentNullException(nameof(dist)); + if (nidx == null) + throw new ArgumentNullException(nameof(nidx)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dist.ThrowIfNotReady(); + nidx.ThrowIfNotReady(); + NativeMethods.core_batchDistance(src1.CvPtr, src2.CvPtr, dist.CvPtr, dtype, nidx.CvPtr, + (int) normType, k, ToPtr(mask), update, crosscheck ? 1 : 0); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dist); + GC.KeepAlive(nidx); + dist.Fix(); + nidx.Fix(); + GC.KeepAlive(mask); + } + + #endregion + + #region Normalize + + /// + /// 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 + /// 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 static void Normalize(InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, + NormTypes normType = NormTypes.L2, int dtype = -1, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_normalize(src.CvPtr, dst.CvPtr, alpha, beta, (int) normType, dtype, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(mask); + } + + #endregion + + #region MinMaxLoc + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + NativeMethods.core_minMaxLoc1(src.CvPtr, out minVal, out maxVal); + GC.KeepAlive(src); + } + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// 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) + { + MinMaxLoc(src, out _, out _, out minLoc, out maxLoc); + } + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// The source single-channel array + /// 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 static void MinMaxLoc(InputArray src, out double minVal, out double maxVal, + out Point minLoc, out Point maxLoc, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + NativeMethods.core_minMaxLoc2(src.CvPtr, out minVal, out maxVal, out minLoc, out maxLoc, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(mask); + } + + #endregion + + #region MinMaxIdx + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + NativeMethods.core_minMaxIdx1(src.CvPtr, out minVal, out maxVal); + GC.KeepAlive(src); + } + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// The source single-channel array + /// + /// + public static void MinMaxIdx(InputArray src, int[] minIdx, int[] maxIdx) + { + MinMaxIdx(src, out _, out _, minIdx, maxIdx); + } + + /// + /// finds global minimum and maximum array elements and returns their values and their locations + /// + /// 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, + int[] minIdx, int[] maxIdx, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (minIdx == null) + throw new ArgumentNullException(nameof(minIdx)); + if (maxIdx == null) + throw new ArgumentNullException(nameof(maxIdx)); + src.ThrowIfDisposed(); + NativeMethods.core_minMaxIdx2(src.CvPtr, out minVal, out maxVal, minIdx, maxIdx, ToPtr(mask)); + GC.KeepAlive(src); + } + + #endregion + + #region Reduce + + /// + /// 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. + /// Its size and type is defined by dim and dtype parameters + /// 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 static void Reduce(InputArray src, OutputArray dst, ReduceDimension dim, ReduceTypes rtype, int dtype) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_reduce(src.CvPtr, dst.CvPtr, (int) dim, (int) rtype, dtype); + dst.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(dst); + } + + #endregion + + #region Merge + + /// + /// makes multi-channel array out of several single-channel arrays + /// + /// + /// + public static void Merge(Mat[] mv, Mat dst) + { + if (mv == null) + throw new ArgumentNullException(nameof(mv)); + if (mv.Length == 0) + throw new ArgumentException("mv.Length == 0"); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + foreach (var m in mv) + { + if (m == null) + throw new ArgumentException("mv contains null element"); + m.ThrowIfDisposed(); + } + + dst.ThrowIfDisposed(); + + var mvPtr = new IntPtr[mv.Length]; + for (var i = 0; i < mv.Length; i++) + { + mvPtr[i] = mv[i].CvPtr; + } + + NativeMethods.core_merge(mvPtr, (uint) mvPtr.Length, dst.CvPtr); + GC.KeepAlive(mv); + GC.KeepAlive(dst); + } + + #endregion + + #region Split + + /// + /// Copies each plane of a multi-channel array to a dedicated array + /// + /// The source multi-channel array + /// The destination array or vector of arrays; + /// The number of arrays must match mtx.channels() . + /// The arrays themselves will be reallocated if needed + public static void Split(Mat src, out Mat[] mv) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + NativeMethods.core_split(src.CvPtr, out var mvPtr); + + using (var vec = new VectorOfMat(mvPtr)) + { + mv = vec.ToArray(); + } + + GC.KeepAlive(src); + } + + /// + /// Copies each plane of a multi-channel array to a dedicated array + /// + /// The source multi-channel array + /// The number of arrays must match mtx.channels() . + /// The arrays themselves will be reallocated if needed + public static Mat[] Split(Mat src) + { + Split(src, out var mv); + return mv; + } + + #endregion + + #region MixChannels + + /// + /// copies selected channels from the input arrays to the selected channels of the output arrays + /// + /// + /// + /// + public static void MixChannels(Mat[] src, Mat[] dst, int[] fromTo) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (fromTo == null) + throw new ArgumentNullException(nameof(fromTo)); + if (src.Length == 0) + throw new ArgumentException("src.Length == 0"); + if (dst.Length == 0) + throw new ArgumentException("dst.Length == 0"); + if (fromTo.Length == 0 || fromTo.Length % 2 != 0) + throw new ArgumentException("fromTo.Length == 0"); + var srcPtr = new IntPtr[src.Length]; + var dstPtr = new IntPtr[dst.Length]; + for (var i = 0; i < src.Length; i++) + { + src[i].ThrowIfDisposed(); + srcPtr[i] = src[i].CvPtr; + } + + for (var i = 0; i < dst.Length; i++) + { + dst[i].ThrowIfDisposed(); + dstPtr[i] = dst[i].CvPtr; + } + + NativeMethods.core_mixChannels(srcPtr, (uint) src.Length, dstPtr, (uint) dst.Length, + fromTo, (uint) (fromTo.Length / 2)); + + GC.KeepAlive(src); + GC.KeepAlive(dst); + } + + #endregion + + #region ExtractChannel + + /// + /// extracts a single channel from src (coi is 0-based index) + /// + /// + /// + /// + public static void ExtractChannel(InputArray src, OutputArray dst, int coi) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_extractChannel(src.CvPtr, dst.CvPtr, coi); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region InsertChannel + + /// + /// inserts a single channel to dst (coi is 0-based index) + /// + /// + /// + /// + public static void InsertChannel(InputArray src, InputOutputArray dst, int coi) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_insertChannel(src.CvPtr, dst.CvPtr, coi); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Flip + + /// + /// reverses the order of the rows, columns or both in a matrix + /// + /// 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, + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_flip(src.CvPtr, dst.CvPtr, (int) flipCode); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Repeat + + /// + /// replicates the input matrix the specified number of times in the horizontal and/or vertical direction + /// + /// The source array to replicate + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_repeat1(src.CvPtr, ny, nx, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// replicates the input matrix the specified number of times in the horizontal and/or vertical direction + /// + /// The source array to replicate + /// How many times the src is repeated along the vertical axis + /// How many times the src is repeated along the horizontal axis + /// + public static Mat Repeat(Mat src, int ny, int nx) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + var matPtr = NativeMethods.core_repeat2(src.CvPtr, ny, nx); + GC.KeepAlive(src); + return new Mat(matPtr); + } + + #endregion + + #region HConcat + + /// + /// + /// + /// + /// + public static void HConcat(Mat[] src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (src.Length == 0) + throw new ArgumentException("src.Length == 0"); + var srcPtr = new IntPtr[src.Length]; + for (var i = 0; i < src.Length; i++) + { + src[i].ThrowIfDisposed(); + srcPtr[i] = src[i].CvPtr; + } + + NativeMethods.core_hconcat1(srcPtr, (uint) src.Length, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// + /// + /// + /// + /// + public static void HConcat(InputArray src1, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_hconcat2(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region VConcat + + /// + /// + /// + /// + /// + public static void VConcat(Mat[] src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (src.Length == 0) + throw new ArgumentException("src.Length == 0"); + var srcPtr = new IntPtr[src.Length]; + for (var i = 0; i < src.Length; i++) + { + src[i].ThrowIfDisposed(); + srcPtr[i] = src[i].CvPtr; + } + + NativeMethods.core_vconcat1(srcPtr, (uint) src.Length, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// + /// + /// + /// + /// + public static void VConcat(InputArray src1, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_vconcat2(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region BitwiseAnd + + /// + /// computes bitwise conjunction of the two arrays (dst = src1 & src2) + /// + /// + /// + /// + /// + public static void BitwiseAnd(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_bitwise_and(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(mask); + } + + #endregion + + #region BitwiseOr + + /// + /// computes bitwise disjunction of the two arrays (dst = src1 | src2) + /// + /// + /// + /// + /// + public static void BitwiseOr(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_bitwise_or(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + + #endregion + + #region BitwiseXor + + /// + /// computes bitwise exclusive-or of the two arrays (dst = src1 ^ src2) + /// + /// + /// + /// + /// + public static void BitwiseXor(InputArray src1, InputArray src2, OutputArray dst, InputArray? mask = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_bitwise_xor(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + + #endregion + + #region BitwiseNot + + /// + /// inverts each bit of array (dst = ~src) + /// + /// + /// + /// + public static void BitwiseNot(InputArray src, OutputArray dst, InputArray? mask = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_bitwise_not(src.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + + #endregion + + #region Absdiff + + /// + /// computes element-wise absolute difference of two arrays (dst = abs(src1 - src2)) + /// + /// + /// + /// + public static void Absdiff(InputArray src1, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_absdiff(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region InRange + + /// + /// set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) + /// + /// The first source array + /// The inclusive lower boundary array of the same size and type as src + /// The exclusive upper boundary array of the same size and type as src + /// The destination array, will have the same size as src and CV_8U type + public static void InRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (lowerb == null) + throw new ArgumentNullException(nameof(lowerb)); + if (upperb == null) + throw new ArgumentNullException(nameof(upperb)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + lowerb.ThrowIfDisposed(); + upperb.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_inRange_InputArray(src.CvPtr, lowerb.CvPtr, upperb.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(lowerb); + GC.KeepAlive(upperb); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) + /// + /// The first source array + /// The inclusive lower boundary array of the same size and type as src + /// The exclusive upper boundary array of the same size and type as src + /// The destination array, will have the same size as src and CV_8U type + public static void InRange(InputArray src, Scalar lowerb, Scalar upperb, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_inRange_Scalar(src.CvPtr, lowerb, upperb, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Compare + + /// + /// Performs the per-element comparison of two arrays or an array and scalar value. + /// + /// first input array or a scalar; when it is an array, it must have a single channel. + /// second input array or a scalar; when it is an array, it must have a single channel. + /// 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) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_compare(src1.CvPtr, src2.CvPtr, dst.CvPtr, (int) cmpop); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Min + + /// + /// computes per-element minimum of two arrays (dst = min(src1, src2)) + /// + /// + /// + /// + public static void Min(InputArray src1, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_min1(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// computes per-element minimum of two arrays (dst = min(src1, src2)) + /// + /// + /// + /// + public static void Min(Mat src1, Mat src2, Mat dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + NativeMethods.core_min_MatMat(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + } + + /// + /// computes per-element minimum of array and scalar (dst = min(src1, src2)) + /// + /// + /// + /// + public static void Min(Mat src1, double src2, Mat dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + NativeMethods.core_min_MatDouble(src1.CvPtr, src2, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(dst); + } + + #endregion + + #region Max + + /// + /// computes per-element maximum of two arrays (dst = max(src1, src2)) + /// + /// + /// + /// + public static void Max(InputArray src1, InputArray src2, OutputArray dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_max1(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// computes per-element maximum of two arrays (dst = max(src1, src2)) + /// + /// + /// + /// + public static void Max(Mat src1, Mat src2, Mat dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + NativeMethods.core_max_MatMat(src1.CvPtr, src2.CvPtr, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + } + + /// + /// computes per-element maximum of array and scalar (dst = max(src1, src2)) + /// + /// + /// + /// + public static void Max(Mat src1, double src2, Mat dst) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + NativeMethods.core_max_MatDouble(src1.CvPtr, src2, dst.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(dst); + } + + #endregion + + #region Sqrt + + /// + /// computes square root of each matrix element (dst = src**0.5) + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_sqrt(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Pow + + /// + /// raises the input matrix elements to the specified power (b = a**power) + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_pow_Mat(src.CvPtr, power, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Exp + + /// + /// computes exponent of each matrix element (dst = e**src) + /// + /// The source array + /// The destination array; will have the same size and same type as src + public static void Exp(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_exp_Mat(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Log + + /// + /// computes natural logarithm of absolute value of each matrix element: dst = log(abs(src)) + /// + /// The source array + /// The destination array; will have the same size and same type as src + public static void Log(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_log_Mat(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region CubeRoot + + /// + /// computes cube root of the argument + /// + /// + /// + public static float CubeRoot(float val) + { + return NativeMethods.core_cubeRoot(val); + } + + #endregion + + #region FastAtan2 + + /// + /// computes the angle in degrees (0..360) of the vector (x,y) + /// + /// + /// + /// + public static float FastAtan2(float y, float x) + { + return NativeMethods.core_fastAtan2(y, x); + } + + #endregion + + #region PolarToCart + + /// + /// converts polar coordinates to Cartesian + /// + /// + /// + /// + /// + /// + public static void PolarToCart(InputArray magnitude, InputArray angle, + OutputArray x, OutputArray y, bool angleInDegrees = false) + { + if (magnitude == null) + throw new ArgumentNullException(nameof(magnitude)); + if (angle == null) + throw new ArgumentNullException(nameof(angle)); + if (x == null) + throw new ArgumentNullException(nameof(x)); + if (y == null) + throw new ArgumentNullException(nameof(y)); + magnitude.ThrowIfDisposed(); + angle.ThrowIfDisposed(); + x.ThrowIfNotReady(); + y.ThrowIfNotReady(); + NativeMethods.core_polarToCart(magnitude.CvPtr, angle.CvPtr, x.CvPtr, y.CvPtr, angleInDegrees ? 1 : 0); + GC.KeepAlive(magnitude); + GC.KeepAlive(angle); + GC.KeepAlive(x); + GC.KeepAlive(y); + x.Fix(); + y.Fix(); + } + + #endregion + + #region CartToPolar + + /// + /// converts Cartesian coordinates to polar + /// + /// + /// + /// + /// + /// + public static void CartToPolar(InputArray x, InputArray y, + OutputArray magnitude, OutputArray angle, bool angleInDegrees = false) + { + if (x == null) + throw new ArgumentNullException(nameof(x)); + if (y == null) + throw new ArgumentNullException(nameof(y)); + if (magnitude == null) + throw new ArgumentNullException(nameof(magnitude)); + if (angle == null) + throw new ArgumentNullException(nameof(angle)); + x.ThrowIfDisposed(); + y.ThrowIfDisposed(); + magnitude.ThrowIfNotReady(); + angle.ThrowIfNotReady(); + NativeMethods.core_cartToPolar(x.CvPtr, y.CvPtr, magnitude.CvPtr, angle.CvPtr, angleInDegrees ? 1 : 0); + GC.KeepAlive(x); + GC.KeepAlive(y); + GC.KeepAlive(magnitude); + GC.KeepAlive(angle); + magnitude.Fix(); + angle.Fix(); + } + + #endregion + + #region Phase + + /// + /// computes angle (angle(i)) of each (x(i), y(i)) vector + /// + /// + /// + /// + /// + public static void Phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false) + { + if (x == null) + throw new ArgumentNullException(nameof(x)); + if (y == null) + throw new ArgumentNullException(nameof(y)); + if (angle == null) + throw new ArgumentNullException(nameof(angle)); + x.ThrowIfDisposed(); + y.ThrowIfDisposed(); + angle.ThrowIfNotReady(); + NativeMethods.core_phase(x.CvPtr, y.CvPtr, angle.CvPtr, angleInDegrees ? 1 : 0); + GC.KeepAlive(x); + GC.KeepAlive(y); + GC.KeepAlive(angle); + angle.Fix(); + } + + #endregion + + #region Magnitude + + /// + /// computes magnitude (magnitude(i)) of each (x(i), y(i)) vector + /// + /// + /// + /// + public static void Magnitude(InputArray x, InputArray y, OutputArray magnitude) + { + if (x == null) + throw new ArgumentNullException(nameof(x)); + if (y == null) + throw new ArgumentNullException(nameof(y)); + if (magnitude == null) + throw new ArgumentNullException(nameof(magnitude)); + x.ThrowIfDisposed(); + y.ThrowIfDisposed(); + magnitude.ThrowIfNotReady(); + NativeMethods.core_magnitude_Mat(x.CvPtr, y.CvPtr, magnitude.CvPtr); + GC.KeepAlive(x); + GC.KeepAlive(y); + GC.KeepAlive(magnitude); + magnitude.Fix(); + } + + #endregion + + #region CheckRange + + /// + /// 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, + /// or they throw an exception. + /// + public static bool CheckRange(InputArray src, bool quiet = true) + { + return CheckRange(src, quiet, out _); + } + + /// + /// 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, + /// 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 static bool CheckRange(InputArray src, bool quiet, out Point pos, + double minVal = double.MinValue, double maxVal = double.MaxValue) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + var ret = NativeMethods.core_checkRange(src.CvPtr, quiet ? 1 : 0, out pos, minVal, maxVal); + GC.KeepAlive(src); + return ret != 0; + } + + #endregion + + #region PatchNaNs + + /// + /// converts NaN's to the given number + /// + /// + /// + public static void PatchNaNs(InputOutputArray a, double val = 0) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfNotReady(); + NativeMethods.core_patchNaNs(a.CvPtr, val); + GC.KeepAlive(a); + } + + #endregion + + #region Gemm + + /// + /// implements generalized matrix product algorithm GEMM from BLAS + /// + /// + /// + /// + /// + /// + /// + /// + // ReSharper disable once IdentifierTypo + public static void Gemm(InputArray src1, InputArray src2, double alpha, + InputArray src3, double gamma, OutputArray dst, GemmFlags flags = GemmFlags.None) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (src3 == null) + throw new ArgumentNullException(nameof(src3)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + src3.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_gemm(src1.CvPtr, src2.CvPtr, alpha, src3.CvPtr, gamma, dst.CvPtr, (int) flags); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(src3); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region MulTransposed + + /// + /// multiplies matrix by its transposition from the left or from the right + /// + /// The source matrix + /// The destination square matrix + /// 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 static void MulTransposed(InputArray src, OutputArray dst, bool aTa, + InputArray? delta = null, double scale = 1, int dtype = -1) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_mulTransposed(src.CvPtr, dst.CvPtr, aTa ? 1 : 0, ToPtr(delta), scale, dtype); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(delta); + dst.Fix(); + } + + #endregion + + #region Transpose + + /// + /// transposes the matrix + /// + /// The source array + /// The destination array of the same type as src + public static void Transpose(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_transpose(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Transform + + /// + /// performs affine transformation of each element of multi-channel input matrix + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + m.ThrowIfDisposed(); + NativeMethods.core_transform(src.CvPtr, dst.CvPtr, m.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(m); + dst.Fix(); + } + + #endregion + + #region PerspectiveTransform + + /// + /// performs perspective transformation of each element of multi-channel input matrix + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + m.ThrowIfDisposed(); + NativeMethods.core_perspectiveTransform(src.CvPtr, dst.CvPtr, m.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(m); + dst.Fix(); + } + + /// + /// performs perspective transformation of each element of multi-channel input matrix + /// + /// The source two-channel or three-channel floating-point array; + /// each element is 2D/3D vector to be transformed + /// 3x3 or 4x4 transformation matrix + /// The destination array; it will have the same size and same type as src + public static Point2f[] PerspectiveTransform(IEnumerable src, Mat m) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + + using (var srcMat = Mat.FromArray(src)) + using (var dstMat = new Mat()) + { + NativeMethods.core_perspectiveTransform_Mat(srcMat.CvPtr, dstMat.CvPtr, m.CvPtr); + GC.KeepAlive(m); + return dstMat.ToArray(); + } + } + + /// + /// performs perspective transformation of each element of multi-channel input matrix + /// + /// The source two-channel or three-channel floating-point array; + /// each element is 2D/3D vector to be transformed + /// 3x3 or 4x4 transformation matrix + /// The destination array; it will have the same size and same type as src + public static Point2d[] PerspectiveTransform(IEnumerable src, Mat m) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + + using (var srcMat = Mat.FromArray(src)) + using (var dstMat = new Mat()) + { + NativeMethods.core_perspectiveTransform_Mat(srcMat.CvPtr, dstMat.CvPtr, m.CvPtr); + GC.KeepAlive(m); + return dstMat.ToArray(); + } + } + + /// + /// performs perspective transformation of each element of multi-channel input matrix + /// + /// The source two-channel or three-channel floating-point array; + /// each element is 2D/3D vector to be transformed + /// 3x3 or 4x4 transformation matrix + /// The destination array; it will have the same size and same type as src + public static Point3f[] PerspectiveTransform(IEnumerable src, Mat m) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + + using (var srcMat = Mat.FromArray(src)) + using (var dstMat = new Mat()) + { + NativeMethods.core_perspectiveTransform_Mat(srcMat.CvPtr, dstMat.CvPtr, m.CvPtr); + GC.KeepAlive(m); + return dstMat.ToArray(); + } + } + + /// + /// performs perspective transformation of each element of multi-channel input matrix + /// + /// The source two-channel or three-channel floating-point array; + /// each element is 2D/3D vector to be transformed + /// 3x3 or 4x4 transformation matrix + /// The destination array; it will have the same size and same type as src + public static Point3d[] PerspectiveTransform(IEnumerable src, Mat m) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + + using (var srcMat = Mat.FromArray(src)) + using (var dstMat = new Mat()) + { + NativeMethods.core_perspectiveTransform_Mat(srcMat.CvPtr, dstMat.CvPtr, m.CvPtr); + GC.KeepAlive(m); + return dstMat.ToArray(); + } + } + + #endregion + + #region CompleteSymm + + /// + /// extends the symmetrical matrix from the lower half or from the upper half + /// + /// Input-output floating-point square matrix + /// 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) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + mtx.ThrowIfNotReady(); + NativeMethods.core_completeSymm(mtx.CvPtr, lowerToUpper ? 1 : 0); + GC.KeepAlive(mtx); + mtx.Fix(); + } + + #endregion + + #region SetIdentity + + /// + /// 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) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + mtx.ThrowIfNotReady(); + var s0 = s.GetValueOrDefault(new Scalar(1)); + NativeMethods.core_setIdentity(mtx.CvPtr, s0); + GC.KeepAlive(mtx); + mtx.Fix(); + } + + #endregion + + #region Determinant + + /// + /// 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) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + mtx.ThrowIfDisposed(); + var ret = NativeMethods.core_determinant(mtx.CvPtr); + GC.KeepAlive(mtx); + return ret; + } + + #endregion + + #region Trace + + /// + /// computes trace of a matrix + /// + /// The source matrix + /// + public static Scalar Trace(InputArray mtx) + { + if (mtx == null) + throw new ArgumentNullException(nameof(mtx)); + mtx.ThrowIfDisposed(); + var ret = NativeMethods.core_trace(mtx.CvPtr); + GC.KeepAlive(mtx); + return ret; + } + + #endregion + + #region Invert + + /// + /// computes inverse or pseudo-inverse matrix + /// + /// The source floating-point MxN matrix + /// The destination matrix; will have NxM size and the same type as src + /// The inversion method + /// + public static double Invert(InputArray src, OutputArray dst, + DecompTypes flags = DecompTypes.LU) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var ret = NativeMethods.core_invert(src.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + return ret; + } + + #endregion + + #region Solve + + /// + /// solves linear system or a least-square problem + /// + /// + /// + /// + /// + /// + public static bool Solve(InputArray src1, InputArray src2, OutputArray dst, + DecompTypes flags = DecompTypes.LU) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var ret = NativeMethods.core_solve(src1.CvPtr, src2.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + dst.Fix(); + return ret != 0; + } + + #endregion + + #region SolveLP + + /// + /// 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). + /// 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 + /// 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 + /// formulation above.It will contain 64-bit floating point numbers. + /// + // ReSharper disable once InconsistentNaming + // ReSharper disable once IdentifierTypo + public static SolveLPResult SolveLP(Mat func, Mat constr, Mat z) + { + if (func == null) + throw new ArgumentNullException(nameof(func)); + if (constr == null) + throw new ArgumentNullException(nameof(constr)); + if (z == null) + throw new ArgumentNullException(nameof(z)); + var ret = NativeMethods.core_solveLP(func.CvPtr, constr.CvPtr, z.CvPtr); + GC.KeepAlive(func); + GC.KeepAlive(constr); + GC.KeepAlive(z); + return (SolveLPResult) ret; + } + + #endregion + + #region Sort + + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_sort(src.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region SortIdx + + /// + /// sorts independently each matrix row or each matrix column + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_sortIdx(src.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region SolveCubic + + /// + /// finds real roots of a cubic polynomial + /// + /// 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) + { + if (coeffs == null) + throw new ArgumentNullException(nameof(coeffs)); + if (roots == null) + throw new ArgumentNullException(nameof(roots)); + coeffs.ThrowIfDisposed(); + roots.ThrowIfNotReady(); + var ret = NativeMethods.core_solveCubic(coeffs.CvPtr, roots.CvPtr); + GC.KeepAlive(coeffs); + GC.KeepAlive(roots); + roots.Fix(); + return ret; + } + + #endregion + + #region SolvePoly + + /// + /// finds real and complex roots of a polynomial + /// + /// The array of polynomial coefficients + /// 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) + { + if (coeffs == null) + throw new ArgumentNullException(nameof(coeffs)); + if (roots == null) + throw new ArgumentNullException(nameof(roots)); + coeffs.ThrowIfDisposed(); + roots.ThrowIfNotReady(); + var ret = NativeMethods.core_solvePoly(coeffs.CvPtr, roots.CvPtr, maxIters); + GC.KeepAlive(coeffs); + GC.KeepAlive(roots); + roots.Fix(); + return ret; + } + + #endregion + + #region Eigen + + /// + /// Computes eigenvalues and eigenvectors of a symmetric matrix. + /// + /// 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 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 + /// as subsequent matrix rows, in the same order as the corresponding eigenvalues + /// + public static bool Eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (eigenvalues == null) + throw new ArgumentNullException(nameof(eigenvalues)); + if (eigenvectors == null) + throw new ArgumentNullException(nameof(eigenvectors)); + src.ThrowIfDisposed(); + eigenvalues.ThrowIfNotReady(); + eigenvectors.ThrowIfNotReady(); + var ret = NativeMethods.core_eigen(src.CvPtr, eigenvalues.CvPtr, eigenvectors.CvPtr); + eigenvalues.Fix(); + eigenvectors.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(eigenvalues); + GC.KeepAlive(eigenvectors); + return ret != 0; + } + + #endregion + + #region CalcCovarMatrix + + /// + /// computes covariation matrix of a set of samples + /// + /// + /// + /// + /// + public static void CalcCovarMatrix(Mat[] samples, Mat covar, Mat mean, CovarFlags flags) + { + CalcCovarMatrix(samples, covar, mean, flags, MatType.CV_64F); + } + + /// + /// computes covariation matrix of a set of samples + /// + /// + /// + /// + /// + /// + public static void CalcCovarMatrix(Mat[] samples, Mat covar, Mat mean, + CovarFlags flags, MatType ctype) + { + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (covar == null) + throw new ArgumentNullException(nameof(covar)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + covar.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + var samplesPtr = EnumerableEx.SelectPtrs(samples); + NativeMethods.core_calcCovarMatrix_Mat(samplesPtr, samples.Length, covar.CvPtr, mean.CvPtr, (int) flags, + ctype); + GC.KeepAlive(samples); + GC.KeepAlive(covar); + GC.KeepAlive(mean); + } + + /// + /// computes covariation matrix of a set of samples + /// + /// + /// + /// + /// + // ReSharper disable once IdentifierTypo + public static void CalcCovarMatrix(InputArray samples, OutputArray covar, + InputOutputArray mean, CovarFlags flags) + { + CalcCovarMatrix(samples, covar, mean, flags, MatType.CV_64F); + } + + /// + /// computes covariation matrix of a set of samples + /// + /// + /// + /// + /// + /// + public static void CalcCovarMatrix(InputArray samples, OutputArray covar, + InputOutputArray mean, CovarFlags flags, MatType ctype) + { + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (covar == null) + throw new ArgumentNullException(nameof(covar)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + samples.ThrowIfDisposed(); + covar.ThrowIfNotReady(); + mean.ThrowIfNotReady(); + NativeMethods.core_calcCovarMatrix_InputArray(samples.CvPtr, covar.CvPtr, mean.CvPtr, (int) flags, ctype); + GC.KeepAlive(samples); + GC.KeepAlive(covar); + GC.KeepAlive(mean); + covar.Fix(); + mean.Fix(); + } + + #endregion + + #region PCA + + /// + /// 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. + /// + /// maximum 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) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (eigenvectors == null) + throw new ArgumentNullException(nameof(eigenvectors)); + data.ThrowIfDisposed(); + mean.ThrowIfNotReady(); + eigenvectors.ThrowIfNotReady(); + NativeMethods.core_PCACompute(data.CvPtr, mean.CvPtr, eigenvectors.CvPtr, maxComponents); + GC.KeepAlive(data); + GC.KeepAlive(mean); + GC.KeepAlive(eigenvectors); + mean.Fix(); + eigenvectors.Fix(); + } + + /// + /// + /// + /// + /// + /// + /// + public static void PCAComputeVar(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, double retainedVariance) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (eigenvectors == null) + throw new ArgumentNullException(nameof(eigenvectors)); + data.ThrowIfDisposed(); + mean.ThrowIfNotReady(); + eigenvectors.ThrowIfNotReady(); + NativeMethods.core_PCAComputeVar(data.CvPtr, mean.CvPtr, eigenvectors.CvPtr, retainedVariance); + GC.KeepAlive(data); + GC.KeepAlive(mean); + GC.KeepAlive(eigenvectors); + mean.Fix(); + eigenvectors.Fix(); + } + + /// + /// + /// + /// + /// + /// + /// + public static void PCAProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (eigenvectors == null) + throw new ArgumentNullException(nameof(eigenvectors)); + if (result == null) + throw new ArgumentNullException(nameof(result)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + eigenvectors.ThrowIfDisposed(); + result.ThrowIfNotReady(); + NativeMethods.core_PCAProject(data.CvPtr, mean.CvPtr, eigenvectors.CvPtr, result.CvPtr); + GC.KeepAlive(data); + GC.KeepAlive(mean); + GC.KeepAlive(eigenvectors); + GC.KeepAlive(result); + result.Fix(); + } + + /// + /// + /// + /// + /// + /// + /// + public static void PCABackProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (eigenvectors == null) + throw new ArgumentNullException(nameof(eigenvectors)); + if (result == null) + throw new ArgumentNullException(nameof(result)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + eigenvectors.ThrowIfDisposed(); + result.ThrowIfNotReady(); + NativeMethods.core_PCABackProject(data.CvPtr, mean.CvPtr, eigenvectors.CvPtr, result.CvPtr); + GC.KeepAlive(data); + GC.KeepAlive(mean); + GC.KeepAlive(eigenvectors); + GC.KeepAlive(result); + result.Fix(); + } + + #endregion + + #region SVD + + /// + /// computes SVD of src + /// + /// + /// + /// + /// + /// + // 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (u == null) + throw new ArgumentNullException(nameof(u)); + if (vt == null) + throw new ArgumentNullException(nameof(vt)); + src.ThrowIfDisposed(); + w.ThrowIfNotReady(); + u.ThrowIfNotReady(); + vt.ThrowIfNotReady(); + NativeMethods.core_SVDecomp(src.CvPtr, w.CvPtr, u.CvPtr, vt.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(w); + GC.KeepAlive(u); + GC.KeepAlive(vt); + w.Fix(); + u.Fix(); + vt.Fix(); + } + + /// + /// performs back substitution for the previously computed SVD + /// + /// + /// + /// + /// + /// +// ReSharper disable once InconsistentNaming + public static void SVBackSubst(InputArray w, InputArray u, InputArray vt, + InputArray rhs, OutputArray dst) + { + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (u == null) + throw new ArgumentNullException(nameof(u)); + if (vt == null) + throw new ArgumentNullException(nameof(vt)); + if (rhs == null) + throw new ArgumentNullException(nameof(rhs)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + w.ThrowIfDisposed(); + u.ThrowIfDisposed(); + vt.ThrowIfDisposed(); + rhs.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_SVBackSubst(w.CvPtr, u.CvPtr, vt.CvPtr, rhs.CvPtr, dst.CvPtr); + GC.KeepAlive(w); + GC.KeepAlive(u); + GC.KeepAlive(vt); + GC.KeepAlive(rhs); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Mahalanobis/Mahalonobis + + /// + /// + /// + /// + /// + /// + /// + public static double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar) + { + if (v1 == null) + throw new ArgumentNullException(nameof(v1)); + if (v2 == null) + throw new ArgumentNullException(nameof(v2)); + if (icovar == null) + throw new ArgumentNullException(nameof(icovar)); + v1.ThrowIfDisposed(); + v2.ThrowIfDisposed(); + icovar.ThrowIfDisposed(); + var res = NativeMethods.core_Mahalanobis(v1.CvPtr, v2.CvPtr, icovar.CvPtr); + GC.KeepAlive(v1); + GC.KeepAlive(v2); + GC.KeepAlive(icovar); + return res; + } + + /// + /// computes Mahalanobis distance between two vectors: sqrt((v1-v2)'*icovar*(v1-v2)), where icovar is the inverse covariation matrix + /// + /// + /// + /// + /// + public static double Mahalonobis(InputArray v1, InputArray v2, InputArray icovar) + { + return Mahalanobis(v1, v2, icovar); + } + + #endregion + + #region Dft/Idft + + /// + /// 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 + /// or convolution using DFT + public static void Dft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_dft(src.CvPtr, dst.CvPtr, (int) flags, nonzeroRows); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// Performs an inverse 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 + /// or convolution using DFT + public static void Idft(InputArray src, OutputArray dst, DftFlags flags = DftFlags.None, int nonzeroRows = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_idft(src.CvPtr, dst.CvPtr, (int) flags, nonzeroRows); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Dct/Idct + + /// + /// Performs forward or inverse 1D or 2D Discrete Cosine Transformation + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_dct(src.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// Performs inverse 1D or 2D Discrete Cosine Transformation + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_idct(src.CvPtr, dst.CvPtr, (int) flags); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region MulSpectrums + + /// + /// computes element-wise product of the two Fourier spectrums. The second spectrum can optionally be conjugated before the multiplication + /// + /// + /// + /// + /// + /// + public static void MulSpectrums( + InputArray a, InputArray b, OutputArray c, + DftFlags flags, bool conjB = false) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + if (c == null) + throw new ArgumentNullException(nameof(c)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + c.ThrowIfNotReady(); + NativeMethods.core_mulSpectrums(a.CvPtr, b.CvPtr, c.CvPtr, (int) flags, conjB ? 1 : 0); + GC.KeepAlive(a); + GC.KeepAlive(b); + GC.KeepAlive(c); + c.Fix(); + } + + #endregion + + #region GetOptimalDFTSize + + /// + /// computes the minimal vector size vecsize1 >= vecSize so that the dft() of the vector of length vecsize1 can be computed efficiently + /// + /// + /// + // ReSharper disable once InconsistentNaming + public static int GetOptimalDFTSize(int vecSize) + { + return NativeMethods.core_getOptimalDFTSize(vecSize); + } + + #endregion + + #region Kmeans + + /// + /// clusters the input data using k-Means algorithm + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static double Kmeans(InputArray data, int k, InputOutputArray bestLabels, + TermCriteria criteria, int attempts, KMeansFlags flags, OutputArray? centers = null) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (bestLabels == null) + throw new ArgumentNullException(nameof(bestLabels)); + data.ThrowIfDisposed(); + bestLabels.ThrowIfDisposed(); + var ret = NativeMethods.core_kmeans(data.CvPtr, k, bestLabels.CvPtr, criteria, attempts, (int) flags, + ToPtr(centers)); + bestLabels.Fix(); + centers?.Fix(); + GC.KeepAlive(data); + GC.KeepAlive(bestLabels); + GC.KeepAlive(centers); + return ret; + } + + #endregion + + #region TheRNG + + /// + /// returns the thread-local Random number generator + /// + /// + public static RNG TheRNG() + { + var state = NativeMethods.core_theRNG(); + return new RNG(state); + } + + #endregion + + #region Randu + + /// + /// fills array with uniformly-distributed random numbers from the range [low, high) + /// + /// 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 + public static void Randu(InputOutputArray dst, InputArray low, InputArray high) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (low == null) + throw new ArgumentNullException(nameof(low)); + if (high == null) + throw new ArgumentNullException(nameof(high)); + dst.ThrowIfNotReady(); + low.ThrowIfDisposed(); + high.ThrowIfDisposed(); + NativeMethods.core_randu_InputArray(dst.CvPtr, low.CvPtr, high.CvPtr); + GC.KeepAlive(dst); + GC.KeepAlive(low); + GC.KeepAlive(high); + dst.Fix(); + } + + /// + /// fills array with uniformly-distributed random numbers from the range [low, high) + /// + /// 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) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + dst.ThrowIfNotReady(); + NativeMethods.core_randu_Scalar(dst.CvPtr, low, high); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Randn + + /// + /// fills array with normally-distributed random numbers with the specified mean and the standard deviation + /// + /// 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) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (stddev == null) + throw new ArgumentNullException(nameof(stddev)); + dst.ThrowIfNotReady(); + mean.ThrowIfDisposed(); + stddev.ThrowIfDisposed(); + NativeMethods.core_randn_InputArray(dst.CvPtr, mean.CvPtr, stddev.CvPtr); + GC.KeepAlive(dst); + GC.KeepAlive(mean); + GC.KeepAlive(stddev); + dst.Fix(); + } + + /// + /// fills array with normally-distributed random numbers with the specified mean and the standard deviation + /// + /// 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) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + dst.ThrowIfNotReady(); + NativeMethods.core_randn_Scalar(dst.CvPtr, mean, stddev); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region RandShuffle + + /// + /// shuffles the input array elements + /// + /// 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. + /// If it is null, theRng() is used instead. + // ReSharper disable once IdentifierTypo + public static void RandShuffle(InputOutputArray dst, double iterFactor, RNG? rng = null) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + dst.ThrowIfNotReady(); + + if (rng == null) + { + NativeMethods.core_randShuffle(dst.CvPtr, iterFactor, IntPtr.Zero); + } + else + { + var state = rng.State; + NativeMethods.core_randShuffle(dst.CvPtr, iterFactor, ref state); + rng.State = state; + } + + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + + #region Write + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, int value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, float value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, double value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, string value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, Mat value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, SparseMat value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, IEnumerable value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + /// + public static void Write(FileStorage fs, string name, IEnumerable value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.Write(name, value); + } + + /// + /// + /// + /// + /// + public static void WriteScalar(FileStorage fs, int value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.WriteScalar(value); + } + + /// + /// + /// + /// + /// + public static void WriteScalar(FileStorage fs, float value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.WriteScalar(value); + } + + /// + /// + /// + /// + /// + public static void WriteScalar(FileStorage fs, double value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.WriteScalar(value); + } + + /// + /// + /// + /// + /// + public static void WriteScalar(FileStorage fs, string value) + { + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.WriteScalar(value); + } + + #endregion + + #region Read + + /// + /// + /// + /// + /// + /// + public static int ReadInt(FileNode node, int defaultValue = default) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadInt(defaultValue); + } + + /// + /// + /// + /// + /// + /// + public static float ReadFloat(FileNode node, float defaultValue = default) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadFloat(defaultValue); + } + + /// + /// + /// + /// + /// + /// + public static double ReadDouble(FileNode node, double defaultValue = default) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadDouble(defaultValue); + } + + /// + /// + /// + /// + /// + /// + public static string ReadString(FileNode node, string? defaultValue = default) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadString(defaultValue); + } + + /// + /// + /// + /// + /// + /// + public static Mat ReadMat(FileNode node, Mat? defaultMat = null) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadMat(defaultMat); + } + + /// + /// + /// + /// + /// + /// + public static SparseMat ReadSparseMat(FileNode node, SparseMat? defaultMat = null) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadSparseMat(defaultMat); + } + + /// + /// + /// + /// + /// + public static KeyPoint[] ReadKeyPoints(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadKeyPoints(); + } + + /// + /// + /// + /// + /// + public static DMatch[] ReadDMatches(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + return node.ReadDMatches(); + } + + #endregion + + #region Partition + + /// + /// Equivalence predicate (a boolean function of two arguments). + /// The predicate returns true when the elements are certainly in the same class, and returns false if they may or may not be in the same class. + /// + /// + /// + /// + /// + public delegate bool PartitionPredicate(T t1, T t2); + + /// + /// Splits an element set into equivalency classes. + /// Consider using GroupBy of Linq instead. + /// + /// + /// Set of elements stored as a vector. + /// Output vector of labels. It contains as many elements as vec. Each label labels[i] is a 0-based cluster index of vec[i] . + /// Equivalence predicate (a boolean function of two arguments). + /// The predicate returns true when the elements are certainly in the same class, and returns false if they may or may not be in the same class. + /// + public static int Partition(IEnumerable vec, out int[] labels, PartitionPredicate predicate) + { + var vecArray = EnumerableEx.ToArray(vec); + labels = new int[vecArray.Length]; + var groupHeads = new List(); + + var index = 0; + foreach (var t in vecArray) + { + var foundGroup = false; + + var label = 0; + foreach (var groupHeadElem in groupHeads) + { + if (predicate(groupHeadElem, t)) + { + labels[index] = label; + foundGroup = true; + break; + } + + label++; + } + + if (!foundGroup) + { + labels[index] = groupHeads.Count; + groupHeads.Add(t); + } + + index++; + } + + return groupHeads.Count; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2_features2d.cs b/OpenVinoOpenCvSharp/Cv2/Cv2_features2d.cs new file mode 100644 index 0000000..d3978f9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2_features2d.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +// ReSharper disable UnusedMember.Global +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp +{ + static partial class Cv2 + { + /// + /// Detects corners using the FAST algorithm + /// + /// grayscale image where keypoints (corners) are detected. + /// threshold on difference between intensity of the central pixel + /// and pixels of a circle around this pixel. + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var kp = new VectorOfKeyPoint()) + { + NativeMethods.features2d_FAST1(image.CvPtr, kp.CvPtr, threshold, nonmaxSupression ? 1 : 0); + GC.KeepAlive(image); + return kp.ToArray(); + } + } + + /// + /// Detects corners using the FAST algorithm + /// + /// grayscale image where keypoints (corners) are detected. + /// threshold on difference between intensity of the central pixel + /// and pixels of a circle around this pixel. + /// if true, non-maximum suppression is applied to + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var kp = new VectorOfKeyPoint()) + { + NativeMethods.features2d_FAST2(image.CvPtr, kp.CvPtr, threshold, nonmaxSupression ? 1 : 0, (int)type); + GC.KeepAlive(image); + return kp.ToArray(); + } + } + + /// + /// Detects corners using the AGAST algorithm + /// + /// grayscale image where keypoints (corners) are detected. + /// threshold on difference between intensity of the central pixel + /// and pixels of a circle around this pixel. + /// if true, non-maximum suppression is applied to + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var vector = new VectorOfKeyPoint()) + { + NativeMethods.features2d_AGAST(image.CvPtr, vector.CvPtr, threshold, nonmaxSuppression ? 1 : 0, + (int) type); + GC.KeepAlive(image); + return vector.ToArray(); + } + } + + /// + /// Draw keypoints. + /// + /// + /// + /// + /// + /// + public static void DrawKeypoints(Mat image, IEnumerable keypoints, Mat outImage, + Scalar? color = null, DrawMatchesFlags flags = DrawMatchesFlags.Default) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (outImage == null) + throw new ArgumentNullException(nameof(outImage)); + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + image.ThrowIfDisposed(); + outImage.ThrowIfDisposed(); + + var keypointsArray = EnumerableEx.ToArray(keypoints); + var color0 = color.GetValueOrDefault(Scalar.All(-1)); + NativeMethods.features2d_drawKeypoints(image.CvPtr, keypointsArray, keypointsArray.Length, + outImage.CvPtr, color0, (int)flags); + GC.KeepAlive(image); + GC.KeepAlive(outImage); + } + + /// + /// Draws matches of keypoints from two images on output image. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void DrawMatches( + Mat img1, + IEnumerable keypoints1, + Mat img2, + IEnumerable keypoints2, + IEnumerable matches1To2, + Mat outImg, + Scalar? matchColor = null, + Scalar? singlePointColor = null, + IEnumerable? matchesMask = null, + DrawMatchesFlags flags = DrawMatchesFlags.Default) + { + if (img1 == null) + throw new ArgumentNullException(nameof(img1)); + if (img2 == null) + throw new ArgumentNullException(nameof(img2)); + if (outImg == null) + throw new ArgumentNullException(nameof(outImg)); + if (keypoints1 == null) + throw new ArgumentNullException(nameof(keypoints1)); + if (keypoints2 == null) + throw new ArgumentNullException(nameof(keypoints2)); + if (matches1To2 == null) + throw new ArgumentNullException(nameof(matches1To2)); + img1.ThrowIfDisposed(); + img2.ThrowIfDisposed(); + outImg.ThrowIfDisposed(); + + var keypoints1Array = EnumerableEx.ToArray(keypoints1); + var keypoints2Array = EnumerableEx.ToArray(keypoints2); + var matches1To2Array = EnumerableEx.ToArray(matches1To2); + var matchColor0 = matchColor.GetValueOrDefault(Scalar.All(-1)); + var singlePointColor0 = singlePointColor.GetValueOrDefault(Scalar.All(-1)); + + byte[]? matchesMaskArray = null; + var matchesMaskLength = 0; + if (matchesMask != null) + { + matchesMaskArray = EnumerableEx.ToArray(matchesMask); + matchesMaskLength = matchesMaskArray.Length; + } + + NativeMethods.features2d_drawMatches1(img1.CvPtr, keypoints1Array, keypoints1Array.Length, + img2.CvPtr, keypoints2Array, keypoints2Array.Length, + matches1To2Array, matches1To2Array.Length, outImg.CvPtr, + matchColor0, singlePointColor0, matchesMaskArray, matchesMaskLength, (int)flags); + GC.KeepAlive(img1); + GC.KeepAlive(img2); + GC.KeepAlive(outImg); + } + + /// + /// Draws matches of keypints from two images on output image. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void DrawMatches(Mat img1, IEnumerable keypoints1, + Mat img2, IEnumerable keypoints2, + IEnumerable> matches1To2, Mat outImg, + Scalar? matchColor = null, Scalar? singlePointColor = null, + IEnumerable>? matchesMask = null, + DrawMatchesFlags flags = DrawMatchesFlags.Default) + { + if (img1 == null) + throw new ArgumentNullException(nameof(img1)); + if (img2 == null) + throw new ArgumentNullException(nameof(img2)); + if (outImg == null) + throw new ArgumentNullException(nameof(outImg)); + if (keypoints1 == null) + throw new ArgumentNullException(nameof(keypoints1)); + if (keypoints2 == null) + throw new ArgumentNullException(nameof(keypoints2)); + if (matches1To2 == null) + throw new ArgumentNullException(nameof(matches1To2)); + img1.ThrowIfDisposed(); + img2.ThrowIfDisposed(); + outImg.ThrowIfDisposed(); + + var keypoints1Array = EnumerableEx.ToArray(keypoints1); + var keypoints2Array = EnumerableEx.ToArray(keypoints2); + var matches1To2Array = EnumerableEx.SelectToArray(matches1To2, EnumerableEx.ToArray); + var matches1To2Size1 = matches1To2Array.Length; + var matches1To2Size2 = EnumerableEx.SelectToArray(matches1To2Array, dm => dm.Length); + var matchColor0 = matchColor.GetValueOrDefault(Scalar.All(-1)); + var singlePointColor0 = singlePointColor.GetValueOrDefault(Scalar.All(-1)); + + using (var matches1To2Ptr = new ArrayAddress2(matches1To2Array)) + { + if (matchesMask == null) + { + NativeMethods.features2d_drawMatches2(img1.CvPtr, keypoints1Array, keypoints1Array.Length, + img2.CvPtr, keypoints2Array, keypoints2Array.Length, + matches1To2Ptr, matches1To2Size1, matches1To2Size2, + outImg.CvPtr, matchColor0, singlePointColor0, + null, 0, null, (int)flags); + } + else + { + var matchesMaskArray = EnumerableEx.SelectToArray(matchesMask, EnumerableEx.ToArray); + var matchesMaskSize1 = matches1To2Array.Length; + var matchesMaskSize2 = EnumerableEx.SelectToArray(matchesMaskArray, dm => dm.Length); + using (var matchesMaskPtr = new ArrayAddress2(matchesMaskArray)) + { + NativeMethods.features2d_drawMatches2(img1.CvPtr, keypoints1Array, keypoints1Array.Length, + img2.CvPtr, keypoints2Array, keypoints2Array.Length, + matches1To2Ptr.Pointer, matches1To2Size1, matches1To2Size2, + outImg.CvPtr, matchColor0, singlePointColor0, + matchesMaskPtr, matchesMaskSize1, matchesMaskSize2, (int)flags); + } + } + GC.KeepAlive(img1); + GC.KeepAlive(img2); + GC.KeepAlive(outImg); + } + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void EvaluateFeatureDetector( + Mat img1, Mat img2, Mat H1to2, + ref KeyPoint[] keypoints1, ref KeyPoint[] keypoints2, + out float repeatability, out int correspCount) + { + if (img1 == null) + throw new ArgumentNullException(nameof(img1)); + if (img2 == null) + throw new ArgumentNullException(nameof(img2)); + if (H1to2 == null) + throw new ArgumentNullException(nameof(H1to2)); + if (keypoints1 == null) + throw new ArgumentNullException(nameof(keypoints1)); + if (keypoints2 == null) + throw new ArgumentNullException(nameof(keypoints2)); + + using (var keypoints1Vec = new VectorOfKeyPoint(keypoints1)) + using (var keypoints2Vec = new VectorOfKeyPoint(keypoints2)) + { + NativeMethods.features2d_evaluateFeatureDetector( + img1.CvPtr, img2.CvPtr, H1to2.CvPtr, + keypoints1Vec.CvPtr, keypoints2Vec.CvPtr, + out repeatability, out correspCount); + GC.KeepAlive(img1); + GC.KeepAlive(img2); + GC.KeepAlive(H1to2); + keypoints1 = keypoints1Vec.ToArray(); + keypoints2 = keypoints2Vec.ToArray(); + } + } + + /// + /// + /// + /// + /// + /// recallPrecisionCurve + public static Point2f[] ComputeRecallPrecisionCurve( + DMatch[][] matches1to2, byte[][] correctMatches1to2Mask) + { + if (matches1to2 == null) + throw new ArgumentNullException(nameof(matches1to2)); + if (correctMatches1to2Mask == null) + throw new ArgumentNullException(nameof(correctMatches1to2Mask)); + + using (var dm = new ArrayAddress2(matches1to2)) + using (var cm = new ArrayAddress2(correctMatches1to2Mask)) + using (var recall = new VectorOfPoint2f()) + { + NativeMethods.features2d_computeRecallPrecisionCurve( + dm.Pointer, dm.Dim1Length, dm.Dim2Lengths, + cm.Pointer, cm.Dim1Length, cm.Dim2Lengths, + recall.CvPtr); + return recall.ToArray(); + } + } + + /// + /// + /// + /// + /// + /// + public static float GetRecall( + IEnumerable recallPrecisionCurve, float lPrecision) + { + if (recallPrecisionCurve == null) + throw new ArgumentNullException(nameof(recallPrecisionCurve)); + + var array = EnumerableEx.ToArray(recallPrecisionCurve); + return NativeMethods.features2d_getRecall(array, array.Length, lPrecision); + } + + /// + /// + /// + /// + /// + /// + public static int GetNearestPoint( + IEnumerable recallPrecisionCurve, float lPrecision) + { + if (recallPrecisionCurve == null) + throw new ArgumentNullException(nameof(recallPrecisionCurve)); + var array = EnumerableEx.ToArray(recallPrecisionCurve); + return NativeMethods.features2d_getNearestPoint(array, array.Length, lPrecision); + } + } +} diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2_imgcodecs.cs b/OpenVinoOpenCvSharp/Cv2/Cv2_imgcodecs.cs new file mode 100644 index 0000000..b6a0724 --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2_imgcodecs.cs @@ -0,0 +1,251 @@ +using System; +using System.Collections.Generic; + +namespace OpenCvSharp +{ + static partial class Cv2 + { + /// + /// Loads an image from a file. + /// + /// Name of file to be loaded. + /// Specifies color type of the loaded image + /// + public static Mat ImRead(string fileName, ImreadModes flags = ImreadModes.Color) + { + return new Mat(fileName, flags); + } + + /// + /// Loads a multi-page image from a file. + /// + /// Name of file to be loaded. + /// A vector of Mat objects holding each page, if more than one. + /// Flag that can take values of @ref cv::ImreadModes, default with IMREAD_ANYCOLOR. + /// + public static bool ImReadMulti(string filename, out Mat[] mats, ImreadModes flags = ImreadModes.AnyColor) + { + if (filename == null) + throw new ArgumentNullException(nameof(filename)); + + using (var matsVec = new VectorOfMat()) + { + var ret = NativeMethods.imgcodecs_imreadmulti(filename, matsVec.CvPtr, (int) flags); + mats = matsVec.ToArray(); + return ret != 0; + } + } + + /// + /// Saves an image to a specified file. + /// + /// Name of the file. + /// Image to be saved. + /// Format-specific save parameters encoded as pairs + /// + public static bool ImWrite(string fileName, Mat img, int[]? prms = null) + { + if (string.IsNullOrEmpty(fileName)) + throw new ArgumentNullException(nameof(fileName)); + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (prms == null) + prms = new int[0]; + + var res = NativeMethods.imgcodecs_imwrite(fileName, img.CvPtr, prms, prms.Length) != 0; + GC.KeepAlive(img); + return res; + } + + /// + /// Saves an image to a specified file. + /// + /// Name of the file. + /// Image to be saved. + /// Format-specific save parameters encoded as pairs + /// + public static bool ImWrite(string fileName, Mat img, params ImageEncodingParam[] prms) + { + if (prms != null && prms.Length > 0) + { + var p = new List(); + foreach (var item in prms) + { + p.Add((int) item.EncodingId); + p.Add(item.Value); + } + return ImWrite(fileName, img, p.ToArray()); + } + + return ImWrite(fileName, img); + } + + /// + /// Saves an image to a specified file. + /// + /// Name of the file. + /// Image to be saved. + /// Format-specific save parameters encoded as pairs + /// + public static bool ImWrite(string fileName, IEnumerable img, int[]? prms = null) + { + if (string.IsNullOrEmpty(fileName)) + throw new ArgumentNullException(nameof(fileName)); + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (prms == null) + prms = new int[0]; + + using (var imgVec = new VectorOfMat(img)) + { + var res = NativeMethods.imgcodecs_imwrite_multi(fileName, imgVec.CvPtr, prms, prms.Length) != 0; + GC.KeepAlive(img); + return res; + } + } + + /// + /// Saves an image to a specified file. + /// + /// Name of the file. + /// Image to be saved. + /// Format-specific save parameters encoded as pairs + /// + public static bool ImWrite(string fileName, IEnumerable img, params ImageEncodingParam[] prms) + { + if (prms != null && prms.Length > 0) + { + var p = new List(); + foreach (var item in prms) + { + p.Add((int)item.EncodingId); + p.Add(item.Value); + } + return ImWrite(fileName, img, p.ToArray()); + } + + return ImWrite(fileName, img); + } + + /// + /// Reads image from the specified buffer in memory. + /// + /// The input array of vector of bytes. + /// The same flags as in imread + /// + public static Mat ImDecode(Mat buf, ImreadModes flags) + { + if (buf == null) + throw new ArgumentNullException(nameof(buf)); + buf.ThrowIfDisposed(); + var matPtr = NativeMethods.imgcodecs_imdecode_Mat(buf.CvPtr, (int) flags); + GC.KeepAlive(buf); + return new Mat(matPtr); + } + + /// + /// Reads image from the specified buffer in memory. + /// + /// The input array of vector of bytes. + /// The same flags as in imread + /// + public static Mat ImDecode(InputArray buf, ImreadModes flags) + { + if (buf == null) + throw new ArgumentNullException(nameof(buf)); + buf.ThrowIfDisposed(); + var matPtr = NativeMethods.imgcodecs_imdecode_InputArray(buf.CvPtr, (int) flags); + GC.KeepAlive(buf); + return new Mat(matPtr); + } + + /// + /// Reads image from the specified buffer in memory. + /// + /// The input array of vector of bytes. + /// The same flags as in imread + /// + public static Mat ImDecode(byte[] buf, ImreadModes flags) + { + if (buf == null) + throw new ArgumentNullException(nameof(buf)); + var matPtr = NativeMethods.imgcodecs_imdecode_vector( + buf, new IntPtr(buf.Length), (int) flags); + return new Mat(matPtr); + } + + /// + /// Compresses the image and stores it in the memory buffer + /// + /// The file extension that defines the output format + /// 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) + { + if (string.IsNullOrEmpty(ext)) + throw new ArgumentNullException(nameof(ext)); + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (prms == null) + prms = new int[0]; + img.ThrowIfDisposed(); + using (var bufVec = new VectorOfByte()) + { + var ret = NativeMethods.imgcodecs_imencode_vector(ext, img.CvPtr, bufVec.CvPtr, prms, prms.Length); + GC.KeepAlive(img); + buf = bufVec.ToArray(); + return ret != 0; + } + } + + /// + /// Compresses the image and stores it in the memory buffer + /// + /// The file extension that defines the output format + /// 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) + { + if (prms != null) + { + var p = new List(); + foreach (var item in prms) + { + p.Add((int) item.EncodingId); + p.Add(item.Value); + } + ImEncode(ext, img, out buf, p.ToArray()); + } + else + { + ImEncode(ext, img, out buf); + } + } + + /// + /// + /// + /// + /// + public static bool HaveImageReader(string fileName) + { + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + return NativeMethods.imgcodecs_haveImageReader(fileName) != 0; + } + + /// + /// + /// + /// + /// + public static bool HaveImageWriter(string fileName) + { + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + return NativeMethods.imgcodecs_haveImageWriter(fileName) != 0; + } + } +} diff --git a/OpenVinoOpenCvSharp/Cv2/Cv2_imgproc.cs b/OpenVinoOpenCvSharp/Cv2/Cv2_imgproc.cs new file mode 100644 index 0000000..5b500db --- /dev/null +++ b/OpenVinoOpenCvSharp/Cv2/Cv2_imgproc.cs @@ -0,0 +1,4563 @@ +using System; +using System.Collections.Generic; + +using OpenCvSharp.Util; + +// ReSharper disable InconsistentNaming +// ReSharper disable CommentTypo +// ReSharper disable IdentifierTypo + +namespace OpenCvSharp +{ + static partial class Cv2 + { + /// + /// Returns Gaussian filter coefficients. + /// + /// Aperture size. It should be odd and positive. + /// Gaussian standard deviation. + /// If it is non-positive, it is computed from ksize as `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. + /// Type of filter coefficients. It can be CV_32F or CV_64F. + /// + public static Mat? GetGaussianKernel(int ksize, double sigma, MatType? ktype = null) + { + var ktype0 = ktype.GetValueOrDefault(MatType.CV_64F); + var ret = NativeMethods.imgproc_getGaussianKernel(ksize, sigma, ktype0); + if (ret == IntPtr.Zero) + return null; + return new Mat(ret); + } + + /// + /// Returns filter coefficients for computing spatial image derivatives. + /// + /// Output matrix of row filter coefficients. It has the type ktype. + /// Output matrix of column filter coefficients. It has the type ktype. + /// Derivative order in respect of x. + /// Derivative order in respect of y. + /// Aperture size. It can be CV_SCHARR, 1, 3, 5, or 7. + /// Flag indicating whether to normalize (scale down) the filter coefficients or not. + /// Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. + /// If you are going to filter floating-point images, you are likely to use the normalized kernels. + /// But if you compute derivatives of an 8-bit image, store the results in a 16-bit image, + /// 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, + bool normalize = false, MatType? ktype = null) + { + if (kx == null) + throw new ArgumentNullException(nameof(kx)); + if (ky == null) + throw new ArgumentNullException(nameof(ky)); + kx.ThrowIfNotReady(); + ky.ThrowIfNotReady(); + + var ktype0 = ktype.GetValueOrDefault(MatType.CV_32F); + NativeMethods.imgproc_getDerivKernels( + kx.CvPtr, ky.CvPtr, dx, dy, ksize, normalize ? 1 : 0, ktype0); + GC.KeepAlive(kx); + GC.KeepAlive(ky); + kx.Fix(); + ky.Fix(); + } + + #region GetGaborKernel + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static Mat GetGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi, int ktype) + { + var matPtr = NativeMethods.imgproc_getGaborKernel(ksize, sigma, theta, lambd, gamma, psi, ktype); + return new Mat(matPtr); + } + #endregion + #region GetStructuringElement + /// + /// + /// + /// + /// + /// + public static Mat GetStructuringElement(MorphShapes shape, Size ksize) + { + return GetStructuringElement(shape, ksize, new Point(-1, -1)); + } + /// + /// + /// + /// + /// + /// + /// + public static Mat GetStructuringElement(MorphShapes shape, Size ksize, Point anchor) + { + var matPtr = NativeMethods.imgproc_getStructuringElement((int)shape, ksize, anchor); + return new Mat(matPtr); + } + #endregion + + #region MedianBlur + /// + /// Smoothes image using median filter + /// + /// The source 1-, 3- or 4-channel image. + /// When ksize is 3 or 5, the image depth should be CV_8U , CV_16U or CV_32F. + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_medianBlur(src.CvPtr, dst.CvPtr, ksize); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region GaussianBlur + /// + /// Blurs an image using a Gaussian filter. + /// + /// input image; the 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. + /// output image of the same size and type as src. + /// 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 static void GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, + double sigmaY = 0, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_GaussianBlur(src.CvPtr, dst.CvPtr, ksize, sigmaX, sigmaY, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region BilateralFilter + /// + /// Applies bilateral filter to the image + /// + /// The source 8-bit or floating-point, 1-channel or 3-channel image + /// The destination image; will have the same size and the same type as src + /// 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 + /// + public static void BilateralFilter(InputArray src, OutputArray dst, int d, double sigmaColor, + double sigmaSpace, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_bilateralFilter(src.CvPtr, dst.CvPtr, d, sigmaColor, sigmaSpace, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region AdaptiveBilateralFilter + /* + /// + /// Applies the adaptive bilateral filter to an image. + /// + /// The source image + /// The destination image; will have the same size and the same type as src + /// The kernel size. This is the neighborhood where the local variance will be calculated, + /// and where pixels will contribute (in a weighted manner). + /// 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. + /// Maximum allowed sigma color (will clamp the value calculated in the + /// ksize neighborhood. Larger value of the parameter means that more dissimilar 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 anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center + /// Pixel extrapolation method. + public static void AdaptiveBilateralFilter(InputArray src, OutputArray dst, Size ksize, + double sigmaSpace, double maxSigmaColor = 20.0, Point? anchor = null, BorderType borderType = BorderType.Default) + { + if (src == null) + throw new ArgumentNullException("src"); + if (dst == null) + throw new ArgumentNullException("dst"); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + Point anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); + NativeMethods.imgproc_adaptiveBilateralFilter(src.CvPtr, dst.CvPtr, ksize, + sigmaSpace, maxSigmaColor, anchor0, (int)borderType); + dst.Fix(); + } + */ + #endregion + #region BoxFilter + /// + /// Smoothes image using box filter + /// + /// The source image + /// The destination image; will have the same size and the same type as src + /// + /// 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 + public static void BoxFilter( + InputArray src, OutputArray dst, MatType ddepth, + Size ksize, Point? anchor = null, bool normalize = true, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); + NativeMethods.imgproc_boxFilter(src.CvPtr, dst.CvPtr, ddepth, ksize, anchor0, normalize ? 1 : 0, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Blur + /// + /// Smoothes image using normalized box filter + /// + /// The source image + /// The destination image; will have the same size and the same type as src + /// 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 + public static void Blur( + InputArray src, OutputArray dst, Size ksize, + Point? anchor = null, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); + NativeMethods.imgproc_blur(src.CvPtr, dst.CvPtr, ksize, anchor0, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Filter2D + /// + /// Convolves an image with the kernel + /// + /// The source image + /// The destination image. It will have the same size and the same number of channels as src + /// 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 + public static void Filter2D( + InputArray src, OutputArray dst, MatType ddepth, + InputArray kernel, Point? anchor = null, double delta = 0, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (kernel == null) + throw new ArgumentNullException(nameof(kernel)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + kernel.ThrowIfDisposed(); + var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); + NativeMethods.imgproc_filter2D(src.CvPtr, dst.CvPtr, ddepth, kernel.CvPtr, + anchor0, delta, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(kernel); + dst.Fix(); + } + #endregion + #region SepFilter2D + /// + /// Applies separable linear filter to an image + /// + /// The source image + /// The destination image; will have the same size and the same number of channels as src + /// 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 + public static void SepFilter2D( + InputArray src, OutputArray dst, MatType ddepth, InputArray kernelX, InputArray kernelY, + Point? anchor = null, double delta = 0, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (kernelX == null) + throw new ArgumentNullException(nameof(kernelX)); + if (kernelY == null) + throw new ArgumentNullException(nameof(kernelY)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + kernelX.ThrowIfDisposed(); + kernelY.ThrowIfDisposed(); + var anchor0 = anchor.GetValueOrDefault(new Point(-1, -1)); + NativeMethods.imgproc_sepFilter2D(src.CvPtr, dst.CvPtr, ddepth, + kernelX.CvPtr, kernelY.CvPtr, anchor0, delta, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(kernelX); + GC.KeepAlive(kernelY); + dst.Fix(); + } + #endregion + #region Sobel + /// + /// Calculates the first, second, third or mixed image derivatives using an extended Sobel operator + /// + /// The source image + /// The destination image; will have the same size and the same number of channels as src + /// 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 + public static void Sobel( + InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, + int ksize = 3, double scale = 1, double delta = 0, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_Sobel(src.CvPtr, dst.CvPtr, ddepth, xorder, yorder, + ksize, scale, delta, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Scharr + /// + /// Calculates the first x- or y- image derivative using Scharr operator + /// + /// The source image + /// The destination image; will have the same size and the same number of channels as src + /// 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 + public static void Scharr( + InputArray src, OutputArray dst, MatType ddepth, int xorder, int yorder, + double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_Scharr(src.CvPtr, dst.CvPtr, ddepth, xorder, yorder, + scale, delta, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Laplacian + /// + /// Calculates the Laplacian of an image + /// + /// Source image + /// Destination image; will have the same size and the same number of channels as src + /// 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 + public static void Laplacian( + InputArray src, OutputArray dst, MatType ddepth, + int ksize = 1, double scale = 1, double delta = 0, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_Laplacian(src.CvPtr, dst.CvPtr, ddepth, ksize, scale, delta, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Canny +#if LANG_JP + /// + /// Cannyアルゴリズムを用いて,画像のエッジを検出します. + /// + /// 8ビット,シングルチャンネルの入力画像 + /// 出力されるエッジのマップ. image と同じサイズ,同じ型 + /// ヒステリシスが存在する処理の,1番目の閾値 + /// ヒステリシスが存在する処理の,2番目の閾値 + /// Sobelオペレータのアパーチャサイズ [既定値はApertureSize.Size3] + /// 画像勾配の強度を求めるために,より精度の高い L2ノルムを利用するか,L1ノルムで十分(false)かを指定します. [既定値はfalse] +#else + /// + /// Finds edges in an image using Canny algorithm. + /// + /// Single-channel 8-bit input image + /// The output edge map. It will have the same size and the same type as image + /// 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] +#endif + public static void Canny(InputArray src, OutputArray edges, + double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (edges == null) + throw new ArgumentNullException(nameof(edges)); + src.ThrowIfDisposed(); + edges.ThrowIfNotReady(); + NativeMethods.imgproc_Canny(src.CvPtr, edges.CvPtr, threshold1, threshold2, apertureSize, L2gradient ? 1 : 0); + GC.KeepAlive(src); + GC.KeepAlive(edges); + edges.Fix(); + } + #endregion + #region CornerEigenValsAndVecs + /// + /// computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix. + /// + /// + /// + /// + /// + /// + public static void CornerEigenValsAndVecs( + InputArray src, OutputArray dst, int blockSize, int ksize, + BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_cornerEigenValsAndVecs(src.CvPtr, dst.CvPtr, blockSize, ksize, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region PreCornerDetect + /// + /// computes another complex cornerness criteria at each pixel + /// + /// + /// + /// + /// + public static void PreCornerDetect( + InputArray src, OutputArray dst, int ksize, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_preCornerDetect(src.CvPtr, dst.CvPtr, ksize, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region CornerSubPix + /// + /// adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria + /// + /// Input image. + /// 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 static Point2f[] CornerSubPix(InputArray image, IEnumerable inputCorners, + Size winSize, Size zeroZone, TermCriteria criteria) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (inputCorners == null) + throw new ArgumentNullException(nameof(inputCorners)); + image.ThrowIfDisposed(); + + var inputCornersSrc = EnumerableEx.ToArray(inputCorners); + var inputCornersCopy = new Point2f[inputCornersSrc.Length]; + Array.Copy(inputCornersSrc, inputCornersCopy, inputCornersSrc.Length); + using (var vector = new VectorOfPoint2f(inputCornersCopy)) + { + NativeMethods.imgproc_cornerSubPix(image.CvPtr, vector.CvPtr, winSize, zeroZone, criteria); + GC.KeepAlive(image); + return vector.ToArray(); + } + } + #endregion + #region GoodFeaturesToTrack + /// + /// finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima + /// + /// Input 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 static Point2f[] GoodFeaturesToTrack(InputArray src, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask, int blockSize, bool useHarrisDetector, double k) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + using (var vector = new VectorOfPoint2f()) + { + var maskPtr = ToPtr(mask); + NativeMethods.imgproc_goodFeaturesToTrack(src.CvPtr, vector.CvPtr, maxCorners, qualityLevel, + minDistance, maskPtr, blockSize, useHarrisDetector ? 0 : 1, k); + GC.KeepAlive(src); + GC.KeepAlive(mask); + return vector.ToArray(); + } + } + #endregion + #region HoughLines +#if LANG_JP + /// + /// 標準ハフ変換を用いて,2値画像から直線を検出します. + /// + /// 8ビット,シングルチャンネルの2値入力画像.この画像は関数により書き換えられる可能性があります + /// ピクセル単位で表される投票空間の距離分解能 + /// ラジアン単位で表される投票空間の角度分解能 + /// 投票の閾値パラメータ.十分な票( > threshold )を得た直線のみが出力されます + /// マルチスケールハフ変換において,距離分解能 rho の除数となる値.[既定値は0] + /// マルチスケールハフ変換において,角度分解能 theta の除数となる値. [既定値は0] + /// 検出された直線.各直線は,2要素のベクトル (rho, theta) で表現されます. + /// rho は原点(画像の左上コーナー)からの距離, theta はラジアン単位で表される直線の回転角度です +#else + /// + /// Finds lines in a binary image using standard Hough transform. + /// + /// The 8-bit, single-channel, binary source image. The 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 +#endif + public static LineSegmentPolar[] HoughLines( + InputArray image, double rho, double theta, int threshold, + double srn = 0, double stn = 0) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + + using (var vec = new VectorOfVec2f()) + { + NativeMethods.imgproc_HoughLines(image.CvPtr, vec.CvPtr, rho, theta, threshold, srn, stn); + GC.KeepAlive(image); + return vec.ToArray(); + } + } + #endregion + #region HoughLinesP +#if LANG_JP + /// + /// 確率的ハフ変換を利用して,2値画像から線分を検出します. + /// + /// 8ビット,シングルチャンネルの2値入力画像.この画像は関数により書き換えられる可能性があります + /// ピクセル単位で表される投票空間の距離分解能 + /// ラジアン単位で表される投票空間の角度分解能 + /// 投票の閾値パラメータ.十分な票( > threshold )を得た直線のみが出力されます + /// 最小の線分長.これより短い線分は棄却されます. [既定値は0] + /// 2点が同一線分上にあると見なす場合に許容される最大距離. [既定値は0] + /// 検出された線分.各線分は,4要素のベクトル (x1, y1, x2, y2) で表現されます. +#else + /// + /// 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) +#endif + public static LineSegmentPoint[] HoughLinesP( + InputArray image, double rho, double theta, int threshold, + double minLineLength = 0, double maxLineGap = 0) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + using (var vec = new VectorOfVec4i()) + { + NativeMethods.imgproc_HoughLinesP(image.CvPtr, vec.CvPtr, rho, theta, threshold, minLineLength, maxLineGap); + GC.KeepAlive(image); + return vec.ToArray(); + } + } + #endregion + #region HoughCircles +#if LANG_JP + /// + /// ハフ変換を用いて,グレースケール画像から円を検出します. + /// + /// 8ビット,シングルチャンネル,グレースケールの入力画像> + /// 現在のところ,HoughCirclesMethod.Gradient メソッドのみが実装されている. + /// 画像分解能に対する投票分解能の比率の逆数. + /// 検出される円の中心同士の最小距離. + /// 手法依存の1番目のパラメータ.[既定値は100] + /// 手法依存の2番目のパラメータ.[既定値は100] + /// 円の半径の最小値 [既定値は0] + /// 円の半径の最大値 [既定値は0] + /// 検出された円.各ベクトルは,3要素の浮動小数点型ベクトル (x, y, radius) としてエンコードされます +#else + /// + /// Finds circles in a grayscale image using a Hough transform. + /// + /// The 8-bit, single-channel, grayscale input image + /// Currently, the only implemented method is HoughCirclesMethod.Gradient + /// 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) +#endif + public static CircleSegment[] HoughCircles( + InputArray image, HoughMethods method, double dp, double minDist, + double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + using (var vec = new VectorOfVec3f()) + { + NativeMethods.imgproc_HoughCircles(image.CvPtr, vec.CvPtr, (int)method, dp, minDist, param1, param2, minRadius, maxRadius); + GC.KeepAlive(image); + return vec.ToArray(); + } + } + #endregion + #region MorphologyDefaultBorderValue + /// + /// Default borderValue for Dilate/Erode + /// + /// + public static Scalar MorphologyDefaultBorderValue() + { + return Scalar.All(double.MaxValue); + } + #endregion + #region Dilate +#if LANG_JP + /// + /// 指定の構造要素を用いて画像の膨張を行います. + /// + /// 入力画像 + /// src と同じサイズ,同じ型の出力画像 + /// 膨張に用いられる構造要素. element=new Mat() の場合, 3x3 の矩形構造要素が用いられます + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します + /// 膨張が行われる回数. [既定値は1] + /// ピクセル外挿手法.[既定値はBorderType.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます.[既定値はCvCpp.MorphologyDefaultBorderValue()] +#else + /// + /// Dilates an image by using a specific structuring element. + /// + /// The source image + /// The destination image. It will have the same size and the same type as src + /// 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 BorderType.Constant] + /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] +#endif + public static void Dilate( + InputArray src, OutputArray dst, InputArray element, + Point? anchor = null, int iterations = 1, + BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == 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 = ToPtr(element); + NativeMethods.imgproc_dilate(src.CvPtr, dst.CvPtr, elementPtr, anchor0, iterations, (int)borderType, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(element); + dst.Fix(); + } + #endregion + #region Erode +#if LANG_JP + /// + /// 指定の構造要素を用いて画像の収縮を行います. + /// + /// 入力画像 + /// src と同じサイズ,同じ型の出力画像 + /// 収縮に用いられる構造要素. element=new Mat() の場合, 3x3 の矩形の構造要素が用いられます + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します + /// 収縮が行われる回数. [既定値は1] + /// ピクセル外挿手法.[既定値はBorderType.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます.[既定値はCvCpp.MorphologyDefaultBorderValue()] +#else + /// + /// Erodes an image by using a specific structuring element. + /// + /// The source image + /// The destination image. It will have the same size and the same type as src + /// 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()] +#endif + public static void Erode( + InputArray src, OutputArray dst, InputArray element, + Point? anchor = null, int iterations = 1, + BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == 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 = ToPtr(element); + NativeMethods.imgproc_erode(src.CvPtr, dst.CvPtr, elementPtr, anchor0, iterations, (int)borderType, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(element); + dst.Fix(); + } + #endregion + #region MorphologyEx +#if LANG_JP + /// + /// 高度なモルフォロジー変換を行います. + /// + /// 入力画像 + /// src と同じサイズ,同じ型の出力画像 + /// モルフォロジー演算の種類 + /// 構造要素 + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します. + /// 収縮と膨張が適用される回数. [既定値は1] + /// ピクセル外挿手法. [既定値はBorderType.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます. [既定値は CvCpp.MorphologyDefaultBorderValue()] +#else + /// + /// Performs advanced morphological transformations + /// + /// Source image + /// Destination image. It will have the same size and the same type as src + /// 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 BorderType.Constant] + /// The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()] +#endif + public static void MorphologyEx( + InputArray src, OutputArray dst, MorphTypes op, InputArray? element, + Point? anchor = null, int iterations = 1, + BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == 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 = ToPtr(element); + NativeMethods.imgproc_morphologyEx(src.CvPtr, dst.CvPtr, (int)op, elementPtr, anchor0, iterations, (int)borderType, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(element); + dst.Fix(); + } + #endregion + #region Resize + /// + /// Resizes an image. + /// + /// input image. + /// 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. + /// 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 + public static void Resize(InputArray src, OutputArray dst, Size dsize, + double fx = 0, double fy = 0, InterpolationFlags interpolation = InterpolationFlags.Linear) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_resize(src.CvPtr, dst.CvPtr, dsize, fx, fy, (int)interpolation); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region WarpAffine + /// + /// Applies an affine transformation to an image. + /// + /// input 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 static void WarpAffine( + InputArray src, OutputArray dst, InputArray m, Size dsize, + InterpolationFlags flags = InterpolationFlags.Linear, + BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + m.ThrowIfDisposed(); + var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); + NativeMethods.imgproc_warpAffine(src.CvPtr, dst.CvPtr, m.CvPtr, dsize, (int)flags, (int)borderMode, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(m); + dst.Fix(); + } + #endregion + #region WarpPerspective +#if LANG_JP + /// + /// 画像の透視変換を行います. + /// + /// 入力画像 + /// サイズが dsize で src と同じタイプの出力画像 + /// 3x3 の変換行列 + /// 出力画像のサイズ + /// 補間手法 + /// ピクセル外挿手法. + /// borderMode=BORDER_TRANSPARENT の場合,入力画像中の「はずれ値」に対応する + /// 出力画像中のピクセルが,この関数では変更されないことを意味します + /// 定数境界モードで利用されるピクセル値. +#else + /// + /// Applies a perspective transformation to an image. + /// + /// input image. + /// output image that has the size dsize and the same type as src. + /// 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. +#endif + public static void WarpPerspective( + InputArray src, OutputArray dst, InputArray m, Size dsize, + InterpolationFlags flags = InterpolationFlags.Linear, + BorderTypes borderMode = BorderTypes.Constant, + Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + m.ThrowIfDisposed(); + var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); + NativeMethods.imgproc_warpPerspective_MisInputArray( + src.CvPtr, dst.CvPtr, m.CvPtr, dsize, (int)flags, (int)borderMode, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(m); + dst.Fix(); + } + +#if LANG_JP + /// + /// 画像の透視変換を行います. + /// + /// 入力画像 + /// サイズが dsize で src と同じタイプの出力画像 + /// 3x3 の変換行列 + /// 出力画像のサイズ + /// 補間手法 + /// ピクセル外挿手法. + /// borderMode=BORDER_TRANSPARENT の場合,入力画像中の「はずれ値」に対応する + /// 出力画像中のピクセルが,この関数では変更されないことを意味します + /// 定数境界モードで利用されるピクセル値. +#else + /// + /// Applies a perspective transformation to an image. + /// + /// input image. + /// output image that has the size dsize and the same type as src. + /// 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. +#endif + public static void WarpPerspective( + InputArray src, OutputArray dst, float[,] m, Size dsize, + InterpolationFlags flags = InterpolationFlags.Linear, + BorderTypes borderMode = BorderTypes.Constant, + Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); + var mRow = m.GetLength(0); + var mCol = m.GetLength(1); + NativeMethods.imgproc_warpPerspective_MisArray( + src.CvPtr, dst.CvPtr, m, mRow, mCol, dsize, (int)flags, (int)borderMode, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Remap + /// + /// Applies a generic geometrical transformation to an image. + /// + /// Source image. + /// Destination image. It has the same size as map1 and the same type as src + /// 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. + public static void Remap( + InputArray src, OutputArray dst, InputArray map1, InputArray map2, + InterpolationFlags interpolation = InterpolationFlags.Linear, + BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (map1 == null) + throw new ArgumentNullException(nameof(map1)); + if (map2 == null) + throw new ArgumentNullException(nameof(map2)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + map1.ThrowIfDisposed(); + map2.ThrowIfDisposed(); + var borderValue0 = borderValue.GetValueOrDefault(Scalar.All(0)); + NativeMethods.imgproc_remap(src.CvPtr, dst.CvPtr, map1.CvPtr, map2.CvPtr, (int)interpolation, (int)borderMode, borderValue0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + GC.KeepAlive(map1); + GC.KeepAlive(map2); + } + #endregion + #region ConvertMaps + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void ConvertMaps(InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, MatType dstmap1Type, bool nnInterpolation = false) + { + if (map1 == null) + throw new ArgumentNullException(nameof(map1)); + if (map2 == null) + throw new ArgumentNullException(nameof(map2)); + if (dstmap1 == null) + throw new ArgumentNullException(nameof(dstmap1)); + if (dstmap2 == null) + throw new ArgumentNullException(nameof(dstmap2)); + map1.ThrowIfDisposed(); + map2.ThrowIfDisposed(); + dstmap1.ThrowIfDisposed(); + dstmap2.ThrowIfDisposed(); + NativeMethods.imgproc_convertMaps(map1.CvPtr, map2.CvPtr, dstmap1.CvPtr, dstmap2.CvPtr, dstmap1Type, nnInterpolation ? 1 : 0); + GC.KeepAlive(map1); + GC.KeepAlive(map2); + GC.KeepAlive(dstmap1); + GC.KeepAlive(dstmap2); + dstmap1.Fix(); + dstmap2.Fix(); + } + #endregion + + #region GetRotationMatrix2D + /// + /// + /// + /// + /// + /// + /// + public static Mat GetRotationMatrix2D(Point2f center, double angle, double scale) + { + var ret = NativeMethods.imgproc_getRotationMatrix2D(center, angle, scale); + return new Mat(ret); + + } + #endregion + #region InvertAffineTransform + /// + /// Inverts an affine transformation. + /// + /// Original affine transformation. + /// Output reverse affine transformation. + public static void InvertAffineTransform(InputArray m, OutputArray im) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + if (im == null) + throw new ArgumentNullException(nameof(im)); + m.ThrowIfDisposed(); + im.ThrowIfNotReady(); + NativeMethods.imgproc_invertAffineTransform(m.CvPtr, im.CvPtr); + GC.KeepAlive(m); + GC.KeepAlive(im); + im.Fix(); + } + #endregion + #region GetPerspectiveTransform + /// + /// + /// + /// + /// + /// + public static Mat GetPerspectiveTransform(IEnumerable src, IEnumerable dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + var srcArray = EnumerableEx.ToArray(src); + var dstArray = EnumerableEx.ToArray(dst); + var ret = NativeMethods.imgproc_getPerspectiveTransform1(srcArray, dstArray); + return new Mat(ret); + } + /// + /// + /// + /// + /// + /// + public static Mat GetPerspectiveTransform(InputArray src, InputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_getPerspectiveTransform2(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + return new Mat(ret); + } + #endregion + #region GetAffineTransform + /// + /// + /// + /// + /// + /// + public static Mat GetAffineTransform(IEnumerable src, IEnumerable dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + var srcArray = EnumerableEx.ToArray(src); + var dstArray = EnumerableEx.ToArray(dst); + var ret = NativeMethods.imgproc_getAffineTransform1(srcArray, dstArray); + return new Mat(ret); + } + + /// + /// + /// + /// + /// + /// + public static Mat GetAffineTransform(InputArray src, InputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_getAffineTransform2(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + return new Mat(ret); + } + #endregion + + #region GetRectSubPix + /// + /// Retrieves a pixel rectangle from an image with sub-pixel accuracy. + /// + /// Source image. + /// 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. + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (patch == null) + throw new ArgumentNullException(nameof(patch)); + image.ThrowIfDisposed(); + patch.ThrowIfNotReady(); + NativeMethods.imgproc_getRectSubPix(image.CvPtr, patchSize, center, patch.CvPtr, patchType); + GC.KeepAlive(image); + GC.KeepAlive(patch); + patch.Fix(); + } + #endregion + + /// + /// Remaps an image to log-polar space. + /// + /// Source image + /// Destination image + /// The transformation center; where the output precision is maximal + /// Magnitude scale parameter. + /// A combination of interpolation methods, see cv::InterpolationFlags + public static void LogPolar( + InputArray src, OutputArray dst, + Point2f center, double m, InterpolationFlags flags) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + + NativeMethods.imgproc_logPolar(src.CvPtr, dst.CvPtr, center, m, (int)flags); + + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + /// + /// Remaps an image to polar space. + /// + /// Source image + /// Destination image + /// The transformation center + /// Inverse magnitude scale parameter + /// A combination of interpolation methods, see cv::InterpolationFlags + public static void LinearPolar( + InputArray src, OutputArray dst, + Point2f center, double maxRadius, InterpolationFlags flags) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + + NativeMethods.imgproc_linearPolar(src.CvPtr, dst.CvPtr, center, maxRadius, (int)flags); + + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #region Integral + /// + /// + /// + /// + /// + /// + public static void Integral(InputArray src, OutputArray sum, int sdepth = -1) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (sum == null) + throw new ArgumentNullException(nameof(sum)); + src.ThrowIfDisposed(); + sum.ThrowIfNotReady(); + NativeMethods.imgproc_integral1(src.CvPtr, sum.CvPtr, sdepth); + GC.KeepAlive(src); + GC.KeepAlive(sum); + sum.Fix(); + } + /// + /// + /// + /// + /// + /// + /// + public static void Integral(InputArray src, OutputArray sum, OutputArray sqsum, int sdepth = -1) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (sum == null) + throw new ArgumentNullException(nameof(sum)); + if (sqsum == null) + throw new ArgumentNullException(nameof(sqsum)); + src.ThrowIfDisposed(); + sum.ThrowIfNotReady(); + sqsum.ThrowIfNotReady(); + NativeMethods.imgproc_integral2(src.CvPtr, sum.CvPtr, sqsum.CvPtr, sdepth); + GC.KeepAlive(src); + GC.KeepAlive(sum); + GC.KeepAlive(sqsum); + sum.Fix(); + sqsum.Fix(); + } + /// + /// + /// + /// + /// + /// + /// + /// + public static void Integral(InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, int sdepth = -1) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (sum == null) + throw new ArgumentNullException(nameof(sum)); + if (sqsum == null) + throw new ArgumentNullException(nameof(sqsum)); + if (tilted == null) + throw new ArgumentNullException(nameof(tilted)); + src.ThrowIfDisposed(); + sum.ThrowIfNotReady(); + sqsum.ThrowIfNotReady(); + tilted.ThrowIfNotReady(); + NativeMethods.imgproc_integral3(src.CvPtr, sum.CvPtr, sqsum.CvPtr, tilted.CvPtr, sdepth); + GC.KeepAlive(src); + GC.KeepAlive(sum); + GC.KeepAlive(sqsum); + GC.KeepAlive(tilted); + sum.Fix(); + sqsum.Fix(); + tilted.Fix(); + } + #endregion + #region Accumulate* + /// + /// Adds an image to the accumulator. + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_accumulate(src.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + /// + /// Adds the square of a source image to the accumulator. + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_accumulateSquare(src.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + /// + /// Adds the per-element product of two input images to the accumulator. + /// + /// First input image, 1- or 3-channel, 8-bit or 32-bit floating point. + /// 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) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_accumulateProduct(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + /// + /// Updates a running average. + /// + /// 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. + /// Weight of the input image. + /// Optional operation mask. + public static void AccumulateWeighted(InputArray src, InputOutputArray dst, double alpha, InputArray mask) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_accumulateWeighted(src.CvPtr, dst.CvPtr, alpha, ToPtr(mask)); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(mask); + dst.Fix(); + } + #endregion + #region PSNR + /// + /// + /// + /// + /// + /// +// ReSharper disable once InconsistentNaming + public static double PSNR(InputArray src1, InputArray src2) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_PSNR(src1.CvPtr, src2.CvPtr); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + return ret; + } + #endregion + #region PhaseCorrelate + /// + /// + /// + /// + /// + /// + /// + public static Point2d PhaseCorrelate(InputArray src1, InputArray src2, + InputArray? window = null) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_phaseCorrelate(src1.CvPtr, src2.CvPtr, ToPtr(window)); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(window); + return ret; + } + + #endregion + #region PhaseCorrelateRes + + /// + /// + /// + /// + /// + /// + /// + public static Point2d PhaseCorrelateRes(InputArray src1, InputArray src2, InputArray window) + { + return PhaseCorrelateRes(src1, src2, window, out _); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public static Point2d PhaseCorrelateRes(InputArray src1, InputArray src2, + InputArray window, out double response) + { + if (src1 == null) + throw new ArgumentNullException(nameof(src1)); + if (src2 == null) + throw new ArgumentNullException(nameof(src2)); + if (window == null) + throw new ArgumentNullException(nameof(window)); + src1.ThrowIfDisposed(); + src2.ThrowIfDisposed(); + window.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_phaseCorrelateRes(src1.CvPtr, src2.CvPtr, window.CvPtr, out response); + GC.KeepAlive(src1); + GC.KeepAlive(src2); + GC.KeepAlive(window); + return ret; + } + + #endregion + #region CreateHanningWindow + + /// + /// Computes a Hanning window coefficients in two dimensions. + /// + /// Destination array to place Hann coefficients in + /// The window size specifications + /// Created array type + public static void CreateHanningWindow(InputOutputArray dst, Size winSize, MatType type) + { + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_createHanningWindow(dst.CvPtr, winSize, type); + GC.KeepAlive(dst); + dst.Fix(); + } + + #endregion + #region Threshold + /// + /// Applies a fixed-level threshold to each array element. + /// + /// input array (single-channel, 8-bit or 32-bit floating point). + /// output array of the same size and type as src. + /// threshold value. + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var ret = NativeMethods.imgproc_threshold(src.CvPtr, dst.CvPtr, thresh, maxval, (int)type); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + return ret; + } + #endregion + #region AdaptiveThreshold + /// + /// Applies an adaptive threshold to an array. + /// + /// Source 8-bit single-channel image. + /// Destination image of the same size and the same type as src . + /// 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. + public static void AdaptiveThreshold(InputArray src, OutputArray dst, + double maxValue, AdaptiveThresholdTypes adaptiveMethod, ThresholdTypes thresholdType, int blockSize, double c) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_adaptiveThreshold(src.CvPtr, dst.CvPtr, maxValue, (int)adaptiveMethod, (int)thresholdType, blockSize, c); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region PyrDown/Up + /// + /// Blurs an image and downsamples it. + /// + /// input image. + /// 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, + Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var dstSize0 = dstSize.GetValueOrDefault(new Size()); + NativeMethods.imgproc_pyrDown(src.CvPtr, dst.CvPtr, dstSize0, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + /// + /// Upsamples an image and then blurs it. + /// + /// input image. + /// 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, + Size? dstSize = null, BorderTypes borderType = BorderTypes.Default) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var dstSize0 = dstSize.GetValueOrDefault(new Size()); + NativeMethods.imgproc_pyrUp(src.CvPtr, dst.CvPtr, dstSize0, (int)borderType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + + #region CalcHist + /// + /// computes the joint dense histogram for a set of images. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void CalcHist(Mat[] images, + int[] channels, InputArray mask, + OutputArray hist, int dims, int[] histSize, + Rangef[] ranges, bool uniform = true, bool accumulate = false) + { + if (ranges == null) + throw new ArgumentNullException(nameof(ranges)); + var rangesFloat = EnumerableEx.SelectToArray( + ranges, r => new [] {r.Start, r.End}); + CalcHist(images, channels, mask, hist, dims, + histSize, rangesFloat, uniform, accumulate); + } + + /// + /// computes the joint dense histogram for a set of images. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void CalcHist(Mat[] images, + int[] channels, InputArray mask, + OutputArray hist, int dims, int[] histSize, + float[][] ranges, bool uniform = true, bool accumulate = false) + { + if (images == null) + throw new ArgumentNullException(nameof(images)); + if (channels == null) + throw new ArgumentNullException(nameof(channels)); + if (hist == null) + throw new ArgumentNullException(nameof(hist)); + if (histSize == null) + throw new ArgumentNullException(nameof(histSize)); + if (ranges == null) + throw new ArgumentNullException(nameof(ranges)); + hist.ThrowIfNotReady(); + + var imagesPtr = EnumerableEx.SelectPtrs(images); + using (var rangesPtr = new ArrayAddress2(ranges)) + { + NativeMethods.imgproc_calcHist1(imagesPtr, images.Length, channels, ToPtr(mask), hist.CvPtr, + dims, histSize, rangesPtr, uniform ? 1 : 0, accumulate ? 1 : 0); + } + GC.KeepAlive(images); + GC.KeepAlive(mask); + GC.KeepAlive(hist); + hist.Fix(); + } + #endregion + #region CalcBackProject + /// + /// computes the joint dense histogram for a set of images. + /// + /// + /// + /// + /// + /// + /// + public static void CalcBackProject(Mat[] images, + int[] channels, InputArray hist, OutputArray backProject, + Rangef[] ranges, bool uniform = true) + { + if (images == null) + throw new ArgumentNullException(nameof(images)); + if (channels == null) + throw new ArgumentNullException(nameof(channels)); + if (hist == null) + throw new ArgumentNullException(nameof(hist)); + if (backProject == null) + throw new ArgumentNullException(nameof(backProject)); + if (ranges == null) + throw new ArgumentNullException(nameof(ranges)); + hist.ThrowIfDisposed(); + backProject.ThrowIfNotReady(); + + var imagesPtr = EnumerableEx.SelectPtrs(images); + var rangesFloat = EnumerableEx.SelectToArray( + ranges, r => new [] {r.Start, r.End}); + using (var rangesPtr = new ArrayAddress2(rangesFloat)) + { + NativeMethods.imgproc_calcBackProject(imagesPtr, images.Length, channels, hist.CvPtr, + backProject.CvPtr, rangesPtr, uniform ? 1 : 0); + } + GC.KeepAlive(images); + GC.KeepAlive(hist); + GC.KeepAlive(backProject); + backProject.Fix(); + } + #endregion + #region CompareHist + /// + /// compares two histograms stored in dense arrays + /// + /// The first compared histogram + /// The second compared histogram of the same size as h1 + /// The comparison method + /// + public static double CompareHist(InputArray h1, InputArray h2, HistCompMethods method) + { + if (h1 == null) + throw new ArgumentNullException(nameof(h1)); + if (h2 == null) + throw new ArgumentNullException(nameof(h2)); + h1.ThrowIfDisposed(); + h2.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_compareHist1(h1.CvPtr, h2.CvPtr, (int)method); + GC.KeepAlive(h1); + GC.KeepAlive(h2); + return ret; + } + #endregion + #region EqualizeHist + /// + /// normalizes the grayscale image brightness and contrast by normalizing its histogram + /// + /// 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) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_equalizeHist(src.CvPtr, dst.CvPtr); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region CreateCLAHE + /// + /// Creates a predefined CLAHE object + /// + /// + /// + /// + public static CLAHE CreateCLAHE(double clipLimit = 40.0, Size? tileGridSize = null) + { + return CLAHE.Create(clipLimit, tileGridSize); + } + #endregion + #region EMD + /// + /// + /// + /// + /// + /// + /// + public static float EMD(InputArray signature1, InputArray signature2, DistanceTypes distType) + { + return EMD(signature1, signature2, distType, null, out _, null); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public static float EMD(InputArray signature1, InputArray signature2, + DistanceTypes distType, InputArray? cost) + { + return EMD(signature1, signature2, distType, cost, out _, null); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static float EMD(InputArray signature1, InputArray signature2, + DistanceTypes distType, InputArray? cost, out float lowerBound) + { + return EMD(signature1, signature2, distType, cost, out lowerBound, null); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static float EMD(InputArray signature1, InputArray signature2, + DistanceTypes distType, InputArray? cost, out float lowerBound, OutputArray? flow) + { + if (signature1 == null) + throw new ArgumentNullException(nameof(signature1)); + if (signature2 == null) + throw new ArgumentNullException(nameof(signature2)); + signature1.ThrowIfDisposed(); + signature2.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_EMD(signature1.CvPtr, signature2.CvPtr, (int)distType, ToPtr(cost), out lowerBound, ToPtr(flow)); + GC.KeepAlive(signature1); + GC.KeepAlive(signature2); + GC.KeepAlive(cost); + GC.KeepAlive(flow); + flow?.Fix(); + return ret; + } + #endregion + #region Watershed + /// + /// Performs a marker-based image segmentation using the watershed algorithm. + /// + /// 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) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (markers == null) + throw new ArgumentNullException(nameof(markers)); + image.ThrowIfDisposed(); + markers.ThrowIfNotReady(); + NativeMethods.imgproc_watershed(image.CvPtr, markers.CvPtr); + GC.KeepAlive(image); + GC.KeepAlive(markers); + markers.Fix(); + } + #endregion + #region PyrMeanShiftFiltering + /// + /// Performs initial step of meanshift segmentation of an image. + /// + /// The source 8-bit, 3-channel image. + /// The destination image of the same format and the same size as the source. + /// The spatial window radius. + /// 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, + double sp, double sr, int maxLevel = 1, TermCriteria? termcrit = null) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + var termcrit0 = termcrit.GetValueOrDefault( + new TermCriteria(CriteriaType.Count | CriteriaType.Eps, 5, 1)); + NativeMethods.imgproc_pyrMeanShiftFiltering(src.CvPtr, dst.CvPtr, sp, sr, maxLevel, termcrit0); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region GrabCut + /// + /// Segments the image using GrabCut algorithm + /// + /// Input 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 static void GrabCut(InputArray img, InputOutputArray mask, Rect rect, + InputOutputArray bgdModel, InputOutputArray fgdModel, + int iterCount, GrabCutModes mode) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (mask == null) + throw new ArgumentNullException(nameof(mask)); + if (bgdModel == null) + throw new ArgumentNullException(nameof(bgdModel)); + if (fgdModel == null) + throw new ArgumentNullException(nameof(fgdModel)); + img.ThrowIfDisposed(); + mask.ThrowIfNotReady(); + bgdModel.ThrowIfNotReady(); + fgdModel.ThrowIfNotReady(); + NativeMethods.imgproc_grabCut(img.CvPtr, mask.CvPtr, rect, + bgdModel.CvPtr, fgdModel.CvPtr, iterCount, (int)mode); + GC.KeepAlive(img); + GC.KeepAlive(mask); + GC.KeepAlive(bgdModel); + GC.KeepAlive(fgdModel); + mask.Fix(); + bgdModel.Fix(); + fgdModel.Fix(); + } + #endregion + #region DistanceTransform + /// + /// builds the discrete Voronoi diagram + /// + /// + /// + /// + /// + /// + /// + public static void DistanceTransformWithLabels(InputArray src, + OutputArray dst, + OutputArray labels, + DistanceTypes distanceType, + DistanceMaskSize maskSize, + DistanceTransformLabelTypes labelType = DistanceTransformLabelTypes.CComp) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (labels == null) + throw new ArgumentNullException(nameof(labels)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + labels.ThrowIfNotReady(); + NativeMethods.imgproc_distanceTransformWithLabels( + src.CvPtr, dst.CvPtr, labels.CvPtr, (int)distanceType, (int)maskSize, (int)labelType); + GC.KeepAlive(src); + GC.KeepAlive(dst); + GC.KeepAlive(labels); + dst.Fix(); + labels.Fix(); + } + + /// + /// computes the distance transform map + /// + /// + /// + /// + /// + public static void DistanceTransform(InputArray src, + OutputArray dst, + DistanceTypes distanceType, + DistanceMaskSize maskSize) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_distanceTransform( + src.CvPtr, dst.CvPtr, (int)distanceType, (int)maskSize); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region FloodFill + /// + /// 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 static int FloodFill(InputOutputArray image, Point seedPoint, Scalar newVal) + { + return FloodFill(image, seedPoint, newVal, out _, null, null, FloodFillFlags.Link4); + } + + /// + /// 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 static int FloodFill(InputOutputArray image, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar? loDiff = null, Scalar? upDiff = null, + FloodFillFlags flags = FloodFillFlags.Link4) + { + return FloodFill(image, seedPoint, newVal, out rect, loDiff, upDiff, (int)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. + /// 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 static int FloodFill(InputOutputArray image, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar? loDiff = null, Scalar? upDiff = null, + int flags = 4) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfNotReady(); + var loDiff0 = loDiff.GetValueOrDefault(new Scalar()); + var upDiff0 = upDiff.GetValueOrDefault(new Scalar()); + var ret = NativeMethods.imgproc_floodFill1(image.CvPtr, seedPoint, newVal, out rect, + loDiff0, upDiff0, flags); + GC.KeepAlive(image); + image.Fix(); + return ret; + } + + /// + /// 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 static int FloodFill(InputOutputArray image, InputOutputArray mask, + Point seedPoint, Scalar newVal) + { + return FloodFill(image, mask, seedPoint, newVal, out _, null, null, FloodFillFlags.Link4); + } + + /// + /// 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 static int FloodFill(InputOutputArray image, InputOutputArray mask, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar? loDiff = null, Scalar? upDiff = null, + FloodFillFlags flags = FloodFillFlags.Link4) + { + return FloodFill(image, mask, seedPoint, newVal, out rect, loDiff, upDiff, (int)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. + /// 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 static int FloodFill(InputOutputArray image, InputOutputArray mask, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar? loDiff = null, Scalar? upDiff = null, + int flags = 4) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (mask == null) + throw new ArgumentNullException(nameof(mask)); + image.ThrowIfNotReady(); + mask.ThrowIfNotReady(); + var loDiff0 = loDiff.GetValueOrDefault(new Scalar()); + var upDiff0 = upDiff.GetValueOrDefault(new Scalar()); + var ret = NativeMethods.imgproc_floodFill2(image.CvPtr, mask.CvPtr, seedPoint, + newVal, out rect, loDiff0, upDiff0, flags); + GC.KeepAlive(image); + GC.KeepAlive(mask); + image.Fix(); + mask.Fix(); + return ret; + } + #endregion + #region CvtColor +#if LANG_JP + /// + /// 画像の色空間を変換します. + /// + /// 8ビット符号なし整数型,16ビット符号なし整数型,または単精度浮動小数型の入力画像 + /// src と同じサイズ,同じタイプの出力画像 + /// 色空間の変換コード. + /// 出力画像のチャンネル数.この値が 0 の場合,チャンネル数は src と code から自動的に求められます +#else + /// + /// Converts image from one color space to another + /// + /// The source image, 8-bit unsigned, 16-bit unsigned or single-precision floating-point + /// The destination image; will have the same size and the same depth as src + /// 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 +#endif + public static void CvtColor(InputArray src, OutputArray dst, ColorConversionCodes code, int dstCn = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + + NativeMethods.imgproc_cvtColor(src.CvPtr, dst.CvPtr, (int)code, dstCn); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + #endregion + #region Moments + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (single-channel, 8-bit or floating-point + /// 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) + { + return new Moments(array, binaryImage); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (8-bit) 2D array + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public static Moments Moments(byte[,] array, bool binaryImage = false) + { + return new Moments(array, binaryImage); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (floating-point) 2D array + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public static Moments Moments(float[,] array, bool binaryImage = false) + { + return new Moments(array, binaryImage); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// Array of 2D points + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public static Moments Moments(IEnumerable array, bool binaryImage = false) + { + return new Moments(array, binaryImage); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// Array of 2D points + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public static Moments Moments(IEnumerable array, bool binaryImage = false) + { + return new Moments(array, binaryImage); + } + + #endregion + #region MatchTemplate + /// + /// Computes the proximity map for the raster template and the image where the template is searched for + /// + /// 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 + /// 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). + /// 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, + TemplateMatchModes method, + InputArray? mask = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (templ == null) + throw new ArgumentNullException(nameof(templ)); + if (result == null) + throw new ArgumentNullException(nameof(result)); + image.ThrowIfDisposed(); + templ.ThrowIfDisposed(); + result.ThrowIfNotReady(); + mask?.ThrowIfDisposed(); + NativeMethods.imgproc_matchTemplate(image.CvPtr, templ.CvPtr, result.CvPtr, (int)method, ToPtr(mask)); + GC.KeepAlive(image); + GC.KeepAlive(templ); + GC.KeepAlive(result); + result.Fix(); + GC.KeepAlive(mask); + } + #endregion + #region ConnectedComponents + + /// + /// 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. + /// + /// the image to be labeled + /// 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, + PixelConnectivity connectivity = PixelConnectivity.Connectivity8) + { + return ConnectedComponents(image, 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. + /// + /// the image to be labeled + /// 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 static int ConnectedComponents(InputArray image, OutputArray labels, + PixelConnectivity connectivity, MatType ltype) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (labels == null) + throw new ArgumentNullException(nameof(labels)); + image.ThrowIfDisposed(); + labels.ThrowIfNotReady(); + + var result = NativeMethods.imgproc_connectedComponents( + image.CvPtr, labels.CvPtr, (int)connectivity, ltype); + + GC.KeepAlive(image); + GC.KeepAlive(labels); + labels.Fix(); + return result; + } + + /// + /// 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. + /// + /// the image to be labeled + /// 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) + { + using (var labelsMat = new Mat()) + { + var result = ConnectedComponents(image, labelsMat, connectivity, MatType.CV_32S); + labels = labelsMat.ToRectangularArray(); + return result; + } + } + + #endregion + #region ConnectedComponentsWithStats + + /// + /// 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. + /// + /// the image to be labeled + /// 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 static int ConnectedComponentsWithStats( + InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + PixelConnectivity connectivity = PixelConnectivity.Connectivity8) + { + return ConnectedComponentsWithStats(image, 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. + /// + /// the image to be labeled + /// 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 static int ConnectedComponentsWithStats( + InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + PixelConnectivity connectivity, + MatType ltype) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (labels == null) + throw new ArgumentNullException(nameof(labels)); + if (stats == null) + throw new ArgumentNullException(nameof(stats)); + if (centroids == null) + throw new ArgumentNullException(nameof(centroids)); + image.ThrowIfDisposed(); + labels.ThrowIfNotReady(); + stats.ThrowIfNotReady(); + centroids.ThrowIfNotReady(); + + var result = NativeMethods.imgproc_connectedComponentsWithStats( + image.CvPtr, labels.CvPtr, stats.CvPtr, centroids.CvPtr, (int) connectivity, ltype); + + GC.KeepAlive(image); + GC.KeepAlive(labels); + GC.KeepAlive(stats); + GC.KeepAlive(centroids); + labels.Fix(); + stats.Fix(); + centroids.Fix(); + return result; + } + + #endregion + #region ConnectedComponentsEx + + /// + /// 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. + /// + /// the image to be labeled + /// 8 or 4 for 8-way or 4-way connectivity respectively + /// + public static ConnectedComponents ConnectedComponentsEx( + InputArray image, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) + { + using (var labelsMat = new Mat()) + using (var statsMat = new Mat()) + using (var centroidsMat = new Mat()) + { + var nLabels = ConnectedComponentsWithStats( + image, labelsMat, statsMat, centroidsMat, connectivity, MatType.CV_32S); + var labels = labelsMat.ToRectangularArray(); + var stats = statsMat.ToRectangularArray(); + var centroids = centroidsMat.ToRectangularArray(); + + var blobs = new ConnectedComponents.Blob[nLabels]; + for (var i = 0; i < nLabels; i++) + { + blobs[i] = new ConnectedComponents.Blob + { + Label = i, + Left = stats[i, 0], + Top = stats[i, 1], + Width = stats[i, 2], + Height = stats[i, 3], + Area = stats[i, 4], + Centroid = new Point2d(centroids[i, 0], centroids[i, 1]), + }; + } + return new ConnectedComponents(blobs, labels, nLabels); + } + } + + #endregion + #region FindContours +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// + /// 入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. + /// 画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して, + /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の + /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合, + /// それに対応する hierarchy[i] の要素は,負の値になります. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. +#else + /// + /// Finds contours in a binary image. + /// + /// Source, 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 the 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. +#endif + public static void FindContours(InputOutputArray image, out Point[][] contours, + out HierarchyIndex[] hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + NativeMethods.imgproc_findContours1_vector(image.CvPtr, out var contoursPtr, out var hierarchyPtr, (int)mode, (int)method, offset0); + + using (var contoursVec = new VectorOfVectorPoint(contoursPtr)) + using (var hierarchyVec = new VectorOfVec4i(hierarchyPtr)) + { + contours = contoursVec.ToArray(); + var hierarchyOrg = hierarchyVec.ToArray(); + hierarchy = EnumerableEx.SelectToArray(hierarchyOrg, HierarchyIndex.FromVec4i); + } + image.Fix(); + GC.KeepAlive(image); + } +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// + /// 入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. + /// 画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して, + /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の + /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合, + /// それに対応する hierarchy[i] の要素は,負の値になります. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. +#else + /// + /// Finds contours in a binary image. + /// + /// Source, 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 the 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. +#endif + public static void FindContours(InputOutputArray image, out Mat[] contours, + OutputArray hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (hierarchy == null) + throw new ArgumentNullException(nameof(hierarchy)); + image.ThrowIfNotReady(); + hierarchy.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + NativeMethods.imgproc_findContours1_OutputArray(image.CvPtr, out var contoursPtr, hierarchy.CvPtr, (int)mode, (int)method, offset0); + + using (var contoursVec = new VectorOfMat(contoursPtr)) + { + contours = contoursVec.ToArray(); + } + image.Fix(); + hierarchy.Fix(); + GC.KeepAlive(image); + GC.KeepAlive(hierarchy); + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// + /// 入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. +#else + /// + /// Finds contours in a binary image. + /// + /// Source, 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 the 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. +#endif + public static Point[][] FindContoursAsArray(InputOutputArray image, + RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + NativeMethods.imgproc_findContours2_vector(image.CvPtr, out var contoursPtr, (int)mode, (int)method, offset0); + image.Fix(); + GC.KeepAlive(image); + + using (var contoursVec = new VectorOfVectorPoint(contoursPtr)) + { + return contoursVec.ToArray(); + } + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// + /// 入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. +#else + /// + /// Finds contours in a binary image. + /// + /// Source, 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 the 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. +#endif + public static Mat[] FindContoursAsMat(InputOutputArray image, + RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + NativeMethods.imgproc_findContours2_OutputArray(image.CvPtr, out var contoursPtr, (int)mode, (int)method, offset0); + image.Fix(); + GC.KeepAlive(image); + + using (var contoursVec = new VectorOfMat(contoursPtr)) + { + return contoursVec.ToArray>(); + } + } + + #endregion + #region ApproxPolyDP + + /// + /// Approximates contour or a curve using Douglas-Peucker algorithm + /// + /// The polygon or curve to approximate. + /// Must be 1 x N or N x 1 matrix of type CV_32SC2 or CV_32FC2. + /// The result of the approximation; + /// The type should match the type of the input curve + /// 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 + public static void ApproxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + if (approxCurve == null) + throw new ArgumentNullException(nameof(approxCurve)); + curve.ThrowIfDisposed(); + approxCurve.ThrowIfNotReady(); + NativeMethods.imgproc_approxPolyDP_InputArray(curve.CvPtr, approxCurve.CvPtr, epsilon, closed ? 1 : 0); + GC.KeepAlive(curve); + GC.KeepAlive(approxCurve); + approxCurve.Fix(); + } + /// + /// Approximates contour or a curve using Douglas-Peucker algorithm + /// + /// The polygon or curve to approximate. + /// 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 + public static Point[] ApproxPolyDP(IEnumerable curve, double epsilon, bool closed) + { + if(curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + NativeMethods.imgproc_approxPolyDP_Point(curveArray, curveArray.Length, out var approxCurvePtr, epsilon, closed ? 1 : 0); + using (var approxCurveVec = new VectorOfPoint(approxCurvePtr)) + { + return approxCurveVec.ToArray(); + } + } + /// + /// Approximates contour or a curve using Douglas-Peucker algorithm + /// + /// The polygon or curve to approximate. + /// Specifies the approximation accuracy. + /// This is the maximum distance between the original curve and its approximation. + /// If true, the approximated curve is closed + /// (i.e. its first and last vertices are connected), otherwise it’s not + /// The result of the approximation; + /// The type should match the type of the input curve + public static Point2f[] ApproxPolyDP(IEnumerable curve, double epsilon, bool closed) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + NativeMethods.imgproc_approxPolyDP_Point2f(curveArray, curveArray.Length, out var approxCurvePtr, epsilon, closed ? 1 : 0); + using (var approxCurveVec = new VectorOfPoint2f(approxCurvePtr)) + { + return approxCurveVec.ToArray(); + } + } + #endregion + #region ArcLength + /// + /// Calculates a contour perimeter or a curve length. + /// + /// 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) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + curve.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_arcLength_InputArray(curve.CvPtr, closed ? 1 : 0); + GC.KeepAlive(curve); + return ret; + } + + /// + /// Calculates a contour perimeter or a curve length. + /// + /// The input vector of 2D points. + /// Indicates, whether the curve is closed or not. + /// + public static double ArcLength(IEnumerable curve, bool closed) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + return NativeMethods.imgproc_arcLength_Point(curveArray, curveArray.Length, closed ? 1 : 0); + } + + /// + /// Calculates a contour perimeter or a curve length. + /// + /// The input vector of 2D points. + /// Indicates, whether the curve is closed or not. + /// + public static double ArcLength(IEnumerable curve, bool closed) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + return NativeMethods.imgproc_arcLength_Point2f(curveArray, curveArray.Length, closed ? 1 : 0); + } + #endregion + #region BoundingRect + /// + /// Calculates the up-right bounding rectangle of a point set. + /// + /// 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) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + curve.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_boundingRect_InputArray(curve.CvPtr); + GC.KeepAlive(curve); + return ret; + } + + /// + /// Calculates the up-right bounding rectangle of a point set. + /// + /// 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(IEnumerable curve) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + return NativeMethods.imgproc_boundingRect_Point(curveArray, curveArray.Length); + } + + /// + /// Calculates the up-right bounding rectangle of a point set. + /// + /// 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(IEnumerable curve) + { + if (curve == null) + throw new ArgumentNullException(nameof(curve)); + var curveArray = EnumerableEx.ToArray(curve); + return NativeMethods.imgproc_boundingRect_Point2f(curveArray, curveArray.Length); + } + #endregion + #region ContourArea + /// + /// Calculates the contour area + /// + /// The contour vertices, represented by CV_32SC2 or CV_32FC2 matrix + /// + /// + public static double ContourArea(InputArray contour, bool oriented = false) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + contour.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_contourArea_InputArray(contour.CvPtr, oriented ? 1 : 0); + GC.KeepAlive(contour); + return ret; + } + /// + /// Calculates the contour area + /// + /// The contour vertices, represented by CV_32SC2 or CV_32FC2 matrix + /// + /// + public static double ContourArea(IEnumerable contour, bool oriented = false) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + return NativeMethods.imgproc_contourArea_Point(contourArray, contourArray.Length, oriented ? 1 : 0); + } + /// + /// Calculates the contour area + /// + /// The contour vertices, represented by CV_32SC2 or CV_32FC2 matrix + /// + /// + public static double ContourArea(IEnumerable contour, bool oriented = false) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + return NativeMethods.imgproc_contourArea_Point2f(contourArray, contourArray.Length, oriented ? 1 : 0); + } + #endregion + #region MinAreaRect + /// + /// Finds the minimum area rotated rectangle enclosing a 2D point set. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. + /// + public static RotatedRect MinAreaRect(InputArray points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + points.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_minAreaRect_InputArray(points.CvPtr); + GC.KeepAlive(points); + return ret; + } + /// + /// Finds the minimum area rotated rectangle enclosing a 2D point set. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. + /// + public static RotatedRect MinAreaRect(IEnumerable points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + return NativeMethods.imgproc_minAreaRect_Point(pointsArray, pointsArray.Length); + } + /// + /// Finds the minimum area rotated rectangle enclosing a 2D point set. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix. + /// + public static RotatedRect MinAreaRect(IEnumerable points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + return NativeMethods.imgproc_minAreaRect_Point2f(pointsArray, pointsArray.Length); + } + #endregion + #region MinEnclosingCircle + /// + /// Finds the minimum area circle enclosing a 2D point set. + /// + /// 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) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + points.ThrowIfDisposed(); + NativeMethods.imgproc_minEnclosingCircle_InputArray(points.CvPtr, out center, out radius); + GC.KeepAlive(points); + } + + /// + /// Finds the minimum area circle enclosing a 2D point set. + /// + /// 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(IEnumerable points, out Point2f center, out float radius) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_minEnclosingCircle_Point(pointsArray, pointsArray.Length, out center, out radius); + } + + /// + /// Finds the minimum area circle enclosing a 2D point set. + /// + /// 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(IEnumerable points, out Point2f center, out float radius) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_minEnclosingCircle_Point2f(pointsArray, pointsArray.Length, out center, out radius); + } + #endregion + #region MatchShapes + /// + /// matches two contours using one of the available algorithms + /// + /// + /// + /// + /// + /// + public static double MatchShapes(InputArray contour1, InputArray contour2, ShapeMatchModes method, double parameter = 0) + { + if (contour1 == null) + throw new ArgumentNullException(nameof(contour1)); + if (contour2 == null) + throw new ArgumentNullException(nameof(contour2)); + var ret = NativeMethods.imgproc_matchShapes_InputArray(contour1.CvPtr, contour2.CvPtr, (int)method, parameter); + GC.KeepAlive(contour1); + GC.KeepAlive(contour2); + return ret; + } + /// + /// matches two contours using one of the available algorithms + /// + /// + /// + /// + /// + /// + public static double MatchShapes(IEnumerable contour1, IEnumerable contour2, + ShapeMatchModes method, double parameter = 0) + { + if (contour1 == null) + throw new ArgumentNullException(nameof(contour1)); + if (contour2 == null) + throw new ArgumentNullException(nameof(contour2)); + var contour1Array = EnumerableEx.ToArray(contour1); + var contour2Array = EnumerableEx.ToArray(contour2); + return NativeMethods.imgproc_matchShapes_Point(contour1Array, contour1Array.Length, + contour2Array, contour2Array.Length, (int)method, parameter); + } + #endregion + #region ConvexHull + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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). + /// 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. + /// + public static void ConvexHull(InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + if (hull == null) + throw new ArgumentNullException(nameof(hull)); + points.ThrowIfDisposed(); + hull.ThrowIfNotReady(); + NativeMethods.imgproc_convexHull_InputArray(points.CvPtr, hull.CvPtr, clockwise ? 1 : 0, returnPoints ? 1 : 0); + GC.KeepAlive(points); + GC.KeepAlive(hull); + hull.Fix(); + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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 static Point[] ConvexHull(IEnumerable points, bool clockwise = false) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_convexHull_Point_ReturnsPoints(pointsArray, pointsArray.Length, out var hullPtr, clockwise ? 1 : 0); + using (var hullVec = new VectorOfPoint(hullPtr)) + { + return hullVec.ToArray(); + } + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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 static Point2f[] ConvexHull(IEnumerable points, bool clockwise = false) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_convexHull_Point2f_ReturnsPoints(pointsArray, pointsArray.Length, out var hullPtr, + clockwise ? 1 : 0); + using (var hullVec = new VectorOfPoint2f(hullPtr)) + { + return hullVec.ToArray(); + } + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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 static int[] ConvexHullIndices(IEnumerable points, bool clockwise = false) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_convexHull_Point_ReturnsIndices(pointsArray, pointsArray.Length, out var hullPtr, clockwise ? 1 : 0); + using (var hullVec = new VectorOfInt32(hullPtr)) + { + return hullVec.ToArray(); + } + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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 static int[] ConvexHullIndices(IEnumerable points, bool clockwise = false) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + NativeMethods.imgproc_convexHull_Point2f_ReturnsIndices(pointsArray, pointsArray.Length, out var hullPtr, clockwise ? 1 : 0); + using (var hullVec = new VectorOfInt32(hullPtr)) + { + return hullVec.ToArray(); + } + } + #endregion + #region ConvexityDefects + + /// + /// Computes the contour convexity defects + /// + /// Input contour. + /// 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 static void ConvexityDefects(InputArray contour, InputArray convexHull, OutputArray convexityDefects) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + if (convexHull == null) + throw new ArgumentNullException(nameof(convexHull)); + if (convexityDefects == null) + throw new ArgumentNullException(nameof(convexityDefects)); + contour.ThrowIfDisposed(); + convexHull.ThrowIfDisposed(); + convexityDefects.ThrowIfNotReady(); + NativeMethods.imgproc_convexityDefects_InputArray(contour.CvPtr, convexHull.CvPtr, convexityDefects.CvPtr); + GC.KeepAlive(contour); + GC.KeepAlive(convexHull); + GC.KeepAlive(convexityDefects); + convexityDefects.Fix(); + } + + /// + /// Computes the contour convexity defects + /// + /// Input contour. + /// 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 static Vec4i[] ConvexityDefects(IEnumerable contour, IEnumerable convexHull) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + if (convexHull == null) + throw new ArgumentNullException(nameof(convexHull)); + var contourArray = EnumerableEx.ToArray(contour); + var convexHullArray = EnumerableEx.ToArray(convexHull); + NativeMethods.imgproc_convexityDefects_Point(contourArray, contourArray.Length, + convexHullArray, convexHullArray.Length, out var convexityDefectsPtr); + + using (var convexityDefects = new VectorOfVec4i(convexityDefectsPtr)) + { + return convexityDefects.ToArray(); + } + } + + /// + /// Computes the contour convexity defects + /// + /// Input contour. + /// 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 static Vec4i[] ConvexityDefects(IEnumerable contour, IEnumerable convexHull) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + if (convexHull == null) + throw new ArgumentNullException(nameof(convexHull)); + var contourArray = EnumerableEx.ToArray(contour); + var convexHullArray = EnumerableEx.ToArray(convexHull); + NativeMethods.imgproc_convexityDefects_Point2f(contourArray, contourArray.Length, + convexHullArray, convexHullArray.Length, out var convexityDefectsPtr); + + using (var convexityDefects = new VectorOfVec4i(convexityDefectsPtr)) + { + return convexityDefects.ToArray(); + } + } + #endregion + #region IsContourConvex + /// + /// returns true if the contour is convex. + /// Does not support contours with self-intersection + /// + /// Input vector of 2D points + /// + public static bool IsContourConvex(InputArray contour) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + contour.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_isContourConvex_InputArray(contour.CvPtr); + GC.KeepAlive(contour); + return ret != 0; + } + /// + /// returns true if the contour is convex. + /// Does not support contours with self-intersection + /// + /// Input vector of 2D points + /// + public static bool IsContourConvex(IEnumerable contour) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + var ret = NativeMethods.imgproc_isContourConvex_Point(contourArray, contourArray.Length); + return ret != 0; + } + /// + /// returns true if the contour is convex. D + /// oes not support contours with self-intersection + /// + /// Input vector of 2D points + /// + public static bool IsContourConvex(IEnumerable contour) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + var ret = NativeMethods.imgproc_isContourConvex_Point2f(contourArray, contourArray.Length); + return ret != 0; + } + #endregion + #region IntersectConvexConvex + /// + /// finds intersection of two convex polygons + /// + /// + /// + /// + /// + /// + public static float IntersectConvexConvex(InputArray p1, InputArray p2, OutputArray p12, bool handleNested = true) + { + if (p1 == null) + throw new ArgumentNullException(nameof(p1)); + if (p2 == null) + throw new ArgumentNullException(nameof(p2)); + if (p12 == null) + throw new ArgumentNullException(nameof(p12)); + p1.ThrowIfDisposed(); + p2.ThrowIfDisposed(); + p12.ThrowIfNotReady(); + var ret = NativeMethods.imgproc_intersectConvexConvex_InputArray(p1.CvPtr, p2.CvPtr, p12.CvPtr, handleNested ? 1 : 0); + GC.KeepAlive(p1); + GC.KeepAlive(p2); + GC.KeepAlive(p12); + p12.Fix(); + return ret; + } + /// + /// finds intersection of two convex polygons + /// + /// + /// + /// + /// + /// + public static float IntersectConvexConvex(IEnumerable p1, IEnumerable p2, + out Point[] p12, bool handleNested = true) + { + if (p1 == null) + throw new ArgumentNullException(nameof(p1)); + if (p2 == null) + throw new ArgumentNullException(nameof(p2)); + var p1Array = EnumerableEx.ToArray(p1); + var p2Array = EnumerableEx.ToArray(p2); + var ret = NativeMethods.imgproc_intersectConvexConvex_Point( + p1Array, p1Array.Length, p2Array, p2Array.Length, out var p12Ptr, handleNested ? 1 : 0); + + using (var p12Vec = new VectorOfPoint(p12Ptr)) + { + p12 = p12Vec.ToArray(); + } + + return ret; + } + /// + /// finds intersection of two convex polygons + /// + /// + /// + /// + /// + /// + public static float IntersectConvexConvex(IEnumerable p1, IEnumerable p2, + out Point2f[] p12, bool handleNested = true) + { + if (p1 == null) + throw new ArgumentNullException(nameof(p1)); + if (p2 == null) + throw new ArgumentNullException(nameof(p2)); + var p1Array = EnumerableEx.ToArray(p1); + var p2Array = EnumerableEx.ToArray(p2); + var ret = NativeMethods.imgproc_intersectConvexConvex_Point2f(p1Array, p1Array.Length, p2Array, p2Array.Length, + out var p12Ptr, handleNested ? 1 : 0); + + using (var p12Vec = new VectorOfPoint2f(p12Ptr)) + { + p12 = p12Vec.ToArray(); + } + + return ret; + } + #endregion + #region FitEllipse + /// + /// Fits ellipse to the set of 2D points. + /// + /// Input 2D point set + /// + public static RotatedRect FitEllipse(InputArray points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + points.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_fitEllipse_InputArray(points.CvPtr); + GC.KeepAlive(points); + return ret; + } + /// + /// Fits ellipse to the set of 2D points. + /// + /// Input 2D point set + /// + public static RotatedRect FitEllipse(IEnumerable points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + return NativeMethods.imgproc_fitEllipse_Point(pointsArray, pointsArray.Length); + } + /// + /// Fits ellipse to the set of 2D points. + /// + /// Input 2D point set + /// + public static RotatedRect FitEllipse(IEnumerable points) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + return NativeMethods.imgproc_fitEllipse_Point2f(pointsArray, pointsArray.Length); + } + #endregion + #region FitLine + + /// + /// Fits line to the set of 2D points using M-estimator algorithm + /// + /// Input vector of 2D or 3D points + /// Output line parameters. + /// In case of 2D fitting, it should be a vector of 4 elements + /// (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector + /// collinear to the line and (x0, y0) is a point on the line. + /// In case of 3D fitting, it should be a vector of 6 elements + /// (like Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a + /// normalized vector collinear to the line and (x0, y0, z0) is a point on the line. + /// 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. + public static void FitLine(InputArray points, OutputArray line, DistanceTypes distType, + double param, double reps, double aeps) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + if (line == null) + throw new ArgumentNullException(nameof(line)); + points.ThrowIfDisposed(); + line.ThrowIfNotReady(); + NativeMethods.imgproc_fitLine_InputArray(points.CvPtr, line.CvPtr, (int)distType, param, reps, aeps); + GC.KeepAlive(points); + GC.KeepAlive(line); + line.Fix(); + } + + /// + /// Fits line to the set of 2D points using M-estimator algorithm + /// + /// Input vector of 2D or 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 static Line2D FitLine(IEnumerable points, DistanceTypes distType, + double param, double reps, double aeps) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + var line = new float[4]; + NativeMethods.imgproc_fitLine_Point(pointsArray, pointsArray.Length, line, (int)distType, param, reps, aeps); + return new Line2D(line); + } + + /// + /// Fits line to the set of 2D points using M-estimator algorithm + /// + /// Input vector of 2D or 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 static Line2D FitLine(IEnumerable points, DistanceTypes distType, + double param, double reps, double aeps) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + var line = new float[4]; + NativeMethods.imgproc_fitLine_Point2f(pointsArray, pointsArray.Length, line, (int)distType, param, reps, aeps); + return new Line2D(line); + } + + /// + /// Fits line to the set of 3D points using M-estimator algorithm + /// + /// Input vector of 2D or 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 static Line3D FitLine(IEnumerable points, DistanceTypes distType, + double param, double reps, double aeps) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + var line = new float[6]; + NativeMethods.imgproc_fitLine_Point3i(pointsArray, pointsArray.Length, line, (int)distType, param, reps, aeps); + return new Line3D(line); + } + + /// + /// Fits line to the set of 3D points using M-estimator algorithm + /// + /// Input vector of 2D or 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 static Line3D FitLine(IEnumerable points, DistanceTypes distType, + double param, double reps, double aeps) + { + if (points == null) + throw new ArgumentNullException(nameof(points)); + var pointsArray = EnumerableEx.ToArray(points); + var line = new float[6]; + NativeMethods.imgproc_fitLine_Point3f(pointsArray, pointsArray.Length, line, (int)distType, param, reps, aeps); + return new Line3D(line); + } + #endregion + #region PointPolygonTest + /// + /// Checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary + /// + /// + /// + /// + /// + public static double PointPolygonTest(InputArray contour, Point2f pt, bool measureDist) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + contour.ThrowIfDisposed(); + var ret = NativeMethods.imgproc_pointPolygonTest_InputArray(contour.CvPtr, pt, measureDist ? 1 : 0); + GC.KeepAlive(contour); + return ret; + } + + /// + /// Checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary + /// + /// + /// + /// + /// + public static double PointPolygonTest(IEnumerable contour, Point2f pt, bool measureDist) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + return NativeMethods.imgproc_pointPolygonTest_Point(contourArray, contourArray.Length, pt, measureDist ? 1 : 0); + } + + /// + /// Checks if the point is inside the contour. + /// Optionally computes the signed distance from the point to the contour boundary. + /// + /// Input contour. + /// 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 static double PointPolygonTest(IEnumerable contour, Point2f pt, bool measureDist) + { + if (contour == null) + throw new ArgumentNullException(nameof(contour)); + var contourArray = EnumerableEx.ToArray(contour); + return NativeMethods.imgproc_pointPolygonTest_Point2f(contourArray, contourArray.Length, pt, measureDist ? 1 : 0); + } + #endregion + + #region RotatedRectangleIntersection + + /// + /// Finds out if there is any intersection between two rotated rectangles. + /// If there is then the vertices of the interesecting region are returned as well. + /// Below are some examples of intersection configurations. + /// The hatched pattern indicates the intersecting region and the red + /// vertices are returned by the function. + /// + /// First rectangle + /// Second rectangle + /// + /// The output array of the verticies of the intersecting region. + /// It returns at most 8 vertices. + /// 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) + { + if (intersectingRegion == null) + throw new ArgumentNullException(nameof(intersectingRegion)); + intersectingRegion.ThrowIfNotReady(); + + var ret = NativeMethods.imgproc_rotatedRectangleIntersection_OutputArray( + rect1, rect2, intersectingRegion.CvPtr); + GC.KeepAlive(intersectingRegion); + intersectingRegion.Fix(); + + return (RectanglesIntersectTypes)ret; + } + + /// + /// Finds out if there is any intersection between two rotated rectangles. + /// If there is then the vertices of the interesecting region are returned as well. + /// Below are some examples of intersection configurations. + /// The hatched pattern indicates the intersecting region and the red + /// vertices are returned by the function. + /// + /// First rectangle + /// Second rectangle + /// + /// The output array of the verticies of the intersecting region. + /// It returns at most 8 vertices. + /// + public static RectanglesIntersectTypes RotatedRectangleIntersection( + RotatedRect rect1, RotatedRect rect2, out Point2f[] intersectingRegion) + { + using (var intersectingRegionVec = new VectorOfPoint2f()) + { + var ret = NativeMethods.imgproc_rotatedRectangleIntersection_vector( + rect1, rect2, intersectingRegionVec.CvPtr); + intersectingRegion = intersectingRegionVec.ToArray(); + return (RectanglesIntersectTypes) ret; + } + } + + #endregion + + /// + /// Applies a GNU Octave/MATLAB equivalent colormap on a given image. + /// + /// + /// + /// + public static void ApplyColorMap(InputArray src, OutputArray dst, ColormapTypes colormap) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.imgproc_applyColorMap(src.CvPtr, dst.CvPtr, (int)colormap); + GC.KeepAlive(src); + GC.KeepAlive(dst); + dst.Fix(); + } + + #region Drawing + #region Line +#if LANG_JP + /// + /// 2点を結ぶ線分を画像上に描画する. + /// + /// 画像 + /// 線分の1番目の端点x + /// 線分の1番目の端点y + /// 線分の2番目の端点x + /// 線分の2番目の端点y + /// 線分の色 + /// 線分の太さ. [既定値は1] + /// 線分の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws a line segment connecting two points + /// + /// The image. + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 2点を結ぶ線分を画像上に描画する. + /// + /// 画像 + /// 線分の1番目の端点 + /// 線分の2番目の端点 + /// 線分の色 + /// 線分の太さ. [既定値は1] + /// 線分の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws a line segment connecting two points + /// + /// The image. + /// 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] +#endif + public static void Line( + InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfNotReady(); + NativeMethods.imgproc_line(img.CvPtr, pt1, pt2, color, thickness, (int)lineType, shift); + img.Fix(); + GC.KeepAlive(img); + } + #endregion + + /// + /// Draws a arrow segment pointing from the first point to the second one. + /// The function arrowedLine draws an arrow between pt1 and pt2 points in the image. + /// See also cv::line. + /// + /// Image. + /// The point the arrow starts from. + /// The point the arrow points to. + /// Line color. + /// Line thickness. + /// Type of the line, see cv::LineTypes + /// 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, + Point pt1, Point pt2, + Scalar color, + int thickness = 1, + LineTypes lineType = LineTypes.Link8, + int shift = 0, + double tipLength = 0.1) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfNotReady(); + + NativeMethods.imgproc_arrowedLine( + img.CvPtr, pt1, pt2, color, thickness, (int)lineType, shift, tipLength); + GC.KeepAlive(img); + img.Fix(); + } + + #region Rectangle +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 画像 + /// 矩形の一つの頂点 + /// 矩形の反対側の頂点 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws simple, thick or filled rectangle + /// + /// Image. + /// 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] +#endif + public static void Rectangle( + InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + NativeMethods.imgproc_rectangle_InputOutputArray(img.CvPtr, pt1, pt2, color, thickness, (int)lineType, shift); + img.Fix(); + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 画像 + /// 矩形 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws simple, thick or filled rectangle + /// + /// Image. + /// 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] +#endif + public static void Rectangle( + InputOutputArray img, Rect rect, Scalar color, int thickness = 1, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + NativeMethods.imgproc_rectangle_InputOutputArray(img.CvPtr, rect.TopLeft, rect.BottomRight, color, thickness, (int)lineType, shift); + img.Fix(); + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 画像 + /// 矩形の一つの頂点 + /// 矩形の反対側の頂点 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws simple, thick or filled rectangle + /// + /// Image. + /// 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] +#endif + public static void Rectangle( + Mat img, Point pt1, Point pt2, Scalar color, int thickness = 1, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + var rect = Rect.FromLTRB(pt1.X, pt1.Y, pt2.X, pt2.Y); + NativeMethods.imgproc_rectangle_Mat(img.CvPtr, rect, color, thickness, (int)lineType, shift); + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 画像 + /// 矩形 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws simple, thick or filled rectangle + /// + /// Image. + /// 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] +#endif + public static void Rectangle( + Mat img, Rect rect, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + NativeMethods.imgproc_rectangle_Mat(img.CvPtr, rect, color, thickness, (int)lineType, shift); + GC.KeepAlive(img); + } + + #endregion + #region Circle +#if LANG_JP + /// + /// 円を描画する + /// + /// 画像 + /// 円の中心のx座標 + /// 円の中心のy座標 + /// 円の半径 + /// 円の色 + /// 線の幅.負の値を指定した場合は塗りつぶされる.[既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 中心座標と半径の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws a circle + /// + /// Image where the circle is drawn. + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 円を描画する + /// + /// 画像 + /// 円の中心 + /// 円の半径 + /// 円の色 + /// 線の幅.負の値を指定した場合は塗りつぶされる.[既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 中心座標と半径の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// Draws a circle + /// + /// Image where the circle is drawn. + /// 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] +#endif + public static void Circle(InputOutputArray img, Point center, int radius, Scalar color, + int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + NativeMethods.imgproc_circle(img.CvPtr, center, radius, color, thickness, (int)lineType, shift); + img.Fix(); + GC.KeepAlive(img); + } + #endregion + #region Ellipse +#if LANG_JP + /// + /// 枠だけの楕円,楕円弧,もしくは塗りつぶされた扇形の楕円を描画する + /// + /// 楕円が描画される画像 + /// 楕円の中心 + /// 楕円の軸の長さ + /// 回転角度 + /// 楕円弧の開始角度 + /// 楕円弧の終了角度 + /// 楕円の色 + /// 楕円弧の線の幅 [既定値は1] + /// 楕円弧の線の種類 [既定値はLineType.Link8] + /// 中心座標と軸の長さの小数点以下の桁を表すビット数 [既定値は0] +#else + /// + /// Draws simple or thick elliptic arc or fills ellipse sector + /// + /// Image. + /// 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] +#endif + public static void Ellipse( + InputOutputArray 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 == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfNotReady(); + NativeMethods.imgproc_ellipse1(img.CvPtr, center, axes, angle, startAngle, endAngle, color, thickness, (int)lineType, shift); + img.Fix(); + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 枠だけの楕円,もしくは塗りつぶされた楕円を描画する + /// + /// 楕円が描かれる画像. + /// 描画したい楕円を囲む矩形領域. + /// 楕円の色. + /// 楕円境界線の幅.[既定値は1] + /// 楕円境界線の種類.[既定値はLineType.Link8] +#else + /// + /// Draws simple or thick elliptic arc or fills ellipse sector + /// + /// Image. + /// 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] +#endif + public static void Ellipse(InputOutputArray img, RotatedRect box, Scalar color, + int thickness = 1, LineTypes lineType = LineTypes.Link8) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + NativeMethods.imgproc_ellipse2(img.CvPtr, box, color, thickness, (int)lineType); + img.Fix(); + GC.KeepAlive(img); + } + #endregion + #region FillConvexPoly +#if LANG_JP + /// + /// 塗りつぶされた凸ポリゴンを描きます. + /// + /// 画像 + /// ポリゴンの頂点. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. +#else + /// + /// Fills a convex polygon. + /// + /// Image + /// The polygon vertices + /// Polygon color + /// Type of the polygon boundaries + /// The number of fractional bits in the vertex coordinates +#endif + public static void FillConvexPoly(Mat img, IEnumerable pts, Scalar color, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + + var ptsArray = EnumerableEx.ToArray(pts); + NativeMethods.imgproc_fillConvexPoly_Mat(img.CvPtr, ptsArray, ptsArray.Length, color, (int)lineType, shift); + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 塗りつぶされた凸ポリゴンを描きます. + /// + /// 画像 + /// ポリゴンの頂点. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. +#else + /// + /// Fills a convex polygon. + /// + /// Image + /// The polygon vertices + /// Polygon color + /// Type of the polygon boundaries + /// The number of fractional bits in the vertex coordinates +#endif + public static void FillConvexPoly(InputOutputArray img, InputArray pts, Scalar color, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (pts == null) + throw new ArgumentNullException(nameof(pts)); + img.ThrowIfDisposed(); + pts.ThrowIfDisposed(); + + NativeMethods.imgproc_fillConvexPoly_InputOutputArray( + img.CvPtr, pts.CvPtr, color, (int)lineType, shift); + GC.KeepAlive(img); + GC.KeepAlive(pts); + } + #endregion + #region FillPoly +#if LANG_JP + /// + /// 1つ,または複数のポリゴンで区切られた領域を塗りつぶします. + /// + /// 画像 + /// ポリゴンの配列.各要素は,点の配列で表現されます. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. + /// +#else + /// + /// Fills the area bounded by one or more polygons + /// + /// Image + /// 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 + /// +#endif + public static void FillPoly( + Mat img, IEnumerable> pts, Scalar color, + LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + var offset0 = offset.GetValueOrDefault(new Point()); + + var ptsList = new List(); + var nptsList = new List(); + foreach (var pts1 in pts) + { + var pts1Arr = EnumerableEx.ToArray(pts1); + ptsList.Add(pts1Arr); + nptsList.Add(pts1Arr.Length); + } + var ptsArr = ptsList.ToArray(); + var npts = nptsList.ToArray(); + var ncontours = ptsArr.Length; + using (var ptsPtr = new ArrayAddress2(ptsArr)) + { + NativeMethods.imgproc_fillPoly_Mat( + img.CvPtr, ptsPtr.Pointer, npts, ncontours, color, (int)lineType, shift, offset0); + } + GC.KeepAlive(img); + } + +#if LANG_JP + /// + /// 1つ,または複数のポリゴンで区切られた領域を塗りつぶします. + /// + /// 画像 + /// ポリゴンの配列.各要素は,点の配列で表現されます. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. + /// +#else + /// + /// Fills the area bounded by one or more polygons + /// + /// Image + /// 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 + /// +#endif + public static void FillPoly( + InputOutputArray img, InputArray pts, Scalar color, + LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (pts == null) + throw new ArgumentNullException(nameof(pts)); + img.ThrowIfDisposed(); + pts.ThrowIfDisposed(); + var offset0 = offset.GetValueOrDefault(new Point()); + + NativeMethods.imgproc_fillPoly_InputOutputArray( + img.CvPtr, pts.CvPtr, color, (int)lineType, shift, offset0); + GC.KeepAlive(img); + GC.KeepAlive(pts); + img.Fix(); + } + #endregion + #region Polylines + /// + /// draws one or more polygonal curves + /// + /// + /// + /// + /// + /// + /// + /// + public static void Polylines( + Mat img, IEnumerable> pts, bool isClosed, Scalar color, + int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + img.ThrowIfDisposed(); + + var ptsList = new List(); + var nptsList = new List(); + foreach (var pts1 in pts) + { + var pts1Arr = EnumerableEx.ToArray(pts1); + ptsList.Add(pts1Arr); + nptsList.Add(pts1Arr.Length); + } + var ptsArr = ptsList.ToArray(); + var npts = nptsList.ToArray(); + var ncontours = ptsArr.Length; + using (var ptsPtr = new ArrayAddress2(ptsArr)) + { + NativeMethods.imgproc_polylines_Mat( + img.CvPtr, ptsPtr.Pointer, npts, ncontours, isClosed ? 1 : 0, color, thickness, (int)lineType, shift); + GC.KeepAlive(img); + } + } + + /// + /// draws one or more polygonal curves + /// + /// + /// + /// + /// + /// + /// + /// + public static void Polylines( + InputOutputArray img, InputArray pts, bool isClosed, Scalar color, + int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (pts == null) + throw new ArgumentNullException(nameof(pts)); + img.ThrowIfDisposed(); + pts.ThrowIfDisposed(); + + NativeMethods.imgproc_polylines_InputOutputArray( + img.CvPtr, pts.CvPtr, isClosed ? 1 : 0, color, thickness, (int)lineType, shift); + GC.KeepAlive(img); + img.Fix(); + GC.KeepAlive(pts); + } + + #endregion + + #region DrawContours +#if LANG_JP + /// + /// 輪郭線,または内側が塗りつぶされた輪郭を描きます. + /// + /// 出力画像 + /// 入力される全輪郭.各輪郭は,点のベクトルとして格納されています. + /// 描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます. + /// 輪郭の色. + /// 輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます. + /// 線の連結性 + /// 階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります. + /// 描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます. + /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と, + /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, + /// hierarchy が有効な場合のみ考慮されます. + /// 輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます. +#else + /// + /// draws contours in the image + /// + /// Destination 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) +#endif + public static void DrawContours( + InputOutputArray image, + IEnumerable> contours, + int contourIdx, + Scalar color, + int thickness = 1, + LineTypes lineType = LineTypes.Link8, + IEnumerable? hierarchy = null, + int maxLevel = Int32.MaxValue, + Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (contours == null) + throw new ArgumentNullException(nameof(contours)); + image.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + var contoursArray = EnumerableEx.SelectToArray(contours, EnumerableEx.ToArray); + var contourSize2 = EnumerableEx.SelectToArray(contoursArray, pts => pts.Length); + using (var contoursPtr = new ArrayAddress2(contoursArray)) + { + if (hierarchy == null) + { + NativeMethods.imgproc_drawContours_vector(image.CvPtr, contoursPtr.Pointer, contoursArray.Length, contourSize2, + contourIdx, color, thickness, (int)lineType, IntPtr.Zero, 0, maxLevel, offset0); + } + else + { + var hierarchyVecs = EnumerableEx.SelectToArray(hierarchy, hi => hi.ToVec4i()); + NativeMethods.imgproc_drawContours_vector(image.CvPtr, contoursPtr.Pointer, contoursArray.Length, contourSize2, + contourIdx, color, thickness, (int)lineType, hierarchyVecs, hierarchyVecs.Length, maxLevel, offset0); + } + } + GC.KeepAlive(image); + image.Fix(); + } +#if LANG_JP + /// + /// 輪郭線,または内側が塗りつぶされた輪郭を描きます. + /// + /// 出力画像 + /// 入力される全輪郭.各輪郭は,点のベクトルとして格納されています. + /// 描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます. + /// 輪郭の色. + /// 輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます. + /// 線の連結性 + /// 階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります. + /// 描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます. + /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と, + /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, + /// hierarchy が有効な場合のみ考慮されます. + /// 輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます. +#else + /// + /// draws contours in the image + /// + /// Destination 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) +#endif + public static void DrawContours( + InputOutputArray image, + IEnumerable contours, + int contourIdx, + Scalar color, + int thickness = 1, + LineTypes lineType = LineTypes.Link8, + Mat? hierarchy = null, + int maxLevel = int.MaxValue, + Point? offset = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (contours == null) + throw new ArgumentNullException(nameof(contours)); + image.ThrowIfNotReady(); + + var offset0 = offset.GetValueOrDefault(new Point()); + var contoursPtr = EnumerableEx.SelectPtrs(contours); + NativeMethods.imgproc_drawContours_InputArray(image.CvPtr, contoursPtr, contoursPtr.Length, + contourIdx, color, thickness, (int)lineType, ToPtr(hierarchy), maxLevel, offset0); + image.Fix(); + GC.KeepAlive(image); + GC.KeepAlive(contours); + GC.KeepAlive(hierarchy); + } + #endregion + + #region ClipLine +#if LANG_JP + /// + /// 線分が画像矩形内に収まるように切り詰めます. + /// + /// 画像サイズ. + /// 線分の1番目の端点. + /// 線分の2番目の端点. + /// +#else + /// + /// Clips the line against the image rectangle + /// + /// The image size + /// The first line point + /// The second line point + /// +#endif + public static bool ClipLine(Size imgSize, ref Point pt1, ref Point pt2) + { + return NativeMethods.imgproc_clipLine1(imgSize, ref pt1, ref pt2) != 0; + } +#if LANG_JP + /// + /// 線分が画像矩形内に収まるように切り詰めます. + /// + /// 画像矩形. + /// 線分の1番目の端点. + /// 線分の2番目の端点. + /// +#else + /// + /// Clips the line against the image rectangle + /// + /// sThe image rectangle + /// The first line point + /// The second line point + /// +#endif + public static bool ClipLine(Rect imgRect, ref Point pt1, ref Point pt2) + { + return NativeMethods.imgproc_clipLine2(imgRect, ref pt1, ref pt2) != 0; + } + #endregion + + /// + /// Approximates an elliptic arc with a polyline. + /// The function ellipse2Poly computes the vertices of a polyline that + /// approximates the specified elliptic arc. It is used by cv::ellipse. + /// + /// Center of the arc. + /// Half of the size of the ellipse main axes. See the ellipse for details. + /// Rotation angle of the ellipse in degrees. See the ellipse for details. + /// Starting angle of the elliptic arc in degrees. + /// Ending angle of the elliptic arc in degrees. + /// Angle between the subsequent polyline vertices. It defines the approximation + /// Output vector of polyline vertices. + public static Point[] Ellipse2Poly(Point center, Size axes, int angle, + int arcStart, int arcEnd, int delta) + { + using (var vec = new VectorOfPoint()) + { + NativeMethods.imgproc_ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta, vec.CvPtr); + return vec.ToArray(); + } + } + + /// + /// renders text string in the image + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + 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) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + if (String.IsNullOrEmpty(text)) + throw new ArgumentNullException(text); + img.ThrowIfDisposed(); + NativeMethods.core_putText(img.CvPtr, text, org, (int)fontFace, fontScale, color, + thickness, (int)lineType, bottomLeftOrigin ? 1 : 0); + img.Fix(); + GC.KeepAlive(img); + } + + /// + /// returns bounding box of the text string + /// + /// + /// + /// + /// + /// + /// + public static Size GetTextSize(string text, HersheyFonts fontFace, + double fontScale, int thickness, out int baseLine) + { + if (String.IsNullOrEmpty(text)) + throw new ArgumentNullException(text); + return NativeMethods.core_getTextSize(text, (int)fontFace, fontScale, thickness, out baseLine); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/CvObject.cs b/OpenVinoOpenCvSharp/Fundamentals/CvObject.cs new file mode 100644 index 0000000..9a6ae04 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/CvObject.cs @@ -0,0 +1,64 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// OpenCVのネイティブポインタをもったクラスの基本クラス + /// +#else + /// + /// A class which has a pointer of OpenCV structure + /// +#endif + public abstract class CvObject : ICvPtrHolder + { + /// + /// Data pointer + /// + protected IntPtr ptr; + +#if LANG_JP + /// + /// + /// +#else + /// + /// Default constructor + /// +#endif + protected CvObject() + { + } + +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + protected CvObject(IntPtr ptr) + { + this.ptr = ptr; + } + +#if LANG_JP + /// + /// OpenCVの構造体へのネイティブポインタ + /// +#else + /// + /// Native pointer of OpenCV structure + /// +#endif + public IntPtr CvPtr + { + get { return ptr; } + } + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/DisposableCvObject.cs b/OpenVinoOpenCvSharp/Fundamentals/DisposableCvObject.cs new file mode 100644 index 0000000..ef4fa23 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/DisposableCvObject.cs @@ -0,0 +1,116 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// リソースを解放すべきOpenCVのクラスに継承させる基本クラス + /// +#else + /// + /// DisposableObject + ICvPtrHolder + /// +#endif + public abstract class DisposableCvObject : DisposableObject, ICvPtrHolder + { + /// + /// Data pointer + /// + protected IntPtr ptr; + + #region Init and Dispose +#if LANG_JP + /// + /// + /// +#else + /// + /// Default constructor + /// +#endif + protected DisposableCvObject() + : this(true) + { + } + +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + protected DisposableCvObject(IntPtr ptr) + : this(ptr, true) + { + } + +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + protected DisposableCvObject(bool isEnabledDispose) + : this(IntPtr.Zero, isEnabledDispose) + { + } + +#if LANG_JP + /// + /// + /// + /// + /// +#else + /// + /// + /// + /// + /// +#endif + protected DisposableCvObject(IntPtr ptr, bool isEnabledDispose) + : base(isEnabledDispose) + { + this.ptr = ptr; + } + + /// + /// releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + ptr = IntPtr.Zero; + base.DisposeUnmanaged(); + } + + #endregion + +#if LANG_JP + /// + /// OpenCVの構造体へのネイティブポインタ + /// +#else + /// + /// Native pointer of OpenCV structure + /// +#endif + public IntPtr CvPtr + { + get + { + ThrowIfDisposed(); + return ptr; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/DisposableObject.cs b/OpenVinoOpenCvSharp/Fundamentals/DisposableObject.cs new file mode 100644 index 0000000..dc920f8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/DisposableObject.cs @@ -0,0 +1,306 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 解放処理を行うクラスが継承するための基本クラス + /// +#else + /// + /// Represents a class which manages its own memory. + /// +#endif + public abstract class DisposableObject : IDisposable + { + /// + /// Gets or sets a handle which allocates using cvSetData. + /// + protected GCHandle DataHandle { get; private set; } + + private volatile int disposeSignaled = 0; + + #region Properties +#if LANG_JP + /// + /// リソースが解放済みかどうかを取得する + /// +#else + /// + /// Gets a value indicating whether this instance has been disposed. + /// +#endif + public bool IsDisposed { get; protected set; } + +#if LANG_JP + /// + /// 解放処理を許可するかどうかを取得・設定する. falseならばDisposeは何もしない. + /// 通常はユーザはこのフラグを変更してはならない. CvCapture.QueryFrameで取得したIplImageのように, + /// 解放処理をするとエラーとなるオブジェクトの場合に自動的にこのフラグがfalseとなる。 + /// +#else + /// + /// Gets or sets a value indicating whether you permit disposing this instance. + /// +#endif + public bool IsEnabledDispose { get; set; } + + +#if LANG_JP + /// + /// cvCreateXXX といった関数がなく自前で構造体の分のメモリを確保する場合、 + /// そのアドレスを入れておく場所 + /// +#else + /// + /// Gets or sets a memory address allocated by AllocMemory. + /// +#endif + protected IntPtr AllocatedMemory { get; set; } + +#if LANG_JP + /// + /// AllocatedMemoryに確保されているメモリのサイズ + /// +#else + /// + /// Gets or sets the byte length of the allocated memory + /// +#endif + protected long AllocatedMemorySize { get; set; } + + #endregion + + #region Init and Dispossal +#if LANG_JP + /// + /// デフォルトコンストラクタ + /// +#else + /// + /// Default constructor + /// +#endif + protected DisposableObject() + : this(true) + { + } + +#if LANG_JP + /// + /// 解放の可否を指定して初期化 + /// + /// GCで解放するならtrue +#else + /// + /// Constructor + /// + /// true if you permit disposing this class by GC +#endif + protected DisposableObject(bool isEnabledDispose) + { + IsDisposed = false; + IsEnabledDispose = isEnabledDispose; + AllocatedMemory = IntPtr.Zero; + AllocatedMemorySize = 0; + } + +#if LANG_JP + /// + /// リソースの解放 + /// +#else + /// + /// Releases the resources + /// +#endif + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + +#if LANG_JP + /// + /// リソースの解放 + /// + /// + /// trueの場合は、このメソッドがユーザコードから直接が呼ばれたことを示す。マネージ・アンマネージ双方のリソースが解放される。 + /// falseの場合は、このメソッドはランタイムからファイナライザによって呼ばれ、もうほかのオブジェクトから参照されていないことを示す。アンマネージリソースのみ解放される。 + /// +#else + /// + /// Releases the resources + /// + /// + /// If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and unmanaged resources can be disposed. + /// If false, the method has been called by the runtime from inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed. + /// +#endif + protected virtual void Dispose(bool disposing) + { +#pragma warning disable 420 + // http://stackoverflow.com/questions/425132/a-reference-to-a-volatile-field-will-not-be-treated-as-volatile-implications + if (Interlocked.Exchange(ref disposeSignaled, 1) != 0) + { + return; + } + + IsDisposed = true; + + if (IsEnabledDispose) + { + if (disposing) + { + DisposeManaged(); + } + DisposeUnmanaged(); + } + } + +#if LANG_JP + /// + /// デストラクタ + /// +#else + /// + /// Destructor + /// +#endif + ~DisposableObject() + { + Dispose(false); + } + + /// + /// Releases managed resources + /// + protected virtual void DisposeManaged() + { + } + + /// + /// Releases unmanaged resources + /// + protected virtual void DisposeUnmanaged() + { + if (DataHandle.IsAllocated) + { + DataHandle.Free(); + } + if (AllocatedMemorySize > 0) + { + GC.RemoveMemoryPressure(AllocatedMemorySize); + AllocatedMemorySize = 0; + } + if (AllocatedMemory != IntPtr.Zero) + { + Marshal.FreeHGlobal(AllocatedMemory); + AllocatedMemory = IntPtr.Zero; + } + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// cvSetDataで割り当てる配列データをGCHandleでピン止めする + /// + /// +#else + /// + /// Pins the object to be allocated by cvSetData. + /// + /// + /// +#endif + // ReSharper disable once InconsistentNaming + protected internal GCHandle AllocGCHandle(object obj) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + if (DataHandle.IsAllocated) + DataHandle.Free(); + DataHandle = GCHandle.Alloc(obj, GCHandleType.Pinned); + return DataHandle; + } + +#if LANG_JP + /// + /// 指定したサイズの量のメモリを割り当てる。 + /// Dispose時に解放する + /// + /// 割り当てたメモリ +#else + /// + /// Allocates the specified size of memory. + /// + /// + /// +#endif + protected IntPtr AllocMemory(int size) + { + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size)); + + if (AllocatedMemory != IntPtr.Zero) + Marshal.FreeHGlobal(AllocatedMemory); + AllocatedMemory = Marshal.AllocHGlobal(size); + NotifyMemoryPressure(size); + return AllocatedMemory; + } + +#if LANG_JP + /// + /// アンマネージメモリを確保したメモリサイズを通知する。 + /// + /// 実際に確保するならAllocMemoryのほうを使う。 + /// 確保はcvCreateXXXがやってくれるという場合はこっちを使う + /// + /// +#else + /// + /// Notifies the allocated size of memory. + /// + /// +#endif + protected void NotifyMemoryPressure(long size) + { + // マルチスレッド動作時にロックがかかるらしい。いったん廃止 + if (!IsEnabledDispose) + return; + if (size == 0) + return; + if (size <= 0) + throw new ArgumentOutOfRangeException(nameof(size)); + + if (AllocatedMemorySize > 0) + GC.RemoveMemoryPressure(AllocatedMemorySize); + + AllocatedMemorySize = size; + GC.AddMemoryPressure(size); + } + +#if LANG_JP + /// + /// このオブジェクトが解放済みの場合はObjectDisposedExceptionを投げる + /// +#else + /// + /// If this object is disposed, then ObjectDisposedException is thrown. + /// +#endif + public void ThrowIfDisposed() + { + if (IsDisposed) + throw new ObjectDisposedException(GetType().FullName); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/ICvPtrHolder.cs b/OpenVinoOpenCvSharp/Fundamentals/ICvPtrHolder.cs new file mode 100644 index 0000000..9284f38 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/ICvPtrHolder.cs @@ -0,0 +1,21 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// OpenCVのネイティブデータポインタを持つことを示すインターフェイス + /// +#else + /// + /// Represents a OpenCV-based class which has a native pointer. + /// +#endif + public interface ICvPtrHolder + { + /// + /// Unmanaged OpenCV data pointer + /// + IntPtr CvPtr { get; } + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/OpenCVException.cs b/OpenVinoOpenCvSharp/Fundamentals/OpenCVException.cs new file mode 100644 index 0000000..bb9c531 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/OpenCVException.cs @@ -0,0 +1,136 @@ +using System; +using System.Runtime.Serialization; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// OpenCVから投げられる例外 + /// +#else + /// + /// The default exception to be thrown by OpenCV + /// +#endif + [Serializable] + // ReSharper disable once InconsistentNaming + public class OpenCVException : Exception + { + #region Properties + +#if LANG_JP + /// + /// エラーステータス + /// +#else + /// + /// The numeric code for error status + /// +#endif + public ErrorCode Status { get; set; } + +#if LANG_JP + /// + /// エラーが発生したOpenCVの関数名. + /// +#else + /// + /// The source file name where error is encountered + /// +#endif + public string FuncName { get; set; } + +#if LANG_JP + /// + /// エラーについての追加情報/診断結果 + /// +#else + /// + /// A description of the error + /// +#endif + public string ErrMsg { get; set; } + +#if LANG_JP + /// + /// エラーが発生したファイル名 + /// +#else + /// + /// The source file name where error is encountered + /// +#endif + public string FileName { get; set; } + +#if LANG_JP + /// + /// エラーが発生した行番号 + /// +#else + /// + /// The line number in the source where error is encountered + /// +#endif + public int Line { get; set; } + + #endregion + +#if LANG_JP + /// + /// 初期化 + /// + /// エラーステータス + /// エラーが発生した関数名 + /// エラーについての追加情報/診断結果 + /// エラーが発生したファイル名 + /// エラーが発生した行番号 +#else + /// + /// Constructor + /// + /// The numeric code for error status + /// The source file name where error is encountered + /// A description of the error + /// The source file name where error is encountered + /// The line number in the souce where error is encountered +#endif + public OpenCVException(ErrorCode status, string funcName, string errMsg, string fileName, int line) + : base(errMsg) + { + Status = status; + FuncName = funcName; + ErrMsg = errMsg; + FileName = fileName; + Line = line; + } + + /// + /// + /// + /// + /// + protected OpenCVException(SerializationInfo info, StreamingContext context) : base(info, context) + { + Status = (ErrorCode) info.GetInt32(nameof(Status)); + FuncName = info.GetString(nameof(FuncName)) ?? ""; + FileName = info.GetString(nameof(FileName)) ?? ""; + ErrMsg = info.GetString(nameof(ErrMsg)) ?? ""; + Line = info.GetInt32(nameof(Line)); + } + + /// + /// + /// + /// + /// + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(Status), Status); + info.AddValue(nameof(FuncName), FuncName); + info.AddValue(nameof(FileName), FileName); + info.AddValue(nameof(ErrMsg), ErrMsg); + info.AddValue(nameof(Line), Line); + } + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/OpenCvSharpException.cs b/OpenVinoOpenCvSharp/Fundamentals/OpenCvSharpException.cs new file mode 100644 index 0000000..b993855 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/OpenCvSharpException.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.Serialization; + +namespace OpenCvSharp +{ +#if LANG_JP +/// +/// OpenCvSharpから投げられる例外 +/// +#else + /// + /// The exception that is thrown by OpenCvSharp. + /// +#endif + [Serializable] + public class OpenCvSharpException : Exception + { + /// + public OpenCvSharpException() + { + } + + /// + /// + public OpenCvSharpException(string message) + : base(message) + { + } + + /// + /// + /// + public OpenCvSharpException(string messageFormat, params object[] args) + : base(string.Format(messageFormat, args)) + { + } + + /// + /// + /// + public OpenCvSharpException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// + /// + protected OpenCvSharpException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} diff --git a/OpenVinoOpenCvSharp/Fundamentals/Ptr.cs b/OpenVinoOpenCvSharp/Fundamentals/Ptr.cs new file mode 100644 index 0000000..1f37e39 --- /dev/null +++ b/OpenVinoOpenCvSharp/Fundamentals/Ptr.cs @@ -0,0 +1,24 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Template class for smart reference-counting pointers + /// + public abstract class Ptr : DisposableCvObject + { + /// + /// Constructor + /// + /// + protected Ptr(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// Returns Ptr<T>.get() pointer + /// + public abstract IntPtr Get(); + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/CalibrationFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/CalibrationFlags.cs new file mode 100644 index 0000000..99a0e3b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/CalibrationFlags.cs @@ -0,0 +1,210 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvCalibrateCamera2やcvStereoCalibrateの処理フラグ + /// +#else + /// + /// Different flags for cvCalibrateCamera2 and cvStereoCalibrate + /// +#endif + [Flags] + public enum CalibrationFlags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// intrinsic_matrixは最適化が行われた正しい初 期値 fx, fy, cx, cyを含む.このパラメータがセッ トされていない場合,(cx, cy) は最初に画像中心にセットされ(image_size はこの計算に用いられ る),焦点距離は最小二乗法で計算される. + /// +#else + /// + /// The flag allows the function to optimize some or all of the intrinsic parameters, depending on the other flags, but the initial values are provided by the user + /// +#endif + UseIntrinsicGuess = 0x00001, + +#if LANG_JP + /// + /// fx と fy のうちのどちらか一方だけが独立変数であるとし,アスペクト比 fx/fy が intrinsic_matrix の初期値として与えられた値か ら変わらないように最適化処理を行う. + /// この場合,実際に用いられる(fx, fy)の初期値は,行列から与えられる (CV_CALIB_USE_INTRINSIC_GUESSがセットされている場合)か,何らかの方法で推定される(後者の場合は, fx, fy は任意の値にセットされ,それらの比率だけが用いられる). + /// +#else + /// + /// fyk is optimized, but the ratio fxk/fyk is fixed. + /// +#endif + FixAspectRatio = 0x00002, + +#if LANG_JP + /// + /// 主点(光学中心) は最適化中には変化せず,中心または別の指定された場所(このパラメータと同時 に UseIntrinsicGuess がセットされ ている場合)に固定される + /// +#else + /// + /// The principal points are fixed during the optimization. + /// +#endif + FixPrincipalPoint = 0x00004, + +#if LANG_JP + /// + /// 円周方向の歪み係数は0にセットされ,最適化中は変化しない + /// +#else + /// + /// Tangential distortion coefficients are set to zeros and do not change during the optimization. + /// +#endif + ZeroTangentDist = 0x00008, + +#if LANG_JP + /// + /// fxk および fyk が固定される. + /// +#else + /// + /// fxk and fyk are fixed. + /// +#endif + FixFocalLength = 0x00010, + +#if LANG_JP + /// + /// 0 番目の歪み係数(k1)が固定される. + /// +#else + /// + /// The 0-th distortion coefficients (k1) are fixed + /// +#endif + FixK1 = 0x00020, + + +#if LANG_JP + /// + /// 1 番目の歪み係数(k2)が固定される. + /// +#else + /// + /// The 1-th distortion coefficients (k2) are fixed + /// +#endif + FixK2 = 0x00040, + + +#if LANG_JP + /// + /// 4 番目の歪み係数(k3)が固定される. + /// +#else + /// + /// The 4-th distortion coefficients (k3) are fixed + /// +#endif + FixK3 = 0x00080, + + +#if LANG_JP + /// + /// 最適化中に,指定した半径方向の歪み係数を変更しません. + /// CV_CALIB_USE_INTRINSIC_GUESS が指定されている場合は,与えられた distCoeffs 行列の係数が利用されます.そうでない場合は,0が利用されます. + /// +#else + /// + /// Do not change the corresponding radial distortion coefficient during the optimization. + /// If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used, otherwise it is set to 0. + /// +#endif + FixK4 = 0x00800, + + +#if LANG_JP + /// + /// 最適化中に,指定した半径方向の歪み係数を変更しません. + /// CV_CALIB_USE_INTRINSIC_GUESS が指定されている場合は,与えられた distCoeffs 行列の係数が利用されます.そうでない場合は,0が利用されます. + /// +#else + /// + /// Do not change the corresponding radial distortion coefficient during the optimization. + /// If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used, otherwise it is set to 0. + /// +#endif + FixK5 = 0x01000, + + +#if LANG_JP + /// + /// 最適化中に,指定した半径方向の歪み係数を変更しません. + /// CV_CALIB_USE_INTRINSIC_GUESS が指定されている場合は,与えられた distCoeffs 行列の係数が利用されます.そうでない場合は,0が利用されます. + /// +#else + /// + /// Do not change the corresponding radial distortion coefficient during the optimization. + /// If CV_CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the supplied distCoeffs matrix is used, otherwise it is set to 0. + /// +#endif + FixK6 = 0x02000, + +#if LANG_JP + /// + /// 係数 k4, k5, k6 を有効にします. + /// 後方互換性を保つためには,このフラグを明示的に指定して,キャリブレーション関数が rational モデルを利用して8個の係数を返すようにします. + /// このフラグが指定されない場合,関数は5つの歪み係数のみを計算し ます. + /// +#else + /// + /// Enable coefficients k4, k5 and k6. + /// To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function + /// use the rational model and return 8 coefficients. If the flag is not set, the function will compute only 5 distortion coefficients. + /// +#endif + RationalModel = 0x04000, + + /// + /// + /// + ThinPrismModel = 0x08000, + + /// + /// + /// + FixS1S2S3S4 = 0x08000, + +#if LANG_JP + /// + /// これがセットされた場合,外部パラメータのみが最適化されるように, camera_matrix1,2 と dist_coeffs1,2 が固定される. + /// +#else + /// + /// If it is set, camera_matrix1,2, as well as dist_coeffs1,2 are fixed, so that only extrinsic parameters are optimized. + /// +#endif + FixIntrinsic = 0x00100, + +#if LANG_JP + /// + /// 強制的に,fx0=fx1, fy0=fy1 とする. + /// +#else + /// + /// Enforces fx0=fx1 and fy0=fy1. CV_CALIB_ZERO_TANGENT_DIST - Tangential distortion coefficients for each camera are set to zeros and fixed there. + /// +#endif + SameFocalLength = 0x00200, + + /// + /// for stereo rectification + /// + ZeroDisparity = 0x00400, + } +} + + + diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/ChessboardFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/ChessboardFlags.cs new file mode 100644 index 0000000..34efe40 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/ChessboardFlags.cs @@ -0,0 +1,75 @@ +using System; + +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvFindChessboardCornersの処理フラグ + /// +#else + /// + /// Various operation flags for cvFindChessboardCorners + /// +#endif + [Flags] + public enum ChessboardFlags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// 画像を二値化する際に,固定の閾値を使うのではなく,(画像の平均輝度値から計算される)適応的な閾値を用いる + /// +#else + /// + /// Use adaptive thresholding to convert the image to black-n-white, rather than a fixed threshold level (computed from the average image brightness). + /// +#endif + AdaptiveThresh = 1, + +#if LANG_JP + /// + /// 固定閾値処理または適応的閾値処理を行う前に,cvNormalizeHistを用いて画像を正規化する + /// +#else + /// + /// Normalize the image using cvNormalizeHist before applying fixed or adaptive thresholding. + /// +#endif + NormalizeImage = 2, + +#if LANG_JP + /// + /// 輪郭の探索 段階で抽出される間違った四角形を無視するために,追加基準(輪郭面積,周囲長,形は正方形など)を使用する + /// +#else + /// + /// Use additional criteria (like contour area, perimeter, square-like shape) to filter out false quads + /// that are extracted at the contour retrieval stage. + /// +#endif + FilterQuads = 4, + + /// + /// Run a fast check on the image that looks for chessboard corners, and shortcut the call if none is found. + /// This can drastically speed up the call in the degenerate condition when no chessboard is observed. + /// + FastCheck = 8, + + /// + /// Run an exhaustive search to improve detection rate. + /// + Exhaustive = 16, + + /// + /// Up sample input image to improve sub-pixel accuracy due to aliasing effects. + /// This should be used if an accurate camera calibration is required. + /// + Accuracy = 32 + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/EssentialMatMethod.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/EssentialMatMethod.cs new file mode 100644 index 0000000..b086a06 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/EssentialMatMethod.cs @@ -0,0 +1,22 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Method for computing the essential matrix + /// + [Flags] + public enum EssentialMatMethod + { + /// + /// for LMedS algorithm. + /// + LMedS = 4, + + + /// + /// for RANSAC algorithm. + /// + Ransac = 8, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FindCirclesGridFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FindCirclesGridFlags.cs new file mode 100644 index 0000000..8696c6b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FindCirclesGridFlags.cs @@ -0,0 +1,26 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Method for solving a PnP problem: + /// + [Flags] + public enum FindCirclesGridFlags + { + /// + /// uses symmetric pattern of circles. + /// + SymmetricGrid = 1, + + /// + /// uses asymmetric pattern of circles. + /// + AsymmetricGrid = 2, + + /// + /// uses a special algorithm for grid detection. It is more robust to perspective distortions but much more sensitive to background clutter. + /// + Clustering = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FishEyeCalibrationFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FishEyeCalibrationFlags.cs new file mode 100644 index 0000000..9223096 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FishEyeCalibrationFlags.cs @@ -0,0 +1,24 @@ +using System; + +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + #pragma warning disable CS1591 + + [Flags] + public enum FishEyeCalibrationFlags + { + None = 0, + UseIntrinsicGuess = 1, + RecomputeExtrinsic = 1 << 1, + CheckCond = 1 << 2, + FixSkew = 1 << 3, + FixK1 = 1 << 4, + FixK2 = 1 << 5, + FixK3 = 1 << 6, + FixK4 = 1 << 7, + FixIntrinsic = 1 << 8, + FixPrincipalPoint = 1 << 9 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FundamentalMatMethod.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FundamentalMatMethod.cs new file mode 100644 index 0000000..2bd4380 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/FundamentalMatMethod.cs @@ -0,0 +1,64 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 基礎行列の計算手法 + /// +#else + /// + /// Method for computing the fundamental matrix + /// +#endif + [Flags] + public enum FundamentalMatMethod + { +#if LANG_JP + /// + /// 7-pointアルゴリズム. N == 7 + /// +#else + /// + /// for 7-point algorithm. N == 7 + /// +#endif + Point7 = 1, + +#if LANG_JP + /// + /// 8-pointアルゴリズム. N > 8 + /// +#else + /// + /// for 8-point algorithm. N >= 8 + /// [CV_FM_8POINT] + /// +#endif + Point8 = 2, + +#if LANG_JP + /// + /// LMedSアルゴリズム. N >= 8 + /// +#else + /// + /// for LMedS algorithm. N > 8 + /// +#endif + LMedS = 4, + + +#if LANG_JP + /// + /// RANSAC アルゴリズム. N > 8 + /// [CV_FM_RANSAC] + /// +#else + /// + /// for RANSAC algorithm. N > 8 + /// +#endif + Ransac = 8, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/HomographyMethods.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/HomographyMethods.cs new file mode 100644 index 0000000..4a97ccf --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/HomographyMethods.cs @@ -0,0 +1,57 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// ホモグラフィ行列を計算するための手法 + /// +#else + /// + /// The method used to computed homography matrix + /// +#endif + [Flags] + public enum HomographyMethods + { +#if LANG_JP + /// + /// 全ての点のペアを利用する標準的な手法 + /// +#else + /// + /// Regular method using all the point pairs + /// +#endif + None = 0, + + +#if LANG_JP + /// + /// LMedS推定によるロバストな手法 + /// +#else + /// + /// Least-Median robust method + /// +#endif + LMedS = 4, + + +#if LANG_JP + /// + /// RANSACアルゴリズムに基づくロバストな手法 + /// +#else + /// + /// RANSAC-based robust method + /// +#endif + Ransac = 8, + + /// + /// RHO algorithm + /// + Rho = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/RobustEstimationAlgorithms.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/RobustEstimationAlgorithms.cs new file mode 100644 index 0000000..25445d8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/RobustEstimationAlgorithms.cs @@ -0,0 +1,25 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + /// + /// type of the robust estimation algorithm + /// + public enum RobustEstimationAlgorithms + { + /// + /// least-median of squares algorithm + /// + LMEDS = 4, + + /// + /// RANSAC algorithm + /// + RANSAC = 8, + + /// + /// RHO algorithm + /// + RHO = 16 + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/SolvePnPFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/SolvePnPFlags.cs new file mode 100644 index 0000000..ab5956e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/SolvePnPFlags.cs @@ -0,0 +1,38 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + /// + /// Method for solving a PnP problem: + /// + public enum SolvePnPFlags + { + /// + /// Iterative method is based on Levenberg-Marquardt optimization. + /// In this case the function finds such a pose that minimizes reprojection error, + /// that is the sum of squared distances between the observed projections imagePoints and the projected (using projectPoints() ) objectPoints . + /// + Iterative = 0, + + /// + /// Method has been introduced by F.Moreno-Noguer, V.Lepetit and P.Fua in the paper “EPnP: Efficient Perspective-n-Point Camera Pose Estimation”. + /// + EPNP = 1, + + /// + /// Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang“Complete Solution Classification for + /// the Perspective-Three-Point Problem”. In this case the function requires exactly four object and image points. + /// + P3P = 2, + + /// + /// Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" + /// + DLS = 3, + + /// + /// A.Penate-Sanchez, J.Andrade-Cetto, F.Moreno-Noguer. "Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation" + /// + UPNP = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/Enum/StereoRectificationFlags.cs b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/StereoRectificationFlags.cs new file mode 100644 index 0000000..ef98b7f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/Enum/StereoRectificationFlags.cs @@ -0,0 +1,39 @@ +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 輪郭の近似手法 + /// +#else + /// + /// The operation flags for cvStereoRectify + /// +#endif + public enum StereoRectificationFlags + { +#if LANG_JP + /// + /// フラグなし (=0). + /// 利用できる画像領域が最大になるように(エピポーラ線の傾きに従って)片方の画像を水平・垂直方向に移動する. + /// +#else + /// + /// Default value (=0). + /// the function can shift one of the image in horizontal or vertical direction (depending on the orientation of epipolar lines) in order to maximise the useful image area. + /// +#endif + None = 0, + + +#if LANG_JP + /// + /// 平行化後のビューにおいて各カメラの主点(光学中心)が同じ座標になるようにする. + /// +#else + /// + /// the function makes the principal points of each camera have the same pixel coordinates in the rectified views. + /// +#endif + ZeroDisparity = 1024, + }; +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/StereoBM.cs b/OpenVinoOpenCvSharp/Modules/calib3d/StereoBM.cs new file mode 100644 index 0000000..220ff75 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/StereoBM.cs @@ -0,0 +1,240 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming +#pragma warning disable 1591 + +#if LANG_JP + /// + /// セミグローバルブロックマッチングアルゴリズムを用てステレオ対応点探索を行うためのクラス + /// +#else + /// + /// Semi-Global Stereo Matching + /// +#endif + public class StereoBM : StereoMatcher + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// constructor + /// + protected StereoBM(IntPtr ptr) + : base(ptr) + { + ptrObj = new Ptr(ptr); + } + + /// + /// + /// + /// + /// + /// + public static StereoBM Create(int numDisparities = 0, int blockSize = 21) + { + var ptrObj = NativeMethods.calib3d_StereoBM_create(numDisparities, blockSize); + return new StereoBM(ptrObj); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int PreFilterType + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getPreFilterType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setPreFilterType(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int PreFilterSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getPreFilterSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setPreFilterSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int PreFilterCap + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getPreFilterCap(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setPreFilterCap(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int TextureThreshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getTextureThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setTextureThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int UniquenessRatio + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getUniquenessRatio(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setUniquenessRatio(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int SmallerBlockSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getSmallerBlockSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setSmallerBlockSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public Rect ROI1 + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getROI1(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setROI1(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public Rect ROI2 + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoBM_getROI2(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoBM_setROI2(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.calib3d_Ptr_StereoBM_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.calib3d_Ptr_StereoBM_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/StereoMatcher.cs b/OpenVinoOpenCvSharp/Modules/calib3d/StereoMatcher.cs new file mode 100644 index 0000000..fcaa676 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/StereoMatcher.cs @@ -0,0 +1,160 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming +#pragma warning disable 1591 + + /// + /// The base class for stereo correspondence algorithms. + /// + public class StereoMatcher : Algorithm + { + /// + /// constructor + /// + protected StereoMatcher(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// Computes disparity map for the specified stereo pair + /// + /// Left 8-bit single-channel image. + /// Right image of the same size and the same type as the left one. + /// 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) + { + if (left == null) + throw new ArgumentNullException(nameof(left)); + if (right == null) + throw new ArgumentNullException(nameof(right)); + if (disparity == null) + throw new ArgumentNullException(nameof(disparity)); + left.ThrowIfDisposed(); + right.ThrowIfDisposed(); + disparity.ThrowIfNotReady(); + NativeMethods.calib3d_StereoMatcher_compute(ptr, left.CvPtr, right.CvPtr, disparity.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(left); + GC.KeepAlive(right); + disparity.Fix(); + } + + #region Properties + + /// + /// + /// + public int MinDisparity + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getMinDisparity(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setMinDisparity(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int NumDisparities + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getNumDisparities(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setNumDisparities(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int BlockSize + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getBlockSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setBlockSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int SpeckleWindowSize + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getSpeckleWindowSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setSpeckleWindowSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int SpeckleRange + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getSpeckleRange(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setSpeckleRange(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int Disp12MaxDiff + { + get + { + var res = NativeMethods.calib3d_StereoMatcher_getDisp12MaxDiff(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.calib3d_StereoMatcher_setDisp12MaxDiff(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + } +} diff --git a/OpenVinoOpenCvSharp/Modules/calib3d/StereoSGBM.cs b/OpenVinoOpenCvSharp/Modules/calib3d/StereoSGBM.cs new file mode 100644 index 0000000..baa0945 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/calib3d/StereoSGBM.cs @@ -0,0 +1,205 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming +#pragma warning disable 1591 + + /// + /// + /// + public enum StereoSGBMMode + { + SGBM = 0, + HH = 1, + } + +#if LANG_JP + /// + /// セミグローバルブロックマッチングアルゴリズムを用てステレオ対応点探索を行うためのクラス + /// +#else + /// + /// Semi-Global Stereo Matching + /// +#endif + public class StereoSGBM : StereoMatcher + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// constructor + /// + protected StereoSGBM(IntPtr ptr) : base(ptr) + { + ptrObj = new Ptr(ptr); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static StereoSGBM Create( + int minDisparity, int numDisparities, int blockSize, + int p1 = 0, int p2 = 0, int disp12MaxDiff = 0, + int preFilterCap = 0, int uniquenessRatio = 0, + int speckleWindowSize = 0, int speckleRange = 0, + StereoSGBMMode mode = StereoSGBMMode.SGBM) + { + var ptrObj = NativeMethods.calib3d_StereoSGBM_create( + minDisparity, numDisparities, blockSize, + p1, p2, disp12MaxDiff, preFilterCap, uniquenessRatio, + speckleWindowSize, speckleRange, (int) mode); + return new StereoSGBM(ptrObj); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int PreFilterCap + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoSGBM_getPreFilterCap(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoSGBM_setPreFilterCap(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int UniquenessRatio + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoSGBM_getUniquenessRatio(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoSGBM_setUniquenessRatio(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int P1 + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoSGBM_getP1(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoSGBM_setP1(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int P2 + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.calib3d_StereoSGBM_getP2(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoSGBM_setP2(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public StereoSGBMMode Mode + { + get + { + ThrowIfDisposed(); + var res = (StereoSGBMMode)NativeMethods.calib3d_StereoSGBM_getMode(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.calib3d_StereoSGBM_setMode(ptr, (int)value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.calib3d_Ptr_StereoSGBM_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.calib3d_Ptr_StereoSGBM_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Algorithm.cs b/OpenVinoOpenCvSharp/Modules/core/Algorithm.cs new file mode 100644 index 0000000..99800cc --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Algorithm.cs @@ -0,0 +1,94 @@ +using System; +using System.Text; + +namespace OpenCvSharp +{ + /// + /// Base class for high-level OpenCV algorithms + /// + public abstract class Algorithm : DisposableCvObject + { + /// + /// Stores algorithm parameters in a file storage + /// + /// + public virtual void Write(FileStorage fs) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + + NativeMethods.core_Algorithm_write(ptr, fs.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(fs); + } + + /// + /// Reads algorithm parameters from a file storage + /// + /// + public virtual void Read(FileNode fn) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (fn == null) + throw new ArgumentNullException(nameof(fn)); + + NativeMethods.core_Algorithm_read(ptr, fn.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(fn); + } + + /// + /// Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read + /// + /// + public virtual bool Empty + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + var res = NativeMethods.core_Algorithm_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + } + + /// + /// Saves the algorithm to a file. + /// In order to make this method work, the derived class must + /// implement Algorithm::write(FileStorage fs). + /// + /// + public virtual void Save(string filename) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (filename == null) + throw new ArgumentNullException(nameof(filename)); + + NativeMethods.core_Algorithm_save(ptr, filename); + GC.KeepAlive(this); + } + + /// + /// Returns the algorithm string identifier. + /// This string is used as top level xml/yml node tag when the object + /// is saved to a file or string. + /// + /// + public virtual string GetDefaultName() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + var buf = new StringBuilder(1024); + NativeMethods.core_Algorithm_getDefaultName(ptr, buf, buf.Capacity); + GC.KeepAlive(this); + return buf.ToString(); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Delegate/CvErrorCallback.cs b/OpenVinoOpenCvSharp/Modules/core/Delegate/CvErrorCallback.cs new file mode 100644 index 0000000..bb356da --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Delegate/CvErrorCallback.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// エラーハンドラ + /// + /// エラーステータス + /// エラーが発生したOpenCVの関数名 + /// エラーについての追加情報/診断結果 + /// エラーが発生したファイル名 + /// エラーが発生した行番号 + /// +#else + /// + /// Error Handler + /// + /// The numeric code for error status + /// The source file name where error is encountered + /// A description of the error + /// The source file name where error is encountered + /// The line number in the souce where error is encountered + /// Pointer to the user data. Ignored by the standard handlers +#endif + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate int CvErrorCallback( + [MarshalAs(UnmanagedType.I4)] ErrorCode status, + [MarshalAs(UnmanagedType.LPStr)] string funcName, + [MarshalAs(UnmanagedType.LPStr)] string errMsg, + [MarshalAs(UnmanagedType.LPStr)] string fileName, + int line, + IntPtr userdata + ); +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Delegate/MatForeachFunction.cs b/OpenVinoOpenCvSharp/Modules/core/Delegate/MatForeachFunction.cs new file mode 100644 index 0000000..5fb7448 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Delegate/MatForeachFunction.cs @@ -0,0 +1,82 @@ +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#pragma warning disable 1591 +// ReSharper disable InconsistentNaming + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionByte(byte* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec2b(Vec2b* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec3b(Vec3b* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec4b(Vec4b* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec6b(Vec6b* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionInt16(short* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec2s(Vec2s* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec3s(Vec3s* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec4s(Vec4s* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec6s(Vec6s* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionInt32(int* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec2i(Vec2i* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec3i(Vec3i* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec4i(Vec4i* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec6i(Vec6i* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionFloat(float* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec2f(Vec2f* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec3f(Vec3f* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec4f(Vec4f* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec6f(Vec6f* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionDouble(double* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec2d(Vec2d* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec3d(Vec3d* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec4d(Vec4d* value, int* position); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public unsafe delegate void MatForeachFunctionVec6d(Vec6d* value, int* position); +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/AlgorithmParamType.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/AlgorithmParamType.cs new file mode 100644 index 0000000..e455dcb --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/AlgorithmParamType.cs @@ -0,0 +1,23 @@ +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + /// + /// cv::Algorithm parameter type + /// + public enum AlgorithmParamType + { + Int = 0, + Boolean = 1, + Real = 2, + String = 3, + Mat = 4, + MatVector = 5, + Algorithm = 6, + Float = 7, + UnsignedInt = 8, + UInt64 = 9, + Short = 10, + UChar = 11 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/CmpTypes.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/CmpTypes.cs new file mode 100644 index 0000000..f1eb97e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/CmpTypes.cs @@ -0,0 +1,87 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// cvCmp, cvCmpS等のメソッドで用いる, CvArrの比較方法 + /// +#else + /// + /// The flag specifying the relation between the elements to be checked + /// +#endif + public enum CmpTypes + { +#if LANG_JP + /// + /// src1(I) と value は等しい + /// +#else + /// + /// src1(I) "equal to" src2(I) + /// +#endif + EQ = 0, + + +#if LANG_JP + /// + /// src1(I) は value より大きい + /// +#else + /// + /// src1(I) "greater than" src2(I) + /// +#endif + GT = 1, + + +#if LANG_JP + /// + /// src1(I) は value より大きいか等しい + /// +#else + /// + /// src1(I) "greater or equal" src2(I) + /// +#endif + GE = 2, + + +#if LANG_JP + /// + /// src1(I) は value より小さい + /// +#else + /// + /// src1(I) "less than" src2(I) + /// +#endif + LT = 3, + + +#if LANG_JP + /// + /// src1(I) は value より小さいか等しい + /// +#else + /// + /// src1(I) "less or equal" src2(I) + /// +#endif + LE = 4, + + +#if LANG_JP + /// + /// src1(I) と value は等しくない + /// +#else + /// + /// src1(I) "not equal to" src2(I) + /// +#endif + NE = 5, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/CovarFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/CovarFlags.cs new file mode 100644 index 0000000..b198779 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/CovarFlags.cs @@ -0,0 +1,106 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// CovarMatrixの処理フラグ + /// +#else + /// + /// Operation flags for Covariation + /// +#endif + [Flags] + public enum CovarFlags + { +#if LANG_JP + /// + /// scale * [vects[0]-avg,vects[1]-avg,...]^T * [vects[0]-avg,vects[1]-avg,...] + /// すなわち,共変動行列はcount×countである. そのような一般的でない共変動行列は, + /// 非常に大きなベクトル集合に対する高速な主成分分析のために使用される(例えば,顔認識のための固有顔). + /// この「スクランブルされた」行列の固有値は,真共変動行列の固有値と一致し, + /// そして「真の」固有ベクトルは「スクランブルされた」共変動行列の固有ベクトルから容易に計算できる. + /// +#else + /// + /// scale * [vects[0]-avg,vects[1]-avg,...]^T * [vects[0]-avg,vects[1]-avg,...] + /// that is, the covariation matrix is count×count. Such an unusual covariation matrix is used for fast PCA of a set of very large vectors + /// (see, for example, Eigen Faces technique for face recognition). Eigenvalues of this "scrambled" matrix will match to the eigenvalues of + /// the true covariation matrix and the "true" eigenvectors can be easily calculated from the eigenvectors of the "scrambled" covariation matrix. + /// +#endif + Scrambled = 0, + + +#if LANG_JP + /// + /// scale * [vects[0]-avg,vects[1]-avg,...]*[vects[0]-avg,vects[1]-avg,...]^T + /// つまり,cov_matはすべての入力ベクトルの要素の合計と同じサイズの一般的な共変動行列となる. + /// CV_COVAR_SCRAMBLEDとCV_COVAR_NORMALのどちらか一つは必ず指定されなくてはならない. + /// +#else + /// + /// scale * [vects[0]-avg,vects[1]-avg,...]*[vects[0]-avg,vects[1]-avg,...]^T + /// that is, cov_mat will be a usual covariation matrix with the same linear size as the total number of elements in every input vector. + /// One and only one of CV_COVAR_SCRAMBLED and CV_COVAR_NORMAL must be specified + /// +#endif + Normal = 1, + + +#if LANG_JP + /// + /// このフラグが指定された場合,関数は入力ベクトルから平均を計算せず,引数で指定された平均ベクトルを使用する. + /// 平均が何らかの方法で既に計算されている場合,または共変動行列が部分的に計算されている場合 (この場合,avgは入力ベクトルの一部の平均ではなく,全ての平均ベクトルである)に有用である. + /// +#else + /// + /// If the flag is specified, the function does not calculate avg from the input vectors, + /// but, instead, uses the passed avg vector. This is useful if avg has been already calculated somehow, + /// or if the covariation matrix is calculated by parts - in this case, avg is not a mean vector of the input sub-set of vectors, + /// but rather the mean vector of the whole set. + /// +#endif + UseAvg = 2, + + +#if LANG_JP + /// + /// このフラグが指定された場合, 共変動行列は入力ベクトルの数によってスケーリングされる. + /// +#else + /// + /// If the flag is specified, the covariation matrix is scaled by the number of input vectors. + /// +#endif + Scale = 4, + + +#if LANG_JP + /// + /// 全ての入力ベクトルは単一の行列(vects[0])の行として保存されることを意味する. + /// そしてavgは適切な大きさの1行のベクトルでなければならない. + /// +#else + /// + /// Means that all the input vectors are stored as rows of a single matrix, vects[0].count is ignored in this case, + /// and avg should be a single-row vector of an appropriate size. + /// +#endif + Rows = 8, + + +#if LANG_JP + /// + /// 全ての入力ベクトルは単一の行列(vects[0])の列として保存されることを意味する.そしてavgは適切な大きさの1列のベクトルでなければならない. + /// +#else + /// + /// Means that all the input vectors are stored as columns of a single matrix, vects[0].count is ignored in this case, + /// and avg should be a single-column vector of an appropriate size. + /// +#endif + Cols = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/CpuFeatures.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/CpuFeatures.cs new file mode 100644 index 0000000..79cca10 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/CpuFeatures.cs @@ -0,0 +1,37 @@ +namespace OpenCvSharp +{ + /// + /// + /// + public enum CpuFeatures + { +#pragma warning disable 1591 +// ReSharper disable InconsistentNaming + MMX = 1, + SSE = 2, + SSE2 = 3, + SSE3 = 4, + SSSE3 = 5, + SSE4_1 = 6, + SSE4_2 = 7, + POPCNT = 8, + + AVX = 10, + AVX2 = 11, + FMA3 = 12, + + AVX_512F = 13, + AVX_512BW = 14, + AVX_512CD = 15, + AVX_512DQ = 16, + AVX_512ER = 17, + AVX_512IFMA512 = 18, + AVX_512PF = 19, + AVX_512VBMI = 20, + AVX_512VL = 21, + + NEON = 100 + } +} + + diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/CriteriaType.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/CriteriaType.cs new file mode 100644 index 0000000..902c07a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/CriteriaType.cs @@ -0,0 +1,52 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 終了条件の種類 + /// +#else + /// + /// Type of termination criteria + /// +#endif + [Flags] + public enum CriteriaType + { +#if LANG_JP + /// + /// 繰り返し回数による条件 + /// +#else + /// + /// the maximum number of iterations or elements to compute + /// +#endif + Count = 1, + + +#if LANG_JP + /// + /// 繰り返し回数による条件 + /// +#else + /// + /// the maximum number of iterations or elements to compute + /// +#endif + MaxIter = Count, + + +#if LANG_JP + /// + /// 目標精度(ε)による条件 + /// +#else + /// + /// the desired accuracy or change in parameters at which the iterative algorithm stops + /// +#endif + Eps = 2, + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/DctFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/DctFlags.cs new file mode 100644 index 0000000..558010f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/DctFlags.cs @@ -0,0 +1,55 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::dct の変換フラグ + /// +#else + /// + /// Transformation flags for cv::dct + /// +#endif + [Flags] +// ReSharper disable once InconsistentNaming + public enum DctFlags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// 1次元または2次元の逆変換を行う.結果のスケーリングは行わない. + /// Forward と Inverse は,もちろん同時には指定できない. + /// +#else + /// + /// Do inverse 1D or 2D transform. + /// (Forward and Inverse are mutually exclusive, of course.) + /// +#endif + Inverse = 1, + + +#if LANG_JP + /// + /// 入力配列のそれぞれの行に対して独立に,順変換あるいは逆変換を行う. + /// このフラグは複数のベクトルの同時変換を許可し, + /// オーバーヘッド(一つの計算の何倍も大きくなることもある)を減らすためや, + /// 3次元以上の高次元に対して変換を行うために使用される. + /// [CV_DXT_ROWS] + /// +#else + /// + /// Do forward or inverse transform of every individual row of the input matrix. + /// This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead + /// (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc. + /// [CV_DXT_ROWS] + /// +#endif + Rows = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/DecompTypes.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/DecompTypes.cs new file mode 100644 index 0000000..8a6e421 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/DecompTypes.cs @@ -0,0 +1,65 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// 逆行列を求める手法 + /// +#else + /// + /// Inversion methods + /// +#endif + public enum DecompTypes + { +#if LANG_JP + /// + /// 最適なピボット選択によるガウスの消去法 + /// [CV_LU] + /// +#else + /// + /// Gaussian elimination with the optimal pivot element chosen. + /// +#endif + + LU = 0, + +#if LANG_JP + /// + /// 特異値分解 + /// [CV_SVD] + /// +#else + /// + /// singular value decomposition (SVD) method; + /// the system can be over-defined and/or the matrix src1 can be singular + /// +#endif + SVD = 1, + + /// + /// eigenvalue decomposition; the matrix src1 must be symmetrical + /// + Eig = 2, + + /// + /// Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical + /// and positively defined + /// + Cholesky = 3, + + /// + /// QR factorization; the system can be over-defined and/or the matrix + /// src1 can be singular + /// + QR = 4, + + /// + /// while all the previous flags are mutually exclusive, + /// this flag can be used together with any of the previous + /// + Normal = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/DftFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/DftFlags.cs new file mode 100644 index 0000000..b517f41 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/DftFlags.cs @@ -0,0 +1,91 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvDFTの変換フラグ + /// +#else + /// + /// Transformation flags for cvDFT + /// +#endif + [Flags] + public enum DftFlags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// 1次元または2次元の逆変換を行う.結果のスケーリングは行わない. + /// Forward と Inverse は,もちろん同時には指定できない. + /// +#else + /// + /// Do inverse 1D or 2D transform. The result is not scaled. + /// (Forward and Inverse are mutually exclusive, of course.) + /// +#endif + Inverse = 1, + + +#if LANG_JP + /// + /// 結果を配列要素数で割り,スケーリングする.通常は Inverse と同時に用いる. + /// ショートカットとして InvScale を用いても良い. + /// [CV_DXT_SCALE] + /// +#else + /// + /// Scale the result: divide it by the number of array elements. Usually, it is combined with Inverse. + /// +#endif + Scale = 2, + +#if LANG_JP + /// + /// 入力配列のそれぞれの行に対して独立に,順変換あるいは逆変換を行う. + /// このフラグは複数のベクトルの同時変換を許可し, + /// オーバーヘッド(一つの計算の何倍も大きくなることもある)を減らすためや, + /// 3次元以上の高次元に対して変換を行うために使用される. + /// +#else + /// + /// Do forward or inverse transform of every individual row of the input matrix. + /// This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead + /// (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc. + /// +#endif + Rows = 4, + + /// + /// performs a forward transformation of 1D or 2D real array; the result, + /// though being a complex array, has complex-conjugate symmetry (*CCS*, + /// see the function description below for details), and such an array can + /// be packed into a real array of the same size as input, which is the fastest + /// option and which is what the function does by default; however, you may + /// wish to get a full complex array (for simpler spectrum analysis, and so on) - + /// pass the flag to enable the function to produce a full-size complex output array. + /// + ComplexOutput = 16, + + /// + /// performs an inverse transformation of a 1D or 2D complex array; + /// the result is normally a complex array of the same size, however, + /// if the input array has conjugate-complex symmetry (for example, + /// it is a result of forward transformation with DFT_COMPLEX_OUTPUT flag), + /// the output is a real array; while the function itself does not + /// check whether the input is symmetrical or not, you can pass the flag + /// and then the function will assume the symmetry and produce the real + /// output array (note that when the input is packed into a real array + /// and inverse transformation is executed, the function treats the input + /// as a packed complex-conjugate symmetrical array, and the output + /// will also be a real array). + /// + RealOutput = 32, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/DistributionType.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/DistributionType.cs new file mode 100644 index 0000000..8b67025 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/DistributionType.cs @@ -0,0 +1,37 @@ +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvRandArrメソッド等で用いる, 分布のタイプ + /// +#else + /// + /// Distribution type for cvRandArr, etc. + /// +#endif + public enum DistributionType + { +#if LANG_JP + /// + /// 一様分布 + /// +#else + /// + /// Uniform distribution + /// +#endif + Uniform = 0, + + +#if LANG_JP + /// + /// 正規分布(ガウス分布) + /// +#else + /// + /// Normal or Gaussian distribution + /// +#endif + Normal = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/ErrorCode.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/ErrorCode.cs new file mode 100644 index 0000000..5f9b668 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/ErrorCode.cs @@ -0,0 +1,262 @@ +namespace OpenCvSharp +{ + /// + /// Error status codes + /// + public enum ErrorCode + { + /* this part of CVStatus is compatible with IPLStatus + Some of below symbols are not [yet] used in OpenCV + */ + + // ReSharper disable InconsistentNaming + + /// + /// everithing is ok [CV_StsOk] + /// + StsOk = 0, + + /// + /// pseudo error for back trace [CV_StsBackTrace] + /// + StsBackTrace = -1, + + /// + /// unknown /unspecified error [CV_StsError] + /// + StsError = -2, + + /// + /// internal error (bad state) [CV_StsInternal] + /// + StsInternal = -3, + + /// + /// insufficient memory [CV_StsNoMem] + /// + StsNoMem = -4, + + /// + /// function arg/param is bad [CV_StsBadArg] + /// + StsBadArg = -5, + + /// + /// unsupported function [CV_StsBadFunc] + /// + StsBadFunc = -6, + + /// + /// iter. didn't converge [CV_StsNoConv] + /// + StsNoConv = -7, + + /// + /// tracing [CV_StsAutoTrace] + /// + StsAutoTrace = -8, + + + /// + /// image header is NULL [CV_HeaderIsNull] + /// + HeaderIsNull = -9, + + /// + /// image size is invalid [CV_BadImageSize] + /// + BadImageSize = -10, + + /// + /// offset is invalid [CV_BadOffset] + /// + BadOffset = -11, + + /// + /// [CV_BadOffset] + /// + BadDataPtr = -12, + + /// + /// [CV_BadStep] + /// + BadStep = -13, + + /// + /// [CV_BadModelOrChSeq] + /// + BadModelOrChSeq = -14, + + /// + /// [CV_BadNumChannels] + /// + BadNumChannels = -15, + + /// + /// [CV_BadNumChannel1U] + /// + BadNumChannel1U = -16, + + /// + /// [CV_BadDepth] + /// + BadDepth = -17, + + /// + /// [CV_BadAlphaChannel] + /// + BadAlphaChannel = -18, + + /// + /// [CV_BadOrder] + /// + BadOrder = -19, + + /// + /// [CV_BadOrigin] + /// + BadOrigin = -20, + + /// + /// [CV_BadAlign] + /// + BadAlign = -21, + + /// + /// [CV_BadCallBack] + /// + BadCallBack = -22, + + /// + /// [CV_BadTileSize] + /// + BadTileSize = -23, + + /// + /// [CV_BadCOI] + /// + BadCOI = -24, + + /// + /// [CV_BadROISize] + /// + BadROISize = -25, + + /// + /// [CV_MaskIsTiled] + /// + MaskIsTiled = -26, + + /// + /// null pointer [CV_StsNullPtr] + /// + StsNullPtr = -27, + + /// + /// incorrect vector length [CV_StsVecLengthErr] + /// + StsVecLengthErr = -28, + + /// + /// incorr. filter structure content [CV_StsFilterStructContentErr] + /// + StsFilterStructContentErr = -29, + + /// + /// incorr. transform kernel content [CV_StsKernelStructContentErr] + /// + StsKernelStructContentErr = -30, + + /// + /// incorrect filter ofset value [CV_StsFilterOffsetErr] + /// + StsFilterOffsetErr = -31, + + /*extra for CV */ + + /// + /// the input/output structure size is incorrect [CV_StsBadSize] + /// + StsBadSize = -201, + + /// + /// division by zero [CV_StsDivByZero] + /// + StsDivByZero = -202, + + /// + /// in-place operation is not supported [CV_StsInplaceNotSupported] + /// + StsInplaceNotSupported = -203, + + /// + /// request can't be completed [CV_StsObjectNotFound] + /// + StsObjectNotFound = -204, + + /// + /// formats of input/output arrays differ [CV_StsUnmatchedFormats] + /// + StsUnmatchedFormats = -205, + + /// + /// flag is wrong or not supported [CV_StsBadFlag] + /// + StsBadFlag = -206, + + /// + /// bad CvPoint [CV_StsBadPoint] + /// + StsBadPoint = -207, + + /// + /// bad format of mask (neither 8uC1 nor 8sC1) [CV_StsBadMask] + /// + StsBadMask = -208, + + /// + /// sizes of input/output structures do not match [CV_StsUnmatchedSizes] + /// + StsUnmatchedSizes = -209, + + /// + /// the data format/type is not supported by the function [CV_StsUnsupportedFormat] + /// + StsUnsupportedFormat = -210, + + /// + /// some of parameters are out of range [CV_StsOutOfRange] + /// + StsOutOfRange = -211, + + /// + /// invalid syntax/structure of the parsed file [CV_StsParseError] + /// + StsParseError = -212, + + /// + /// the requested function/feature is not implemented [CV_StsNotImplemented] + /// + StsNotImplemented = -213, + + /// + /// an allocated block has been corrupted [CV_StsBadMemBlock] + /// + StsBadMemBlock = -214, + + /// + /// assertion failed + /// + StsAssert = -215, + +#pragma warning disable 1591 + GpuNotSupported = -216, + GpuApiCallError = -217, + OpenGlNotSupported = -218, + OpenGlApiCallError = -219, + OpenCLApiCallError = -220, + OpenCLDoubleNotSupported = -221, + OpenCLInitError = -222, + OpenCLNoAMDBlasFft = -223 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/FormatType.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/FormatType.cs new file mode 100644 index 0000000..91a760b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/FormatType.cs @@ -0,0 +1,49 @@ +// ReSharper disable InconsistentNaming +namespace OpenCvSharp +{ + /// + /// Output string format of Mat.Dump() + /// + public enum FormatType + { + /// + /// Default format. + /// [1, 2, 3, 4, 5, 6; \n + /// 7, 8, 9, ... ] + /// + Default = 0, + + /// + /// + /// + MATLAB = 1, + + /// + /// CSV format. + /// 1, 2, 3, 4, 5, 6\n + /// 7, 8, 9, ... + /// + CSV = 2, + + /// + /// Python format. + /// [[[1, 2, 3], [4, 5, 6]], \n + /// [[7, 8, 9], ... ] + /// + Python = 3, + + /// + /// NumPy format. + /// array([[[1, 2, 3], [4, 5, 6]], \n + /// [[7, 8, 9], .... ]]], type='uint8'); + /// + NumPy = 4, + + /// + /// C language format. + /// {1, 2, 3, 4, 5, 6, \n + /// 7, 8, 9, ...}; + /// + C = 5, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/GemmFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/GemmFlags.cs new file mode 100644 index 0000000..0383ee3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/GemmFlags.cs @@ -0,0 +1,60 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// cv::GEMMメソッドの操作フラグ + /// +#else + /// + /// The operation flags for cv::GEMM + /// +#endif + [Flags] + public enum GemmFlags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// src1を転置 + /// +#else + /// + /// Transpose src1 + /// +#endif + + A_T = 1, + + +#if LANG_JP + /// + /// src2を転置 + /// +#else + /// + /// Transpose src2 + /// +#endif + B_T = 2, + + +#if LANG_JP + /// + /// src3を転置 + /// +#else + /// + /// Transpose src3 + /// +#endif + C_T = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/HersheyFonts.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/HersheyFonts.cs new file mode 100644 index 0000000..55c2807 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/HersheyFonts.cs @@ -0,0 +1,64 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// フォント名の識別子.現在はHershey fontsの一部のみサポートされている. + /// フォント名のフラグにはイタリックフラグ(Italic)を合成することができる. + /// +#else + /// + /// Font name identifier. + /// Only a subset of Hershey fonts (http://sources.isc.org/utils/misc/hershey-font.txt) are supported now. + /// +#endif + [Flags] + public enum HersheyFonts + { + /// + /// normal size sans-serif font + /// + HersheySimplex = 0, + + /// + /// small size sans-serif font + /// + HersheyPlain = 1, + + /// + /// normal size sans-serif font (more complex than HERSHEY_SIMPLEX) + /// + HersheyDuplex = 2, + + /// + /// normal size serif font + /// + HersheyComplex = 3, + + /// + /// normal size serif font (more complex than HERSHEY_COMPLEX) + /// + HersheyTriplex = 4, + + /// + /// smaller version of HERSHEY_COMPLEX + /// + HersheyComplexSmall = 5, + + /// + /// hand-writing style font + /// + HersheyScriptSimplex = 6, + + /// + /// more complex variant of HERSHEY_SCRIPT_SIMPLEX + /// + HersheyScriptComplex = 7, + + /// + /// flag for italic font + /// + Italic = 16 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/InOutArrayKind.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/InOutArrayKind.cs new file mode 100644 index 0000000..6d0f478 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/InOutArrayKind.cs @@ -0,0 +1,33 @@ +using System; +// ReSharper disable InconsistentNaming +// ReSharper disable IdentifierTypo + +namespace OpenCvSharp +{ +#pragma warning disable 1591 + + /// + /// + /// + [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/OpenVinoOpenCvSharp/Modules/core/Enum/KMeansFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/KMeansFlags.cs new file mode 100644 index 0000000..0316db5 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/KMeansFlags.cs @@ -0,0 +1,35 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::kmeans の処理フラグ + /// +#else + /// + /// Miscellaneous flags for cv::kmeans + /// +#endif + [Flags] + public enum KMeansFlags + { + /// + /// Select random initial centers in each attempt. + /// + RandomCenters = 0, + + /// + /// Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007]. + /// + PpCenters = 2, + + /// + /// During the first (and possibly the only) attempt, use the + /// user-supplied labels instead of computing them from the initial centers. + /// For the second and further attempts, use the random or semi-random centers. + /// Use one of KMEANS_\*_CENTERS flag to specify the exact method. + /// + UseInitialLabels = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/MatDiagType.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/MatDiagType.cs new file mode 100644 index 0000000..1ad1a6a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/MatDiagType.cs @@ -0,0 +1,55 @@ +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// diagonal type + /// +#else + /// + /// diagonal type + /// +#endif + public enum MatDiagType + { +#if LANG_JP + /// + /// a diagonal from the upper half + /// [< 0] + /// +#else + /// + /// a diagonal from the upper half + /// [< 0] + /// +#endif + Upper = -1, + +#if LANG_JP + /// + /// Main dialonal + /// [= 0] + /// +#else + /// + /// Main dialonal + /// [= 0] + /// +#endif + Main = 0, + +#if LANG_JP + /// + /// a diagonal from the lower half + /// [> 0] + /// +#else + /// + /// a diagonal from the lower half + /// [> 0] + /// +#endif + Lower = +1, + } +} + + diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/NormTypes.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/NormTypes.cs new file mode 100644 index 0000000..d286b06 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/NormTypes.cs @@ -0,0 +1,78 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// 正規化のタイプ + /// +#else + /// + /// Type of norm + /// +#endif + [Flags] + public enum NormTypes + { + /// + /// + /// + + INF = 1, + +#if LANG_JP + /// + /// 配列のL1-norm(絶対値の合計)を正規化 + /// +#else + /// + /// The L1-norm (sum of absolute values) of the array is normalized. + /// +#endif + L1 = 2, + +#if LANG_JP + /// + /// 配列のL2-norm(ユークリッド距離)を正規化 + /// +#else + /// + /// The (Euclidean) L2-norm of the array is normalized. + /// +#endif + L2 = 4, + + /// + /// + /// + L2SQR = 5, + + /// + /// + /// + Hamming = 6, + + /// + /// + /// + Hamming2 = 7, + + /// + /// + /// + Relative = 8, + +#if LANG_JP + /// + /// 配列の値が指定の範囲に収まるようにスケーリングとシフトを行う + /// +#else + /// + /// The array values are scaled and shifted to the specified range. + /// +#endif + MinMax = 32, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceDimension.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceDimension.cs new file mode 100644 index 0000000..30a8443 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceDimension.cs @@ -0,0 +1,54 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvReduceで、配列をどのように縮小するかを示すインデックス + /// +#else + /// + /// The dimension index along which the matrix is reduce. + /// +#endif + public enum ReduceDimension + { +#if LANG_JP + /// + /// 行列を1行ベクトルに縮小する + /// [= 0] + /// +#else + /// + /// The matrix is reduced to a single row. + /// [= 0] + /// +#endif + Row = 0, + +#if LANG_JP + /// + /// 行列を1列ベクトルに縮小する + /// [= 1] + /// +#else + /// + /// The matrix is reduced to a single column. + /// [= 1] + /// +#endif + Column = 1, + +#if LANG_JP + /// + /// 出力行列のサイズから次元を解析し,自動的に選択する + /// [= -1] + /// +#else + /// + /// The dimension is chosen automatically by analysing the dst size. + /// [= -1] + /// +#endif + Auto = -1 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceTypes.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceTypes.cs new file mode 100644 index 0000000..c81e278 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/ReduceTypes.cs @@ -0,0 +1,62 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvReduceで用いる縮小処理の種類 + /// +#else + /// + /// The reduction operations for cvReduce + /// +#endif + public enum ReduceTypes + { +#if LANG_JP + /// + /// 出力は各行(または各列)の総和 + /// +#else + /// + /// The output is the sum of all the matrix rows/columns. + /// +#endif + Sum = 0, + + +#if LANG_JP + /// + /// 出力は各行(または各列)の平均ベクトル + /// +#else + /// + /// The output is the mean vector of all the matrix rows/columns. + /// +#endif + Avg = 1, + + +#if LANG_JP + /// + /// 出力は各行(または各列)における最大値 + /// +#else + /// + /// The output is the maximum (column/row-wise) of all the matrix rows/columns. + /// +#endif + Max = 2, + + +#if LANG_JP + /// + /// 出力は各行(または各列)における最小値 + /// +#else + /// + /// The output is the minimum (column/row-wise) of all the matrix rows/columns. + /// +#endif + Min = 3, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/SolveLPResult.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/SolveLPResult.cs new file mode 100644 index 0000000..e6fdbc7 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/SolveLPResult.cs @@ -0,0 +1,30 @@ +// ReSharper disable UnusedMember.Global +namespace OpenCvSharp +{ + /// + /// return codes for cv::solveLP() function + /// + // ReSharper disable once InconsistentNaming + public enum SolveLPResult + { + /// + /// problem is unbounded (target function can achieve arbitrary high values) + /// + Unbounded = -2, + + /// + /// problem is unfeasible (there are no points that satisfy all the constraints imposed) + /// + Unfeasible = -1, + + /// + /// there is only one maximum for target function + /// + Single = 0, + + /// + /// there are multiple maxima for target function - the arbitrary one is returned + /// + Multi = 1 + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Enum/SortFlags.cs b/OpenVinoOpenCvSharp/Modules/core/Enum/SortFlags.cs new file mode 100644 index 0000000..640537e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Enum/SortFlags.cs @@ -0,0 +1,39 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::sortで用いる、配列の並び順指定 + /// +#else + /// + /// Signals an error and raises the exception. + /// +#endif + [Flags] + public enum SortFlags + { + /// + /// each matrix row is sorted independently + /// + EveryRow = 0, + + /// + /// each matrix column is sorted independently; + /// this flag and the previous one are mutually exclusive. + /// + EveryColumn = 1, + + /// + /// each matrix row is sorted in the ascending order. + /// + Ascending = 0, + + /// + /// each matrix row is sorted in the descending order; + /// this flag and the previous one are also mutually exclusive. + /// + Descending = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/FileNode.cs b/OpenVinoOpenCvSharp/Modules/core/FileNode.cs new file mode 100644 index 0000000..425ac80 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/FileNode.cs @@ -0,0 +1,1088 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// File Storage Node class + /// + public class FileNode : DisposableCvObject, IEnumerable + { + // ReSharper disable InconsistentNaming + + #region Init & Disposal + + /// + /// The default constructor + /// + public FileNode() + { + ptr = NativeMethods.core_FileNode_new1(); + } + + /// + /// Initializes from cv::FileNode* + /// + /// + public FileNode(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_FileNode_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Cast + + /// + /// Returns the node content as an integer. If the node stores floating-point number, it is rounded. + /// + /// + /// + public static explicit operator int(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + var res = NativeMethods.core_FileNode_toInt(node.CvPtr); + GC.KeepAlive(node); + return res; + } + + /// + /// Returns the node content as float + /// + /// + /// + public static explicit operator float(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + var res = NativeMethods.core_FileNode_toFloat(node.CvPtr); + GC.KeepAlive(node); + return res; + } + + /// + /// Returns the node content as double + /// + /// + /// + public static explicit operator double(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + var res = NativeMethods.core_FileNode_toDouble(node.CvPtr); + GC.KeepAlive(node); + return res; + } + + /// + /// Returns the node content as text string + /// + /// + /// + public static explicit operator string(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + var buf = new StringBuilder(1 << 16); + NativeMethods.core_FileNode_toString(node.CvPtr, buf, buf.Capacity); + GC.KeepAlive(node); + return buf.ToString(); + } + + /// + /// Returns the node content as OpenCV Mat + /// + /// + /// + public static explicit operator Mat(FileNode node) + { + if (node == null) + throw new ArgumentNullException(nameof(node)); + node.ThrowIfDisposed(); + + var matrix = new Mat(); + NativeMethods.core_FileNode_toMat(node.CvPtr, matrix.CvPtr); + GC.KeepAlive(node); + return matrix; + } + + #endregion + + #region Properties + + /// + /// returns element of a mapping node + /// + public FileNode? this[string nodeName] + { + get + { + ThrowIfDisposed(); + if (nodeName == null) + throw new ArgumentNullException(nameof(nodeName)); + var node = NativeMethods.core_FileNode_operatorThis_byString(ptr, nodeName); + GC.KeepAlive(this); + if (node == IntPtr.Zero) + return null; + return new FileNode(node); + } + } + + /// + /// returns element of a sequence node + /// + public FileNode? this[int i] + { + get + { + ThrowIfDisposed(); + var node = NativeMethods.core_FileNode_operatorThis_byInt(ptr, i); + GC.KeepAlive(this); + if (node == IntPtr.Zero) + return null; + return new FileNode(node); + } + } + + /// + /// Returns true if the node is empty + /// + /// + public bool Empty + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_empty(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is a "none" object + /// + /// + public bool IsNone + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isNone(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is a sequence + /// + /// + public bool IsSeq + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isSeq(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is a mapping + /// + /// + public bool IsMap + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isMap(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is an integer + /// + /// + public bool IsInt + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isInt(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is a floating-point number + /// + /// + public bool IsReal + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isReal(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node is a text string + /// + /// + public bool IsString + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isString(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns true if the node has a name + /// + /// + public bool IsNamed + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_isNamed(ptr); + GC.KeepAlive(this); + return ret != 0; + } + } + + /// + /// Returns the node name or an empty string if the node is nameless + /// + /// + public string Name + { + get + { + ThrowIfDisposed(); + var buf = new StringBuilder(1024); + NativeMethods.core_FileNode_name(ptr, buf, buf.Capacity); + GC.KeepAlive(this); + return buf.ToString(); + } + } + + /// + /// Returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. + /// + /// + public long Size + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_FileNode_size(ptr).ToInt64(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Returns type of the node. + /// + /// Type of the node. + public Types Type + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_FileNode_type(ptr); + GC.KeepAlive(this); + return (Types)res; + } + } + + #endregion + + #region Methods + + /// + /// returns iterator pointing to the first node element + /// + /// + public FileNodeIterator Begin() + { + ThrowIfDisposed(); + var p = NativeMethods.core_FileNode_begin(ptr); + GC.KeepAlive(this); + return new FileNodeIterator(p); + } + //! + /// + /// returns iterator pointing to the element following the last node element + /// + /// + public FileNodeIterator End() + { + ThrowIfDisposed(); + var p = NativeMethods.core_FileNode_end(ptr); + GC.KeepAlive(this); + return new FileNodeIterator(p); + } + + /// + /// + /// + /// + public IEnumerator GetEnumerator() + { + using (FileNodeIterator it = Begin(), end = End()) + { + for (; !it.Equals(end); it.MoveNext()) + { + yield return it.Current; + } + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Reads node elements to the buffer with the specified format + /// + /// + /// + /// + public void ReadRaw(string fmt, IntPtr vec, long len) + { + ThrowIfDisposed(); + if (fmt == null) + throw new ArgumentNullException(nameof(fmt)); + NativeMethods.core_FileNode_readRaw(ptr, fmt, vec, new IntPtr(len)); + GC.KeepAlive(this); + } + + /// + /// Writes a comment. + /// The function writes a comment into file storage.The comments are skipped when the storage is read. + /// + /// The written comment, single-line or multi-line + /// If true, the function tries to put the comment at the end of current line. + /// Else if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line. + public void WriteComment(string comment, bool append = false) + { + ThrowIfDisposed(); + if (comment == null) + throw new ArgumentNullException(nameof(comment)); + NativeMethods.core_FileStorage_writeComment(ptr, comment, append ? 1 : 0); + GC.KeepAlive(this); + } + + #region Read + + /// + /// + /// + /// + /// + public int ReadInt(int defaultValue = default) + { + NativeMethods.core_FileNode_read_int(ptr, out var value, defaultValue); + GC.KeepAlive(this); + return value; + } + + /// + /// + /// + /// + /// + public float ReadFloat(float defaultValue = default) + { + NativeMethods.core_FileNode_read_float(ptr, out var value, defaultValue); + GC.KeepAlive(this); + return value; + } + + /// + /// + /// + /// + /// + public double ReadDouble(double defaultValue = default) + { + NativeMethods.core_FileNode_read_double(ptr, out var value, defaultValue); + GC.KeepAlive(this); + return value; + } + + /// + /// + /// + /// + /// + public string ReadString(string? defaultValue = null) + { + var value = new StringBuilder(65536); + NativeMethods.core_FileNode_read_String(ptr, value, value.Capacity, defaultValue); + GC.KeepAlive(this); + return value.ToString(); + } + + /// + /// + /// + /// + /// + public Mat ReadMat(Mat? defaultMat = null) + { + var value = new Mat(); + try + { + NativeMethods.core_FileNode_read_Mat(ptr, value.CvPtr, Cv2.ToPtr(defaultMat)); + GC.KeepAlive(this); + GC.KeepAlive(defaultMat); + } + catch + { + value.Dispose(); + throw; + } + return value; + } + + /// + /// + /// + /// + /// + public SparseMat ReadSparseMat(SparseMat? defaultMat = null) + { + var value = new SparseMat(); + try + { + NativeMethods.core_FileNode_read_SparseMat(ptr, value.CvPtr, Cv2.ToPtr(defaultMat)); + GC.KeepAlive(this); + GC.KeepAlive(defaultMat); + } + catch + { + value.Dispose(); + throw; + } + return value; + } + + /// + /// + /// + /// + public KeyPoint[] ReadKeyPoints() + { + using (var valueVector = new VectorOfKeyPoint()) + { + NativeMethods.core_FileNode_read_vectorOfKeyPoint(ptr, valueVector.CvPtr); + GC.KeepAlive(this); + return valueVector.ToArray(); + } + } + + /// + /// + /// + /// + public DMatch[] ReadDMatches() + { + using (var valueVector = new VectorOfDMatch()) + { + NativeMethods.core_FileNode_read_vectorOfDMatch(ptr, valueVector.CvPtr); + GC.KeepAlive(this); + return valueVector.ToArray(); + } + } + + /// + /// + /// + /// + public Range ReadRange() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Range(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public KeyPoint ReadKeyPoint() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_KeyPoint(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public DMatch ReadDMatch() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_DMatch(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point ReadPoint() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point2i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point2f ReadPoint2f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point2f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point2d ReadPoint2d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point2d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point3i ReadPoint3i() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point3i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point3f ReadPoint3f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point3f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Point3d ReadPoint3d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Point3d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Size ReadSize() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Size2i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Size2f ReadSize2f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Size2f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Size2d ReadSize2d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Size2d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Rect ReadRect() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Rect2i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Rect2f ReadRect2f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Rect2f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Rect2d ReadRect2d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Rect2d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Scalar ReadScalar() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Scalar(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec2i ReadVec2i() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3i ReadVec3i() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4i ReadVec4i() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6i ReadVec6i() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6i(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec2d ReadVec2d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3d ReadVec3d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4d ReadVec4d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6d ReadVec6d() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6d(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec2f ReadVec2f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3f ReadVec3f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4f ReadVec4f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6f ReadVec6f() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6f(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec2b ReadVec2b() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2b(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3b ReadVec3b() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3b(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4b ReadVec4b() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4b(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6b ReadVec6b() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6b(ptr); + GC.KeepAlive(this); + return ret; + } + + + /// + /// + /// + /// + public Vec2s ReadVec2s() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2s(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3s ReadVec3s() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3s(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4s ReadVec4s() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4s(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6s ReadVec6s() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6s(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec2w ReadVec2w() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec2w(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec3w ReadVec3w() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec3w(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec4w ReadVec4w() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec4w(ptr); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public Vec6w ReadVec6w() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_FileNode_read_Vec6w(ptr); + GC.KeepAlive(this); + return ret; + } + + #endregion + + #endregion + + /// + /// type of the file storage node + /// + [Flags] + public enum Types + { + /// + /// empty node + /// + None = 0, + + /// + /// an integer + /// + Int = 1, + + /// + /// floating-point number + /// + Real = 2, + + /// + /// synonym or REAL + /// + Float = Real, + + /// + /// text string in UTF-8 encoding + /// + Str = 3, + + /// + /// synonym for STR + /// + String = Str, + + /// + /// sequence + /// + Seq = 4, + + /// + /// mapping + /// + Map = 5, + + /// + /// + /// + TypeMask = 7, + + /// + /// compact representation of a sequence or mapping. Used only by YAML writer + /// + Flow = 8, + + // ReSharper disable once CommentTypo + /// + /// if set, means that all the collection elements are numbers of the same type (real's or int's). + /// UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit + /// + Uniform = 8, + + /// + /// empty structure (sequence or mapping) + /// + Empty = 16, + + /// + /// the node has a name (i.e. it is element of a mapping) + /// + Named = 32, + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/FileNodeIterator.cs b/OpenVinoOpenCvSharp/Modules/core/FileNodeIterator.cs new file mode 100644 index 0000000..77166ae --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/FileNodeIterator.cs @@ -0,0 +1,181 @@ +using System; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// + /// File Storage Node class + /// + public class FileNodeIterator : DisposableCvObject, IEquatable/*, IEnumerator*/ + { + /// + /// The default constructor + /// + public FileNodeIterator() + { + ptr = NativeMethods.core_FileNodeIterator_new1(); + } + + /// + /// Initializes from cv::FileNode* + /// + /// + public FileNodeIterator(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_FileNodeIterator_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// Reads node elements to the buffer with the specified format. + /// Usually it is more convenient to use operator `>>` instead of this method. + /// + /// Specification of each array element.See @ref format_spec "format specification" + /// Pointer to the destination array. + /// Number of elements to read. If it is greater than number of remaining elements then all of them will be read. + /// + public FileNodeIterator ReadRaw(string fmt, IntPtr vec, long maxCount = int.MaxValue) + { + if (fmt == null) + throw new ArgumentNullException(nameof(fmt)); + NativeMethods.core_FileNodeIterator_readRaw(ptr, fmt, vec, new IntPtr(maxCount)); + GC.KeepAlive(this); + return this; + } + + /// + /// *iterator + /// + public FileNode Current + { + get + { + ThrowIfDisposed(); + var p = NativeMethods.core_FileNodeIterator_operatorAsterisk(ptr); + GC.KeepAlive(this); + return new FileNode(p); + } + } + + //object IEnumerator.Current => Current; + + /// + /// iterator++ + /// + /// + public bool MoveNext() + { + ThrowIfDisposed(); + var changed = NativeMethods.core_FileNodeIterator_operatorIncrement(ptr); + GC.KeepAlive(this); + return changed != 0; + } + + /// + /// iterator += ofs + /// + /// + /// + public bool MoveNext(int ofs) + { + ThrowIfDisposed(); + var changed = NativeMethods.core_FileNodeIterator_operatorPlusEqual(ptr, ofs); + GC.KeepAlive(this); + return changed != 0; + } + + /// + /// Reads node elements to the buffer with the specified format. + /// Usually it is more convenient to use operator `>>` instead of this method. + /// + /// Specification of each array element.See @ref format_spec "format specification" + /// Pointer to the destination array. + /// Number of elements to read. If it is greater than number of remaining elements then all of them will be read. + /// + public FileNodeIterator ReadRaw(string fmt, byte[] vec, long maxCount = int.MaxValue) + { + if (fmt == null) + throw new ArgumentNullException(nameof(fmt)); + if (vec == null) + throw new ArgumentNullException(nameof(vec)); + unsafe + { + fixed (byte* vecPtr = vec) + { + NativeMethods.core_FileNodeIterator_readRaw(ptr, fmt, new IntPtr(vecPtr), new IntPtr(maxCount)); + } + } + GC.KeepAlive(this); + return this; + } + + /// + /// + /// + /// + /// + public bool Equals(FileNodeIterator it) + { + if (it is null) + return false; + ThrowIfDisposed(); + it.ThrowIfDisposed(); + + var ret = NativeMethods.core_FileNodeIterator_operatorEqual(ptr, it.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(it); + + return ret != 0; + } + + /// + /// + /// + /// + /// + public long Minus(FileNodeIterator it) + { + if (it == null) + throw new ArgumentNullException(nameof(it)); + ThrowIfDisposed(); + it.ThrowIfDisposed(); + + var ret = NativeMethods.core_FileNodeIterator_operatorMinus(ptr, it.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(it); + + return ret.ToInt64(); + } + + /// + /// + /// + /// + /// + public bool LessThan(FileNodeIterator it) + { + if (it == null) + throw new ArgumentNullException(nameof(it)); + ThrowIfDisposed(); + it.ThrowIfDisposed(); + + var ret = NativeMethods.core_FileNodeIterator_operatorLessThan(ptr, it.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(it); + + return ret != 0; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/FileStorage.cs b/OpenVinoOpenCvSharp/Modules/core/FileStorage.cs new file mode 100644 index 0000000..49f4b3f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/FileStorage.cs @@ -0,0 +1,1138 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using OpenCvSharp.Util; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// XML/YAML File Storage Class. + /// + public class FileStorage : DisposableCvObject + { + #region Init & Disposal + + /// + /// Default constructor. + /// You should call FileStorage::open() after initialization. + /// + public FileStorage() + { + ptr = NativeMethods.core_FileStorage_new1(); + } + + /// + /// The full constructor + /// + /// Name of the file to open or the text string to read the data from. + /// Extension of the file (.xml or .yml/.yaml) determines its format + /// (XML or YAML respectively). Also you can append .gz to work with + /// compressed files, for example myHugeMatrix.xml.gz. + /// If both FileStorage::WRITE and FileStorage::MEMORY flags are specified, + /// source is used just to specify the output file format + /// (e.g. mydata.xml, .yml etc.). + /// + /// Encoding of the file. Note that UTF-16 XML encoding is not supported + /// currently and you should use 8-bit encoding instead of it. + public FileStorage(string source, Mode flags, string? encoding = null) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + ptr = NativeMethods.core_FileStorage_new2(source, (int)flags, encoding); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_FileStorage_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Properties + + /// + /// Returns the specified element of the top-level mapping + /// + /// + /// + public FileNode? this[string nodeName] + { + get + { + ThrowIfDisposed(); + if (nodeName == null) + throw new ArgumentNullException(nameof(nodeName)); + var node = NativeMethods.core_FileStorage_indexer(ptr, nodeName); + GC.KeepAlive(this); + if (node == IntPtr.Zero) + return null; + return new FileNode(node); + } + } + + /// + /// the currently written element + /// + public string? ElName + { + get + { + ThrowIfDisposed(); + unsafe + { + var buf = NativeMethods.core_FileStorage_elname(ptr); + if (buf == null) + return null; + var res = StringHelper.PtrToStringAnsi(buf); + GC.KeepAlive(this); + return res; + } + } + } + + /// + /// the writer state + /// + public States State + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_FileStorage_state(ptr); + GC.KeepAlive(this); + return (States)res; + } + } + + #endregion + + #region Methods + + /// + /// operator that performs PCA. The previously stored data, if any, is released + /// + /// + /// + /// Encoding of the file. Note that UTF-16 XML encoding is not supported + /// currently and you should use 8-bit encoding instead of it. + /// + public virtual bool Open(string fileName, Mode flags, string? encoding = null) + { + ThrowIfDisposed(); + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + var ret = NativeMethods.core_FileStorage_open(ptr, fileName, (int)flags, encoding); + GC.KeepAlive(this); + return ret != 0; + } + + /// + /// Returns true if the object is associated with currently opened file. + /// + /// + public virtual bool IsOpened() + { + ThrowIfDisposed(); + var res = NativeMethods.core_FileStorage_isOpened(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Closes the file and releases all the memory buffers + /// + public virtual void Release() + { + ThrowIfDisposed(); + Dispose(); + } + + /// + /// Closes the file, releases all the memory buffers and returns the text string + /// + /// + public string ReleaseAndGetString() + { + ThrowIfDisposed(); + + try + { + using (var stdString = new StdString()) + { + NativeMethods.core_FileStorage_releaseAndGetString_stdString(ptr, stdString.CvPtr); + return stdString.ToString(); + } + } + finally + { + Dispose(); + } + } + + /// + /// Returns the first element of the top-level mapping + /// + /// + public FileNode? GetFirstTopLevelNode() + { + ThrowIfDisposed(); + var node = NativeMethods.core_FileStorage_getFirstTopLevelNode(ptr); + GC.KeepAlive(this); + if (node == IntPtr.Zero) + return null; + return new FileNode(node); + } + + /// + /// Returns the top-level mapping. YAML supports multiple streams + /// + /// + /// + public FileNode? Root(int streamIdx = 0) + { + ThrowIfDisposed(); + var node = NativeMethods.core_FileStorage_root(ptr, streamIdx); + GC.KeepAlive(this); + if (node == IntPtr.Zero) + return null; + return new FileNode(node); + } + + /// + /// Writes one or more numbers of the specified format to the currently written structure + /// + /// + /// + /// + public void WriteRaw(string fmt, IntPtr vec, long len) + { + ThrowIfDisposed(); + throw new NotImplementedException(); + } + + /// + /// + /// + /// + /// + /// + public void StartWriteStruct(string name, int flags, string typeName) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_startWriteStruct(ptr, name, flags, typeName); + GC.KeepAlive(this); + } + + /// + /// + /// + public void EndWriteStruct() + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_endWriteStruct(ptr); + GC.KeepAlive(this); + } + + /// + /// Returns the normalized object name for the specified file name + /// + /// + /// + public static string GetDefaultObjectName(string fileName) + { + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + if (!File.Exists(fileName)) + throw new FileNotFoundException("", fileName); + + var buf = new StringBuilder(1 << 16); + NativeMethods.core_FileStorage_getDefaultObjectName(fileName, buf, buf.Capacity); + return buf.ToString(); + } + + #region Write + + /// + /// + /// + /// + /// + public void Write(string name, int value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + NativeMethods.core_FileStorage_write_int(ptr, name, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + /// + public void Write(string name, float value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + NativeMethods.core_FileStorage_write_float(ptr, name, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + /// + public void Write(string name, double value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + NativeMethods.core_FileStorage_write_double(ptr, name, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + /// + public void Write(string name, string value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + NativeMethods.core_FileStorage_write_String(ptr, name, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + /// + public void Write(string name, Mat value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + NativeMethods.core_FileStorage_write_Mat(ptr, name, value.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(value); + } + + /// + /// + /// + /// + /// + public void Write(string name, SparseMat value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + NativeMethods.core_FileStorage_write_SparseMat(ptr, name, value.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(value); + } + + /// + /// + /// + /// + /// + public void Write(string name, IEnumerable value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + using (var valueVector = new VectorOfKeyPoint(value)) + { + NativeMethods.core_FileStorage_write_vectorOfKeyPoint(ptr, name, valueVector.CvPtr); + GC.KeepAlive(this); + } + } + + /// + /// + /// + /// + /// + public void Write(string name, IEnumerable value) + { + ThrowIfDisposed(); + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (value == null) + throw new ArgumentNullException(nameof(value)); + using (var valueVector = new VectorOfDMatch(value)) + { + NativeMethods.core_FileStorage_write_vectorOfDMatch(ptr, name, valueVector.CvPtr); + GC.KeepAlive(this); + } + } + + /// + /// + /// + /// + public void WriteScalar(int value) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_writeScalar_int(ptr, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + public void WriteScalar(float value) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_writeScalar_float(ptr, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + public void WriteScalar(double value) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_writeScalar_double(ptr, value); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + public void WriteScalar(string value) + { + ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + NativeMethods.core_FileStorage_writeScalar_String(ptr, value); + GC.KeepAlive(this); + } + + #endregion + + #region Add + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(string val) + { + if (val == null) + throw new ArgumentNullException(nameof(val)); + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_String(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(int val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_int(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(float val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_float(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(double val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_double(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Mat val) + { + if (val == null) + throw new ArgumentNullException(nameof(val)); + ThrowIfDisposed(); + val.ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Mat(ptr, val.CvPtr); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(SparseMat val) + { + if (val == null) + throw new ArgumentNullException(nameof(val)); + ThrowIfDisposed(); + val.ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_SparseMat(ptr, val.CvPtr); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Range val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Range(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(KeyPoint val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_KeyPoint(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(DMatch val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_DMatch(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(IEnumerable val) + { + if (val == null) + throw new ArgumentNullException(nameof(val)); + ThrowIfDisposed(); + using (var valVec = new VectorOfKeyPoint(val)) + { + NativeMethods.core_FileStorage_shift_vectorOfKeyPoint(ptr, valVec.CvPtr); + } + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(IEnumerable val) + { + if (val == null) + throw new ArgumentNullException(nameof(val)); + ThrowIfDisposed(); + using (var valVec = new VectorOfDMatch(val)) + { + NativeMethods.core_FileStorage_shift_vectorOfDMatch(ptr, valVec.CvPtr); + } + GC.KeepAlive(this); + return this; + } + + /// + /// /Writes data to a file storage. + /// + /// + public FileStorage Add(Point val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point2i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Point2f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point2f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Point2d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point2d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Point3i val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point3i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Point3f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point3f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Point3d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Point3d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Size val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Size2i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Size2f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Size2f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Size2d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Size2d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Rect val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Rect2i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Rect2f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Rect2f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Rect2d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Rect2d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Scalar val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Scalar(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2i val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3i val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4i val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6i val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6i(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6d val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6d(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6f val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6f(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2b val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2b(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3b val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3b(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4b val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4b(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6b val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6b(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2s val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2s(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3s val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3s(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4s val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4s(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6s val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6s(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec2w val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec2w(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec3w val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec3w(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec4w val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec4w(ptr, val); + GC.KeepAlive(this); + return this; + } + + /// + /// Writes data to a file storage. + /// + /// + public FileStorage Add(Vec6w val) + { + ThrowIfDisposed(); + NativeMethods.core_FileStorage_shift_Vec6w(ptr, val); + GC.KeepAlive(this); + return this; + } + + #endregion + + #endregion + + /// + /// + /// + [Flags] + public enum States + { + /// + /// + /// + Undefined = 0, + + /// + /// + /// + ValueExpected = 1, + + /// + /// + /// + NameExpected = 2, + + /// + /// + /// + InsideMap = 4 + } + +#if LANG_JP + /// + /// FileStorageのモード + /// +#else + /// + /// File storage mode + /// +#endif + [Flags] + public enum Mode + { +#if LANG_JP + /// + /// データ読み込みのためのファイルオープン + /// +#else + /// + /// The storage is open for reading + /// +#endif + Read = 0, + +#if LANG_JP + /// + /// データ書き込みのためのファイルオープン + /// +#else + /// + /// The storage is open for writing + /// +#endif + Write = 1, + +#if LANG_JP + /// + /// データ追加書き込みのためのファイルオープン + /// +#else + /// + /// The storage is open for appending + /// +#endif + Append = 2, + + /// + /// flag, read data from source or write data to the internal buffer + /// (which is returned by FileStorage::release) + /// + Memory = 4, + + /// + /// mask for format flags + /// + FormatMask = (7 << 3), + + /// + /// flag, auto format + /// + FormatAuto = 0, + + /// + /// flag, XML format + /// + FormatXml = (1 << 3), + + /// + /// flag, YAML format + /// + FormatYaml = (2 << 3), + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/InputArray.cs b/OpenVinoOpenCvSharp/Modules/core/InputArray.cs new file mode 100644 index 0000000..303ad85 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/InputArray.cs @@ -0,0 +1,952 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +#if ENABLED_CUDA +using OpenCvSharp.Cuda; +#endif + +namespace OpenCvSharp +{ + /// + /// Proxy datatype for passing Mat's and vector<>'s as input parameters + /// + public class InputArray : DisposableCvObject + { + enum HandleKind + { + Unknown, + Mat, + Scalar, + Double, + } + + private object? obj; + private readonly IntPtr handle; + private readonly HandleKind handleKind; + +#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 + + #region Init & Disposal + + /// + /// + /// + /// + internal InputArray(IntPtr ptr) + { + this.ptr = ptr; + obj = null; + handleKind = HandleKind.Unknown; + } + + /// + /// + /// + /// + internal InputArray(Mat mat) + { + // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression + if (mat == null) + ptr = IntPtr.Zero; + else + ptr = NativeMethods.core_InputArray_new_byMat(mat.CvPtr); + GC.KeepAlive(mat); + obj = mat; + handleKind = HandleKind.Mat; + } + + /// + /// + /// + /// + internal InputArray(MatExpr expr) + { + // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression + if (expr == null) + ptr = IntPtr.Zero; + else + ptr = NativeMethods.core_InputArray_new_byMatExpr(expr.CvPtr); + GC.KeepAlive(expr); + obj = null; + } + + /// + /// + /// + /// + internal InputArray(Scalar val) + { + ptr = NativeMethods.core_InputArray_new_byScalar(val, out handle); + handleKind = HandleKind.Scalar; + } + + /// + /// + /// + /// + internal InputArray(double val) + { + handle = Marshal.AllocHGlobal(sizeof(double)); + Marshal.StructureToPtr(val, handle, false); + ptr = NativeMethods.core_InputArray_new_byDouble(handle); + handleKind = HandleKind.Double; + } + +#if ENABLED_CUDA + /// + /// + /// + /// + internal InputArray(GpuMat mat) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + ptr = NativeMethods.core_InputArray_new_byGpuMat(mat.CvPtr); + GC.KeepAlive(mat); + obj = mat; + } +#endif + + /// + /// + /// + /// + internal InputArray(IEnumerable mat) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + using (var matVector = new VectorOfMat(mat)) + { + ptr = NativeMethods.core_InputArray_new_byVectorOfMat(matVector.CvPtr); + } + obj = mat; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + switch (handleKind) + { + case HandleKind.Scalar: + NativeMethods.core_InputArray_delete_withScalar(ptr, handle); + break; + case HandleKind.Double: + Marshal.FreeHGlobal(handle); + goto default; + default: + NativeMethods.core_InputArray_delete(ptr); + break; + } + + base.DisposeUnmanaged(); + } + + #endregion + + #region Create + + /// + /// Creates a proxy class of the specified Mat + /// + /// + /// + public static InputArray Create(Mat mat) + { + return new InputArray(mat); + } + + /// + /// Creates a proxy class of the specified MatExpr + /// + /// + /// + public static InputArray Create(MatExpr expr) + { + return new InputArray(expr); + } + + /// + /// Creates a proxy class of the specified Scalar + /// + /// + /// + public static InputArray Create(Scalar val) + { + return new InputArray(val); + } + + /// + /// Creates a proxy class of the specified double + /// + /// + /// + public static InputArray Create(double val) + { + return new InputArray(val); + } + +#if ENABLED_CUDA + /// + /// Creates a proxy class of the specified GpuMat + /// + /// + /// + public static InputArray Create(GpuMat mat) + { + return new InputArray(mat); + } +#endif + + /// + /// Creates a proxy class of the specified array of Mat + /// + /// + /// + public static InputArray Create(IEnumerable matVector) + { + return new InputArray(matVector); + } + + /// + /// Creates a proxy class of the specified list + /// + /// Array object + /// + public static InputArray Create(IEnumerable enumerable) + where T : struct + { + if (enumerable == 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 == 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 == null) + throw new ArgumentNullException(nameof(array)); + if (array.Length == 0) + throw new ArgumentException("array.Length == 0"); + + var rows = array.Length; + var mat = new Mat(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 == 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 = new Mat(rows, cols, type, array); + return new InputArray(mat); + } + + /// + /// + /// + /// + /// + private static MatType EstimateType(Type t) + { +#if NET20 || NET40 + if (!t.IsValueType) +#else + if (!t.GetTypeInfo().IsValueType) +#endif + throw new ArgumentException(); + + // 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_32FC3; + 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 + + /// + /// + /// + /// + /// + public static implicit operator InputArray(Mat mat) + { + return Create(mat); + } + + /// + /// + /// + /// + /// + public static implicit operator InputArray(MatExpr expr) + { + return Create(expr); + } + + /// + /// + /// + /// + /// + public static implicit operator InputArray(Scalar val) + { + return Create(val); + } + + /// + /// + /// + /// + /// + public static implicit operator InputArray(double val) + { + return Create(val); + } + +#if ENABLED_CUDA + /// + /// + /// + /// + /// + public static implicit operator InputArray(GpuMat mat) + { + return Create(mat); + } +#endif + + /// + /// + /// + /// + /// + public static explicit operator InputArray(List mats) + { + return Create(mats); + } + + /// + /// + /// + /// + /// + public static explicit operator InputArray(Mat[] mats) + { + return Create(mats); + } + + #endregion + + #region Methods + + /// + /// + /// + /// + /// + public Mat GetMat(int i = -1) + { + ThrowIfDisposed(); + var result = NativeMethods.core_InputArray_getMat(ptr, i); + GC.KeepAlive(this); + return new Mat(result); + } + + //public Mat getMat_(int idx = -1) { } + //public UMat getUMat(int idx = -1) const; + + /// + /// + /// + /// + public Mat[] GetMatVector() + { + ThrowIfDisposed(); + using (var vec = new VectorOfMat()) + { + NativeMethods.core_InputArray_getMatVector(ptr, vec.CvPtr); + GC.KeepAlive(this); + return vec.ToArray(); + } + } + + //public void getUMatVector(std::vector& umv) { } + +#if ENABLED_CUDA + /// + /// + /// + /// + public GpuMat[] GetGpuMatVector() + { + ThrowIfDisposed(); + /*using (var vec = new VectorOfGpuMat()) + { + NativeMethods.core_InputArray_getMatVector(ptr, vec.CvPtr); + return vec.ToArray(); + }*/ + throw new NotImplementedException(); + } + + /// + /// + /// + /// + public GpuMat GetGpuMat() + { + ThrowIfDisposed(); + IntPtr result = NativeMethods.core_InputArray_getGpuMat(ptr); + GC.KeepAlive(this); + return new GpuMat(result); + } +#endif + + //public ogl::Buffer getOGlBuffer() const; + + /// + /// + /// + /// + public int GetFlags() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_getFlags(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public IntPtr GetObj() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_getObj(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public Size GetSz() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_getSz(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + public InOutArrayKind Kind() + { + ThrowIfDisposed(); + var res = (InOutArrayKind)NativeMethods.core_InputArray_kind(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public int Dims(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_dims(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public int Cols(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_cols(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public int Rows(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_rows(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public Size Size(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_size(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public int SizeND(int[] sz, int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_sizend(ptr, sz, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public bool SameSize(InputArray arr) + { + if (arr == null) + throw new ArgumentNullException(nameof(arr)); + arr.ThrowIfDisposed(); + ThrowIfDisposed(); + var result = NativeMethods.core_InputArray_sameSize(ptr, arr.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(arr); + return result != 0; + } + + /// + /// + /// + /// + /// + public long Total(int i = -1) + { + ThrowIfDisposed(); + var result = NativeMethods.core_InputArray_total(ptr, i); + GC.KeepAlive(this); + return result.ToInt64(); + } + + /// + /// + /// + /// + /// + public int Type(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_type(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public int Depth(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_depth(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public int Channels(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_channels(ptr, i); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public bool IsContinuous(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isContinuous(ptr, i) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public bool IsSubmatrix(int i = -1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isSubmatrix(ptr, i) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool Empty() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public void CopyTo(OutputArray arr) + { + if (arr == null) + throw new ArgumentNullException(nameof(arr)); + arr.ThrowIfNotReady(); + ThrowIfDisposed(); + NativeMethods.core_InputArray_copyTo1(ptr, arr.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(arr); + } + + /// + /// + /// + /// + /// + public void CopyTo(OutputArray arr, InputArray mask) + { + if (arr == null) + throw new ArgumentNullException(nameof(arr)); + if (mask == null) + throw new ArgumentNullException(nameof(mask)); + arr.ThrowIfNotReady(); + mask.ThrowIfDisposed(); + ThrowIfDisposed(); + NativeMethods.core_InputArray_copyTo2(ptr, arr.CvPtr, mask.CvPtr); + arr.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(arr); + GC.KeepAlive(mask); + } + + /// + /// + /// + /// + /// + public long Offset(int i = -1) + { + ThrowIfDisposed(); + var result = NativeMethods.core_InputArray_offset(ptr, i); + GC.KeepAlive(this); + return result.ToInt64(); + } + + /// + /// + /// + /// + /// + public long Step(int i = -1) + { + ThrowIfDisposed(); + var result = NativeMethods.core_InputArray_step(ptr, i); + GC.KeepAlive(this); + return result.ToInt64(); + } + + /// + /// + /// + /// + public bool IsMat() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isMat(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsUMat() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isUMat(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsMatVector() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isMatVector(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsUMatVector() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isUMatVector(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsMatx() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isMatx(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsVector() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isVector(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public bool IsGpuMatVector() + { + ThrowIfDisposed(); + var res = NativeMethods.core_InputArray_isGpuMatVector(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/InputOutputArray.cs b/OpenVinoOpenCvSharp/Modules/core/InputOutputArray.cs new file mode 100644 index 0000000..4e34ae2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/InputOutputArray.cs @@ -0,0 +1,29 @@ + +namespace OpenCvSharp +{ + /// + /// Proxy data type for passing Mat's and vector<>'s as input parameters. + /// Synonym for OutputArray. + /// + public class InputOutputArray : OutputArray + { + /// + /// + /// + /// + internal InputOutputArray(Mat mat) + : base(mat) + { + } + + /// + /// + /// + /// + /// + public static implicit operator InputOutputArray(Mat mat) + { + return new InputOutputArray(mat); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/LDA.cs b/OpenVinoOpenCvSharp/Modules/core/LDA.cs new file mode 100644 index 0000000..0cf2a0e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/LDA.cs @@ -0,0 +1,261 @@ +using System; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// + /// Linear Discriminant Analysis + /// + // ReSharper disable once InconsistentNaming + public class LDA : DisposableCvObject + { + #region Init & Disposal + + /// + /// constructor + /// + /// + // ReSharper disable once InheritdocConsiderUsage + public LDA(int numComponents = 0) + { + ptr = NativeMethods.core_LDA_new1(numComponents); + } + + /// + /// Initializes and performs a Discriminant Analysis with Fisher's + /// Optimization Criterion on given data in src and corresponding labels + /// in labels.If 0 (or less) number of components are given, they are + /// automatically determined for given data in computation. + /// + /// + /// + /// + // ReSharper disable once InheritdocConsiderUsage + public LDA(InputArray src, InputArray labels, int numComponents = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (labels == null) + throw new ArgumentNullException(nameof(labels)); + src.ThrowIfDisposed(); + labels.ThrowIfDisposed(); + ptr = NativeMethods.core_LDA_new2(src.CvPtr, labels.CvPtr, numComponents); + GC.KeepAlive(src); + GC.KeepAlive(labels); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_LDA_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// Returns the eigenvectors of this LDA. + /// + public Mat Eigenvectors() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_LDA_eigenvectors(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// Returns the eigenvalues of this LDA. + /// + public Mat Eigenvalues() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_LDA_eigenvalues(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// Serializes this object to a given filename. + /// + /// + public void Save(string fileName) + { + ThrowIfDisposed(); + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + NativeMethods.core_LDA_save_String(ptr, fileName); + GC.KeepAlive(this); + } + + /// + /// Deserializes this object from a given filename. + /// + /// + public void Load(string fileName) + { + ThrowIfDisposed(); + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + NativeMethods.core_LDA_load_String(ptr, fileName); + GC.KeepAlive(this); + } + + /// + /// Serializes this object to a given cv::FileStorage. + /// + /// + public void Save(FileStorage fs) + { + ThrowIfDisposed(); + if (fs == null) + throw new ArgumentNullException(nameof(fs)); + fs.ThrowIfDisposed(); + NativeMethods.core_LDA_save_FileStorage(ptr, fs.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(fs); + } + + /// + /// Deserializes this object from a given cv::FileStorage. + /// + /// + public void Load(FileStorage node) + { + ThrowIfDisposed(); + if (node == null) + throw new ArgumentNullException(nameof(node)); + node.ThrowIfDisposed(); + NativeMethods.core_LDA_load_FileStorage(ptr, node.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(node); + } + + /// + /// Compute the discriminants for data in src (row aligned) and labels. + /// + /// + /// + public void Compute(InputArray src, InputArray labels) + { + ThrowIfDisposed(); + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (labels == null) + throw new ArgumentNullException(nameof(labels)); + src.ThrowIfDisposed(); + labels.ThrowIfDisposed(); + + NativeMethods.core_LDA_compute(ptr, src.CvPtr, labels.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(src); + GC.KeepAlive(labels); + } + + /// + /// Projects samples into the LDA subspace. + /// src may be one or more row aligned samples. + /// + /// + /// + public Mat Project(InputArray src) + { + ThrowIfDisposed(); + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + var ret = NativeMethods.core_LDA_project(ptr, src.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(src); + + return new Mat(ret); + } + + /// + /// Reconstructs projections from the LDA subspace. + /// src may be one or more row aligned projections. + /// + /// + /// + public Mat Reconstruct(InputArray src) + { + ThrowIfDisposed(); + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + var ret = NativeMethods.core_LDA_reconstruct(ptr, src.CvPtr); + + GC.KeepAlive(this); + GC.KeepAlive(src); + + return new Mat(ret); + } + + #endregion + + #region Static + + /// + /// + /// + /// + /// + /// + /// + public static Mat SubspaceProject(InputArray w, InputArray mean, InputArray src) + { + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (src == null) + throw new ArgumentNullException(nameof(src)); + w.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + src.ThrowIfDisposed(); + + var ret = NativeMethods.core_LDA_subspaceProject(w.CvPtr, mean.CvPtr, src.CvPtr); + + GC.KeepAlive(w); + GC.KeepAlive(mean); + GC.KeepAlive(src); + + return new Mat(ret); + } + + /// + /// + /// + /// + /// + /// + /// + public static Mat SubspaceReconstruct(InputArray w, InputArray mean, InputArray src) + { + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + if (src == null) + throw new ArgumentNullException(nameof(src)); + w.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + src.ThrowIfDisposed(); + + var ret = NativeMethods.core_LDA_subspaceProject(w.CvPtr, mean.CvPtr, src.CvPtr); + + GC.KeepAlive(w); + GC.KeepAlive(mean); + GC.KeepAlive(src); + + return new Mat(ret); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Mat/Mat.cs b/OpenVinoOpenCvSharp/Modules/core/Mat/Mat.cs new file mode 100644 index 0000000..5078db7 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Mat/Mat.cs @@ -0,0 +1,5761 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// OpenCV C++ n-dimensional dense array class (cv::Mat) + /// + public partial class Mat : DisposableCvObject + { + #region Static Constructor + + /// + /// typeof(T) -> MatType + /// + protected static readonly Dictionary TypeMap; + + /// + /// / + /// + static Mat() + { + TypeMap = new Dictionary + { + [typeof(byte)] = MatType.CV_8UC1, + [typeof(sbyte)] = MatType.CV_8SC1, + [typeof(short)] = MatType.CV_16SC1, + [typeof(char)] = MatType.CV_16UC1, + [typeof(ushort)] = MatType.CV_16UC1, + [typeof(int)] = MatType.CV_32SC1, + [typeof(float)] = MatType.CV_32FC1, + [typeof(double)] = MatType.CV_64FC1, + + [typeof(Vec2b)] = MatType.CV_8UC2, + [typeof(Vec3b)] = MatType.CV_8UC3, + [typeof(Vec4b)] = MatType.CV_8UC4, + [typeof(Vec6b)] = MatType.CV_8UC(6), + + [typeof(Vec2s)] = MatType.CV_16SC2, + [typeof(Vec3s)] = MatType.CV_16SC3, + [typeof(Vec4s)] = MatType.CV_16SC4, + [typeof(Vec6s)] = MatType.CV_16SC(6), + + [typeof(Vec2w)] = MatType.CV_16UC2, + [typeof(Vec3w)] = MatType.CV_16UC3, + [typeof(Vec4w)] = MatType.CV_16UC4, + [typeof(Vec6w)] = MatType.CV_16UC(6), + + [typeof(Vec2i)] = MatType.CV_32SC2, + [typeof(Vec3i)] = MatType.CV_32SC3, + [typeof(Vec4i)] = MatType.CV_32SC4, + [typeof(Vec6i)] = MatType.CV_32SC(6), + + [typeof(Vec2f)] = MatType.CV_32FC2, + [typeof(Vec3f)] = MatType.CV_32FC3, + [typeof(Vec4f)] = MatType.CV_32FC4, + [typeof(Vec6f)] = MatType.CV_32FC(6), + + [typeof(Vec2d)] = MatType.CV_64FC2, + [typeof(Vec3d)] = MatType.CV_64FC3, + [typeof(Vec4d)] = MatType.CV_64FC4, + [typeof(Vec6d)] = MatType.CV_64FC(6), + + [typeof(Point)] = MatType.CV_32SC2, + [typeof(Point2f)] = MatType.CV_32FC2, + [typeof(Point2d)] = MatType.CV_64FC2, + + [typeof(Point3i)] = MatType.CV_32SC3, + [typeof(Point3f)] = MatType.CV_32FC3, + [typeof(Point3d)] = MatType.CV_64FC3, + + [typeof(Size)] = MatType.CV_32SC2, + [typeof(Size2f)] = MatType.CV_32FC2, + [typeof(Size2d)] = MatType.CV_64FC2, + + [typeof(Rect)] = MatType.CV_32SC4, + [typeof(Rect2f)] = MatType.CV_32FC4, + [typeof(Rect2d)] = MatType.CV_64FC4, + + [typeof(DMatch)] = MatType.CV_32FC4, + }; + } + + #endregion + + #region Init & Disposal + +#if LANG_JP +/// +/// OpenCVネイティブの cv::Mat* ポインタから初期化 +/// +/// +#else + /// + /// Creates from native cv::Mat* pointer + /// + /// +#endif + public Mat(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Native object address is NULL"); + this.ptr = ptr; + } + +#if LANG_JP +/// +/// 空の行列として初期化 +/// +#else + /// + /// Creates empty Mat + /// +#endif + public Mat() + { + ptr = NativeMethods.core_Mat_new1(); + } + + /// + /// + /// + /// + protected Mat(Mat m) + { + ptr = NativeMethods.core_Mat_new12(m.ptr); + } + +#if LANG_JP +/// +/// 画像ファイルから読み込んで初期化 (cv::imread) +/// +/// 読み込まれる画像ファイル名 +/// 画像読み込みフラグ. +#else + /// + /// Loads an image from a file. (cv::imread) + /// + /// Name of file to be loaded. + /// Specifies color type of the loaded image +#endif + public Mat(string fileName, ImreadModes flags = ImreadModes.Color) + { + if (string.IsNullOrEmpty(fileName)) + throw new ArgumentNullException(nameof(fileName)); + + if (!File.Exists(fileName)) + throw new FileNotFoundException("", fileName); + + ptr = NativeMethods.imgcodecs_imread(fileName, (int) flags); + } + +#if LANG_JP +/// +/// 指定したサイズ・型の2次元の行列として初期化 +/// +/// 2次元配列における行数. +/// 2次元配列における列数. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +#else + /// + /// constructs 2D matrix of the specified size and type + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. +#endif + public Mat(int rows, int cols, MatType type) + { + ptr = NativeMethods.core_Mat_new2(rows, cols, type); + } + +#if LANG_JP +/// +/// 指定したサイズ・型の2次元の行列として初期化 +/// +/// 2次元配列のサイズ: Size(cols, rows) . Size コンストラクタでは,行数と列数が逆順になっていることに注意してください. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +#else + /// + /// constructs 2D matrix of the specified size and type + /// + /// 2D array size: Size(cols, rows) . In the Size() constructor, + /// the number of rows and the number of columns go in the reverse order. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType.CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. +#endif + public Mat(Size size, MatType type) + { + ptr = NativeMethods.core_Mat_new2(size.Height, size.Width, type); + } + +#if LANG_JP +/// +/// 指定したサイズ・型の2次元の行列で、要素をスカラー値で埋めて初期化 +/// +/// 2次元配列における行数. +/// 2次元配列における列数. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, +/// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs 2D matrix and fills it with the specified Scalar value. + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(int rows, int cols, MatType type, Scalar s) + { + ptr = NativeMethods.core_Mat_new3(rows, cols, type, s); + } + +#if LANG_JP +/// +/// 指定したサイズ・型の2次元の行列で、要素をスカラー値で埋めて初期化 +/// +/// 2 次元配列のサイズ: Size(cols, rows) . Size() コンストラクタでは,行数と列数が逆順になっていることに注意してください. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, +/// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs 2D matrix and fills it with the specified Scalar value. + /// + /// 2D array size: Size(cols, rows) . In the Size() constructor, + /// the number of rows and the number of columns go in the reverse order. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(Size size, MatType type, Scalar s) + { + ptr = NativeMethods.core_Mat_new3(size.Height, size.Width, type, s); + } + +#if LANG_JP +/// +/// 他の行列の部分行列として初期化 +/// +/// 作成された行列に(全体的,部分的に)割り当てられる配列. +/// これらのコンストラクタによってデータがコピーされる事はありません. +/// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, +/// 関連した参照カウンタがあれば,それがインクリメントされます. +/// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も +/// 変更することになります.もし部分配列の独立したコピーが必要ならば, +/// Mat.Clone() を利用してください. +/// 扱われる 行列の行の範囲.すべての行を扱う場合は,Range.All を利用してください. +/// 扱われる 行列の列の範囲.すべての列を扱う場合は,Range.All を利用してください. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat::clone() . + /// Range of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. + /// Use Range.All to take all the rows. + /// Range of the m columns to take. Use Range.All to take all the columns. +#endif + public Mat(Mat m, Range rowRange, Range? colRange = null) + { + // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression + if (colRange.HasValue) + ptr = NativeMethods.core_Mat_new4(m.ptr, rowRange, colRange.Value); + else + ptr = NativeMethods.core_Mat_new5(m.ptr, rowRange); + GC.KeepAlive(m); + } + +#if LANG_JP +/// +/// 他の行列の部分行列として初期化 +/// +/// 作成された行列に(全体的,部分的に)割り当てられる配列. +/// これらのコンストラクタによってデータがコピーされる事はありません. +/// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, +/// 関連した参照カウンタがあれば,それがインクリメントされます. +/// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も +/// 変更することになります.もし部分配列の独立したコピーが必要ならば, +/// Mat.Clone() を利用してください. +/// 多次元行列の各次元毎の選択範囲を表す配列. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat.Clone() . + /// Array of selected ranges of m along each dimensionality. +#endif + public Mat(Mat m, params Range[] ranges) + { + if (ranges == null) + throw new ArgumentNullException(nameof(ranges)); + if (ranges.Length == 0) + throw new ArgumentException("empty ranges", nameof(ranges)); + + ptr = NativeMethods.core_Mat_new6(m.ptr, ranges); + GC.KeepAlive(m); + } + +#if LANG_JP +/// +/// 他の行列の部分行列として初期化 +/// +/// 作成された行列に(全体的,部分的に)割り当てられる配列. +/// これらのコンストラクタによってデータがコピーされる事はありません. +/// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, +/// 関連した参照カウンタがあれば,それがインクリメントされます. +/// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も +/// 変更することになります.もし部分配列の独立したコピーが必要ならば, +/// Mat.Clone() を利用してください. +/// 元の行列からくりぬかれる範囲. ROI[Region of interest]. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat.Clone() . + /// Region of interest. +#endif + public Mat(Mat m, Rect roi) + { + ptr = NativeMethods.core_Mat_new7(m.ptr, roi); + GC.KeepAlive(m); + } + +#if LANG_JP +/// +/// 利用者が別に確保したデータで初期化 +/// +/// 2次元配列における行数. +/// 2次元配列における列数. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// ユーザデータへのポインタ. data と step パラメータを引数にとる +/// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す +/// 行列ヘッダを初期化します.つまり,データのコピーは行われません. +/// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. +/// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. +/// 行列の各行が占めるバイト数を指定できます. +/// この値は,各行の終端にパディングバイトが存在すれば,それも含みます. +/// このパラメータが指定されない場合,パディングは存在しないとみなされ, +/// 実際の step は cols*elemSize() として計算されます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. + /// If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() . +#endif + public Mat(int rows, int cols, MatType type, IntPtr data, long step = 0) + { + ptr = NativeMethods.core_Mat_new8(rows, cols, type, data, new IntPtr(step)); + } + +#if LANG_JP +/// +/// 利用者が別に確保したデータで初期化 +/// +/// 2次元配列における行数. +/// 2次元配列における列数. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// ユーザデータへのポインタ. data と step パラメータを引数にとる +/// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す +/// 行列ヘッダを初期化します.つまり,データのコピーは行われません. +/// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. +/// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. +/// 行列の各行が占めるバイト数を指定できます. +/// この値は,各行の終端にパディングバイトが存在すれば,それも含みます. +/// このパラメータが指定されない場合,パディングは存在しないとみなされ, +/// 実際の step は cols*elemSize() として計算されます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. + /// If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() . +#endif + public Mat(int rows, int cols, MatType type, Array data, long step = 0) + { + var handle = AllocGCHandle(data); + ptr = NativeMethods.core_Mat_new8(rows, cols, type, + handle.AddrOfPinnedObject(), new IntPtr(step)); + } + +#if LANG_JP +/// +/// 利用者が別に確保したデータで初期化 +/// +/// Array of integers specifying an n-dimensional array shape. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// ユーザデータへのポインタ. data と step パラメータを引数にとる +/// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す +/// 行列ヘッダを初期化します.つまり,データのコピーは行われません. +/// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. +/// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. +/// 多次元配列における ndims-1 個のステップを表す配列 +/// (最後のステップは常に要素サイズになります).これが指定されないと, +/// 行列は連続したものとみなされます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Array of integers specifying an n-dimensional array shape. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). + /// If not specified, the matrix is assumed to be continuous. +#endif + public Mat(IEnumerable sizes, MatType type, IntPtr data, IEnumerable? steps = null) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + if (data == IntPtr.Zero) + throw new ArgumentNullException(nameof(data)); + var sizesArray = EnumerableEx.ToArray(sizes); + if (steps == null) + { + ptr = NativeMethods.core_Mat_new9(sizesArray.Length, sizesArray, type, data, IntPtr.Zero); + } + else + { + var stepsArray = EnumerableEx.SelectToArray(steps, s => new IntPtr(s)); + ptr = NativeMethods.core_Mat_new9(sizesArray.Length, sizesArray, type, data, stepsArray); + } + } + +#if LANG_JP +/// +/// 利用者が別に確保したデータで初期化 +/// +/// n-次元配列の形状を表す,整数型の配列. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// ユーザデータへのポインタ. data と step パラメータを引数にとる +/// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す +/// 行列ヘッダを初期化します.つまり,データのコピーは行われません. +/// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. +/// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. +/// 多次元配列における ndims-1 個のステップを表す配列 +/// (最後のステップは常に要素サイズになります).これが指定されないと, +/// 行列は連続したものとみなされます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Array of integers specifying an n-dimensional array shape. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). + /// If not specified, the matrix is assumed to be continuous. +#endif + public Mat(IEnumerable sizes, MatType type, Array data, IEnumerable? steps = null) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + if (data == null) + throw new ArgumentNullException(nameof(data)); + + var handle = AllocGCHandle(data); + var sizesArray = EnumerableEx.ToArray(sizes); + if (steps == null) + { + ptr = NativeMethods.core_Mat_new9(sizesArray.Length, sizesArray, + type, handle.AddrOfPinnedObject(), IntPtr.Zero); + } + else + { + var stepsArray = EnumerableEx.SelectToArray(steps, s => new IntPtr(s)); + ptr = NativeMethods.core_Mat_new9(sizesArray.Length, sizesArray, + type, handle.AddrOfPinnedObject(), stepsArray); + } + } + +#if LANG_JP +/// +/// N次元行列として初期化 +/// +/// n-次元配列の形状を表す,整数型の配列. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +#else + /// + /// constructs n-dimensional matrix + /// + /// Array of integers specifying an n-dimensional array shape. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. +#endif + public Mat(IEnumerable sizes, MatType type) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + + var sizesArray = EnumerableEx.ToArray(sizes); + ptr = NativeMethods.core_Mat_new10(sizesArray.Length, sizesArray, type); + } + +#if LANG_JP +/// +/// N次元行列として初期化 +/// +/// n-次元配列の形状を表す,整数型の配列. +/// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, +/// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +/// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, +/// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs n-dimensional matrix + /// + /// Array of integers specifying an n-dimensional array shape. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(IEnumerable sizes, MatType type, Scalar s) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + var sizesArray = EnumerableEx.ToArray(sizes); + ptr = NativeMethods.core_Mat_new11(sizesArray.Length, sizesArray, type, s); + } + +#if LANG_JP +/// +/// リソースの解放 +/// +#else + /// + /// Releases the resources + /// +#endif + public void Release() + { + Dispose(); + } + + /// + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + if (ptr != IntPtr.Zero) + NativeMethods.core_Mat_delete(ptr); + base.DisposeUnmanaged(); + } + + #region Static Initializers + +#if LANG_JP + /// + /// System.IO.StreamのインスタンスからMatを生成する + /// + /// + /// + /// +#else + /// + /// Creates the Mat instance from System.IO.Stream + /// + /// + /// + /// +#endif + public static Mat FromStream(Stream stream, ImreadModes mode) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + if (stream.Length > int.MaxValue) + throw new ArgumentException("Not supported stream (too long)"); + + var buf = new byte[stream.Length]; + var currentPosition = stream.Position; + try + { + stream.Position = 0; + var count = 0; + while (count < stream.Length) + { + var bytesRead = stream.Read(buf, count, buf.Length - count); + if (bytesRead == 0) + { + break; + } + + count += bytesRead; + } + } + finally + { + stream.Position = currentPosition; + } + + return FromImageData(buf, mode); + } + +#if LANG_JP +/// +/// 画像データ(JPEG等の画像をメモリに展開したもの)からMatを生成する (cv::decode) +/// +/// +/// +/// +#else + /// + /// Creates the Mat instance from image data (using cv::decode) + /// + /// + /// + /// +#endif + public static Mat ImDecode(byte[] imageBytes, ImreadModes mode = ImreadModes.Color) + { + if (imageBytes == null) + throw new ArgumentNullException(nameof(imageBytes)); + return Cv2.ImDecode(imageBytes, mode); + } + +#if LANG_JP +/// +/// 画像データ(JPEG等の画像をメモリに展開したもの)からMatを生成する (cv::decode) +/// +/// +/// +/// +#else + /// + /// Creates the Mat instance from image data (using cv::decode) + /// + /// + /// + /// +#endif + public static Mat FromImageData(byte[] imageBytes, ImreadModes mode = ImreadModes.Color) + { + return ImDecode(imageBytes, mode); + } + + #endregion + + #endregion + + #region Static + + /// + /// sizeof(cv::Mat) + /// + public static readonly int SizeOf = (int) NativeMethods.core_Mat_sizeof(); + + #region Diag + + /// + /// Extracts a diagonal from a matrix, or creates a diagonal matrix. + /// + /// + /// + public static Mat Diag(Mat d) + { + var retPtr = NativeMethods.core_Mat_diag3(d.CvPtr); + GC.KeepAlive(d); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region Eye + + /// + /// Returns an identity matrix of the specified size and type. + /// + /// Alternative to the matrix size specification Size(cols, rows) . + /// Created matrix type. + /// + public static MatExpr Eye(Size size, MatType type) + { + return Eye(size.Height, size.Width, type); + } + + /// + /// Returns an identity matrix of the specified size and type. + /// + /// Number of rows. + /// Number of columns. + /// Created matrix type. + /// + public static MatExpr Eye(int rows, int cols, MatType type) + { + var retPtr = NativeMethods.core_Mat_eye(rows, cols, type); + var retVal = new MatExpr(retPtr); + return retVal; + } + + #endregion + + #region Ones + + /// + /// Returns an array of all 1’s of the specified size and type. + /// + /// Number of rows. + /// Number of columns. + /// Created matrix type. + /// + public static MatExpr Ones(int rows, int cols, MatType type) + { + var retPtr = NativeMethods.core_Mat_ones1(rows, cols, type); + var retVal = new MatExpr(retPtr); + return retVal; + } + + /// + /// Returns an array of all 1’s of the specified size and type. + /// + /// Alternative to the matrix size specification Size(cols, rows) . + /// Created matrix type. + /// + public static MatExpr Ones(Size size, MatType type) + { + return Ones(size.Height, size.Width, type); + } + + /// + /// Returns an array of all 1’s of the specified size and type. + /// + /// Created matrix type. + /// Array of integers specifying the array shape. + /// + public static MatExpr Ones(MatType type, params int[] sizes) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + + var retPtr = NativeMethods.core_Mat_ones2(sizes.Length, sizes, type); + var retVal = new MatExpr(retPtr); + return retVal; + } + + #endregion + + #region Zeros + + /// + /// Returns a zero array of the specified size and type. + /// + /// Number of rows. + /// Number of columns. + /// Created matrix type. + /// + public static MatExpr Zeros(int rows, int cols, MatType type) + { + var retPtr = NativeMethods.core_Mat_zeros1(rows, cols, type); + var retVal = new MatExpr(retPtr); + return retVal; + } + + /// + /// Returns a zero array of the specified size and type. + /// + /// Alternative to the matrix size specification Size(cols, rows) . + /// Created matrix type. + /// + public static MatExpr Zeros(Size size, MatType type) + { + return Zeros(size.Height, size.Width, type); + } + + /// + /// Returns a zero array of the specified size and type. + /// + /// Created matrix type. + /// + /// + /// + public static MatExpr Zeros(MatType type, int cols, params int[] sizes) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + + var retPtr = NativeMethods.core_Mat_zeros2(sizes.Length, sizes, type); + var retVal = new MatExpr(retPtr); + return retVal; + } + + #endregion + + #endregion + + #region Operators + + #region Unary + + /// + /// + /// + /// + /// + public static MatExpr operator -(Mat mat) + { + var expr = NativeMethods.core_Mat_operatorUnaryMinus(mat.CvPtr); + GC.KeepAlive(mat); + return new MatExpr(expr); + } + + /// + /// + /// + /// + /// + public static Mat operator +(Mat mat) + { + return mat; + } + + #endregion + + #region Binary + + #region + + + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + + var retPtr = NativeMethods.core_Mat_operatorAdd_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(Mat a, Scalar s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + + var retPtr = NativeMethods.core_Mat_operatorAdd_MatScalar(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(Scalar s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorAdd_ScalarMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region - + + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorSubtract_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(Mat a, Scalar s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorSubtract_MatScalar(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(Scalar s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorSubtract_ScalarMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region * + + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorMultiply_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(Mat a, double s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorMultiply_MatDouble(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(double s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorMultiply_DoubleMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region / + + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorDivide_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(Mat a, double s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorDivide_MatDouble(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(double s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorDivide_DoubleMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region And + + /// + /// + /// + /// + /// + /// + public static MatExpr operator &(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorAnd_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator &(Mat a, double s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorAnd_MatDouble(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator &(double s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorAnd_DoubleMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region Or + + /// + /// + /// + /// + /// + /// + public static MatExpr operator |(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorOr_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator |(Mat a, double s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorOr_MatDouble(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator |(double s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorOr_DoubleMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region Xor + + /// + /// + /// + /// + /// + /// + public static MatExpr operator ^(Mat a, Mat b) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorXor_MatMat(a.CvPtr, b.CvPtr); + GC.KeepAlive(a); + GC.KeepAlive(b); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator ^(Mat a, double s) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorXor_MatDouble(a.CvPtr, s); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + /// + /// + /// + /// + /// + /// + public static MatExpr operator ^(double s, Mat a) + { + if (a == null) + throw new ArgumentNullException(nameof(a)); + a.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorXor_DoubleMat(s, a.CvPtr); + GC.KeepAlive(a); + return new MatExpr(retPtr); + } + + #endregion + + #region Not + + /// + /// + /// + /// + /// + public static MatExpr operator ~(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + m.ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_operatorNot(m.CvPtr); + GC.KeepAlive(m); + return new MatExpr(retPtr); + } + + #endregion + + #endregion + + #endregion + + #region Comparison + + /// + /// operator < + /// + /// + /// + public MatExpr LessThan(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorLT_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + var ret = new MatExpr(expr); + return ret; + } + + /// + /// operator < + /// + /// + /// + public MatExpr LessThan(double d) + { + var expr = NativeMethods.core_Mat_operatorLT_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + return ret; + } + + /// + /// operator <= + /// + /// + /// + public MatExpr LessThanOrEqual(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorLE_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + GC.KeepAlive(m); + return ret; + } + + /// + /// operator <= + /// + /// + /// + public MatExpr LessThanOrEqual(double d) + { + var expr = NativeMethods.core_Mat_operatorLE_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + return ret; + } + + /// + /// operator == + /// + /// + /// + public MatExpr Equals(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorEQ_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + GC.KeepAlive(m); + return ret; + } + + /// + /// operator == + /// + /// + /// + public MatExpr Equals(double d) + { + var expr = NativeMethods.core_Mat_operatorEQ_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + return ret; + } + + /// + /// operator != + /// + /// + /// + public MatExpr NotEquals(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorNE_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + GC.KeepAlive(m); + return ret; + } + + /// + /// operator != + /// + /// + /// + public MatExpr NotEquals(double d) + { + var expr = NativeMethods.core_Mat_operatorNE_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + return ret; + } + + /// + /// operator > + /// + /// + /// + public MatExpr GreaterThan(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorGT_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + GC.KeepAlive(m); + return ret; + } + + /// + /// operator > + /// + /// + /// + public MatExpr GreaterThan(double d) + { + var expr = NativeMethods.core_Mat_operatorGT_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + return ret; + } + + /// + /// operator >= + /// + /// + /// + public MatExpr GreaterThanOrEqual(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + + var expr = NativeMethods.core_Mat_operatorGE_MatMat(ptr, m.CvPtr); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + GC.KeepAlive(m); + return ret; + } + + /// + /// operator >= + /// + /// + /// + public MatExpr GreaterThanOrEqual(double d) + { + var expr = NativeMethods.core_Mat_operatorGE_MatDouble(ptr, d); + GC.KeepAlive(this); + var ret = new MatExpr(expr); + + return ret; + } + + #endregion + + #region Public Methods + + #region Mat Indexers + + /// + /// Extracts a rectangular submatrix. + /// + /// Start row of the extracted submatrix. The upper boundary is not included. + /// End row of the extracted submatrix. The upper boundary is not included. + /// Start column of the extracted submatrix. The upper boundary is not included. + /// End column of the extracted submatrix. The upper boundary is not included. + /// + public Mat this[int rowStart, int rowEnd, int colStart, int colEnd] + { + get => SubMat(rowStart, rowEnd, colStart, colEnd); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + //if (Type() != value.Type()) + // throw new ArgumentException("Mat type mismatch"); + if (Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var sub = SubMat(rowStart, rowEnd, colStart, colEnd); + if (sub.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(sub); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Start and end row of the extracted submatrix. The upper boundary is not included. + /// To select all the rows, use Range.All(). + /// Start and end column of the extracted submatrix. + /// The upper boundary is not included. To select all the columns, use Range.All(). + /// + public Mat this[Range rowRange, Range colRange] + { + get => SubMat(rowRange, colRange); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + //if (Type() != value.Type()) + // throw new ArgumentException("Mat type mismatch"); + if (Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var sub = SubMat(rowRange, colRange); + if (sub.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(sub); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Extracted submatrix specified as a rectangle. + /// + public Mat this[Rect roi] + { + get => SubMat(roi); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + //if (Type() != value.Type()) + // throw new ArgumentException("Mat type mismatch"); + if (Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + if (roi.Size != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + var sub = SubMat(roi); + value.CopyTo(sub); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Array of selected ranges along each array dimension. + /// + public Mat this[params Range[] ranges] + { + get => SubMat(ranges); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + //if (Type() != value.Type()) + // throw new ArgumentException("Mat type mismatch"); + + var sub = SubMat(ranges); + + var dims = Dims(); + if (dims != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + for (var i = 0; i < dims; i++) + { + if (sub.Size(i) != value.Size(i)) + throw new ArgumentException("Size mismatch at dimension " + i); + } + + value.CopyTo(sub); + } + } + + #endregion + + #region MatExpr Indexers + + #region SubMat + + /// + /// + /// + public class MatExprIndexer : MatExprRangeIndexer + { + /// + /// + /// + /// + protected internal MatExprIndexer(Mat parent) + : base(parent) + { + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Start row of the extracted submatrix. The upper boundary is not included. + /// End row of the extracted submatrix. The upper boundary is not included. + /// Start column of the extracted submatrix. The upper boundary is not included. + /// End column of the extracted submatrix. The upper boundary is not included. + /// + public override MatExpr this[int rowStart, int rowEnd, int colStart, int colEnd] + { + get => Parent.SubMat(rowStart, rowEnd, colStart, colEnd); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + using var submat = Parent.SubMat(rowStart, rowEnd, colStart, colEnd); + NativeMethods.core_Mat_assignment_FromMatExpr(submat.CvPtr, value.CvPtr); + GC.KeepAlive(submat); + GC.KeepAlive(value); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Start and end row of the extracted submatrix. The upper boundary is not included. + /// To select all the rows, use Range.All(). + /// Start and end column of the extracted submatrix. + /// The upper boundary is not included. To select all the columns, use Range.All(). + /// + public override MatExpr this[Range rowRange, Range colRange] + { + get => Parent.SubMat(rowRange, colRange); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + using var submat = Parent.SubMat(rowRange, colRange); + NativeMethods.core_Mat_assignment_FromMatExpr(submat.CvPtr, value.CvPtr); + GC.KeepAlive(submat); + GC.KeepAlive(value); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Extracted submatrix specified as a rectangle. + /// + public override MatExpr this[Rect roi] + { + get => Parent.SubMat(roi); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + using var submat = Parent.SubMat(roi); + NativeMethods.core_Mat_assignment_FromMatExpr(submat.CvPtr, value.CvPtr); + GC.KeepAlive(submat); + GC.KeepAlive(value); + } + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Array of selected ranges along each array dimension. + /// + public override MatExpr this[params Range[] ranges] + { + get => Parent.SubMat(ranges); + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + using var submat = Parent.SubMat(ranges); + NativeMethods.core_Mat_assignment_FromMatExpr(submat.CvPtr, value.CvPtr); + GC.KeepAlive(submat); + GC.KeepAlive(value); + } + } + } + + /// + /// Indexer to access partial Mat as MatExpr + /// + /// + public MatExprIndexer Expr + { + get { return matExprIndexer ??= new MatExprIndexer(this); } + } + + private MatExprIndexer? matExprIndexer; + + #endregion + + #region ColExpr + + /// + /// Mat column's indexer object + /// + public class ColExprIndexer : MatRowColExprIndexer + { + /// + /// + /// + /// + protected internal ColExprIndexer(Mat parent) + : base(parent) + { + } + + /// + /// Creates a matrix header for the specified matrix column. + /// + /// A 0-based column index. + /// + public override MatExpr this[int x] + { + get + { + Parent.ThrowIfDisposed(); + var matExprPtr = NativeMethods.core_Mat_col_toMatExpr(Parent.ptr, x); + GC.KeepAlive(this); + var matExpr = new MatExpr(matExprPtr); + return matExpr; + } + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + Parent.ThrowIfDisposed(); + var colMatPtr = NativeMethods.core_Mat_col_toMat(Parent.ptr, x); + NativeMethods.core_Mat_assignment_FromMatExpr(colMatPtr, value.CvPtr); + NativeMethods.core_Mat_delete(colMatPtr); + GC.KeepAlive(this); + GC.KeepAlive(value); + } + } + + /// + /// Creates a matrix header for the specified column span. + /// + /// An inclusive 0-based start index of the column span. + /// An exclusive 0-based ending index of the column span. + /// + public override MatExpr this[int startCol, int endCol] + { + get + { + Parent.ThrowIfDisposed(); + var matExprPtr = NativeMethods.core_Mat_colRange_toMatExpr(Parent.ptr, startCol, endCol); + GC.KeepAlive(this); + var matExpr = new MatExpr(matExprPtr); + return matExpr; + } + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + Parent.ThrowIfDisposed(); + var colMatPtr = NativeMethods.core_Mat_colRange_toMat(Parent.ptr, startCol, endCol); + GC.KeepAlive(this); + NativeMethods.core_Mat_assignment_FromMatExpr(colMatPtr, value.CvPtr); + GC.KeepAlive(value); + NativeMethods.core_Mat_delete(colMatPtr); + } + } + } + + /// + /// Indexer to access Mat column as MatExpr + /// + /// + public ColExprIndexer ColExpr + { + get { return colExprIndexer ??= new ColExprIndexer(this); } + } + + private ColExprIndexer? colExprIndexer; + + #endregion + + #region RowExpr + + /// + /// Mat row's indexer object + /// + public class RowExprIndexer : MatRowColExprIndexer + { + /// + /// + /// + /// + protected internal RowExprIndexer(Mat parent) + : base(parent) + { + } + + /// + /// Creates a matrix header for the specified matrix row. [Mat::row] + /// + /// A 0-based row index. + /// + public override MatExpr this[int y] + { + get + { + Parent.ThrowIfDisposed(); + var matExprPtr = NativeMethods.core_Mat_row_toMatExpr(Parent.ptr, y); + GC.KeepAlive(this); + var matExpr = new MatExpr(matExprPtr); + return matExpr; + } + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + Parent.ThrowIfDisposed(); + var rowMatPtr = NativeMethods.core_Mat_row_toMat(Parent.ptr, y); + GC.KeepAlive(this); + NativeMethods.core_Mat_assignment_FromMatExpr(rowMatPtr, value.CvPtr); + GC.KeepAlive(value); + NativeMethods.core_Mat_delete(rowMatPtr); + } + } + + /// + /// Creates a matrix header for the specified row span. (Mat::rowRange) + /// + /// An inclusive 0-based start index of the row span. + /// An exclusive 0-based ending index of the row span. + /// + public override MatExpr this[int startRow, int endRow] + { + get + { + Parent.ThrowIfDisposed(); + var matExprPtr = NativeMethods.core_Mat_rowRange_toMatExpr(Parent.ptr, startRow, endRow); + GC.KeepAlive(this); + var matExpr = new MatExpr(matExprPtr); + return matExpr; + } + set + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + Parent.ThrowIfDisposed(); + var rowMatPtr = NativeMethods.core_Mat_rowRange_toMat(Parent.ptr, startRow, endRow); + GC.KeepAlive(this); + NativeMethods.core_Mat_assignment_FromMatExpr(rowMatPtr, value.CvPtr); + GC.KeepAlive(value); + NativeMethods.core_Mat_delete(rowMatPtr); + } + } + } + + /// + /// Indexer to access Mat row as MatExpr + /// + /// + public RowExprIndexer RowExpr + { + get { return rowExprIndexer ??= new RowExprIndexer(this); } + } + + private RowExprIndexer? rowExprIndexer; + + #endregion + + #endregion + + #region AdjustROI + + /// + /// Adjusts a submatrix size and position within the parent matrix. + /// + /// Shift of the top submatrix boundary upwards. + /// Shift of the bottom submatrix boundary downwards. + /// Shift of the left submatrix boundary to the left. + /// Shift of the right submatrix boundary to the right. + /// + // ReSharper disable once InconsistentNaming + public Mat AdjustROI(int dtop, int dbottom, int dleft, int dright) + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_adjustROI(ptr, dtop, dbottom, dleft, dright); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region AssignTo + + /// + /// Provides a functional form of convertTo. + /// + /// Destination array. + /// Desired destination array depth (or -1 if it should be the same as the source type). + public void AssignTo(Mat m, MatType type) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + NativeMethods.core_Mat_assignTo2(ptr, m.CvPtr, type); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// Provides a functional form of convertTo. + /// + /// Destination array. + public void AssignTo(Mat m) + { + NativeMethods.core_Mat_assignTo1(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + #endregion + + #region Channels + + /// + /// Returns the number of matrix channels. + /// + /// + public int Channels() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_channels(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region CheckVector + + /// + /// + /// + /// + /// + public int CheckVector(int elemChannels) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_checkVector1(ptr, elemChannels); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + /// + public int CheckVector(int elemChannels, int depth) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_checkVector2(ptr, elemChannels, depth); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + /// + /// + public int CheckVector(int elemChannels, int depth, bool requireContinuous) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_checkVector3( + ptr, elemChannels, depth, requireContinuous ? 1 : 0); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Clone + + /// + /// Creates a full copy of the matrix. + /// + /// + public Mat Clone() + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_clone(ptr); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + /// + /// Returns the partial Mat of the specified Mat + /// + /// + /// + public Mat Clone(Rect roi) + { + using (var part = new Mat(this, roi)) + { + return part.Clone(); + } + } + + #endregion + + #region Cols + + /// + /// the number of columns or -1 when the array has more than 2 dimensions + /// + /// + public int Cols + { + get + { + //行列データが新たに確保された場合に対応できない。 + //if (colsVal == int.MinValue) + //{ + // colsVal = NativeMethods.core_Mat_cols(ptr); + //} + //return colsVal; + var res = NativeMethods.core_Mat_cols(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// the number of columns or -1 when the array has more than 2 dimensions + /// + /// + public int Width + { + get + { + //if (colsVal == int.MinValue) + //{ + // colsVal = Cols; + //} + //return colsVal; + var res = NativeMethods.core_Mat_cols(ptr); + GC.KeepAlive(this); + return res; + } + } + + //private int colsVal = int.MinValue; + + #endregion + + #region Dims + + /// + /// the array dimensionality, >= 2 + /// + public int Dims() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_dims(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region ConvertTo + + /// + /// Converts an array to another data type with optional scaling. + /// + /// output matrix; if it does not have a proper size or type before the operation, it is reallocated. + /// desired output matrix type or, rather, the depth since the number of channels are the same as the input has; + /// 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(Mat m, MatType rtype, double alpha = 1, double beta = 0) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + NativeMethods.core_Mat_convertTo(ptr, m.CvPtr, rtype, alpha, beta); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + #endregion + + #region CopyTo + + /// + /// Copies the matrix to another one. + /// + /// Destination matrix. If it does not have a proper size or type before the operation, it is reallocated. + public void CopyTo(Mat m) + { + CopyTo(m, null); + } + + /// + /// Copies the matrix to another one. + /// + /// 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, Mat? mask) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + var maskPtr = Cv2.ToPtr(mask); + NativeMethods.core_Mat_copyTo(ptr, m.CvPtr, maskPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + GC.KeepAlive(mask); + } + + #endregion + + #region Create + + /// + /// Allocates new array data if needed. + /// + /// New number of rows. + /// New number of columns. + /// New matrix type. + public void Create(int rows, int cols, MatType type) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_create1(ptr, rows, cols, type); + GC.KeepAlive(this); + } + + /// + /// Allocates new array data if needed. + /// + /// Alternative new matrix size specification: Size(cols, rows) + /// New matrix type. + public void Create(Size size, MatType type) + { + Create(size.Height, size.Width, type); + } + + /// + /// Allocates new array data if needed. + /// + /// Array of integers specifying a new array shape. + /// New matrix type. + public void Create(MatType type, params int[] sizes) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + if (sizes.Length < 2) + throw new ArgumentException("sizes.Length < 2"); + NativeMethods.core_Mat_create2(ptr, sizes.Length, sizes, type); + GC.KeepAlive(this); + } + + #endregion + + #region Cross + + /// + /// Computes a cross-product of two 3-element vectors. + /// + /// Another cross-product operand. + /// + public Mat Cross(Mat m) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + var retPtr = NativeMethods.core_Mat_cross(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region Data + + /// + /// pointer to the data + /// + public IntPtr Data + { + get + { + unsafe + { + return new IntPtr(DataPointer); + } + } + } + + /// + /// unsafe pointer to the data + /// + public unsafe byte* DataPointer + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_data(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// The pointer that is possible to compute a relative sub-array position in the main container array using locateROI() + /// + public IntPtr DataStart + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_datastart(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// The pointer that is possible to compute a relative sub-array position in the main container array using locateROI() + /// + public IntPtr DataEnd + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_dataend(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// The pointer that is possible to compute a relative sub-array position in the main container array using locateROI() + /// + public IntPtr DataLimit + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_datalimit(ptr); + GC.KeepAlive(this); + return res; + } + } + + #endregion + + #region Depth + + /// + /// Returns the depth of a matrix element. + /// + /// + public int Depth() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_depth(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Diag + + /// + /// Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values: + /// + /// Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values: + /// + public Mat Diag(MatDiagType d = MatDiagType.Main) + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_diag2(ptr, (int) d); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region Dot + + /// + /// Computes a dot-product of two vectors. + /// + /// another dot-product operand. + /// + public double Dot(Mat m) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + var res = NativeMethods.core_Mat_dot(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + return res; + } + + #endregion + + #region ElemSize + + /// + /// Returns the matrix element size in bytes. + /// + /// + public int ElemSize() + { + ThrowIfDisposed(); + var res = (int) NativeMethods.core_Mat_elemSize(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region ElemSize1 + + /// + /// Returns the size of each matrix element channel in bytes. + /// + /// + public int ElemSize1() + { + ThrowIfDisposed(); + var res = (int) NativeMethods.core_Mat_elemSize1(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Empty + + /// + /// Returns true if the array has no elements. + /// + /// + public bool Empty() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Inv + + /// + /// Inverses a matrix. + /// + /// Matrix inversion method + /// + public Mat Inv(DecompTypes method = DecompTypes.LU) + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_inv2(ptr, (int) method); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region IsContinuous + + /// + /// Reports whether the matrix is continuous or not. + /// + /// + public bool IsContinuous() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_isContinuous(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + #endregion + + #region IsSubmatrix + + /// + /// Returns whether this matrix is a part of other matrix or not. + /// + /// + public bool IsSubmatrix() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_isSubmatrix(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + #endregion + + #region LocateROI + + /// + /// Locates the matrix header within a parent matrix. + /// + /// Output parameter that contains the size of the whole matrix containing *this as a part. + /// Output parameter that contains an offset of *this inside the whole matrix. + // ReSharper disable once InconsistentNaming + public void LocateROI(out Size wholeSize, out Point ofs) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_locateROI(ptr, out wholeSize, out ofs); + GC.KeepAlive(this); + } + + #endregion + + #region Mul + + /// + /// Performs an element-wise multiplication or division of the two matrices. + /// + /// + /// + /// + public MatExpr Mul(Mat m, double scale = 1) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(); + var mPtr = m.CvPtr; + var retPtr = NativeMethods.core_Mat_mul2(ptr, mPtr, scale); + GC.KeepAlive(this); + GC.KeepAlive(m); + var retVal = new MatExpr(retPtr); + return retVal; + } + + #endregion + + #region Reshape + + /// + /// Changes the shape and/or the number of channels of a 2D matrix without copying the data. + /// + /// New number of channels. If the parameter is 0, the number of channels remains the same. + /// New number of rows. If the parameter is 0, the number of rows remains the same. + /// + public Mat Reshape(int cn, int rows = 0) + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_reshape2(ptr, cn, rows); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + /// + /// Changes the shape and/or the number of channels of a 2D matrix without copying the data. + /// + /// New number of channels. If the parameter is 0, the number of channels remains the same. + /// New number of rows. If the parameter is 0, the number of rows remains the same. + /// + public Mat Reshape(int cn, params int[] newDims) + { + ThrowIfDisposed(); + if (newDims == null) + throw new ArgumentNullException(nameof(newDims)); + var retPtr = NativeMethods.core_Mat_reshape3(ptr, cn, newDims.Length, newDims); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region Rows + + /// + /// the number of rows or -1 when the array has more than 2 dimensions + /// + public int Rows + { + get + { + //if (rowsVal == int.MinValue) + //{ + // rowsVal = NativeMethods.core_Mat_rows(ptr); + //} + //return rowsVal; + var res = NativeMethods.core_Mat_rows(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// the number of rows or -1 when the array has more than 2 dimensions + /// + /// + public int Height + { + get + { + //if (rowsVal == int.MinValue) + //{ + // rowsVal = Rows; + //} + //return rowsVal; + var res = NativeMethods.core_Mat_rows(ptr); + GC.KeepAlive(this); + return res; + } + } + + //private int rowsVal = int.MinValue; + + #endregion + + #region SetTo + + /// + /// Sets all or some of the array elements to the specified value. + /// + /// + /// + /// + public Mat SetTo(Scalar value, Mat? mask = null) + { + ThrowIfDisposed(); + var maskPtr = Cv2.ToPtr(mask); + + NativeMethods.core_Mat_setTo_Scalar(ptr, value, maskPtr); + + GC.KeepAlive(this); + GC.KeepAlive(mask); + return this; + } + + /// + /// Sets all or some of the array elements to the specified value. + /// + /// + /// + /// + public Mat SetTo(InputArray value, Mat? mask = null) + { + ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + var maskPtr = Cv2.ToPtr(mask); + + NativeMethods.core_Mat_setTo_InputArray(ptr, value.CvPtr, maskPtr); + + GC.KeepAlive(this); + GC.KeepAlive(value); + GC.KeepAlive(mask); + return this; + } + + #endregion + + #region Size + + /// + /// Returns a matrix size. + /// + /// + public Size Size() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_size(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns a matrix size. + /// + /// + /// + public int Size(int dim) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_sizeAt(ptr, dim); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Step + + /// + /// + /// + /// + public long Step() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_step(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + /// + public long Step(int i) + { + ThrowIfDisposed(); + var res = (long) NativeMethods.core_Mat_stepAt(ptr, i); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Step1 + + /// + /// Returns a normalized step. + /// + /// + public long Step1() + { + ThrowIfDisposed(); + var res = (long) NativeMethods.core_Mat_step11(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns a normalized step. + /// + /// + /// + public long Step1(int i) + { + ThrowIfDisposed(); + var res = (long) NativeMethods.core_Mat_step12(ptr, i); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region T + + /// + /// Transposes a matrix. + /// + /// + public Mat T() + { + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_t(ptr); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + #endregion + + #region Total + + /// + /// Returns the total number of array elements. + /// + /// + public long Total() + { + ThrowIfDisposed(); + var res = (long) NativeMethods.core_Mat_total(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Type + + /// + /// Returns the type of a matrix element. + /// + /// + public MatType Type() + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_type(ptr); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region ToString + + /// + /// Returns a string that represents this Mat. + /// + /// + public override string ToString() + { + return "Mat [ " + + Rows + "*" + Cols + "*" + Type().ToString() + + ", IsContinuous=" + IsContinuous() + ", IsSubmatrix=" + IsSubmatrix() + + ", Ptr=0x" + Convert.ToString(ptr.ToInt64(), 16) + + ", Data=0x" + Convert.ToString(Data.ToInt64(), 16) + + " ]"; + } + + #endregion + + #region Dump + + /// + /// Returns a string that represents each element value of Mat. + /// This method corresponds to std::ostream << Mat + /// + /// + /// + public string? Dump(FormatType format = FormatType.Default) + { + ThrowIfDisposed(); + return Cv2.Format(this, format); + } + + #endregion + + #region EmptyClone + +#if LANG_JP +/// +/// このMatと同じサイズ・ビット深度・チャネル数を持つ +/// Matオブジェクトを新たに作成し、返す +/// +/// コピーされた画像 +#else + /// + /// Makes a Mat that have the same size, depth and channels as this image + /// + /// +#endif + public Mat EmptyClone() + { + return new Mat(Size(), Type()); + } + + #endregion + + #region Ptr + + /// + /// Returns a pointer to the specified matrix row. + /// + /// Index along the dimension 0 + /// + public IntPtr Ptr(int i0) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_ptr1d(ptr, i0); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns a pointer to the specified matrix element. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// + public IntPtr Ptr(int i0, int i1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_ptr2d(ptr, i0, i1); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns a pointer to the specified matrix element. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// + public IntPtr Ptr(int i0, int i1, int i2) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_ptr3d(ptr, i0, i1, i2); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns a pointer to the specified matrix element. + /// + /// Array of Mat::dims indices. + /// + public IntPtr Ptr(params int[] idx) + { + ThrowIfDisposed(); + var res = NativeMethods.core_Mat_ptrnd(ptr, idx); + GC.KeepAlive(this); + return res; + } + + #endregion + + #region Element Indexer + + /// + /// Gets a type-specific indexer. The indexer has getters/setters to access each matrix element. + /// + /// + /// + public Indexer GetGenericIndexer() where T : struct + { + return new Indexer(this); + } + + /// + /// Gets a type-specific unsafe indexer. The indexer has getters/setters to access each matrix element. + /// + /// + /// + public UnsafeIndexer GetUnsafeGenericIndexer() where T : unmanaged + { + return new UnsafeIndexer(this); + } + + /// + /// Mat Indexer + /// + /// + public sealed class Indexer : MatIndexer where T : struct + { + private readonly long ptrVal; + + internal Indexer(Mat parent) + : base(parent) + { + ptrVal = parent.Data.ToInt64(); + } + + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public override T this[int i0] + { + get + { + var p = new IntPtr(ptrVal + (Steps[0] * i0)); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = new IntPtr(ptrVal + (Steps[0] * i0)); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public override T this[int i0, int i1] + { + get + { + var p = new IntPtr(ptrVal + (Steps[0] * i0) + (Steps[1] * i1)); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = new IntPtr(ptrVal + (Steps[0] * i0) + (Steps[1] * i1)); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public override T this[int i0, int i1, int i2] + { + get + { + var p = new IntPtr(ptrVal + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = new IntPtr(ptrVal + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public override T this[params int[] idx] + { + get + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + + var p = new IntPtr(ptrVal + offset); + return MarshalHelper.PtrToStructure(p); + } + set + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + + var p = new IntPtr(ptrVal + offset); + Marshal.StructureToPtr(value, p, false); + } + } + } + + /// + /// Mat Indexer + /// + /// + public sealed class UnsafeIndexer : MatIndexer where T : unmanaged + { + private readonly long ptrVal; + + internal UnsafeIndexer(Mat parent) + : base(parent) + { + ptrVal = parent.Data.ToInt64(); + } + + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public override unsafe T this[int i0] + { + get + { + var p = (T*) (ptrVal + (Steps[0] * i0)); + return *p; + } + set + { + var p = (T*) (ptrVal + (Steps[0] * i0)); + *p = value; + } + } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public override unsafe T this[int i0, int i1] + { + get + { + var p = (T*) (ptrVal + (Steps[0] * i0) + (Steps[1] * i1)); + return *p; + } + set + { + var p = (T*) (ptrVal + (Steps[0] * i0) + (Steps[1] * i1)); + *p = value; + } + } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public override unsafe T this[int i0, int i1, int i2] + { + get + { + var p = (T*) (ptrVal + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)); + return *p; + } + set + { + var p = (T*) (ptrVal + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)); + *p = value; + } + } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public override unsafe T this[params int[] idx] + { + get + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + + var p = (T*) (ptrVal + offset); + return *p; + } + set + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + + var p = (T*) (ptrVal + offset); + *p = value; + } + } + } + + #endregion + + #region Get/Set + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public T Get(int i0) where T : struct + { + return new Indexer(this)[i0]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public T Get(int i0, int i1) where T : struct + { + return new Indexer(this)[i0, i1]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public T Get(int i0, int i1, int i2) where T : struct + { + return new Indexer(this)[i0, i1, i2]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public T Get(params int[] idx) where T : struct + { + return new Indexer(this)[idx]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public T At(int i0) where T : struct + { + return new Indexer(this)[i0]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public T At(int i0, int i1) where T : struct + { + return new Indexer(this)[i0, i1]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public T At(int i0, int i1, int i2) where T : struct + { + return new Indexer(this)[i0, i1, i2]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public T At(params int[] idx) where T : struct + { + return new Indexer(this)[idx]; + } + + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// + public void Set(int i0, T value) where T : struct + { + (new Indexer(this))[i0] = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// + public void Set(int i0, int i1, T value) where T : struct + { + (new Indexer(this))[i0, i1] = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// + public void Set(int i0, int i1, int i2, T value) where T : struct + { + (new Indexer(this)[i0, i1, i2]) = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Array of Mat::dims indices. + /// + public void Set(int[] idx, T value) where T : struct + { + (new Indexer(this)[idx]) = value; + } + + #endregion + + #region Col/ColRange + + /* + /// + /// + /// + /// + /// + public Mat Col(int x) + { + ThrowIfDisposed(); + IntPtr matPtr = NativeMethods.core_Mat_col_toMat(ptr, x); + return new Mat(matPtr); + } + */ + + /// + /// + /// + /// + /// + /// + public Mat ColRange(int startCol, int endCol) + { + ThrowIfDisposed(); + var matPtr = NativeMethods.core_Mat_colRange_toMat(ptr, startCol, endCol); + GC.KeepAlive(this); + return new Mat(matPtr); + } + + /// + /// + /// + /// + /// + public Mat ColRange(Range range) + { + return ColRange(range.Start, range.End); + } + + + /// + /// Mat column's indexer object + /// + public class ColIndexer : MatRowColIndexer + { + /// + /// + /// + /// + protected internal ColIndexer(Mat parent) + : base(parent) + { + } + + /// + /// Creates a matrix header for the specified matrix column. + /// + /// A 0-based column index. + /// + public override Mat this[int x] + { + get + { + Parent.ThrowIfDisposed(); + var matPtr = NativeMethods.core_Mat_col_toMat(Parent.ptr, x); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + return mat; + } + set + { + Parent.ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + if (Parent.Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var matPtr = NativeMethods.core_Mat_col_toMat(Parent.ptr, x); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + if (mat.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(mat); + } + } + + /// + /// Creates a matrix header for the specified column span. + /// + /// An inclusive 0-based start index of the column span. + /// An exclusive 0-based ending index of the column span. + /// + public override Mat this[int startCol, int endCol] + { + get + { + Parent.ThrowIfDisposed(); + var matPtr = NativeMethods.core_Mat_colRange_toMat(Parent.ptr, startCol, endCol); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + return mat; + } + set + { + Parent.ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + if (Parent.Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var colMatPtr = NativeMethods.core_Mat_colRange_toMat(Parent.ptr, startCol, endCol); + GC.KeepAlive(this); + var colMat = new Mat(colMatPtr); + if (colMat.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(colMat); + } + } + } + + /// + /// Indexer to access Mat column as Mat + /// + /// + public ColIndexer Col + { + get { return colIndexer ??= new ColIndexer(this); } + } + + private ColIndexer? colIndexer; + + #endregion + + #region Row/RowRange + + /* + /// + /// + /// + /// + /// + public Mat Row(int y) + { + ThrowIfDisposed(); + IntPtr matPtr = NativeMethods.core_Mat_row_toMat(ptr, y); + return new Mat(matPtr); + } + */ + + /// + /// + /// + /// + /// + /// + public Mat RowRange(int startRow, int endRow) + { + ThrowIfDisposed(); + var matPtr = NativeMethods.core_Mat_rowRange_toMat(ptr, startRow, endRow); + GC.KeepAlive(this); + return new Mat(matPtr); + } + + /// + /// + /// + /// + /// + public Mat RowRange(Range range) + { + return RowRange(range.Start, range.End); + } + + /// + /// Mat row's indexer object + /// + public class RowIndexer : MatRowColIndexer + { + /// + /// + /// + /// + protected internal RowIndexer(Mat parent) + : base(parent) + { + } + + /// + /// Creates a matrix header for the specified matrix row. + /// + /// A 0-based row index. + /// + public override Mat this[int x] + { + get + { + Parent.ThrowIfDisposed(); + var matPtr = NativeMethods.core_Mat_row_toMat(Parent.ptr, x); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + return mat; + } + set + { + Parent.ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + if (Parent.Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var matPtr = NativeMethods.core_Mat_row_toMat(Parent.ptr, x); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + if (mat.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(mat); + } + } + + /// + /// Creates a matrix header for the specified row span. + /// + /// An inclusive 0-based start index of the row span. + /// An exclusive 0-based ending index of the row span. + /// + public override Mat this[int startRow, int endRow] + { + get + { + Parent.ThrowIfDisposed(); + // todo: rsb - is this row or col range? + var matPtr = NativeMethods.core_Mat_rowRange_toMat(Parent.ptr, startRow, endRow); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + return mat; + } + set + { + Parent.ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + value.ThrowIfDisposed(); + if (Parent.Dims() != value.Dims()) + throw new ArgumentException("Dimension mismatch"); + + var matPtr = NativeMethods.core_Mat_rowRange_toMat(Parent.ptr, startRow, endRow); + GC.KeepAlive(this); + var mat = new Mat(matPtr); + if (mat.Size() != value.Size()) + throw new ArgumentException("Specified ROI != mat.Size()"); + value.CopyTo(mat); + } + } + } + + /// + /// Indexer to access Mat row as Mat + /// + /// + public RowIndexer Row + { + get { return rowIndexer ??= new RowIndexer(this); } + } + + private RowIndexer? rowIndexer; + + #endregion + + #region SubMat + + /// + /// + /// + /// + /// + /// + /// + /// + public Mat SubMat(int rowStart, int rowEnd, int colStart, int colEnd) + { + if (rowStart >= rowEnd) + throw new ArgumentException("rowStart >= rowEnd"); + if (colStart >= colEnd) + throw new ArgumentException("colStart >= colEnd"); + + ThrowIfDisposed(); + var retPtr = NativeMethods.core_Mat_subMat1(ptr, rowStart, rowEnd, colStart, colEnd); + GC.KeepAlive(this); + var retVal = new Mat(retPtr); + return retVal; + } + + /// + /// + /// + /// + /// + /// + public Mat SubMat(Range rowRange, Range colRange) + { + return SubMat(rowRange.Start, rowRange.End, colRange.Start, colRange.End); + } + + /// + /// + /// + /// + /// + public Mat SubMat(Rect roi) + { + return SubMat(roi.Y, roi.Y + roi.Height, roi.X, roi.X + roi.Width); + } + + + /// + /// + /// + /// + /// + public Mat SubMat(params Range[] ranges) + { + if (ranges == null) + throw new ArgumentNullException(); + + ThrowIfDisposed(); + + IntPtr retPtr = NativeMethods.core_Mat_subMat2(ptr, ranges.Length, ranges); + Mat retVal = new Mat(retPtr); + GC.KeepAlive(this); + return retVal; + } + + #endregion + + #region GetArray + + /* + private void CheckArgumentsForConvert(int row, int col, Array data, + MatType[] acceptableTypes) + { + ThrowIfDisposed(); + if (row < 0 || row >= Rows) + throw new ArgumentOutOfRangeException(nameof(row)); + if (col < 0 || col >= Cols) + throw new ArgumentOutOfRangeException(nameof(col)); + if (data == null) + throw new ArgumentNullException(nameof(data)); + + MatType t = Type(); + if (data == null || data.Length % t.Channels != 0) + throw new OpenCvSharpException( + "Provided data element number ({0}) should be multiple of the Mat channels count ({1})", + data.Length, t.Channels); + + if (acceptableTypes != null && acceptableTypes.Length > 0) + { + bool isValidDepth = EnumerableEx.Any(acceptableTypes, type => type == t); + if (!isValidDepth) + throw new OpenCvSharpException("Mat data type is not compatible: " + t); + } + } + */ + + private void CheckArgumentsForConvert(int row, int col, Array data, int dataDimension, + MatType[]? acceptableTypes) + { + ThrowIfDisposed(); + if (row < 0 || row >= Rows) + throw new ArgumentOutOfRangeException(nameof(row)); + if (col < 0 || col >= Cols) + throw new ArgumentOutOfRangeException(nameof(col)); + if (data == null) + throw new ArgumentNullException(nameof(data)); + + var t = Type(); + if ((data.Length * dataDimension) % t.Channels != 0) + throw new OpenCvSharpException( + "Provided data element number ({0}) should be multiple of the Mat channels count ({1})", + data.Length, t.Channels); + + if (acceptableTypes != null && acceptableTypes.Length > 0) + { + var isValidDepth = EnumerableEx.Any(acceptableTypes, type => type == t); + if (!isValidDepth) + throw new OpenCvSharpException("Mat data type is not compatible: " + t); + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, byte[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_8SC1, MatType.CV_8UC1}); + unsafe + { + fixed (byte* pData = data) + { + NativeMethods.core_Mat_nGetB(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, byte[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_8SC1, MatType.CV_8UC1}); + unsafe + { + fixed (byte* pData = data) + { + NativeMethods.core_Mat_nGetB(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, short[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (short* pData = data) + { + NativeMethods.core_Mat_nGetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, short[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (short* pData = data) + { + NativeMethods.core_Mat_nGetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, ushort[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (ushort* pData = data) + { + NativeMethods.core_Mat_nGetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, ushort[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (ushort* pData = data) + { + NativeMethods.core_Mat_nGetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, int[] data) + { + CheckArgumentsForConvert(row, col, data, MatType.CV_32S, null); + unsafe + { + fixed (int* pData = data) + { + NativeMethods.core_Mat_nGetI(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, int[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32SC1}); + unsafe + { + fixed (int* pData = data) + { + NativeMethods.core_Mat_nGetI(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, float[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32FC1}); + unsafe + { + fixed (float* pData = data) + { + NativeMethods.core_Mat_nGetF(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, float[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32FC1}); + unsafe + { + fixed (float* pData = data) + { + NativeMethods.core_Mat_nGetF(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, double[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_64FC1}); + unsafe + { + fixed (double* pData = data) + { + NativeMethods.core_Mat_nGetD(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, double[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_64FC1}); + unsafe + { + fixed (double* pData = data) + { + NativeMethods.core_Mat_nGetD(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public double[] GetArray(int row, int col) + { + ThrowIfDisposed(); + if (row < 0 || row >= Rows) + throw new ArgumentOutOfRangeException(nameof(row)); + if (col < 0 || col >= Cols) + throw new ArgumentOutOfRangeException(nameof(col)); + + var ret = new double[Channels()]; + unsafe + { + fixed (double* pData = ret) + { + NativeMethods.core_Mat_nGetD(ptr, row, col, pData, ret.Length); + GC.KeepAlive(this); + return ret; + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec3b[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_8UC3}); + unsafe + { + fixed (Vec3b* pData = data) + { + NativeMethods.core_Mat_nGetVec3b(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec3b[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_8UC3}); + unsafe + { + fixed (Vec3b* pData = data) + { + NativeMethods.core_Mat_nGetVec3b(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec3d[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Vec3d* pData = data) + { + NativeMethods.core_Mat_nGetVec3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec3d[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Vec3d* pData = data) + { + NativeMethods.core_Mat_nGetVec3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec4f[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32FC4}); + unsafe + { + fixed (Vec4f* pData = data) + { + NativeMethods.core_Mat_nGetVec4f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec4f[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32FC4}); + unsafe + { + fixed (Vec4f* pData = data) + { + NativeMethods.core_Mat_nGetVec4f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec6f[] data) + { + CheckArgumentsForConvert(row, col, data, 6, new[] {MatType.CV_32FC(6)}); + unsafe + { + fixed (Vec6f* pData = data) + { + NativeMethods.core_Mat_nGetVec6f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec6f[,] data) + { + CheckArgumentsForConvert(row, col, data, 6, new[] {MatType.CV_32FC(6)}); + unsafe + { + fixed (Vec6f* pData = data) + { + NativeMethods.core_Mat_nGetVec6f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec4i[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Vec4i* pData = data) + { + NativeMethods.core_Mat_nGetVec4i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Vec4i[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Vec4i* pData = data) + { + NativeMethods.core_Mat_nGetVec4i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32SC2}); + unsafe + { + fixed (Point* pData = data) + { + NativeMethods.core_Mat_nGetPoint(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32SC2}); + unsafe + { + fixed (Point* pData = data) + { + NativeMethods.core_Mat_nGetPoint(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point2f[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32FC2}); + unsafe + { + fixed (Point2f* pData = data) + { + NativeMethods.core_Mat_nGetPoint2f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point2f[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32FC2}); + unsafe + { + fixed (Point2f* pData = data) + { + NativeMethods.core_Mat_nGetPoint2f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point2d[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_64FC2}); + unsafe + { + fixed (Point2d* pData = data) + { + NativeMethods.core_Mat_nGetPoint2d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point2d[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_64FC2}); + unsafe + { + fixed (Point2d* pData = data) + { + NativeMethods.core_Mat_nGetPoint2d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3i[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32SC3}); + unsafe + { + fixed (Point3i* pData = data) + { + NativeMethods.core_Mat_nGetPoint3i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3i[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32SC3}); + unsafe + { + fixed (Point3i* pData = data) + { + NativeMethods.core_Mat_nGetPoint3i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3f[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32FC3}); + unsafe + { + fixed (Point3f* pData = data) + { + NativeMethods.core_Mat_nGetPoint3f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3f[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32FC3}); + unsafe + { + fixed (Point3f* pData = data) + { + NativeMethods.core_Mat_nGetPoint3f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3d[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Point3d* pData = data) + { + NativeMethods.core_Mat_nGetPoint3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Point3d[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Point3d* pData = data) + { + NativeMethods.core_Mat_nGetPoint3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Rect[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Rect* pData = data) + { + NativeMethods.core_Mat_nGetRect(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, Rect[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Rect* pData = data) + { + NativeMethods.core_Mat_nGetRect(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, DMatch[] data) + { + CheckArgumentsForConvert(row, col, data, 4, null); + unsafe + { + var dataV = new Vec4f[data.Length]; + fixed (Vec4f* pData = dataV) + { + NativeMethods.core_Mat_nGetVec4f(ptr, row, col, pData, dataV.Length); + GC.KeepAlive(this); + for (var i = 0; i < data.Length; i++) + { + data[i] = (DMatch) dataV[i]; + } + } + } + } + + /// + /// Get the data of this matrix as array + /// + /// + /// + /// + public void GetArray(int row, int col, DMatch[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, null); + var dim0 = data.GetLength(0); + var dim1 = data.GetLength(1); + unsafe + { + var dataV = new Vec4f[dim0, dim1]; + fixed (Vec4f* pData = dataV) + { + NativeMethods.core_Mat_nGetVec4f(ptr, row, col, pData, dataV.Length); + GC.KeepAlive(this); + for (var i = 0; i < dim0; i++) + { + for (var j = 0; j < dim1; j++) + { + data[i, j] = (DMatch) dataV[i, j]; + } + } + } + } + } + + #endregion + + #region SetArray + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, byte[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_8UC1}); + unsafe + { + fixed (byte* pData = data) + { + NativeMethods.core_Mat_nSetB(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, byte[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_8UC1}); + unsafe + { + fixed (byte* pData = data) + { + NativeMethods.core_Mat_nSetB(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, short[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (short* pData = data) + { + NativeMethods.core_Mat_nSetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, short[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (short* pData = data) + { + NativeMethods.core_Mat_nSetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, ushort[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (ushort* pData = data) + { + NativeMethods.core_Mat_nSetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, ushort[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_16SC1, MatType.CV_16UC1}); + unsafe + { + fixed (ushort* pData = data) + { + NativeMethods.core_Mat_nSetS(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, int[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32SC1}); + unsafe + { + fixed (int* pData = data) + { + NativeMethods.core_Mat_nSetI(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, int[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32SC1}); + unsafe + { + fixed (int* pData = data) + { + NativeMethods.core_Mat_nSetI(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, float[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32FC1}); + unsafe + { + fixed (float* pData = data) + { + NativeMethods.core_Mat_nSetF(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, float[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_32FC1}); + unsafe + { + fixed (float* pData = data) + { + NativeMethods.core_Mat_nSetF(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, double[] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_64FC1}); + unsafe + { + fixed (double* pData = data) + { + NativeMethods.core_Mat_nSetD(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, double[,] data) + { + CheckArgumentsForConvert(row, col, data, 1, new[] {MatType.CV_64FC1}); + unsafe + { + fixed (double* pData = data) + { + NativeMethods.core_Mat_nSetD(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec3b[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_8UC3}); + unsafe + { + fixed (Vec3b* pData = data) + { + NativeMethods.core_Mat_nSetVec3b(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec3b[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_8UC3}); + unsafe + { + fixed (Vec3b* pData = data) + { + NativeMethods.core_Mat_nSetVec3b(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec3d[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Vec3d* pData = data) + { + NativeMethods.core_Mat_nSetVec3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec3d[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Vec3d* pData = data) + { + NativeMethods.core_Mat_nSetVec3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec4f[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32FC4}); + unsafe + { + fixed (Vec4f* pData = data) + { + NativeMethods.core_Mat_nSetVec4f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec4f[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32FC4}); + unsafe + { + fixed (Vec4f* pData = data) + { + NativeMethods.core_Mat_nSetVec4f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec6f[] data) + { + CheckArgumentsForConvert(row, col, data, 6, new[] {MatType.CV_32FC(6)}); + unsafe + { + fixed (Vec6f* pData = data) + { + NativeMethods.core_Mat_nSetVec6f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec6f[,] data) + { + CheckArgumentsForConvert(row, col, data, 6, new[] {MatType.CV_32FC(6)}); + unsafe + { + fixed (Vec6f* pData = data) + { + NativeMethods.core_Mat_nSetVec6f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec4i[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Vec4i* pData = data) + { + NativeMethods.core_Mat_nSetVec4i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Vec4i[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Vec4i* pData = data) + { + NativeMethods.core_Mat_nSetVec4i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32SC2}); + unsafe + { + fixed (Point* pData = data) + { + NativeMethods.core_Mat_nSetPoint(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32SC2}); + unsafe + { + fixed (Point* pData = data) + { + NativeMethods.core_Mat_nSetPoint(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point2f[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32FC2}); + unsafe + { + fixed (Point2f* pData = data) + { + NativeMethods.core_Mat_nSetPoint2f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point2f[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_32FC2}); + unsafe + { + fixed (Point2f* pData = data) + { + NativeMethods.core_Mat_nSetPoint2f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point2d[] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_64FC2}); + unsafe + { + fixed (Point2d* pData = data) + { + NativeMethods.core_Mat_nSetPoint2d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point2d[,] data) + { + CheckArgumentsForConvert(row, col, data, 2, new[] {MatType.CV_64FC2}); + unsafe + { + fixed (Point2d* pData = data) + { + NativeMethods.core_Mat_nSetPoint2d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3i[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32SC3}); + unsafe + { + fixed (Point3i* pData = data) + { + NativeMethods.core_Mat_nSetPoint3i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3i[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32SC3}); + unsafe + { + fixed (Point3i* pData = data) + { + NativeMethods.core_Mat_nSetPoint3i(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3f[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32FC3}); + unsafe + { + fixed (Point3f* pData = data) + { + NativeMethods.core_Mat_nSetPoint3f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3f[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_32FC3}); + unsafe + { + fixed (Point3f* pData = data) + { + NativeMethods.core_Mat_nSetPoint3f(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3d[] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Point3d* pData = data) + { + NativeMethods.core_Mat_nSetPoint3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Point3d[,] data) + { + CheckArgumentsForConvert(row, col, data, 3, new[] {MatType.CV_64FC3}); + unsafe + { + fixed (Point3d* pData = data) + { + NativeMethods.core_Mat_nSetPoint3d(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Rect[] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Rect* pData = data) + { + NativeMethods.core_Mat_nSetRect(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, Rect[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, new[] {MatType.CV_32SC4}); + unsafe + { + fixed (Rect* pData = data) + { + NativeMethods.core_Mat_nSetRect(ptr, row, col, pData, data.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, DMatch[] data) + { + CheckArgumentsForConvert(row, col, data, 4, null); + var dataV = EnumerableEx.SelectToArray(data, d => (Vec4f) d); + unsafe + { + fixed (Vec4f* pData = dataV) + { + NativeMethods.core_Mat_nSetVec4f(ptr, row, col, pData, dataV.Length); + GC.KeepAlive(this); + } + } + } + + /// + /// Set the specified array data to this matrix + /// + /// + /// + /// + public void SetArray(int row, int col, DMatch[,] data) + { + CheckArgumentsForConvert(row, col, data, 4, null); + var dataV = EnumerableEx.SelectToArray(data, (DMatch d) => (Vec4f) d); + unsafe + { + fixed (Vec4f* pData = dataV) + { + NativeMethods.core_Mat_nSetVec4f(ptr, row, col, pData, dataV.Length); + GC.KeepAlive(this); + } + } + } + + #endregion + + #region Reserve + + /// + /// reserves enough space to fit sz hyper-planes + /// + /// + public void Reserve(long sz) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_reserve(ptr, new IntPtr(sz)); + GC.KeepAlive(this); + } + + #endregion + + #region Resize + + /// + /// resizes matrix to the specified number of hyper-planes + /// + /// + public void Resize(long sz) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_resize1(ptr, new IntPtr(sz)); + GC.KeepAlive(this); + } + + /// + /// resizes matrix to the specified number of hyper-planes; initializes the newly added elements + /// + /// + /// + public void Resize(long sz, Scalar s) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_resize2(ptr, new IntPtr(sz), s); + GC.KeepAlive(this); + } + + #endregion + + #region PushBack + + /// + /// Adds elements to the bottom of the matrix. (Mat.push_back) + /// + /// Added line(s) + public void Add(Mat m) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(); + m.ThrowIfDisposed(); + NativeMethods.core_Mat_push_back_Mat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// Adds elements to the bottom of the matrix. (Mat.push_back) + /// + /// Added line(s) + public void PushBack(Mat m) + { + Add(m); + } + + #endregion + + #region PopBack + + /// + /// removes several hyper-planes from bottom of the matrix (Mat.pop_back) + /// + /// + public void PopBack(long nElems = 1) + { + ThrowIfDisposed(); + NativeMethods.core_Mat_pop_back(ptr, new IntPtr(nElems)); + GC.KeepAlive(this); + } + + #endregion + + #region To* + + /// + /// Encodes an image into a memory buffer. + /// + /// Encodes an image into a memory buffer. + /// Format-specific parameters. + /// + public byte[] ToBytes(string ext = ".png", int[]? prms = null) + { + return ImEncode(ext, prms); + } + + /// + /// Encodes an image into a memory buffer. + /// + /// Encodes an image into a memory buffer. + /// Format-specific parameters. + /// + public byte[] ToBytes(string ext = ".png", params ImageEncodingParam[] prms) + { + return ImEncode(ext, prms); + } + + /// + /// Converts Mat to System.IO.MemoryStream + /// + /// + /// + /// + public MemoryStream ToMemoryStream(string ext = ".png", params ImageEncodingParam[] prms) + { + return new MemoryStream(ToBytes(ext, prms)); + } + + /// + /// Writes image data encoded from this Mat to System.IO.Stream + /// + /// + /// + /// + /// + public void WriteToStream(Stream stream, string ext = ".png", params ImageEncodingParam[] prms) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + var imageBytes = ToBytes(ext, prms); + stream.Write(imageBytes, 0, imageBytes.Length); + } + + #endregion + + #region DrawMarker + +#pragma warning disable 1591 + + public void DrawMarker( + int x, int y, Scalar color, + MarkerStyle style = MarkerStyle.Cross, + int size = 10, + LineTypes lineType = LineTypes.Link8, + int thickness = 1) + { + var r = size / 2; + + switch (style) + { + case MarkerStyle.CircleLine: + Circle(x, y, r, color, thickness, lineType); + break; + case MarkerStyle.CircleFilled: + Circle(x, y, r, color, -1, lineType); + break; + case MarkerStyle.Cross: + Line(x, y - r, x, y + r, color, thickness, lineType); + Line(x - r, y, x + r, y, color, thickness, lineType); + break; + case MarkerStyle.TiltedCross: + Line(x - r, y - r, x + r, y + r, color, thickness, lineType); + Line(x + r, y - r, x - r, y + r, color, thickness, lineType); + break; + case MarkerStyle.CircleAndCross: + Circle(x, y, r, color, thickness, lineType); + Line(x, y - r, x, y + r, color, thickness, lineType); + Line(x - r, y, x + r, y, color, thickness, lineType); + break; + case MarkerStyle.CircleAndTiltedCross: + Circle(x, y, r, color, thickness, lineType); + Line(x - r, y - r, x + r, y + r, color, thickness, lineType); + Line(x + r, y - r, x - r, y + r, color, thickness, lineType); + break; + case MarkerStyle.DiamondLine: + case MarkerStyle.DiamondFilled: + { + var r2 = (int) (size * Math.Sqrt(2) / 2.0); + Point[] pts = + { + new Point(x, y - r2), + new Point(x + r2, y), + new Point(x, y + r2), + new Point(x - r2, y) + }; + switch (style) + { + case MarkerStyle.DiamondLine: + Polylines(new[] {pts}, true, color, thickness, lineType); + break; + case MarkerStyle.DiamondFilled: + FillConvexPoly(pts, color, lineType); + break; + } + + } + break; + case MarkerStyle.SquareLine: + case MarkerStyle.SquareFilled: + { + Point[] pts = + { + new Point(x - r, y - r), + new Point(x + r, y - r), + new Point(x + r, y + r), + new Point(x - r, y + r) + }; + switch (style) + { + case MarkerStyle.SquareLine: + Polylines(new[] {pts}, true, color, thickness, lineType); + break; + case MarkerStyle.SquareFilled: + FillConvexPoly(pts, color, lineType); + break; + } + } + break; + default: + throw new NotImplementedException(); + } + } +#pragma warning restore 1591 + + #endregion + + /// + /// + /// + /// + /// + public Mat Alignment(int n = 4) + { + var newCols = Cv2.AlignSize(Cols, n); + var pMat = new Mat(Rows, newCols, Type()); + var roiMat = new Mat(pMat, new Rect(0, 0, Cols, Rows)); + CopyTo(roiMat); + return roiMat; + } + + /// + /// Creates type-specific Mat instance from this. + /// + /// + /// + public TMat Cast() + where TMat : Mat + { + var type = typeof(TMat); + + var obj = Activator.CreateInstance(type, this); + if (obj is TMat mat) + return mat; + + throw new NotSupportedException($"Failed to convert Mat to {typeof(TMat).Name}"); + } + + #region ForEach + +// ReSharper disable InconsistentNaming + + /// + /// + /// + /// + public void ForEachAsByte(MatForeachFunctionByte operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_uchar(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec2b(MatForeachFunctionVec2b operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec2b(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec3b(MatForeachFunctionVec3b operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec3b(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec4b(MatForeachFunctionVec4b operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec4b(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec6b(MatForeachFunctionVec6b operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec6b(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsInt16(MatForeachFunctionInt16 operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_short(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec2s(MatForeachFunctionVec2s operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec2s(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec3s(MatForeachFunctionVec3s operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec3s(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec4s(MatForeachFunctionVec4s operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec4s(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec6s(MatForeachFunctionVec6s operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec6s(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsInt32(MatForeachFunctionInt32 operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_int(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec2i(MatForeachFunctionVec2i operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec2i(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec3i(MatForeachFunctionVec3i operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec3i(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec4i(MatForeachFunctionVec4i operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec4i(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec6i(MatForeachFunctionVec6i operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec6i(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsFloat(MatForeachFunctionFloat operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_float(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec2f(MatForeachFunctionVec2f operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec2f(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec3f(MatForeachFunctionVec3f operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec3f(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec4f(MatForeachFunctionVec4f operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec4f(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec6f(MatForeachFunctionVec6f operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec6f(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + + /// + /// + /// + /// + public void ForEachAsDouble(MatForeachFunctionDouble operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_double(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec2d(MatForeachFunctionVec2d operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec2d(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec3d(MatForeachFunctionVec3d operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec3d(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec4d(MatForeachFunctionVec4d operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec4d(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + + /// + /// + /// + /// + public void ForEachAsVec6d(MatForeachFunctionVec6d operation) + { + ThrowIfDisposed(); + if (operation == null) + throw new ArgumentNullException(nameof(operation)); + + NativeMethods.core_Mat_forEach_Vec6d(ptr, operation); + GC.KeepAlive(this); + GC.KeepAlive(operation); + } + +// ReSharper restore InconsistentNaming + + #endregion + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Mat/MatIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/Mat/MatIndexer.cs new file mode 100644 index 0000000..efcc6a9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Mat/MatIndexer.cs @@ -0,0 +1,66 @@ +namespace OpenCvSharp +{ + /// + /// Abstract definition of Mat indexer + /// + /// + public abstract class MatIndexer where T : struct + { + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public abstract T this[int i0] { get; set; } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public abstract T this[int i0, int i1] { get; set; } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public abstract T this[int i0, int i1, int i2] { get; set; } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public abstract T this[params int[] idx] { get; set; } + + /// + /// Parent matrix object + /// + protected readonly Mat Parent; + + /// + /// Step byte length for each dimension + /// + protected readonly long[] Steps; + + /// + /// Constructor + /// + /// + internal MatIndexer(Mat parent) + { + Parent = parent; + + var dims = parent.Dims(); + Steps = new long[dims]; + for (var i = 0; i < dims; i++) + { + Steps[i] = parent.Step(i); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Mat/MatOfT.cs b/OpenVinoOpenCvSharp/Modules/core/Mat/MatOfT.cs new file mode 100644 index 0000000..370a824 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Mat/MatOfT.cs @@ -0,0 +1,1010 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; + +namespace OpenCvSharp +{ + /// + /// Type-specific abstract matrix + /// + /// Element Type + public class Mat : Mat, ICollection + where TElem : unmanaged + { + #region FromArray +#if LANG_JP + /// + /// N x 1 の行列(ベクトル)として初期化し、指定した配列からデータをコピーする + /// + /// この行列にコピーされるデータ +#else + /// + /// Initializes as N x 1 matrix and copies array data to this + /// + /// Source array data to be copied to this +#endif + public static Mat FromArray(params TElem[] arr) + { + if (arr == null) + throw new ArgumentNullException(nameof(arr)); + if (arr.Length == 0) + throw new ArgumentException("arr.Length == 0"); + + var numElems = arr.Length/* / ThisChannels*/; + var mat = new Mat(numElems, 1); + + var methodInfo = typeof(Mat).GetMethod( + "SetArray", + BindingFlags.Public | BindingFlags.Instance, + null, + new[] { typeof(int), typeof(int), arr.GetType() }, + null); + if (methodInfo == null) + throw new NotSupportedException($"Invalid Mat type {typeof(TElem)}"); + methodInfo.Invoke(mat, new object[] { 0, 0, arr }); + + return mat; + } + +#if LANG_JP + /// + /// M x N の行列として初期化し、指定した配列からデータをコピーする + /// + /// この行列にコピーされるデータ +#else + /// + /// Initializes as M x N matrix and copies array data to this + /// + /// Source array data to be copied to this +#endif + public static Mat FromArray(TElem[,] arr) + { + if (arr == null) + throw new ArgumentNullException(nameof(arr)); + if (arr.Length == 0) + throw new ArgumentException("arr.Length == 0"); + + var rows = arr.GetLength(0); + var cols = arr.GetLength(1); + var mat = new Mat(rows, cols); + //mat.SetArray(0, 0, arr); + + var methodInfo = typeof(Mat).GetMethod( + "SetArray", + BindingFlags.Public | BindingFlags.Instance, + null, + new[] { typeof(int), typeof(int), arr.GetType() }, + null); + if (methodInfo == null) + throw new NotSupportedException($"Invalid Mat type {typeof(TElem)}"); + methodInfo.Invoke(mat, new object[] { 0, 0, arr }); + + return mat; + } + +#if LANG_JP + /// + /// N x 1 の行列(ベクトル)として初期化し、指定した配列からデータをコピーする + /// + /// この行列にコピーされるデータ +#else + /// + /// Initializes as N x 1 matrix and copies array data to this + /// + /// Source array data to be copied to this +#endif + public static Mat FromArray(IEnumerable enumerable) + { + return FromArray(Util.EnumerableEx.ToArray(enumerable)); + } + + #endregion + + #region Init & Disposal + + private static MatType GetMatType() + { + var type = typeof(TElem); + if (TypeMap.TryGetValue(type, out var value)) + return value; + throw new NotSupportedException($"Type parameter {type} is not supported by Mat"); + } + +#if LANG_JP + /// + /// Creates empty Mat + /// +#else + /// + /// Creates empty Mat + /// +#endif + public Mat() + { + } + +#if LANG_JP + /// + /// OpenCVネイティブの cv::Mat* ポインタから初期化 + /// + /// +#else + /// + /// Creates from native cv::Mat* pointer + /// + /// +#endif + public Mat(IntPtr ptr) + : base(ptr) + { + } + +#if LANG_JP + /// + /// Matオブジェクトから初期化 + /// + /// Matオブジェクト +#else + /// + /// Initializes by Mat object + /// + /// Managed Mat object +#endif + public Mat(Mat mat) + : base(mat) + { + } + +#if LANG_JP + /// + /// 指定したサイズ・型の2次元の行列として初期化 + /// + /// 2次元配列における行数. + /// 2次元配列における列数. +#else + /// + /// constructs 2D matrix of the specified size and type + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. +#endif + public Mat(int rows, int cols) + : base(rows, cols, GetMatType()) + { + } + +#if LANG_JP + /// + /// 指定したサイズ・型の2次元の行列として初期化 + /// + /// 2次元配列のサイズ: Size(cols, rows) . Size コンストラクタでは,行数と列数が逆順になっていることに注意してください. +#else + /// + /// constructs 2D matrix of the specified size and type + /// + /// 2D array size: Size(cols, rows) . In the Size() constructor, + /// the number of rows and the number of columns go in the reverse order. +#endif + public Mat(Size size) + : base(size, GetMatType()) + { + } + +#if LANG_JP + /// + /// 指定したサイズ・型の2次元の行列で、要素をスカラー値で埋めて初期化 + /// + /// 2次元配列における行数. + /// 2次元配列における列数. + /// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, + /// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs 2D matrix and fills it with the specified Scalar value. + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(int rows, int cols, Scalar s) + : base(rows, cols, GetMatType(), s) + { + } + +#if LANG_JP + /// + /// 指定したサイズ・型の2次元の行列で、要素をスカラー値で埋めて初期化 + /// + /// 2 次元配列のサイズ: Size(cols, rows) . Size() コンストラクタでは,行数と列数が逆順になっていることに注意してください. + /// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, + /// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs 2D matrix and fills it with the specified Scalar value. + /// + /// 2D array size: Size(cols, rows) . In the Size() constructor, + /// the number of rows and the number of columns go in the reverse order. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(Size size, Scalar s) + : base(size, GetMatType(), s) + { + } + + +#if LANG_JP + /// + /// 他の行列の部分行列として初期化 + /// + /// 作成された行列に(全体的,部分的に)割り当てられる配列. + /// これらのコンストラクタによってデータがコピーされる事はありません. + /// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, + /// 関連した参照カウンタがあれば,それがインクリメントされます. + /// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も + /// 変更することになります.もし部分配列の独立したコピーが必要ならば, + /// Mat.Clone() を利用してください. + /// 扱われる 行列の行の範囲.すべての行を扱う場合は,Range.All を利用してください. + /// 扱われる 行列の列の範囲.すべての列を扱う場合は,Range.All を利用してください. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat::clone() . + /// Range of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. + /// Use Range.All to take all the rows. + /// Range of the m columns to take. Use Range.All to take all the columns. +#endif + public Mat(Mat m, Range rowRange, Range? colRange = null) + : base(m, rowRange, colRange) + { + } + +#if LANG_JP + /// + /// 他の行列の部分行列として初期化 + /// + /// 作成された行列に(全体的,部分的に)割り当てられる配列. + /// これらのコンストラクタによってデータがコピーされる事はありません. + /// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, + /// 関連した参照カウンタがあれば,それがインクリメントされます. + /// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も + /// 変更することになります.もし部分配列の独立したコピーが必要ならば, + /// Mat.Clone() を利用してください. + /// 多次元行列の各次元毎の選択範囲を表す配列. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat.Clone() . + /// Array of selected ranges of m along each dimensionality. +#endif + protected Mat(Mat m, params Range[] ranges) + : base(m, ranges) + { + } + +#if LANG_JP + /// + /// 他の行列の部分行列として初期化 + /// + /// 作成された行列に(全体的,部分的に)割り当てられる配列. + /// これらのコンストラクタによってデータがコピーされる事はありません. + /// 代わりに,データ m ,またはその部分配列を指し示すヘッダが作成され, + /// 関連した参照カウンタがあれば,それがインクリメントされます. + /// つまり,新しく作成された配列の内容を変更することで, m の対応する要素も + /// 変更することになります.もし部分配列の独立したコピーが必要ならば, + /// Mat.Clone() を利用してください. + /// 元の行列からくりぬかれる範囲. ROI[Region of interest]. +#else + /// + /// creates a matrix header for a part of the bigger matrix + /// + /// Array that (as a whole or partly) is assigned to the constructed matrix. + /// No data is copied by these constructors. Instead, the header pointing to m data or its sub-array + /// is constructed and associated with it. The reference counter, if any, is incremented. + /// So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . + /// If you want to have an independent copy of the sub-array, use Mat.Clone() . + /// Region of interest. +#endif + public Mat(Mat m, Rect roi) + : base(m, roi) + { + } + +#if LANG_JP + /// + /// 利用者が別に確保したデータで初期化 + /// + /// 2次元配列における行数. + /// 2次元配列における列数. + /// ユーザデータへのポインタ. data と step パラメータを引数にとる + /// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す + /// 行列ヘッダを初期化します.つまり,データのコピーは行われません. + /// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. + /// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. + /// 行列の各行が占めるバイト数を指定できます. + /// この値は,各行の終端にパディングバイトが存在すれば,それも含みます. + /// このパラメータが指定されない場合,パディングは存在しないとみなされ, + /// 実際の step は cols*elemSize() として計算されます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. + /// If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() . +#endif + protected Mat(int rows, int cols, IntPtr data, long step = 0) + : base(rows, cols, GetMatType(), data, step) + { + } + +#if LANG_JP + /// + /// 利用者が別に確保したデータで初期化 + /// + /// 2次元配列における行数. + /// 2次元配列における列数. + /// ユーザデータへのポインタ. data と step パラメータを引数にとる + /// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す + /// 行列ヘッダを初期化します.つまり,データのコピーは行われません. + /// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. + /// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. + /// 行列の各行が占めるバイト数を指定できます. + /// この値は,各行の終端にパディングバイトが存在すれば,それも含みます. + /// このパラメータが指定されない場合,パディングは存在しないとみなされ, + /// 実際の step は cols*elemSize() として計算されます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Number of rows in a 2D array. + /// Number of columns in a 2D array. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. + /// If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() . +#endif + public Mat(int rows, int cols, Array data, long step = 0) + : base(rows, cols, GetMatType(), data, step) + { + } + +#if LANG_JP + /// + /// 利用者が別に確保したデータで初期化 + /// + /// Array of integers specifying an n-dimensional array shape. + /// ユーザデータへのポインタ. data と step パラメータを引数にとる + /// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す + /// 行列ヘッダを初期化します.つまり,データのコピーは行われません. + /// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. + /// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. + /// 多次元配列における ndims-1 個のステップを表す配列 + /// (最後のステップは常に要素サイズになります).これが指定されないと, + /// 行列は連続したものとみなされます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Array of integers specifying an n-dimensional array shape. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). + /// If not specified, the matrix is assumed to be continuous. +#endif + public Mat(IEnumerable sizes, IntPtr data, IEnumerable? steps = null) + : base(sizes, GetMatType(), data, steps) + { + } + +#if LANG_JP + /// + /// 利用者が別に確保したデータで初期化 + /// + /// n-次元配列の形状を表す,整数型の配列. + /// ユーザデータへのポインタ. data と step パラメータを引数にとる + /// 行列コンストラクタは,行列データ領域を確保しません.代わりに,指定のデータを指し示す + /// 行列ヘッダを初期化します.つまり,データのコピーは行われません. + /// この処理は,非常に効率的で,OpenCV の関数を利用して外部データを処理することができます. + /// 外部データが自動的に解放されることはありませんので,ユーザが解放する必要があります. + /// 多次元配列における ndims-1 個のステップを表す配列 + /// (最後のステップは常に要素サイズになります).これが指定されないと, + /// 行列は連続したものとみなされます. +#else + /// + /// constructor for matrix headers pointing to user-allocated data + /// + /// Array of integers specifying an n-dimensional array shape. + /// Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. + /// Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. + /// This operation is very efficient and can be used to process external data using OpenCV functions. + /// The external data is not automatically de-allocated, so you should take care of it. + /// Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). + /// If not specified, the matrix is assumed to be continuous. +#endif + public Mat(IEnumerable sizes, Array data, IEnumerable? steps = null) + : base(sizes, GetMatType(), data, steps) + { + } + +#if LANG_JP + /// + /// N次元行列として初期化 + /// + /// n-次元配列の形状を表す,整数型の配列. +#else + /// + /// constructs n-dimensional matrix + /// + /// Array of integers specifying an n-dimensional array shape. +#endif + public Mat(IEnumerable sizes) + : base(sizes, GetMatType()) + { + } + +#if LANG_JP + /// + /// N次元行列として初期化 + /// + /// n-次元配列の形状を表す,整数型の配列. + /// 各行列要素を初期化するオプション値.初期化の後ですべての行列要素を特定の値にセットするには, + /// コンストラクタの後で,SetTo(Scalar value) メソッドを利用してください. +#else + /// + /// constructs n-dimensional matrix + /// + /// Array of integers specifying an n-dimensional array shape. + /// An optional value to initialize each matrix element with. + /// To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method . +#endif + public Mat(IEnumerable sizes, Scalar s) + : base(sizes, GetMatType(), s) + { + } + + #endregion + + #region Indexer + + /// + /// Matrix indexer + /// + public sealed unsafe class Indexer : MatIndexer + { + private readonly byte* ptr; + + internal Indexer(Mat parent) + : base(parent) + { + ptr = (byte*)parent.Data.ToPointer(); + } + + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// A value to the specified array element. + public override TElem this[int i0] + { + get => *(TElem*)(ptr + (Steps[0] * i0)); + set => *(TElem*)(ptr + (Steps[0] * i0)) = value; + } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// A value to the specified array element. + public override TElem this[int i0, int i1] + { + get => *(TElem*)(ptr + (Steps[0] * i0) + (Steps[1] * i1)); + set => *(TElem*)(ptr + (Steps[0] * i0) + (Steps[1] * i1)) = value; + } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// A value to the specified array element. + public override TElem this[int i0, int i1, int i2] + { + get => *(TElem*)(ptr + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)); + set => *(TElem*)(ptr + (Steps[0] * i0) + (Steps[1] * i1) + (Steps[2] * i2)) = value; + } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// A value to the specified array element. + public override TElem this[params int[] idx] + { + get + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + return *(TElem*)(ptr + offset); + } + set + { + long offset = 0; + for (var i = 0; i < idx.Length; i++) + { + offset += Steps[i] * idx[i]; + } + *(TElem*)(ptr + offset) = value; + } + } + } + + #endregion + + #region Methods + + /// + /// Gets a type-specific indexer. The indexer has getters/setters to access each matrix element. + /// + /// + public MatIndexer GetIndexer() + { + return new Indexer(this); + } + + /// + /// Gets read-only enumerator + /// + /// + public IEnumerator GetEnumerator() + { + ThrowIfDisposed(); + var indexer = new Indexer(this); + + var dims = Dims(); + if (dims == 2) + { + var rows = Rows; + var cols = Cols; + for (var r = 0; r < rows; r++) + { + for (var c = 0; c < cols; c++) + { + yield return indexer[r, c]; + } + } + } + else + { + throw new NotImplementedException("GetEnumerator supports only 2-dimensional Mat"); + } + } + + /// + /// For non-generic IEnumerable + /// + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Convert this mat to managed array + /// + /// + public TElem[] ToArray() + { + var numOfElems = Total(); + if (numOfElems == 0) + return new TElem[0]; + var arr = new TElem[numOfElems]; + //GetArray(0, 0, arr); + + var methodInfo = typeof(Mat).GetMethod( + "GetArray", + BindingFlags.Public | BindingFlags.Instance, + null, + new[] {typeof(int), typeof(int), arr.GetType()}, + null); + if (methodInfo == null) + throw new NotSupportedException($"Invalid Mat type {typeof(TElem)}"); + methodInfo.Invoke(this, new object[] { 0, 0, arr }); + + return arr; + } + + /// + /// Convert this mat to managed rectangular array + /// + /// + public TElem[,] ToRectangularArray() + { + if (Rows == 0 || Cols == 0) + return new TElem[0, 0]; + var arr = new TElem[Rows, Cols]; + //GetArray(0, 0, arr); + + var methodInfo = typeof(Mat).GetMethod( + "GetArray", + BindingFlags.Public | BindingFlags.Instance, + null, + new[] { typeof(int), typeof(int), arr.GetType() }, + null); + if (methodInfo == null) + throw new NotSupportedException($"Invalid Mat type {typeof(TElem)}"); + methodInfo.Invoke(this, new object[] { 0, 0, arr }); + + return arr; + } + +#endregion + +#region Mat Methods + /// + /// + /// + /// + /// + protected Mat Wrap(Mat mat) + { + var ret = new Mat(); + mat.AssignTo(ret); + return ret; + } + +#region Clone + + /// + /// Creates a full copy of the matrix. + /// + /// + public new Mat Clone() + { + using (var result = base.Clone()) + { + return Wrap(result); + } + } + +#endregion +#region Reshape + + /// + /// Changes the shape of channels of a 2D matrix without copying the data. + /// + /// New number of rows. If the parameter is 0, the number of rows remains the same. + /// + public Mat Reshape(int rows) + { + var result = base.Reshape(0, rows); + return Wrap(result); + } + + /// + /// Changes the shape of a 2D matrix without copying the data. + /// + /// New number of rows. If the parameter is 0, the number of rows remains the same. + /// + public Mat Reshape(params int[] newDims) + { + var result = base.Reshape(0, newDims); + return Wrap(result); + } + +#endregion +#region T + + /// + /// Transposes a matrix. + /// + /// + public new Mat T() + { + using (var result = base.T()) + { + return Wrap(result); + } + } + +#endregion + +#region SubMat + /// + /// Extracts a rectangular submatrix. + /// + /// Start row of the extracted submatrix. The upper boundary is not included. + /// End row of the extracted submatrix. The upper boundary is not included. + /// Start column of the extracted submatrix. The upper boundary is not included. + /// End column of the extracted submatrix. The upper boundary is not included. + /// + public new Mat SubMat(int rowStart, int rowEnd, int colStart, int colEnd) + { + var result = base.SubMat(rowStart, rowEnd, colStart, colEnd); + return Wrap(result); + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Start and end row of the extracted submatrix. The upper boundary is not included. + /// To select all the rows, use Range.All(). + /// Start and end column of the extracted submatrix. + /// The upper boundary is not included. To select all the columns, use Range.All(). + /// + public new Mat SubMat(Range rowRange, Range colRange) + { + return SubMat(rowRange.Start, rowRange.End, colRange.Start, colRange.End); + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Extracted submatrix specified as a rectangle. + /// + public new Mat SubMat(Rect roi) + { + return SubMat(roi.Y, roi.Y + roi.Height, roi.X, roi.X + roi.Width); + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Array of selected ranges along each array dimension. + /// + public new Mat SubMat(params Range[] ranges) + { + var result = base.SubMat(ranges); + return Wrap(result); + } + +#endregion +#region Mat Indexers + /// + /// Extracts a rectangular submatrix. + /// + /// Start row of the extracted submatrix. The upper boundary is not included. + /// End row of the extracted submatrix. The upper boundary is not included. + /// Start column of the extracted submatrix. The upper boundary is not included. + /// End column of the extracted submatrix. The upper boundary is not included. + /// + public new Mat this[int rowStart, int rowEnd, int colStart, int colEnd] + { + get + { + var result = base[rowStart, rowEnd, colStart, colEnd]; + return Wrap(result); + } + set => base[rowStart, rowEnd, colStart, colEnd] = value; + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Start and end row of the extracted submatrix. The upper boundary is not included. + /// To select all the rows, use Range.All(). + /// Start and end column of the extracted submatrix. + /// The upper boundary is not included. To select all the columns, use Range.All(). + /// + public new Mat this[Range rowRange, Range colRange] + { + get + { + var result = base[rowRange, colRange]; + return Wrap(result); + } + set => base[rowRange, colRange] = value; + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Extracted submatrix specified as a rectangle. + /// + public new Mat this[Rect roi] + { + get + { + var result = base[roi]; + return Wrap(result); + } + set => base[roi] = value; + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Array of selected ranges along each array dimension. + /// + public new Mat this[params Range[] ranges] + { + get + { + var result = base[ranges]; + return Wrap(result); + } + set => base[ranges] = value; + } +#endregion + +#endregion + +#region ICollection + + /// + /// Adds elements to the bottom of the matrix. (Mat::push_back) + /// + /// Added element(s) + public void Add(TElem value) + { + ThrowIfDisposed(); + + var methodInfo = typeof(AddFunctions).GetMethod( + "Run", + BindingFlags.Public | BindingFlags.Static, + null, + new[] { typeof(IntPtr), typeof(TElem) }, + null); + if (methodInfo == null) + throw new NotSupportedException($"Invalid argument type {typeof(TElem)}"); + methodInfo.Invoke(this, new object[] { ptr, value }); + + GC.KeepAlive(this); + } + + // ReSharper disable UnusedMember.Local + private static class AddFunctions + { + public static void Run(IntPtr ptr, byte v) => NativeMethods.core_Mat_push_back_uchar(ptr, v); + public static void Run(IntPtr ptr, sbyte v) => NativeMethods.core_Mat_push_back_char(ptr, v); + public static void Run(IntPtr ptr, ushort v) => NativeMethods.core_Mat_push_back_ushort(ptr, v); + public static void Run(IntPtr ptr, short v) => NativeMethods.core_Mat_push_back_short(ptr, v); + public static void Run(IntPtr ptr, int v) => NativeMethods.core_Mat_push_back_int(ptr, v); + public static void Run(IntPtr ptr, float v) => NativeMethods.core_Mat_push_back_float(ptr, v); + public static void Run(IntPtr ptr, double v) => NativeMethods.core_Mat_push_back_double(ptr, v); + public static void Run(IntPtr ptr, Vec2b v) => NativeMethods.core_Mat_push_back_Vec2b(ptr, v); + public static void Run(IntPtr ptr, Vec3b v) => NativeMethods.core_Mat_push_back_Vec3b(ptr, v); + public static void Run(IntPtr ptr, Vec4b v) => NativeMethods.core_Mat_push_back_Vec4b(ptr, v); + public static void Run(IntPtr ptr, Vec6b v) => NativeMethods.core_Mat_push_back_Vec6b(ptr, v); + public static void Run(IntPtr ptr, Vec2w v) => NativeMethods.core_Mat_push_back_Vec2w(ptr, v); + public static void Run(IntPtr ptr, Vec3w v) => NativeMethods.core_Mat_push_back_Vec3w(ptr, v); + public static void Run(IntPtr ptr, Vec4w v) => NativeMethods.core_Mat_push_back_Vec4w(ptr, v); + public static void Run(IntPtr ptr, Vec6w v) => NativeMethods.core_Mat_push_back_Vec6w(ptr, v); + public static void Run(IntPtr ptr, Vec2s v) => NativeMethods.core_Mat_push_back_Vec2s(ptr, v); + public static void Run(IntPtr ptr, Vec3s v) => NativeMethods.core_Mat_push_back_Vec3s(ptr, v); + public static void Run(IntPtr ptr, Vec4s v) => NativeMethods.core_Mat_push_back_Vec4s(ptr, v); + public static void Run(IntPtr ptr, Vec6s v) => NativeMethods.core_Mat_push_back_Vec6s(ptr, v); + public static void Run(IntPtr ptr, Vec2i v) => NativeMethods.core_Mat_push_back_Vec2i(ptr, v); + public static void Run(IntPtr ptr, Vec3i v) => NativeMethods.core_Mat_push_back_Vec3i(ptr, v); + public static void Run(IntPtr ptr, Vec4i v) => NativeMethods.core_Mat_push_back_Vec4i(ptr, v); + public static void Run(IntPtr ptr, Vec6i v) => NativeMethods.core_Mat_push_back_Vec6i(ptr, v); + public static void Run(IntPtr ptr, Vec2f v) => NativeMethods.core_Mat_push_back_Vec2f(ptr, v); + public static void Run(IntPtr ptr, Vec3f v) => NativeMethods.core_Mat_push_back_Vec3f(ptr, v); + public static void Run(IntPtr ptr, Vec4f v) => NativeMethods.core_Mat_push_back_Vec4f(ptr, v); + public static void Run(IntPtr ptr, Vec6f v) => NativeMethods.core_Mat_push_back_Vec6f(ptr, v); + public static void Run(IntPtr ptr, Vec2d v) => NativeMethods.core_Mat_push_back_Vec2d(ptr, v); + public static void Run(IntPtr ptr, Vec3d v) => NativeMethods.core_Mat_push_back_Vec3d(ptr, v); + public static void Run(IntPtr ptr, Vec4d v) => NativeMethods.core_Mat_push_back_Vec4d(ptr, v); + public static void Run(IntPtr ptr, Vec6d v) => NativeMethods.core_Mat_push_back_Vec6d(ptr, v); + public static void Run(IntPtr ptr, Point v) => NativeMethods.core_Mat_push_back_Point(ptr, v); + public static void Run(IntPtr ptr, Point2d v) => NativeMethods.core_Mat_push_back_Point2d(ptr, v); + public static void Run(IntPtr ptr, Point2f v) => NativeMethods.core_Mat_push_back_Point2f(ptr, v); + public static void Run(IntPtr ptr, Point3i v) => NativeMethods.core_Mat_push_back_Point3i(ptr, v); + public static void Run(IntPtr ptr, Point3d v) => NativeMethods.core_Mat_push_back_Point3d(ptr, v); + public static void Run(IntPtr ptr, Point3f v) => NativeMethods.core_Mat_push_back_Point3f(ptr, v); + public static void Run(IntPtr ptr, Size v) => NativeMethods.core_Mat_push_back_Size(ptr, v); + public static void Run(IntPtr ptr, Size2f v) => NativeMethods.core_Mat_push_back_Size2f(ptr, v); + public static void Run(IntPtr ptr, Rect v) => NativeMethods.core_Mat_push_back_Rect(ptr, v); + } + // ReSharper restore UnusedMember.Local + + /// + /// Removes the first occurrence of a specific object from the ICollection<T>. + /// + /// The object to remove from the ICollection<T>. + /// true if item was successfully removed from the ICollection<T> otherwise, false. + /// This method also returns false if item is not found in the original ICollection<T>. + public bool Remove(TElem item) + { + throw new NotImplementedException(); + } + + /// + /// Determines whether the ICollection<T> contains a specific value. + /// + /// The object to locate in the ICollection<T>. + /// true if item is found in the ICollection<T> otherwise, false. + public bool Contains(TElem item) + { + return IndexOf(item) >= 0; + } + + /// + /// Determines the index of a specific item in the list. + /// + /// The object to locate in the list. + /// The index of value if found in the list; otherwise, -1. + public int IndexOf(TElem item) + { + var array = ToArray(); + return Array.IndexOf(array, item); + } + + /// + /// Removes all items from the ICollection<T>. + /// + public void Clear() + { + ThrowIfDisposed(); + NativeMethods.core_Mat_pop_back(ptr, new IntPtr(Total())); + GC.KeepAlive(this); + } + + /// + /// Copies the elements of the ICollection<T> to an Array, starting at a particular Array index. + /// + /// The one-dimensional Array that is the destination of the elements copied from ICollection<T>. + /// The Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(TElem[] array, int arrayIndex) + { + ThrowIfDisposed(); + + if (array == null) + throw new ArgumentNullException(nameof(array)); + var result = ToArray(); + if (array.Length > result.Length + arrayIndex) + throw new ArgumentException("Too short array.Length"); + Array.Copy(result, 0, array, arrayIndex, result.Length); + } + + /// + /// Returns the total number of matrix elements (Mat.total) + /// + /// Total number of list(Mat) elements + public int Count + { + get + { + ThrowIfDisposed(); + var res = (int)NativeMethods.core_Mat_total(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// + public bool IsReadOnly => false; + +#endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs b/OpenVinoOpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs new file mode 100644 index 0000000..25f814a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Mat/Mat_CvMethods.cs @@ -0,0 +1,2591 @@ +using System.Collections.Generic; + +namespace OpenCvSharp +{ + partial class Mat + { + #region core + + /// + /// Computes absolute value of each matrix element + /// + /// + public MatExpr Abs() + { + return Cv2.Abs(this); + } + +#if LANG_JP + /// + /// スケーリング後,絶対値を計算し,結果を結果を 8 ビットに変換します. + /// + /// オプションのスケールファクタ. [既定値は1] + /// スケーリングされた値に加えられるオプション値. [既定値は0] + /// +#else + /// + /// 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] + /// +#endif + 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(InputArray lut, int interpolation = 0) + { + var dst = new Mat(); + Cv2.LUT(this, lut, dst, interpolation); + 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, int interpolation = 0) + { + var dst = new Mat(); + Cv2.LUT(this, lut, dst, interpolation); + 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(InputArray? mask = null) + { + 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(OutputArray mean, OutputArray stddev, InputArray? mask = null) + { + 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, InputArray? mask = null) + { + 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, InputArray? mask = null) + { + 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, InputArray? mask = null) + { + 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, InputArray? mask = null) + { + 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(InputOutputArray 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; + } + + /// + /// set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) + /// + /// The inclusive lower boundary array of the same size and type as src + /// The exclusive upper boundary array of the same size and type as src + /// The destination array, will have the same size as src and CV_8U type + public Mat InRange(InputArray lowerb, InputArray upperb) + { + var dst = new Mat(); + Cv2.InRange(this, lowerb, upperb, dst); + return dst; + } + + /// + /// set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) + /// + /// The inclusive lower boundary array of the same size and type as src + /// The exclusive upper boundary array of the same size and type as src + /// 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, InputArray? delta = null, 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(InputArray 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(InputArray 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(InputArray low, InputArray 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(InputArray mean, InputArray 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 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, RNG? rng = null) + { + Cv2.RandShuffle(this, iterFactor, rng); + } + + #region Drawing + + #region Line + +#if LANG_JP + /// + /// 2点を結ぶ線分を画像上に描画する. + /// + /// 線分の1番目の端点x + /// 線分の1番目の端点y + /// 線分の2番目の端点x + /// 線分の2番目の端点y + /// 線分の色 + /// 線分の太さ. [既定値は1] + /// 線分の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 2点を結ぶ線分を画像上に描画する. + /// + /// 線分の1番目の端点 + /// 線分の2番目の端点 + /// 線分の色 + /// 線分の太さ. [既定値は1] + /// 線分の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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 + +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 矩形の一つの頂点 + /// 矩形の反対側の頂点 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 枠のみ,もしくは塗りつぶされた矩形を描画する + /// + /// 矩形 + /// 線の色(RGB),もしくは輝度(グレースケール画像). + /// 矩形を描く線の太さ.負の値を指定した場合は塗りつぶされる. [既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 座標の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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 + +#if LANG_JP + /// + /// 円を描画する + /// + /// 円の中心のx座標 + /// 円の中心のy座標 + /// 円の半径 + /// 円の色 + /// 線の幅.負の値を指定した場合は塗りつぶされる.[既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 中心座標と半径の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 円を描画する + /// + /// 円の中心 + /// 円の半径 + /// 円の色 + /// 線の幅.負の値を指定した場合は塗りつぶされる.[既定値は1] + /// 線の種類. [既定値はLineType.Link8] + /// 中心座標と半径の小数点以下の桁を表すビット数. [既定値は0] +#else + /// + /// 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] +#endif + 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 + +#if LANG_JP + /// + /// 枠だけの楕円,楕円弧,もしくは塗りつぶされた扇形の楕円を描画する + /// + /// 楕円の中心 + /// 楕円の軸の長さ + /// 回転角度 + /// 楕円弧の開始角度 + /// 楕円弧の終了角度 + /// 楕円の色 + /// 楕円弧の線の幅 [既定値は1] + /// 楕円弧の線の種類 [既定値はLineType.Link8] + /// 中心座標と軸の長さの小数点以下の桁を表すビット数 [既定値は0] +#else + /// + /// 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] +#endif + 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); + } + +#if LANG_JP + /// + /// 枠だけの楕円,もしくは塗りつぶされた楕円を描画する + /// + /// 描画したい楕円を囲む矩形領域. + /// 楕円の色. + /// 楕円境界線の幅.[既定値は1] + /// 楕円境界線の種類.[既定値はLineType.Link8] +#else + /// + /// 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] +#endif + public void Ellipse(RotatedRect box, Scalar color, + int thickness = 1, LineTypes lineType = LineTypes.Link8) + { + Cv2.Ellipse(this, box, color, thickness, lineType); + } + + #endregion + + #region FillConvexPoly + +#if LANG_JP + /// + /// 塗りつぶされた凸ポリゴンを描きます. + /// + /// ポリゴンの頂点. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. +#else + /// + /// Fills a convex polygon. + /// + /// The polygon vertices + /// Polygon color + /// Type of the polygon boundaries + /// The number of fractional bits in the vertex coordinates +#endif + public void FillConvexPoly(IEnumerable pts, Scalar color, + LineTypes lineType = LineTypes.Link8, int shift = 0) + { + Cv2.FillConvexPoly(this, pts, color, lineType, shift); + } + + #endregion + + #region FillPoly + +#if LANG_JP + /// + /// 1つ,または複数のポリゴンで区切られた領域を塗りつぶします. + /// + /// ポリゴンの配列.各要素は,点の配列で表現されます. + /// ポリゴンの色. + /// ポリゴンの枠線の種類, + /// ポリゴンの頂点座標において,小数点以下の桁を表すビット数. + /// +#else + /// + /// 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 + /// +#endif + 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) + { + 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) + { + 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; + } + +#if LANG_JP + /// + /// Cannyアルゴリズムを用いて,画像のエッジを検出します. + /// + /// ヒステリシスが存在する処理の,1番目の閾値 + /// ヒステリシスが存在する処理の,2番目の閾値 + /// Sobelオペレータのアパーチャサイズ [既定値はApertureSize.Size3] + /// 画像勾配の強度を求めるために,より精度の高い L2ノルムを利用するか,L1ノルムで十分(false)かを指定します. [既定値はfalse] + /// 出力されるエッジのマップ. image と同じサイズ,同じ型 +#else + /// + /// 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 +#endif + // 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); + } + +#if LANG_JP + /// + /// 標準ハフ変換を用いて,2値画像から直線を検出します. + /// + /// ピクセル単位で表される投票空間の距離分解能 + /// ラジアン単位で表される投票空間の角度分解能 + /// 投票の閾値パラメータ.十分な票( > threshold )を得た直線のみが出力されます + /// マルチスケールハフ変換において,距離分解能 rho の除数となる値.[既定値は0] + /// マルチスケールハフ変換において,角度分解能 theta の除数となる値. [既定値は0] + /// 検出された直線.各直線は,2要素のベクトル (rho, theta) で表現されます. + /// rho は原点(画像の左上コーナー)からの距離, theta はラジアン単位で表される直線の回転角度です +#else + /// + /// 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 +#endif + public LineSegmentPolar[] HoughLines(double rho, double theta, int threshold, + double srn = 0, double stn = 0) + { + return Cv2.HoughLines(this, rho, theta, threshold, srn, stn); + } + +#if LANG_JP + /// + /// 確率的ハフ変換を利用して,2値画像から線分を検出します. + /// + /// ピクセル単位で表される投票空間の距離分解能 + /// ラジアン単位で表される投票空間の角度分解能 + /// 投票の閾値パラメータ.十分な票( > threshold )を得た直線のみが出力されます + /// 最小の線分長.これより短い線分は棄却されます. [既定値は0] + /// 2点が同一線分上にあると見なす場合に許容される最大距離. [既定値は0] + /// 検出された線分.各線分は,4要素のベクトル (x1, y1, x2, y2) で表現されます. +#else + /// + /// 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) +#endif + public LineSegmentPoint[] HoughLinesP(double rho, double theta, int threshold, + double minLineLength = 0, double maxLineGap = 0) + { + return Cv2.HoughLinesP(this, rho, theta, threshold, minLineLength, maxLineGap); + } + +#if LANG_JP + /// + /// ハフ変換を用いて,グレースケール画像から円を検出します. + /// + /// 現在のところ,HoughCirclesMethod.Gradient メソッドのみが実装されている. + /// 画像分解能に対する投票分解能の比率の逆数. + /// 検出される円の中心同士の最小距離. + /// 手法依存の1番目のパラメータ.[既定値は100] + /// 手法依存の2番目のパラメータ.[既定値は100] + /// 円の半径の最小値 [既定値は0] + /// 円の半径の最大値 [既定値は0] + /// 検出された円.各ベクトルは,3要素の浮動小数点型ベクトル (x, y, radius) としてエンコードされます +#else + /// + /// Finds circles in a grayscale image using a Hough transform. + /// The input matrix must be 8-bit, single-channel and grayscale. + /// + /// Currently, the only implemented method is HoughCirclesMethod.Gradient + /// 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) +#endif + public CircleSegment[] HoughCircles(HoughMethods 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); + } + +#if LANG_JP + /// + /// 指定の構造要素を用いて画像の膨張を行います. + /// + /// 膨張に用いられる構造要素. element=new Mat() の場合, 3x3 の矩形構造要素が用いられます + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します + /// 膨張が行われる回数. [既定値は1] + /// ピクセル外挿手法.[既定値はBorderTypes.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます.[既定値はCvCpp.MorphologyDefaultBorderValue()] + /// src と同じサイズ,同じ型の出力画像 +#else + /// + /// 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 +#endif + 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; + } + +#if LANG_JP + /// + /// 指定の構造要素を用いて画像の収縮を行います. + /// + /// 収縮に用いられる構造要素. element=new Mat() の場合, 3x3 の矩形の構造要素が用いられます + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します + /// 収縮が行われる回数. [既定値は1] + /// ピクセル外挿手法.[既定値はBorderTypes.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます.[既定値はCvCpp.MorphologyDefaultBorderValue()] + /// src と同じサイズ,同じ型の出力画像 +#else + /// + /// 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 +#endif + 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; + } + +#if LANG_JP + /// + /// 高度なモルフォロジー変換を行います. + /// + /// モルフォロジー演算の種類 + /// 構造要素 + /// 構造要素内のアンカー位置.デフォルト値の (-1, -1) は,アンカーが構造要素の中心にあることを意味します. + /// 収縮と膨張が適用される回数. [既定値は1] + /// ピクセル外挿手法. [既定値はBorderTypes.Constant] + /// 定数境界モードで利用されるピクセル値.デフォルト値は特別な意味を持ちます. [既定値は CvCpp.MorphologyDefaultBorderValue()] + /// src と同じサイズ,同じ型の出力画像 +#else + /// + /// 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 +#endif + 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; + } + + /// + /// 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); + } + +#if LANG_JP + /// + /// 画像の色空間を変換します. + /// + /// 色空間の変換コード. + /// 出力画像のチャンネル数.この値が 0 の場合,チャンネル数は src と code から自動的に求められます + /// src と同じサイズ,同じタイプの出力画像 +#else + /// + /// 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 +#endif + 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 + /// 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) + { + var dst = new Mat(); + Cv2.MatchTemplate(this, templ, dst, method); + 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); + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// 入力画像は,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像の中身を書き換えます. + /// + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. + /// 画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して, + /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の + /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合, + /// それに対応する hierarchy[i] の要素は,負の値になります. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. +#else + /// + /// 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. +#endif + 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); + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// 入力画像は,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像の中身を書き換えます. + /// + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. + /// 画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して, + /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の + /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合, + /// それに対応する hierarchy[i] の要素は,負の値になります. + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. +#else + /// + /// 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. +#endif + public void FindContours(out Mat[] contours, OutputArray hierarchy, + RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + Cv2.FindContours(this, out contours, hierarchy, mode, method, offset); + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// 入力画像は,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像の中身を書き換えます. + /// + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. +#else + /// + /// 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. +#endif + public Point[][] FindContoursAsArray(RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + return Cv2.FindContoursAsArray(this, mode, method, offset); + } + +#if LANG_JP + /// + /// 2値画像中の輪郭を検出します. + /// 入力画像は,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます. + /// また,この関数は,輪郭抽出処理中に入力画像の中身を書き換えます. + /// + /// 輪郭抽出モード + /// 輪郭の近似手法 + /// オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます. + /// 検出された輪郭.各輪郭は,点のベクトルとして格納されます. +#else + /// + /// 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. +#endif + public Mat[] FindContoursAsMat(RetrievalModes mode, ContourApproximationModes method, Point? offset = null) + { + return Cv2.FindContoursAsMat(this, mode, method, offset); + } + +#if LANG_JP + /// + /// 輪郭線,または内側が塗りつぶされた輪郭を描きます. + /// + /// 入力される全輪郭.各輪郭は,点のベクトルとして格納されています. + /// 描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます. + /// 輪郭の色. + /// 輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます. + /// 線の連結性 + /// 階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります. + /// 描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます. + /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と, + /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, + /// hierarchy が有効な場合のみ考慮されます. + /// 輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます. +#else + /// + /// 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) +#endif + 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); + } + +#if LANG_JP + /// + /// 輪郭線,または内側が塗りつぶされた輪郭を描きます. + /// + /// 出力画像 + /// 入力される全輪郭.各輪郭は,点のベクトルとして格納されています. + /// 描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます. + /// 輪郭の色. + /// 輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます. + /// 線の連結性 + /// 階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります. + /// 描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます. + /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と, + /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, + /// hierarchy が有効な場合のみ考慮されます. + /// 輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます. +#else + /// + /// Draws contours in the image + /// + /// Destination 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) +#endif + public void DrawContours( + InputOutputArray image, + 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(image, 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. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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(InputArray points, bool clockwise = false, bool returnPoints = true) + { + var dst = new Mat(); + Cv2.ConvexHull(points, dst, clockwise, returnPoints); + return dst; + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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(InputArray points, bool clockwise = false) + { + var dst = new Mat(); + Cv2.ConvexHull(points, dst, clockwise); + return dst.ToArray(); + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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(InputArray points, bool clockwise = false) + { + var dst = new Mat(); + Cv2.ConvexHull(points, dst, clockwise); + return dst.ToArray(); + } + + /// + /// Computes convex hull for a set of 2D points. + /// + /// The input 2D point set, represented by CV_32SC2 or CV_32FC2 matrix + /// 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(InputArray points, bool clockwise = false) + { + var dst = new Mat(); + Cv2.ConvexHull(points, 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, DistanceMaskSize maskSize) + { + var dst = new Mat(); + Cv2.DistanceTransform(this, dst, distanceType, maskSize); + return dst; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatExpr.cs b/OpenVinoOpenCvSharp/Modules/core/MatExpr.cs new file mode 100644 index 0000000..0d521c0 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatExpr.cs @@ -0,0 +1,1051 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// Matrix expression + /// + public sealed partial class MatExpr : DisposableCvObject + { + #region Init & Disposal + + /// + /// + /// + /// + internal MatExpr(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + internal MatExpr(Mat mat) + { + if(mat == null) + throw new ArgumentNullException(nameof(mat)); + ptr = NativeMethods.core_MatExpr_new2(mat.CvPtr); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_MatExpr_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Cast + + /// + /// + /// + /// + /// + public static implicit operator Mat(MatExpr self) + { + try + { + var retPtr = NativeMethods.core_MatExpr_toMat(self.ptr); + GC.KeepAlive(self); + var retVal = new Mat(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + + /// + /// + /// + /// + public Mat ToMat() + { + return this; + } + + /// + /// + /// + /// + /// + public static implicit operator MatExpr(Mat mat) + { + return new MatExpr(mat); + } + + /// + /// + /// + /// + /// + public static MatExpr FromMat(Mat mat) + { + return new MatExpr(mat); + } + + #endregion + + #region Operators + #region Unary + /// + /// + /// + /// + /// + public static MatExpr operator +(MatExpr e) + { + return e; + } + + /// + /// + /// + /// + /// + public static MatExpr operator -(MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorUnaryMinus_MatExpr(e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + + /// + /// + /// + /// + /// + public static MatExpr operator ~(MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorUnaryNot_MatExpr(e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region + + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(MatExpr e, Mat m) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + e.ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorAdd_MatExprMat(e.CvPtr, m.CvPtr); + GC.KeepAlive(e); + GC.KeepAlive(m); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(Mat m, MatExpr e) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + if (e == null) + throw new ArgumentNullException(nameof(e)); + m.ThrowIfDisposed(); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorAdd_MatMatExpr(m.CvPtr, e.CvPtr); + GC.KeepAlive(m); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(MatExpr e, Scalar s) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorAdd_MatExprScalar(e.CvPtr, s); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(Scalar s, MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorAdd_ScalarMatExpr(s, e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator +(MatExpr e1, MatExpr e2) + { + if (e1 == null) + throw new ArgumentNullException(nameof(e1)); + if (e2 == null) + throw new ArgumentNullException(nameof(e2)); + e1.ThrowIfDisposed(); + e2.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorAdd_MatExprMatExpr(e1.CvPtr, e2.CvPtr); + GC.KeepAlive(e1); + GC.KeepAlive(e2); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region - + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(MatExpr e, Mat m) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + e.ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorSubtract_MatExprMat(e.CvPtr, m.CvPtr); + GC.KeepAlive(e); + GC.KeepAlive(m); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(Mat m, MatExpr e) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + if (e == null) + throw new ArgumentNullException(nameof(e)); + m.ThrowIfDisposed(); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorSubtract_MatMatExpr(m.CvPtr, e.CvPtr); + GC.KeepAlive(m); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(MatExpr e, Scalar s) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorSubtract_MatExprScalar(e.CvPtr, s); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(Scalar s, MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorSubtract_ScalarMatExpr(s, e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator -(MatExpr e1, MatExpr e2) + { + if (e1 == null) + throw new ArgumentNullException(nameof(e1)); + if (e2 == null) + throw new ArgumentNullException(nameof(e2)); + e1.ThrowIfDisposed(); + e2.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorSubtract_MatExprMatExpr(e1.CvPtr, e2.CvPtr); + GC.KeepAlive(e1); + GC.KeepAlive(e2); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region * + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(MatExpr e, Mat m) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + e.ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorMultiply_MatExprMat(e.CvPtr, m.CvPtr); + GC.KeepAlive(e); + GC.KeepAlive(m); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(Mat m, MatExpr e) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + if (e == null) + throw new ArgumentNullException(nameof(e)); + m.ThrowIfDisposed(); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorMultiply_MatMatExpr(m.CvPtr, e.CvPtr); + GC.KeepAlive(m); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(MatExpr e, double s) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorMultiply_MatExprDouble(e.CvPtr, s); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(double s, MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorMultiply_DoubleMatExpr(s, e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator *(MatExpr e1, MatExpr e2) + { + if (e1 == null) + throw new ArgumentNullException(nameof(e1)); + if (e2 == null) + throw new ArgumentNullException(nameof(e2)); + e1.ThrowIfDisposed(); + e2.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorMultiply_MatExprMatExpr(e1.CvPtr, e2.CvPtr); + GC.KeepAlive(e1); + GC.KeepAlive(e2); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region / + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(MatExpr e, Mat m) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + if (m == null) + throw new ArgumentNullException(nameof(m)); + e.ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorDivide_MatExprMat(e.CvPtr, m.CvPtr); + GC.KeepAlive(e); + GC.KeepAlive(m); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(Mat m, MatExpr e) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + if (e == null) + throw new ArgumentNullException(nameof(e)); + m.ThrowIfDisposed(); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorDivide_MatMatExpr(m.CvPtr, e.CvPtr); + GC.KeepAlive(m); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(MatExpr e, double s) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorDivide_MatExprDouble(e.CvPtr, s); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(double s, MatExpr e) + { + if (e == null) + throw new ArgumentNullException(nameof(e)); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorDivide_DoubleMatExpr(s, e.CvPtr); + GC.KeepAlive(e); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public static MatExpr operator /(MatExpr e1, MatExpr e2) + { + if (e1 == null) + throw new ArgumentNullException(nameof(e1)); + if (e2 == null) + throw new ArgumentNullException(nameof(e2)); + e1.ThrowIfDisposed(); + e2.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_operatorDivide_MatExprMatExpr(e1.CvPtr, e2.CvPtr); + GC.KeepAlive(e1); + GC.KeepAlive(e2); + return new MatExpr(retPtr); + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #endregion + + #region Methods + + #region Indexers + /// + /// + /// + /// + /// + /// + /// + /// + public MatExpr this[int rowStart, int rowEnd, int colStart, int colEnd] + { + get + { + ThrowIfDisposed(); + return SubMat(rowStart, rowEnd, colStart, colEnd); + } + } + + /// + /// + /// + /// + /// + /// + public MatExpr this[Range rowRange, Range colRange] + { + get + { + ThrowIfDisposed(); + return SubMat(rowRange, colRange); + } + set + { + ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + var subMatExpr = SubMat(rowRange, colRange); + NativeMethods.core_Mat_assignment_FromMatExpr(subMatExpr.CvPtr, value.CvPtr); + GC.KeepAlive(subMatExpr); + GC.KeepAlive(value); + } + } + + /// + /// + /// + /// + /// + public MatExpr this[Rect roi] + { + get + { + ThrowIfDisposed(); + return SubMat(roi); + } + set + { + ThrowIfDisposed(); + if (value == null) + throw new ArgumentNullException(nameof(value)); + var subMatExpr = SubMat(roi); + NativeMethods.core_Mat_assignment_FromMatExpr(subMatExpr.CvPtr, value.CvPtr); + GC.KeepAlive(subMatExpr); + GC.KeepAlive(value); + } + } + #endregion + + #region Col + /// + /// + /// + public class ColIndexer : MatExprRowColIndexer + { + /// + /// + /// + /// + protected internal ColIndexer(MatExpr parent) + : base(parent) + { + } + + /// + /// + /// + /// + /// + public override MatExpr this[int x] + { + get + { + Parent.ThrowIfDisposed(); + var retPtr = NativeMethods.core_MatExpr_col(Parent.CvPtr, x); + GC.KeepAlive(this); + return new MatExpr(retPtr); + } + } + } + /// + /// + /// + public ColIndexer Col + { + get { return col ??= new ColIndexer(this); } + } + private ColIndexer? col; + #endregion + #region Cross + /// + /// + /// + /// + /// + public Mat Cross(Mat m) + { + ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_cross(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + var retVal = new Mat(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Diag + /// + /// + /// + /// + /// + public MatExpr Diag(int d = 0) + { + ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_diag2(ptr, d); + GC.KeepAlive(this); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Dot + /// + /// + /// + /// + /// + public double Dot(Mat m) + { + ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var res = NativeMethods.core_MatExpr_dot(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + return res; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Inv + /// + /// + /// + /// + /// + public MatExpr Inv(DecompTypes method = DecompTypes.LU) + { + ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_inv2(ptr, (int)method); + GC.KeepAlive(this); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Mul + /// + /// + /// + /// + /// + /// + public MatExpr Mul(MatExpr e, double scale = 1.0) + { + ThrowIfDisposed(); + e.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_mul_toMatExpr(ptr, e.CvPtr, scale); + GC.KeepAlive(this); + GC.KeepAlive(e); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public MatExpr Mul(Mat m, double scale = 1.0) + { + ThrowIfDisposed(); + m.ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_mul_toMat(ptr, m.CvPtr, scale); + GC.KeepAlive(this); + GC.KeepAlive(m); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Row + /// + /// + /// + public class RowIndexer : MatExprRowColIndexer + { + /// + /// + /// + /// + protected internal RowIndexer(MatExpr parent) + : base(parent) + { + } + /// + /// + /// + /// + /// + public override MatExpr this[int y] + { + get + { + Parent.ThrowIfDisposed(); + var retPtr = NativeMethods.core_MatExpr_row(Parent.CvPtr, y); + GC.KeepAlive(this); + return new MatExpr(retPtr); + } + } + } + /// + /// + /// + public RowIndexer Row + { + get { return row ??= new RowIndexer(this); } + } + private RowIndexer? row; + #endregion + #region + /// + /// + /// + public Size Size + { + get + { + ThrowIfDisposed(); + try + { + var res = NativeMethods.core_MatExpr_size(ptr); + GC.KeepAlive(this); + return res; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + } + #endregion + #region SubMat + /// + /// + /// + /// + /// + /// + /// + /// + public MatExpr SubMat(int rowStart, int rowEnd, int colStart, int colEnd) + { + ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_submat(ptr, rowStart, rowEnd, colStart, colEnd); + GC.KeepAlive(this); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + /// + /// + /// + /// + /// + /// + public MatExpr SubMat(Range rowRange, Range colRange) + { + return SubMat(rowRange.Start, rowRange.End, colRange.Start, colRange.End); + } + /// + /// + /// + /// + /// + public MatExpr SubMat(Rect roi) + { + return SubMat(roi.Y, roi.Y + roi.Height, roi.X, roi.X + roi.Width); + } + #endregion + #region T + /// + /// + /// + /// + public MatExpr T() + { + ThrowIfDisposed(); + try + { + var retPtr = NativeMethods.core_MatExpr_t(ptr); + GC.KeepAlive(this); + var retVal = new MatExpr(retPtr); + return retVal; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + #endregion + #region Type + /// + /// + /// + public MatType Type + { + get + { + ThrowIfDisposed(); + try + { + var res = (MatType)NativeMethods.core_MatExpr_type(ptr); + GC.KeepAlive(this); + return res; + } + catch (BadImageFormatException ex) + { + throw PInvokeHelper.CreateException(ex); + } + } + } + #endregion + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatExprRangeIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/MatExprRangeIndexer.cs new file mode 100644 index 0000000..099dbbd --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatExprRangeIndexer.cs @@ -0,0 +1,129 @@ +namespace OpenCvSharp +{ + /// + /// + /// + public abstract class MatExprRangeIndexer + { + /// + /// + /// + protected readonly Mat Parent; + + /// + /// + /// + /// + protected internal MatExprRangeIndexer(Mat parent) + { + Parent = parent; + } + + /// + /// Creates a matrix header for the specified matrix row/column. + /// + /// + /// + /// + /// + /// + public abstract MatExpr this[int rowStart, int rowEnd, int colStart, int colEnd] { get; set; } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + /// + public abstract MatExpr this[Range rowRange, Range colRange] { get; set; } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + public virtual MatExpr this[Rect roi] + { + get => this[roi.Top, roi.Bottom, roi.Left, roi.Right]; + set => this[roi.Top, roi.Bottom, roi.Left, roi.Right] = value; + } + + /// + /// Extracts a rectangular submatrix. + /// + /// Array of selected ranges along each array dimension. + /// + public abstract MatExpr this[params Range[] ranges] { get; set; } + + /// + /// Creates a matrix header for the specified matrix row/column. + /// + /// + /// + /// + /// + /// + public MatExpr Get(int rowStart, int rowEnd, int colStart, int colEnd) + { + return this[rowStart, rowEnd, colStart, colEnd]; + } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + /// + public MatExpr Get(Range rowRange, Range colRange) + { + return this[rowRange, colRange]; + } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + public MatExpr Get(Rect roi) + { + return this[roi]; + } + + /// + /// Sets a matrix header for the specified matrix row/column. + /// + /// + /// + /// + /// + /// + /// + public void Set(int rowStart, int rowEnd, int colStart, int colEnd, MatExpr value) + { + this[rowStart, rowEnd, colStart, colEnd] = value; + } + + /// + /// Sets a matrix header for the specified matrix row/column span. + /// + /// + /// + /// + /// + public void Set(Range rowRange, Range colRange, MatExpr value) + { + this[rowRange, colRange] = value; + } + + /// + /// Sets a matrix header for the specified matrix row/column span. + /// + /// + /// + /// + public void Set(Rect roi, MatExpr value) + { + this[roi] = value; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatExprRowColIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/MatExprRowColIndexer.cs new file mode 100644 index 0000000..478b809 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatExprRowColIndexer.cs @@ -0,0 +1,39 @@ +namespace OpenCvSharp +{ + /// + /// + /// + public abstract class MatExprRowColIndexer + { + /// + /// + /// + protected readonly MatExpr Parent; + + /// + /// + /// + /// + protected internal MatExprRowColIndexer(MatExpr parent) + { + Parent = parent; + } + + /// + /// + /// + /// + /// + public abstract MatExpr this[int pos] { get; } + + /// + /// + /// + /// + /// + public virtual MatExpr Get(int pos) + { + return this[pos]; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatExpr_CvMethods.cs b/OpenVinoOpenCvSharp/Modules/core/MatExpr_CvMethods.cs new file mode 100644 index 0000000..2661fe2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatExpr_CvMethods.cs @@ -0,0 +1,14 @@ +namespace OpenCvSharp +{ + partial class MatExpr + { + /// + /// Computes absolute value of each matrix element + /// + /// + public MatExpr Abs() + { + return Cv2.Abs(this); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatRowColExprIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/MatRowColExprIndexer.cs new file mode 100644 index 0000000..f527a85 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatRowColExprIndexer.cs @@ -0,0 +1,110 @@ +namespace OpenCvSharp +{ + /// + /// + /// + public abstract class MatRowColExprIndexer + { + /// + /// + /// + protected readonly Mat Parent; + + /// + /// + /// + /// + protected internal MatRowColExprIndexer(Mat parent) + { + Parent = parent; + } + + /// + /// Creates a matrix header for the specified matrix row/column. + /// + /// + /// + public abstract MatExpr this[int pos] { get; set; } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + /// + public abstract MatExpr this[int start, int end] { get; set; } + + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + public virtual MatExpr this[Range range] + { + get => this[range.Start, range.End]; + set => this[range.Start, range.End] = value; + } + + /// + /// Creates a matrix header for the specified matrix row/column. + /// + /// + /// + public MatExpr Get(int pos) + { + return this[pos]; + } + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + /// + public MatExpr Get(int start, int end) + { + return this[start, end]; + } + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + public MatExpr Get(Range range) + { + return this[range]; + } + + /// + /// Sets a matrix header for the specified matrix row/column. + /// + /// + /// + /// + public void Set(int pos, MatExpr value) + { + this[pos] = value; + } + + /// + /// Sets a matrix header for the specified matrix row/column span. + /// + /// + /// + /// + /// + public void Set(int start, int end, MatExpr value) + { + this[start, end] = value; + } + /// + /// Sets a matrix header for the specified matrix row/column span. + /// + /// + /// + /// + public void Set(Range range, MatExpr value) + { + this[range] = value; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/MatRowColIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/MatRowColIndexer.cs new file mode 100644 index 0000000..b9cd969 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/MatRowColIndexer.cs @@ -0,0 +1,104 @@ +namespace OpenCvSharp +{ + /// + /// + /// + public abstract class MatRowColIndexer + { + /// + /// + /// + protected readonly Mat Parent; + + /// + /// + /// + /// + protected internal MatRowColIndexer(Mat parent) + { + this.Parent = parent; + } + + /// + /// Creates/Sets a matrix header for the specified matrix row/column. + /// + /// + /// + public abstract Mat this[int pos] { get; set; } + + /// + /// Creates/Sets a matrix header for the specified row/column span. + /// + /// + /// + /// + public abstract Mat this[int start, int end] { get; set; } + + /// + /// Creates/Sets a matrix header for the specified row/column span. + /// + /// + /// + public virtual Mat this[Range range] => this[range.Start, range.End]; + + /// + /// Creates a matrix header for the specified matrix row/column. + /// + /// + /// + public virtual Mat Get(int pos) + { + return this[pos]; + } + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + /// + public virtual Mat Get(int start, int end) + { + return this[start, end]; + } + /// + /// Creates a matrix header for the specified row/column span. + /// + /// + /// + public virtual Mat Get(Range range) + { + return this[range]; + } + + /// + /// Creates/Sets a matrix header for the specified matrix row/column. + /// + /// + /// + public virtual void Set(int pos, Mat value) + { + this[pos] = value; + } + + /// + /// Creates/Sets a matrix header for the specified row/column span. + /// + /// + /// + /// + public virtual void Set(int start, int end, Mat value) + { + this[start, end] = value; + } + + /// + /// Creates/Sets a matrix header for the specified row/column span. + /// + /// + /// + public virtual void Set(Range range, Mat value) + { + this[range.Start, range.End] = value; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/OutputArray.cs b/OpenVinoOpenCvSharp/Modules/core/OutputArray.cs new file mode 100644 index 0000000..b9bd073 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/OutputArray.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +#if ENABLED_CUDA +using OpenCvSharp.Cuda; +#endif + +namespace OpenCvSharp +{ + /// + /// Proxy datatype for passing Mat's and List<>'s as output parameters + /// + public class OutputArray : DisposableCvObject + { + private readonly object obj; + + #region Init & Disposal + /// + /// + /// + /// + internal OutputArray(Mat mat) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + ptr = NativeMethods.core_OutputArray_new_byMat(mat.CvPtr); + GC.KeepAlive(mat); + obj = mat; + } + +#if ENABLED_CUDA + /// + /// + /// + /// + internal OutputArray(GpuMat mat) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + ptr = NativeMethods.core_OutputArray_new_byGpuMat(mat.CvPtr); + GC.KeepAlive(mat); + obj = mat; + } +#endif + + /// + /// + /// + /// + internal OutputArray(IEnumerable mat) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + using (var matVector = new VectorOfMat(mat)) + { + ptr = NativeMethods.core_OutputArray_new_byVectorOfMat(matVector.CvPtr); + } + obj = mat; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_OutputArray_delete(ptr); + base.DisposeUnmanaged(); + } + +#endregion + +#region Cast + /// + /// + /// + /// + /// + public static implicit operator OutputArray(Mat mat) + { + return new OutputArray(mat); + } + +#if ENABLED_CUDA + /// + /// + /// + /// + /// + public static implicit operator OutputArray(GpuMat mat) + { + return new OutputArray(mat); + } +#endif + +#endregion + +#region Operators +#endregion + +#region Methods + /// + /// + /// + /// + public bool IsMat() + { + return obj is Mat; + } + + /// + /// + /// + /// + public virtual Mat? GetMat() + { + return obj as Mat; + } + +#if ENABLED_CUDA + /// + /// + /// + /// + public bool IsGpuMat() + { + return obj is GpuMat; + } +#endif + +#if ENABLED_CUDA + /// + /// + /// + /// + public virtual Mat GetGpuMat() + { + return obj as GpuMat; + } +#endif + + /// + /// + /// + /// + public bool IsVectorOfMat() + { + return obj is IEnumerable; + } + + /// + /// + /// + /// + public virtual IEnumerable? GetVectorOfMat() + { + return obj as IEnumerable; + } + + /// + /// + /// + public virtual void AssignResult() + { + if (!IsReady()) + throw new NotSupportedException(); + + // OutputArrayの実体が cv::Mat のとき + if (IsMat()) + { + // 実は、何もしなくても結果入ってるっぽい? + /* + Mat mat = GetMat(); + // OutputArrayからMatオブジェクトを取得 + IntPtr outMat = NativeMethods.core_OutputArray_getMat(ptr); + // ポインタをセット + //NativeMethods.core_Mat_assignment_FromMat(mat.CvPtr, outMat); + NativeMethods.core_Mat_assignTo(outMat, mat.CvPtr); + // OutputArrayから取り出したMatをdelete + NativeMethods.core_Mat_delete(outMat); + */ + } +#if ENABLED_CUDA + else if (IsGpuMat()) + { + // do nothing + } +#endif + else + { + throw new OpenCvSharpException("Not supported OutputArray-compatible type"); + } + } + + /// + /// + /// + public void Fix() + { + AssignResult(); + Dispose(); + } + + /// + /// + /// + /// + public bool IsReady() + { + return + ptr != IntPtr.Zero && + !IsDisposed && + obj != null && +#if ENABLED_CUDA + (IsMat() || IsGpuMat()); +#else + IsMat(); +#endif + } + /// + /// + /// + /// + 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 OutputArray(mat); + } + +#if ENABLED_CUDA + /// + /// Creates a proxy class of the specified matrix + /// + /// + /// + public static OutputArray Create(GpuMat mat) + { + return new OutputArray(mat); + } +#endif + + /// + /// Creates a proxy class of the specified list + /// + /// + /// + /// + public static OutputArrayOfStructList Create(List list) + where T : unmanaged + { + if (list == 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 == null) + throw new ArgumentNullException(nameof(list)); + return new OutputArrayOfMatList(list); + } + +#endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfMatList.cs b/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfMatList.cs new file mode 100644 index 0000000..0a19b07 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfMatList.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; + +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(); + + // Matで結果取得 + using (var vectorOfMat = new VectorOfMat()) + { + NativeMethods.core_OutputArray_getVectorOfMat(ptr, vectorOfMat.CvPtr); + GC.KeepAlive(this); + list.Clear(); + list.AddRange(vectorOfMat.ToArray()); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfStructList.cs b/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfStructList.cs new file mode 100644 index 0000000..9663e4f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/OutputArrayOfStructList.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +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(); + + // Matで結果取得 + var matPtr = NativeMethods.core_OutputArray_getMat(ptr); + GC.KeepAlive(this); + using (var mat = new Mat(matPtr)) + { + // 配列サイズ + var size = mat.Rows * mat.Cols; + // 配列にコピー + var array = new T[size]; + using (var aa = new ArrayAddress1(array)) + { + var elemSize = MarshalHelper.SizeOf(); + MemoryHelper.CopyMemory(aa.Pointer, mat.Data, size * elemSize); + } + // リストにコピー + list.Clear(); + list.AddRange(array); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/PCA.cs b/OpenVinoOpenCvSharp/Modules/core/PCA.cs new file mode 100644 index 0000000..6275fa2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/PCA.cs @@ -0,0 +1,287 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Principal Component Analysis + /// + public class PCA : DisposableCvObject + { + #region Init & Disposal + + /// + /// + /// + public PCA() + { + ptr = NativeMethods.core_PCA_new1(); + } + + /// + /// + /// + /// + /// + /// + /// + public PCA(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + ptr = NativeMethods.core_PCA_new2(data.CvPtr, mean.CvPtr, (int)flags, maxComponents); + GC.KeepAlive(data); + GC.KeepAlive(mean); + } + + /// + /// + /// + /// + /// + /// + /// + public PCA(InputArray data, InputArray mean, Flags flags, double retainedVariance) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + ptr = NativeMethods.core_PCA_new3(data.CvPtr, mean.CvPtr, (int)flags, retainedVariance); + GC.KeepAlive(data); + GC.KeepAlive(mean); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_PCA_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Properties + /// + /// eigenvalues of the covariation matrix + /// + public Mat Eigenvectors + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_PCA_eigenvectors(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + } + + /// + /// eigenvalues of the covariation matrix + /// + public Mat Eigenvalues + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_PCA_eigenvalues(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + } + + /// + /// mean value subtracted before the projection and added after the back projection + /// + public Mat Mean + { + get + { + ThrowIfDisposed(); + var ret = NativeMethods.core_PCA_mean(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + } + + #endregion + + #region Methods + + /// + /// operator that performs PCA. The previously stored data, if any, is released + /// + /// + /// + /// + /// + /// + public PCA Compute(InputArray data, InputArray mean, Flags flags, int maxComponents = 0) + { + ThrowIfDisposed(); + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + NativeMethods.core_PCA_operatorThis(ptr, data.CvPtr, mean.CvPtr, (int)flags, maxComponents); + GC.KeepAlive(data); + GC.KeepAlive(mean); + return this; + } + + /// + /// operator that performs PCA. The previously stored data, if any, is released + /// + /// + /// + /// + /// + /// + public PCA ComputeVar(InputArray data, InputArray mean, Flags flags, double retainedVariance) + { + ThrowIfDisposed(); + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (mean == null) + throw new ArgumentNullException(nameof(mean)); + data.ThrowIfDisposed(); + mean.ThrowIfDisposed(); + NativeMethods.core_PCA_computeVar(ptr, data.CvPtr, mean.CvPtr, (int)flags, retainedVariance); + GC.KeepAlive(data); + GC.KeepAlive(mean); + return this; + } + + /// + /// projects vector from the original space to the principal components subspace + /// + /// + /// + public Mat Project(InputArray vec) + { + ThrowIfDisposed(); + if (vec == null) + throw new ArgumentNullException(nameof(vec)); + vec.ThrowIfDisposed(); + var ret = NativeMethods.core_PCA_project1(ptr, vec.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(vec); + return new Mat(ret); + } + /// + /// projects vector from the original space to the principal components subspace + /// + /// + /// + public void Project(InputArray vec, OutputArray result) + { + ThrowIfDisposed(); + if (vec == null) + throw new ArgumentNullException(nameof(vec)); + if (result == null) + throw new ArgumentNullException(nameof(result)); + vec.ThrowIfDisposed(); + result.ThrowIfNotReady(); + NativeMethods.core_PCA_project2(ptr, vec.CvPtr, result.CvPtr); + result.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(vec); + GC.KeepAlive(result); + } + + /// + /// reconstructs the original vector from the projection + /// + /// + /// + public Mat BackProject(InputArray vec) + { + ThrowIfDisposed(); + if (vec == null) + throw new ArgumentNullException(nameof(vec)); + vec.ThrowIfDisposed(); + var ret = NativeMethods.core_PCA_backProject1(ptr, vec.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(vec); + return new Mat(ret); + } + /// + /// reconstructs the original vector from the projection + /// + /// + /// + public void BackProject(InputArray vec, OutputArray result) + { + ThrowIfDisposed(); + if (vec == null) + throw new ArgumentNullException(nameof(vec)); + if (result == null) + throw new ArgumentNullException(nameof(result)); + vec.ThrowIfDisposed(); + result.ThrowIfNotReady(); + NativeMethods.core_PCA_backProject2(ptr, vec.CvPtr, result.CvPtr); + result.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(vec); + GC.KeepAlive(result); + } + #endregion + +#if LANG_JP + /// + /// PCAの操作フラグ + /// +#else + /// + /// Flags for PCA operations + /// +#endif + [Flags] + public enum Flags + { +#if LANG_JP + /// + /// 行としてベクトルが保存される(つまり,あるベクトルの全ての要素は連続的に保存される) + /// +#else + /// + /// The vectors are stored as rows (i.e. all the components of a certain vector are stored continously) + /// +#endif + DataAsRow = 0, + + +#if LANG_JP + /// + /// 列としてベクトルが保存される(つまり,あるベクトル成分に属する値は連続的に保存される) + /// +#else + /// + /// The vectors are stored as columns (i.e. values of a certain vector component are stored continuously) + /// +#endif + DataAsCol = 1, + + +#if LANG_JP + /// + /// 事前に計算された平均ベクトルを用いる + /// +#else + /// + /// Use pre-computed average vector + /// +#endif + UseAvg = 2, + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/RNG.cs b/OpenVinoOpenCvSharp/Modules/core/RNG.cs new file mode 100644 index 0000000..9f0cb2e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/RNG.cs @@ -0,0 +1,248 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Random Number Generator. + /// The class implements RNG using Multiply-with-Carry algorithm. + /// + /// operations.hpp + public class RNG + { + private ulong state; + + /// + /// + /// + public ulong State + { + get => state; + set => state = value; + } + + #region Init & Disposal + + /// + /// + /// + public RNG() + { + state = 0xffffffff; + } + + /// + /// + /// + /// + public RNG(ulong state) + { + this.state = (state != 0) ? state : 0xffffffff; + } + + #endregion + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator byte(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (byte) self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator sbyte(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (sbyte)self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator ushort(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (ushort)self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator short(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (short)self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator uint(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator int(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (int)self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator float(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return self.Next() * 2.3283064365386962890625e-10f; + } + + /// + /// + /// + /// + /// + public static explicit operator double(RNG self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + var t = self.Next(); + return (((ulong)t << 32) | self.Next()) * 5.4210108624275221700372640043497e-20; + } + + #endregion + + #region Methods + + /// + /// updates the state and returns the next 32-bit unsigned integer random number + /// + /// + public uint Next() + { + state = (ulong)(uint)State * /*CV_RNG_COEFF*/ 4164903690U + (uint)(State >> 32); + return (uint)State; + } + + /// + /// returns a random integer sampled uniformly from [0, N). + /// + /// + /// + public uint Run(uint n) + { + return (uint)Uniform(0, n); + } + + /// + /// + /// + /// + public uint Run() + { + return Next(); + } + + /// + /// returns uniformly distributed integer random number from [a,b) range + /// + /// + /// + /// + public int Uniform(int a, int b) + { + return a == b ? a : (int)(Next() % (b - a) + a); + } + + /// + /// returns uniformly distributed floating-point random number from [a,b) range + /// + /// + /// + /// + public float Uniform(float a, float b) + { + return ((float)this) * (b - a) + a; + } + + /// + /// returns uniformly distributed double-precision floating-point random number from [a,b) range + /// + /// + /// + /// + public double Uniform(double a, double b) + { + return ((double)this) * (b - a) + a; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void Fill(InputOutputArray mat, DistributionType distType, InputArray a, InputArray b, + bool saturateRange = false) + { + if (mat == null) + throw new ArgumentNullException(nameof(mat)); + if (a == null) + throw new ArgumentNullException(nameof(a)); + if (b == null) + throw new ArgumentNullException(nameof(b)); + mat.ThrowIfNotReady(); + a.ThrowIfDisposed(); + b.ThrowIfDisposed(); + NativeMethods.core_RNG_fill(ref state, mat.CvPtr, (int) distType, a.CvPtr, b.CvPtr, saturateRange ? 1 : 0); + mat.Fix(); + GC.KeepAlive(mat); + GC.KeepAlive(a); + GC.KeepAlive(b); + } + + /// + /// returns Gaussian random variate with mean zero. + /// + /// + /// + public double Gaussian(double sigma) + { + return NativeMethods.core_RNG_gaussian(ref state, sigma); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/RNG_MT19937.cs b/OpenVinoOpenCvSharp/Modules/core/RNG_MT19937.cs new file mode 100644 index 0000000..a5bc128 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/RNG_MT19937.cs @@ -0,0 +1,214 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Mersenne Twister random number generator + /// + /// operations.hpp + // ReSharper disable once InconsistentNaming + public class RNG_MT19937 + { + private static class PeriodParameters + { + public const int N = 624, M = 397; + } + private readonly uint[] state; + private int mti; + + #region Init & Disposal + + /// + /// + /// + public RNG_MT19937() + : this(5489U) + { + } + + /// + /// + /// + /// + public RNG_MT19937(uint s) + { + state = new uint[PeriodParameters.N]; + Seed(s); + } + + #endregion + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator uint(RNG_MT19937 self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator int(RNG_MT19937 self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return (int)self.Next(); + } + + /// + /// + /// + /// + /// + public static explicit operator float(RNG_MT19937 self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + return self.Next() * (1.0f / 4294967296.0f); + } + + /// + /// + /// + /// + /// + public static explicit operator double(RNG_MT19937 self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + var a = self.Next() >> 5; + var b = self.Next() >> 6; + return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); + } + + #endregion + + #region Methods + + /// + /// + /// + /// + public void Seed(uint s) + { + state[0] = s; + for (mti = 1; mti < PeriodParameters.N; mti++) + { + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + state[mti] = (uint) (1812433253U * (state[mti - 1] ^ (state[mti - 1] >> 30)) + mti); + } + } + + /// + /// updates the state and returns the next 32-bit unsigned integer random number + /// + /// + public uint Next() + { + /* mag01[x] = x * MATRIX_A for x=0,1 */ + uint[] mag01 = { 0x0U, /*MATRIX_A*/ 0x9908b0dfU }; + + const uint upperMask = 0x80000000U; + const uint lowerMask = 0x7fffffffU; + const int n = PeriodParameters.N; + const int m = PeriodParameters.M; + + /* generate N words at one time */ + uint y; + if (mti >= n) + { + var kk = 0; + + for (; kk < n - m; ++kk) + { + y = (state[kk] & upperMask) | (state[kk + 1] & lowerMask); + state[kk] = state[kk + m] ^ (y >> 1) ^ mag01[y & 0x1U]; + } + + for (; kk < n - 1; ++kk) + { + y = (state[kk] & upperMask) | (state[kk + 1] & lowerMask); + state[kk] = state[kk + (m - n)] ^ (y >> 1) ^ mag01[y & 0x1U]; + } + + y = (state[n - 1] & upperMask) | (state[0] & lowerMask); + state[n - 1] = state[m - 1] ^ (y >> 1) ^ mag01[y & 0x1U]; + + mti = 0; + } + + y = state[mti++]; + + /* Tempering */ + y ^= (y >> 11); + y ^= (y << 7) & 0x9d2c5680U; + y ^= (y << 15) & 0xefc60000U; + y ^= (y >> 18); + + return y; + } + + /// + /// returns a random integer sampled uniformly from [0, N). + /// + /// + /// + public uint Run(uint b) + { + return Next() % b; + } + + /// + /// + /// + /// + public uint Run() + { + return Next(); + } + + /// + /// returns uniformly distributed integer random number from [a,b) range + /// + /// + /// + /// + public int Uniform(int a, int b) + { + return (int)(Next() % (b - a) + a); + } + + /// + /// returns uniformly distributed floating-point random number from [a,b) range + /// + /// + /// + /// + public float Uniform(float a, float b) + { + return ((float)this) * (b - a) + a; + } + + /// + /// returns uniformly distributed double-precision floating-point random number from [a,b) range + /// + /// + /// + /// + public double Uniform(double a, double b) + { + return ((double)this) * (b - a) + a; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/SVD.cs b/OpenVinoOpenCvSharp/Modules/core/SVD.cs new file mode 100644 index 0000000..65eb9b1 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/SVD.cs @@ -0,0 +1,276 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Singular Value Decomposition class + /// + // ReSharper disable once InconsistentNaming + public class SVD : DisposableCvObject + { + #region Init & Disposal + + /// + /// the default constructor + /// + public SVD() + { + ptr = NativeMethods.core_SVD_new1(); + } + /// + /// the constructor that performs SVD + /// + /// + /// + public SVD(InputArray src, Flags flags = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + ptr = NativeMethods.core_SVD_new2(src.CvPtr, (int)flags); + GC.KeepAlive(src); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_SVD_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Methods + + /// + /// eigenvalues of the covariation matrix + /// + public Mat U() + { + + ThrowIfDisposed(); + var ret = NativeMethods.core_SVD_u(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// eigenvalues of the covariation matrix + /// + public Mat W() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_SVD_w(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// mean value subtracted before the projection and added after the back projection + /// + public Mat Vt() + { + ThrowIfDisposed(); + var ret = NativeMethods.core_SVD_vt(ptr); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// the operator that performs SVD. The previously allocated SVD::u, SVD::w are SVD::vt are released. + /// + /// + /// + /// + public SVD Run(InputArray src, Flags flags = 0) + { + ThrowIfDisposed(); + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + NativeMethods.core_SVD_operatorThis(ptr, src.CvPtr, (int)flags); + GC.KeepAlive(src); + return this; + } + + /// + /// performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix + /// + /// + /// + /// + public void BackSubst(InputArray rhs, OutputArray dst) + { + ThrowIfDisposed(); + if (rhs == null) + throw new ArgumentNullException(nameof(rhs)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + rhs.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_SVD_backSubst(ptr, rhs.CvPtr, dst.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(rhs); + GC.KeepAlive(dst); + } + #endregion + + #region Static + + /// + /// decomposes matrix and stores the results to user-provided matrices + /// + /// + /// + /// + /// + /// + public static void Compute(InputArray src, OutputArray w, + OutputArray u, OutputArray vt, Flags flags = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (u == null) + throw new ArgumentNullException(nameof(u)); + if (vt == null) + throw new ArgumentNullException(nameof(vt)); + src.ThrowIfDisposed(); + w.ThrowIfNotReady(); + u.ThrowIfNotReady(); + vt.ThrowIfNotReady(); + NativeMethods.core_SVD_static_compute1(src.CvPtr, w.CvPtr, u.CvPtr, vt.CvPtr, (int)flags); + w.Fix(); + u.Fix(); + vt.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(w); + GC.KeepAlive(u); + GC.KeepAlive(vt); + } + + /// + /// computes singular values of a matrix + /// + /// + /// + /// + public static void Compute(InputArray src, OutputArray w, Flags flags = 0) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (w == null) + throw new ArgumentNullException(nameof(w)); + src.ThrowIfDisposed(); + w.ThrowIfNotReady(); + NativeMethods.core_SVD_static_compute2(src.CvPtr, w.CvPtr, (int)flags); + w.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(w); + } + + /// + /// performs back substitution + /// + /// + /// + /// + /// + /// + public static void BackSubst(InputArray w, InputArray u, + InputArray vt, InputArray rhs, OutputArray dst) + { + if (w == null) + throw new ArgumentNullException(nameof(w)); + if (u == null) + throw new ArgumentNullException(nameof(u)); + if (vt == null) + throw new ArgumentNullException(nameof(vt)); + if (rhs == null) + throw new ArgumentNullException(nameof(rhs)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + w.ThrowIfDisposed(); + u.ThrowIfDisposed(); + vt.ThrowIfDisposed(); + rhs.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_SVD_static_backSubst(w.CvPtr, u.CvPtr, vt.CvPtr, rhs.CvPtr, dst.CvPtr); + dst.Fix(); + GC.KeepAlive(w); + GC.KeepAlive(u); + GC.KeepAlive(vt); + GC.KeepAlive(rhs); + GC.KeepAlive(dst); + } + + /// + /// finds dst = arg min_{|dst|=1} |m*dst| + /// + /// + /// + public static void SolveZ(InputArray src, OutputArray dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + NativeMethods.core_SVD_static_solveZ(src.CvPtr, dst.CvPtr); + dst.Fix(); + GC.KeepAlive(src); + GC.KeepAlive(dst); + } + + #endregion + +#if LANG_JP + /// + /// SVDの操作フラグ + /// +#else + /// + /// Operation flags for SVD + /// +#endif + [Flags] + public enum Flags + { + /// + /// + /// + None = 0, + +#if LANG_JP + /// + /// 計算中に行列Aの変更を行うことができる.このフラグの指定は処理速度を向上させる. + /// +#else + /// + /// enables modification of matrix src1 during the operation. It speeds up the processing. + /// +#endif + ModifyA = 1, + + /// + /// indicates that only a vector of singular values `w` is to be processed, + /// while u and vt will be set to empty matrices + /// +// ReSharper disable once InconsistentNaming + NoUV = 2, + + /// + /// when the matrix is not square, by default the algorithm produces u and + /// vt matrices of sufficiently large size for the further A reconstruction; + /// if, however, FULL_UV flag is specified, u and vt will be full-size square + /// orthogonal matrices. + /// +// ReSharper disable once InconsistentNaming + FullUV = 4, + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/SparseMat.cs b/OpenVinoOpenCvSharp/Modules/core/SparseMat.cs new file mode 100644 index 0000000..61255db --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/SparseMat.cs @@ -0,0 +1,941 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// Sparse matrix class. + /// + public class SparseMat : DisposableCvObject + { + #region Init & Disposal + +#if LANG_JP + /// + /// OpenCVネイティブの cv::SparseMat* ポインタから初期化 + /// + /// +#else + /// + /// Creates from native cv::SparseMat* pointer + /// + /// +#endif + public SparseMat(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Native object address is NULL"); + this.ptr = ptr; + } + +#if LANG_JP + /// + /// 空の疎行列として初期化 + /// +#else + /// + /// Creates empty SparseMat + /// +#endif + public SparseMat() + { + ptr = NativeMethods.core_SparseMat_new1(); + } + + +#if LANG_JP + /// + /// N次元疎行列として初期化 + /// + /// n-次元配列の形状を表す,整数型の配列. + /// 配列の型.1-4 チャンネルの行列を作成するには MatType.CV_8UC1, ..., CV_64FC4 を, + /// マルチチャンネルの行列を作成するには,MatType.CV_8UC(n), ..., CV_64FC(n) を利用してください. +#else + /// + /// constructs n-dimensional sparse matrix + /// + /// Array of integers specifying an n-dimensional array shape. + /// Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, + /// or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices. +#endif + public SparseMat(IEnumerable sizes, MatType type) + { + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + + var sizesArray = EnumerableEx.ToArray(sizes); + ptr = NativeMethods.core_SparseMat_new2(sizesArray.Length, sizesArray, type); + } + +#if LANG_JP + /// + /// cv::Matデータから初期化 + /// + /// cv::Matオブジェクトへの参照. +#else + /// + /// converts old-style CvMat to the new matrix; the data is not copied by default + /// + /// cv::Mat object +#endif + public SparseMat(Mat m) + { + if (m == null) + throw new ArgumentNullException(nameof(m)); + m.ThrowIfDisposed(); + ptr = NativeMethods.core_SparseMat_new3(m.CvPtr); + GC.KeepAlive(m); + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException(); + } + +#if LANG_JP + /// + /// リソースの解放 + /// +#else + /// + /// Releases the resources + /// +#endif + public void Release() + { + Dispose(); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.core_SparseMat_delete(ptr); + base.DisposeUnmanaged(); + } + + #region Static Initializers + + /// + /// + /// + /// + /// + public static SparseMat FromMat(Mat mat) + { + return new SparseMat(mat); + } + + #endregion + + #endregion + + #region Static + /// + /// sizeof(cv::Mat) + /// + public static readonly int SizeOf = (int)NativeMethods.core_SparseMat_sizeof(); + + #endregion + + #region Public Methods + + /// + /// Assignment operator. This is O(1) operation, i.e. no data is copied + /// + /// + /// + public SparseMat AssignFrom(SparseMat m) + { + ThrowIfDisposed(); + if(m == null) + throw new ArgumentNullException(nameof(m)); + NativeMethods.core_SparseMat_operatorAssign_SparseMat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + return this; + } + + /// + /// Assignment operator. equivalent to the corresponding constructor. + /// + /// + /// + public SparseMat AssignFrom(Mat m) + { + ThrowIfDisposed(); + if (m == null) + throw new ArgumentNullException(nameof(m)); + NativeMethods.core_SparseMat_operatorAssign_Mat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + return this; + } + + /// + /// creates full copy of the matrix + /// + /// + public SparseMat Clone() + { + ThrowIfDisposed(); + var p = NativeMethods.core_SparseMat_clone(ptr); + GC.KeepAlive(this); + return new SparseMat(p); + } + + /// + /// copies all the data to the destination matrix. All the previous content of m is erased. + /// + /// + public void CopyTo(SparseMat m) + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_copyTo_SparseMat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + /// + /// converts sparse matrix to dense matrix. + /// + /// + public void CopyTo(Mat m) + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_copyTo_Mat(ptr, m.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type + /// + /// + /// + /// + public void ConvertTo(SparseMat m, int rtype, double alpha = 1) + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_convertTo_SparseMat(ptr, m.CvPtr, rtype, alpha); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. + /// + /// + /// The output matrix data type. When it is =-1, the output array will have the same data type as (*this) + /// The scale factor + /// The optional delta added to the scaled values before the conversion + public void ConvertTo(Mat m, int rtype, double alpha = 1, double beta = 0) + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_convertTo_Mat(ptr, m.CvPtr, rtype, alpha, beta); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// not used now + /// + /// + /// + public void AssignTo(SparseMat m, int type = -1) + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_assignTo(ptr, m.CvPtr, type); + GC.KeepAlive(this); + GC.KeepAlive(m); + } + + /// + /// Reallocates sparse matrix. + /// If the matrix already had the proper size and type, + /// it is simply cleared with clear(), otherwise, + /// the old matrix is released (using release()) and the new one is allocated. + /// + /// + /// + public void Create(MatType type, params int[] sizes) + { + ThrowIfDisposed(); + if (sizes == null) + throw new ArgumentNullException(nameof(sizes)); + if (sizes.Length == 1) + throw new ArgumentException("sizes is empty"); + NativeMethods.core_SparseMat_create(ptr, sizes.Length, sizes, type); + GC.KeepAlive(this); + } + + /// + /// sets all the sparse matrix elements to 0, which means clearing the hash table. + /// + public void Clear() + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_clear(ptr); + GC.KeepAlive(this); + } + + /// + /// manually increments the reference counter to the header. + /// + public void Addref() + { + ThrowIfDisposed(); + NativeMethods.core_SparseMat_addref(ptr); + GC.KeepAlive(this); + } + + /// + /// returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) + /// + /// + public int ElemSize() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_elemSize(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// returns elemSize()/channels() + /// + /// + public int ElemSize1() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_elemSize1(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns the type of sparse matrix element. + /// + /// + public MatType Type() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_type(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns the depth of sparse matrix element. + /// + /// + public int Depth() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_depth(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns the matrix dimensionality + /// + public int Dims() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_dims(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns the number of sparse matrix channels. + /// + /// + public int Channels() + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_channels(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns the array of sizes, or null if the matrix is not allocated + /// + /// + public int[] Size() + { + ThrowIfDisposed(); + + var sizePtr = NativeMethods.core_SparseMat_size1(ptr); + if (sizePtr == IntPtr.Zero) + throw new OpenCvSharpException("core_SparseMat_size1 == IntPtr.Zero"); + + var length = Dims(); + var size = new int[length]; + Marshal.Copy(sizePtr, size, 0, length); + GC.KeepAlive(this); + return size; + } + + /// + /// Returns the size of i-th matrix dimension (or 0) + /// + /// + /// + public int Size(int dim) + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_size2(ptr, dim); + GC.KeepAlive(this); + return res; + } + + #region Hash + + /// + /// Computes the element hash value (1D case) + /// + /// Index along the dimension 0 + /// + public long Hash(int i0) + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_hash_1d(ptr, i0).ToInt64(); + GC.KeepAlive(this); + return res; + } + + /// + /// Computes the element hash value (2D case) + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// + public long Hash(int i0, int i1) + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_hash_2d(ptr, i0, i1).ToInt64(); + GC.KeepAlive(this); + return res; + } + + /// + /// Computes the element hash value (3D case) + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// + public long Hash(int i0, int i1, int i2) + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_hash_3d(ptr, i0, i1, i2).ToInt64(); + GC.KeepAlive(this); + return res; + } + + /// + /// Computes the element hash value (nD case) + /// + /// Array of Mat::dims indices. + /// + public long Hash(params int[] idx) + { + ThrowIfDisposed(); + var res = NativeMethods.core_SparseMat_hash_nd(ptr, idx).ToInt64(); + GC.KeepAlive(this); + return res; + } + + #endregion + #region Ptr + + /// + /// Low-level element-access function. + /// + /// Index along the dimension 0 + /// Create new element with 0 value if it does not exist in SparseMat. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public IntPtr Ptr(int i0, bool createMissing, long? hashVal = null) + { + IntPtr res; + //ThrowIfDisposed(); + if (hashVal.HasValue) + { + var hashVal0 = (ulong)hashVal.Value; + res = NativeMethods.core_SparseMat_ptr_1d( + ptr, i0, createMissing ? 1 : 0, ref hashVal0); + } + else + res = NativeMethods.core_SparseMat_ptr_1d( + ptr, i0, createMissing ? 1 : 0, IntPtr.Zero); + + GC.KeepAlive(this); + return res; + } + + /// + /// Low-level element-access function. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Create new element with 0 value if it does not exist in SparseMat. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public IntPtr Ptr(int i0, int i1, bool createMissing, long? hashVal = null) + { + IntPtr res; + //ThrowIfDisposed(); + if (hashVal.HasValue) + { + var hashVal0 = (ulong)hashVal.Value; + res = NativeMethods.core_SparseMat_ptr_2d( + ptr, i0, i1, createMissing ? 1 : 0, ref hashVal0); + } + else + res = NativeMethods.core_SparseMat_ptr_2d( + ptr, i0, i1, createMissing ? 1 : 0, IntPtr.Zero); + + GC.KeepAlive(this); + return res; + } + + /// + /// Low-level element-access function. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// Create new element with 0 value if it does not exist in SparseMat. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public IntPtr Ptr(int i0, int i1, int i2, bool createMissing, long? hashVal = null) + { + IntPtr res; + //ThrowIfDisposed(); + if (hashVal.HasValue) + { + var hashVal0 = (ulong)hashVal.Value; + res = NativeMethods.core_SparseMat_ptr_3d( + ptr, i0, i1, i2, createMissing ? 1 : 0, ref hashVal0); + } + else + res = NativeMethods.core_SparseMat_ptr_3d( + ptr, i0, i1, i2, createMissing ? 1 : 0, IntPtr.Zero); + + GC.KeepAlive(this); + return res; + } + + /// + /// Low-level element-access function. + /// + /// Array of Mat::dims indices. + /// Create new element with 0 value if it does not exist in SparseMat. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public IntPtr Ptr(int[] idx, bool createMissing, long? hashVal = null) + { + IntPtr res; + //ThrowIfDisposed(); + if (hashVal.HasValue) + { + var hashVal0 = (ulong)hashVal.Value; + res = NativeMethods.core_SparseMat_ptr_nd( + ptr, idx, createMissing ? 1 : 0, ref hashVal0); + } + else + res = NativeMethods.core_SparseMat_ptr_nd( + ptr, idx, createMissing ? 1 : 0, IntPtr.Zero); + GC.KeepAlive(this); + return res; + } + + #endregion + #region Find + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, null. + /// + /// Index along the dimension 0 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T? Find(int i0, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, false, hashVal); + if (p == IntPtr.Zero) + return null; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, null. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T? Find(int i0, int i1, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, i1, false, hashVal); + if (p == IntPtr.Zero) + return null; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, null. + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T? Find(int i0, int i1, int i2, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, i1, i2, false, hashVal); + if (p == IntPtr.Zero) + return null; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, null. + /// + /// Array of Mat::dims indices. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T? Find(int[] idx, long? hashVal = null) + where T : struct + { + var p = Ptr(idx, false, hashVal); + if (p == IntPtr.Zero) + return null; + + return MarshalHelper.PtrToStructure(p); + } + + #endregion + #region Value + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, default(T). + /// + /// Index along the dimension 0 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T Value(int i0, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, false, hashVal); + if (p == IntPtr.Zero) + return default; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, default(T). + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T Value(int i0, int i1, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, i1, false, hashVal); + if (p == IntPtr.Zero) + return default; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, default(T). + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T Value(int i0, int i1, int i2, long? hashVal = null) + where T : struct + { + var p = Ptr(i0, i1, i2, false, hashVal); + if (p == IntPtr.Zero) + return default; + + return MarshalHelper.PtrToStructure(p); + } + + /// + /// Return pthe specified sparse matrix element if it exists; otherwise, default(T). + /// + /// Array of Mat::dims indices. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// + public T Value(int[] idx, long? hashVal = null) + where T : struct + { + var p = Ptr(idx, false, hashVal); + if (p == IntPtr.Zero) + return default; + + return MarshalHelper.PtrToStructure(p); + } + + #endregion + #region Element Indexer + + /// + /// Mat Indexer + /// + /// + public sealed class Indexer : SparseMatIndexer where T : struct + { + internal Indexer(SparseMat parent) + : base(parent) + { + } + + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public override T this[int i0, long? hashVal = null] + { + get + { + var p = Parent.Ptr(i0, true, hashVal); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = Parent.Ptr(i0, true, hashVal); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public override T this[int i0, int i1, long? hashVal = null] + { + get + { + var p = Parent.Ptr(i0, i1, true, hashVal); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = Parent.Ptr(i0, i1, true, hashVal); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public override T this[int i0, int i1, int i2, long? hashVal = null] + { + get + { + var p = Parent.Ptr(i0, i1, i2, true, hashVal); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = Parent.Ptr(i0, i1, i2, true, hashVal); + Marshal.StructureToPtr(value, p, false); + } + } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public override T this[int[] idx, long? hashVal = null] + { + get + { + var p = Parent.Ptr(idx, true, hashVal); + return MarshalHelper.PtrToStructure(p); + } + set + { + var p = Parent.Ptr(idx, true, hashVal); + Marshal.StructureToPtr(value, p, false); + } + } + } + + /// + /// Gets a type-specific indexer. + /// The indexer has getters/setters to access each matrix element. + /// + /// + /// + public Indexer Ref() where T : struct + { + return new Indexer(this); + } + /// + /// Gets a type-specific indexer. + /// The indexer has getters/setters to access each matrix element. + /// + /// + /// + public Indexer GetIndexer() where T : struct + { + return new Indexer(this); + } + + #endregion + #region Get/Set + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public T Get(int i0, long? hashVal = null) where T : struct + { + return new Indexer(this)[i0, hashVal]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public T Get(int i0, int i1, long? hashVal = null) where T : struct + { + return new Indexer(this)[i0, i1, hashVal]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public T Get(int i0, int i1, int i2, long? hashVal = null) where T : struct + { + return new Indexer(this)[i0, i1, i2, hashVal]; + } + + /// + /// Returns a value to the specified array element. + /// + /// + /// Array of Mat::dims indices. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public T Get(int[] idx, long? hashVal = null) where T : struct + { + return new Indexer(this)[idx, hashVal]; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// + /// + public void Set(int i0, T value, long? hashVal = null) where T : struct + { + (new Indexer(this))[i0, hashVal] = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + public void Set(int i0, int i1, T value, long? hashVal = null) where T : struct + { + (new Indexer(this))[i0, i1, hashVal] = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + public void Set(int i0, int i1, int i2, T value, long? hashVal = null) where T : struct + { + (new Indexer(this)[i0, i1, i2, hashVal]) = value; + } + + /// + /// Set a value to the specified array element. + /// + /// + /// Array of Mat::dims indices. + /// + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + public void Set(int[] idx, T value, long? hashVal = null) where T : struct + { + (new Indexer(this)[idx, hashVal]) = value; + } + + #endregion + + #region ToString + + /// + /// Returns a string that represents this Mat. + /// + /// + public override string ToString() + { + return "Mat [ " + + "Dims=" + Dims() + + "Type=" + Type().ToString() + + " ]"; + } + + #endregion + + #endregion + } + +} diff --git a/OpenVinoOpenCvSharp/Modules/core/SparseMatIndexer.cs b/OpenVinoOpenCvSharp/Modules/core/SparseMatIndexer.cs new file mode 100644 index 0000000..d1500ba --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/SparseMatIndexer.cs @@ -0,0 +1,58 @@ +namespace OpenCvSharp +{ + /// + /// Abstract definition of Mat indexer + /// + /// + public abstract class SparseMatIndexer where T : struct + { + /// + /// 1-dimensional indexer + /// + /// Index along the dimension 0 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public abstract T this[int i0, long? hashVal = null] { get; set; } + + /// + /// 2-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public abstract T this[int i0, int i1, long? hashVal = null] { get; set; } + + /// + /// 3-dimensional indexer + /// + /// Index along the dimension 0 + /// Index along the dimension 1 + /// Index along the dimension 2 + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public abstract T this[int i0, int i1, int i2, long? hashVal = null] { get; set; } + + /// + /// n-dimensional indexer + /// + /// Array of Mat::dims indices. + /// If hashVal is not null, the element hash value is not computed but hashval is taken instead. + /// A value to the specified array element. + public abstract T this[int[] idx, long? hashVal = null] { get; set; } + + /// + /// Parent matrix object + /// + protected readonly SparseMat Parent; + + /// + /// Constructor + /// + /// + internal SparseMatIndexer(SparseMat parent) + { + Parent = parent; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/DMatch.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/DMatch.cs new file mode 100644 index 0000000..a37a6b9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/DMatch.cs @@ -0,0 +1,139 @@ +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 2つのキーポイントディスクリプタ同士のマッチング情報 + /// +#else + /// + /// Struct for matching: query descriptor index, train descriptor index, train image index and distance between descriptors. + /// +#endif + public struct DMatch + { +#if LANG_JP + /// + /// クエリディスクリプタインデックス + /// +#else + /// + /// query descriptor index + /// +#endif + public int QueryIdx; + +#if LANG_JP + /// + /// 訓練ディスクリプタインデックス + /// +#else + /// + /// train descriptor index + /// +#endif + public int TrainIdx; + +#if LANG_JP + /// + /// 訓練画像インデックス + /// +#else + /// + /// train image index + /// +#endif + public int ImgIdx; + + + /// + /// + /// + public float Distance; + + /// + /// + /// + /// + public static DMatch Empty() + { + return new DMatch(-1, -1, -1, float.MaxValue); + } + + /// + /// + /// + /// + /// + /// + public DMatch(int queryIdx, int trainIdx, float distance) : + this(queryIdx, trainIdx, -1, distance) + { + } + /// + /// + /// + /// + /// + /// + /// + public DMatch(int queryIdx, int trainIdx, int imgIdx, float distance) + { + QueryIdx = queryIdx; + TrainIdx = trainIdx; + ImgIdx = imgIdx; + Distance = distance; + } + + /// + /// Compares by distance (less is beter) + /// + /// + /// + /// + public static bool operator <(DMatch d1, DMatch d2) + { + return d1.Distance < d2.Distance; + } + /// + /// Compares by distance (less is beter) + /// + /// + /// + /// + public static bool operator >(DMatch d1, DMatch d2) + { + return d1.Distance > d2.Distance; + } + + /// + /// + /// + /// + /// + public static explicit operator Vec4f(DMatch self) + { + return new Vec4f(self.QueryIdx, self.TrainIdx, self.ImgIdx, self.Distance); + } + /// + /// + /// + /// + /// + public static explicit operator DMatch(Vec4f v) + { + return new DMatch((int)v.Item0, (int)v.Item1, (int)v.Item2, v.Item3); + } + + /// + /// + /// + /// + public override string ToString() + { + // ReSharper disable once UseStringInterpolation + return string.Format("DMatch (QueryIdx:{0}, TrainIdx:{1}, ImgIdx:{2}, Distance:{3})", + QueryIdx, TrainIdx, ImgIdx, Distance); + } + } + +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/KeyPoint.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/KeyPoint.cs new file mode 100644 index 0000000..1a37bde --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/KeyPoint.cs @@ -0,0 +1,288 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 特徴点検出器のためのデータ構造体 + /// +#else + /// + /// Data structure for salient point detectors + /// +#endif + [Serializable] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct KeyPoint : IEquatable + { + #region Properties + +#if LANG_JP + /// + /// 特徴点の座標 + /// +#else + /// + /// Coordinate of the point + /// +#endif + public Point2f Pt; + +#if LANG_JP + /// + /// 特徴点のサイズ + /// +#else + /// + /// Feature size + /// +#endif + public float Size; + +#if LANG_JP + /// + /// 特徴点の向き(度数法)。 向きが定義されない、若しくは計算されない場合には負数。 + /// +#else + /// + /// Feature orientation in degrees (has negative value if the orientation is not defined/not computed) + /// +#endif + public float Angle; + +#if LANG_JP + /// + /// 特徴点の強さ(もっとも顕著なキーポイントを求めるために使われる) + /// +#else + /// + /// Feature strength (can be used to select only the most prominent key points) + /// +#endif + public float Response; + +#if LANG_JP + /// + /// 特徴点が見つかったscale-spaceのoctave。サイズと相関がある場合がある。 + /// +#else + /// + /// Scale-space octave in which the feature has been found; may correlate with the size + /// +#endif + public int Octave; + +#if LANG_JP + /// + /// 特徴点のクラス(特徴点分類機または物体検出器において用いられる) + /// +#else + /// + /// Point class (can be used by feature classifiers or object detectors) + /// +#endif + public int ClassId; + + #endregion + + #region Constructors + +#if LANG_JP + /// + /// 初期化 + /// + /// 特徴点の座標 + /// 特徴点のサイズ + /// 特徴点の向き(度数法)。 向きが定義されない、若しくは計算されない場合には負数。 + /// 特徴点の強さ(もっとも顕著なキーポイントを求めるために使われる) + /// 特徴点が見つかったscale-spaceのoctave。サイズと相関がある場合がある。 + /// 特徴点のクラス(特徴点分類機または物体検出器において用いられる) +#else + /// + /// Complete constructor + /// + /// Coordinate of the point + /// Feature size + /// Feature orientation in degrees (has negative value if the orientation is not defined/not computed) + /// Feature strength (can be used to select only the most prominent key points) + /// Scale-space octave in which the feature has been found; may correlate with the size + /// Point class (can be used by feature classifiers or object detectors) +#endif + public KeyPoint(Point2f pt, float size, float angle = -1, float response = 0, int octave = 0, + int classId = -1) + { + Pt = pt; + Size = size; + Angle = angle; + Response = response; + Octave = octave; + ClassId = classId; + } + +#if LANG_JP + /// + /// 初期化 + /// + /// 特徴点のx座標 + /// 特徴点のy座標 + /// 特徴点のサイズ + /// 特徴点の向き(度数法)。 向きが定義されない、若しくは計算されない場合には負数。 + /// 特徴点の強さ(もっとも顕著なキーポイントを求めるために使われる) + /// 特徴点が見つかったscale-spaceのoctave。サイズと相関がある場合がある。 + /// 特徴点のクラス(特徴点分類機または物体検出器において用いられる) +#else + /// + /// Complete constructor + /// + /// X-coordinate of the point + /// Y-coordinate of the point + /// Feature size + /// Feature orientation in degrees (has negative value if the orientation is not defined/not computed) + /// Feature strength (can be used to select only the most prominent key points) + /// Scale-space octave in which the feature has been found; may correlate with the size + /// Point class (can be used by feature classifiers or object detectors) +#endif + public KeyPoint(float x, float y, float size, float angle = -1, float response = 0, int octave = 0, + int classId = -1) + : this(new Point2f(x, y), size, angle, response, octave, classId) + { + } + + #endregion + + #region Operators + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(KeyPoint obj) + { + return ( + Pt == obj.Pt && + Math.Abs(Size - obj.Size) < 1e-9 && + Math.Abs(Angle - obj.Angle) < 1e-9 && + Math.Abs(Response - obj.Response) < 1e-9 && + Octave == obj.Octave && + ClassId == obj.ClassId + ); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(KeyPoint lhs, KeyPoint rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(KeyPoint lhs, KeyPoint rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region Overrided Methods + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + unchecked + { + return ( + Pt.GetHashCode() + + Size.GetHashCode() + + Angle.GetHashCode() + + Response.GetHashCode() + + Octave.GetHashCode() + + ClassId.GetHashCode()); + } + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + // ReSharper disable once UseStringInterpolation + return string.Format("[Pt:{0}, Size:{1}, Angle:{2}, Response:{3}, Octave:{4}, ClassId:{5}]", + Pt, Size, Angle, Response, Octave, ClassId); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/MatType.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/MatType.cs new file mode 100644 index 0000000..25f97ee --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/MatType.cs @@ -0,0 +1,245 @@ +using System; + +namespace OpenCvSharp +{ +// ReSharper disable InconsistentNaming +#pragma warning disable 1591 + + /// + /// Matrix data type (depth and number of channels) + /// + public struct MatType : IEquatable, IEquatable + { + /// + /// Entity value + /// + public int Value; + + /// + /// + /// + /// + public MatType(int value) + { + Value = value; + } + + /// + /// + /// + /// + /// + public static implicit operator int(MatType self) + { + return self.Value; + } + + /// + /// + /// + /// + /// + public static implicit operator MatType(int value) + { + return new MatType(value); + } + + /// + /// + /// + public int Depth => Value & (CV_DEPTH_MAX - 1); + + /// + /// + /// + public bool IsInteger => Depth < CV_32F; + + /// + /// + /// + public int Channels => (Value >> CV_CN_SHIFT) + 1; + + public bool Equals(MatType other) + { + return Value == other.Value; + } + + public bool Equals(int other) + { + return Value == other; + } + + public override bool Equals(object? other) + { + if (other is null) + return false; + if (other.GetType() != typeof (MatType)) + return false; + return Equals((MatType) other); + } + + public static bool operator ==(MatType self, MatType other) + { + return self.Equals(other); + } + + public static bool operator !=(MatType self, MatType other) + { + return !self.Equals(other); + } + + public static bool operator ==(MatType self, int other) + { + return self.Equals(other); + } + + public static bool operator !=(MatType self, int other) + { + return !self.Equals(other); + } + + public override int GetHashCode() + { + return Value.GetHashCode(); + } + + /// + /// + /// + /// + public override string ToString() + { + string s; + switch (Depth) + { + case CV_8U: + s = "CV_8U"; + break; + case CV_8S: + s = "CV_8S"; + break; + case CV_16U: + s = "CV_16U"; + break; + case CV_16S: + s = "CV_16S"; + break; + case CV_32S: + s = "CV_32S"; + break; + case CV_32F: + s = "CV_32F"; + break; + case CV_64F: + s = "CV_64F"; + break; + case CV_USRTYPE1: + s = "CV_USRTYPE1"; + break; + default: + throw new OpenCvSharpException("Unsupported CvType value: " + Value); + } + + var ch = Channels; + if (ch <= 4) + return s + "C" + ch; + else + return s + "C(" + ch + ")"; + } + + private const int CV_CN_MAX = 512, + CV_CN_SHIFT = 3, + CV_DEPTH_MAX = (1 << CV_CN_SHIFT); + + /// + /// type depth constants + /// + public const int + CV_8U = 0, + CV_8S = 1, + CV_16U = 2, + CV_16S = 3, + CV_32S = 4, + CV_32F = 5, + CV_64F = 6, + CV_USRTYPE1 = 7; + + /// + /// predefined type constants + /// + public static readonly MatType + CV_8UC1 = CV_8UC(1), + CV_8UC2 = CV_8UC(2), + CV_8UC3 = CV_8UC(3), + CV_8UC4 = CV_8UC(4), + CV_8SC1 = CV_8SC(1), + CV_8SC2 = CV_8SC(2), + CV_8SC3 = CV_8SC(3), + CV_8SC4 = CV_8SC(4), + CV_16UC1 = CV_16UC(1), + CV_16UC2 = CV_16UC(2), + CV_16UC3 = CV_16UC(3), + CV_16UC4 = CV_16UC(4), + CV_16SC1 = CV_16SC(1), + CV_16SC2 = CV_16SC(2), + CV_16SC3 = CV_16SC(3), + CV_16SC4 = CV_16SC(4), + CV_32SC1 = CV_32SC(1), + CV_32SC2 = CV_32SC(2), + CV_32SC3 = CV_32SC(3), + CV_32SC4 = CV_32SC(4), + CV_32FC1 = CV_32FC(1), + CV_32FC2 = CV_32FC(2), + CV_32FC3 = CV_32FC(3), + CV_32FC4 = CV_32FC(4), + CV_64FC1 = CV_64FC(1), + CV_64FC2 = CV_64FC(2), + CV_64FC3 = CV_64FC(3), + CV_64FC4 = CV_64FC(4); + + + public static MatType CV_8UC(int ch) + { + return MakeType(CV_8U, ch); + } + + public static MatType CV_8SC(int ch) + { + return MakeType(CV_8S, ch); + } + + public static MatType CV_16UC(int ch) + { + return MakeType(CV_16U, ch); + } + + public static MatType CV_16SC(int ch) + { + return MakeType(CV_16S, ch); + } + + public static MatType CV_32SC(int ch) + { + return MakeType(CV_32S, ch); + } + + public static MatType CV_32FC(int ch) + { + return MakeType(CV_32F, ch); + } + + public static MatType CV_64FC(int ch) + { + return MakeType(CV_64F, ch); + } + + public static MatType MakeType(int depth, int channels) + { + if (channels <= 0 || channels >= CV_CN_MAX) + throw new OpenCvSharpException("Channels count should be 1.." + (CV_CN_MAX - 1)); + if (depth < 0 || depth >= CV_DEPTH_MAX) + throw new OpenCvSharpException("Data type depth should be 0.." + (CV_DEPTH_MAX - 1)); + return (depth & (CV_DEPTH_MAX - 1)) + ((channels - 1) << CV_CN_SHIFT); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point.cs new file mode 100644 index 0000000..b8e2ff9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point.cs @@ -0,0 +1,412 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Point : IEquatable + { + /// + /// + /// + public int X; + + /// + /// + /// + public int Y; + + /// + /// + /// + public const int SizeOf = sizeof (int) + sizeof (int); + + /// + /// + /// + /// + /// + public Point(int x, int y) + { + X = x; + Y = y; + } + + /// + /// + /// + /// + /// + public Point(double x, double y) + { + X = (int) x; + Y = (int) y; + } + + #region Cast + + /// + /// + /// + /// + /// + public static implicit operator Vec2i(Point point) + { + return new Vec2i(point.X, point.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Point(Vec2i vec) + { + return new Point(vec.Item0, vec.Item1); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point obj) + { + return (X == obj.X && Y == obj.Y); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two Point objects. The result specifies whether the values of the X and Y properties of the two Point objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point lhs, Point rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two Point objects. The result specifies whether the values of the X or Y properties of the two Point objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point lhs, Point rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point operator +(Point pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point operator -(Point pt) + { + return new Point(-pt.X, -pt.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point operator +(Point p1, Point p2) + { + return new Point(p1.X + p2.X, p1.Y + p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point operator -(Point p1, Point p2) + { + return new Point(p1.X - p2.X, p1.Y - p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point operator *(Point pt, double scale) + { + return new Point((int) (pt.X*scale), (int) (pt.Y*scale)); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y})"; + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// + /// +#endif + public static double Distance(Point p1, Point p2) + { + return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)); + } + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// +#endif + public double DistanceTo(Point p) + { + return Distance(this, p); + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double DotProduct(Point p1, Point p2) + { + return p1.X*p2.X + p1.Y*p2.Y; + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// +#endif + public double DotProduct(Point p) + { + return DotProduct(this, p); + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double CrossProduct(Point p1, Point p2) + { + return p1.X*p2.Y - p2.X*p1.Y; + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// +#endif + public double CrossProduct(Point p) + { + return CrossProduct(this, p); + } + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point2d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point2d.cs new file mode 100644 index 0000000..1bc0ea2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point2d.cs @@ -0,0 +1,421 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Point2d : IEquatable + { + /// + /// + /// + public double X; + + /// + /// + /// + public double Y; + + /// + /// + /// + public const int SizeOf = sizeof (double) + sizeof (double); + + /// + /// + /// + /// + /// + public Point2d(double x, double y) + { + X = x; + Y = y; + } + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator Point(Point2d self) + { + return new Point((int) self.X, (int) self.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Point2d(Point point) + { + return new Point2d(point.X, point.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Vec2d(Point2d point) + { + return new Vec2d(point.X, point.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Point2d(Vec2d vec) + { + return new Point2d(vec.Item0, vec.Item1); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point2d obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && Math.Abs(Y - obj.Y) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point2d lhs, Point2d rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point2d lhs, Point2d rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point2d operator +(Point2d pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point2d operator -(Point2d pt) + { + return new Point2d(-pt.X, -pt.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2d operator +(Point2d p1, Point2d p2) + { + return new Point2d(p1.X + p2.X, p1.Y + p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2d operator -(Point2d p1, Point2d p2) + { + return new Point2d(p1.X - p2.X, p1.Y - p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2d operator *(Point2d pt, double scale) + { + return new Point2d((float) (pt.X*scale), (float) (pt.Y*scale)); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y})"; + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// + /// +#endif + public static double Distance(Point2d p1, Point2d p2) + { + return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)); + } + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// +#endif + public double DistanceTo(Point2d p) + { + return Distance(this, p); + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double DotProduct(Point2d p1, Point2d p2) + { + return p1.X*p2.X + p1.Y*p2.Y; + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// +#endif + public double DotProduct(Point2d p) + { + return DotProduct(this, p); + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double CrossProduct(Point2d p1, Point2d p2) + { + return p1.X*p2.Y - p2.X*p1.Y; + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// +#endif + public double CrossProduct(Point2d p) + { + return CrossProduct(this, p); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point2f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point2f.cs new file mode 100644 index 0000000..d75d618 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point2f.cs @@ -0,0 +1,422 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Point2f : IEquatable + { + /// + /// + /// + public float X; + + /// + /// + /// + public float Y; + + /// + /// + /// + public const int SizeOf = sizeof (float) + sizeof (float); + + /// + /// + /// + /// + /// + public Point2f(float x, float y) + { + X = x; + Y = y; + } + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator Point(Point2f self) + { + return new Point((int) self.X, (int) self.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Point2f(Point point) + { + return new Point2f(point.X, point.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Vec2f(Point2f point) + { + return new Vec2f(point.X, point.Y); + } + + /// + /// + /// + /// + /// + public static implicit operator Point2f(Vec2f vec) + { + return new Point2f(vec.Item0, vec.Item1); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point2f obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && Math.Abs(Y - obj.Y) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point2f lhs, Point2f rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point2f lhs, Point2f rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point2f operator +(Point2f pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point2f operator -(Point2f pt) + { + return new Point2f(-pt.X, -pt.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2f operator +(Point2f p1, Point2f p2) + { + return new Point2f(p1.X + p2.X, p1.Y + p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2f operator -(Point2f p1, Point2f p2) + { + return new Point2f(p1.X - p2.X, p1.Y - p2.Y); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point2f operator *(Point2f pt, double scale) + { + return new Point2f((float) (pt.X*scale), (float) (pt.Y*scale)); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y})"; + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// + /// +#endif + public static double Distance(Point2f p1, Point2f p2) + { + return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2)); + } + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// +#else + /// + /// Returns the distance between the specified two points + /// + /// + /// +#endif + public double DistanceTo(Point2f p) + { + return Distance(this, p); + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double DotProduct(Point2f p1, Point2f p2) + { + return p1.X*p2.X + p1.Y*p2.Y; + } + +#if LANG_JP + /// + /// ベクトルの内積を求める + /// + /// + /// +#else + /// + /// Calculates the dot product of two 2D vectors. + /// + /// + /// +#endif + public double DotProduct(Point2f p) + { + return DotProduct(this, p); + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// + /// +#endif + public static double CrossProduct(Point2f p1, Point2f p2) + { + return p1.X*p2.Y - p2.X*p1.Y; + } + +#if LANG_JP + /// + /// ベクトルの外積を求める + /// + /// + /// +#else + /// + /// Calculates the cross product of two 2D vectors. + /// + /// + /// +#endif + public double CrossProduct(Point2f p) + { + return CrossProduct(this, p); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point3d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3d.cs new file mode 100644 index 0000000..7dfd366 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3d.cs @@ -0,0 +1,312 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Point3d : IEquatable + { + /// + /// + /// + public double X; + + /// + /// + /// + public double Y; + + /// + /// + /// + public double Z; + + /// + /// + /// + public const int SizeOf = sizeof (double) + sizeof (double) + sizeof (double); + + /// + /// + /// + /// + /// + /// + public Point3d(double x, double y, double z) + { + X = x; + Y = y; + Z = z; + } + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator Point3i(Point3d self) + { + return new Point3i((int)self.X, (int)self.Y, (int)self.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Point3d(Point3i point) + { + return new Point3d(point.X, point.Y, point.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Vec3d(Point3d point) + { + return new Vec3d(point.X, point.Y, point.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Point3d(Vec3d vec) + { + return new Point3d(vec.Item0, vec.Item1, vec.Item2); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point3d obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && + Math.Abs(Y - obj.Y) < 1e-9 && + Math.Abs(Z - obj.Z) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point3d lhs, Point3d rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point3d lhs, Point3d rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point3d operator +(Point3d pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point3d operator -(Point3d pt) + { + return new Point3d(-pt.X, -pt.Y, -pt.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3d operator +(Point3d p1, Point3d p2) + { + return new Point3d(p1.X + p2.X, p1.Y + p2.Y, p1.Z + p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3d operator -(Point3d p1, Point3d p2) + { + return new Point3d(p1.X - p2.X, p1.Y - p2.Y, p1.Z - p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3d operator *(Point3d pt, double scale) + { + return new Point3d(pt.X*scale, pt.Y*scale, pt.Z*scale); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} z:{Z})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point3f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3f.cs new file mode 100644 index 0000000..dfe468c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3f.cs @@ -0,0 +1,313 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Point3f : IEquatable + { + /// + /// + /// + public float X; + + /// + /// + /// + public float Y; + + /// + /// + /// + public float Z; + + /// + /// + /// + public const int SizeOf = sizeof (float) + sizeof (float) + sizeof (float); + + /// + /// + /// + /// + /// + /// + public Point3f(float x, float y, float z) + { + X = x; + Y = y; + Z = z; + } + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator Point3i(Point3f self) + { + return new Point3i((int)self.X, (int)self.Y, (int)self.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Point3f(Point3i point) + { + return new Point3f(point.X, point.Y, point.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Vec3f(Point3f point) + { + return new Vec3f(point.X, point.Y, point.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Point3f(Vec3f vec) + { + return new Point3f(vec.Item0, vec.Item1, vec.Item2); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point3f obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && + Math.Abs(Y - obj.Y) < 1e-9 && + Math.Abs(Z - obj.Z) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point3f lhs, Point3f rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point3f lhs, Point3f rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point3f operator +(Point3f pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point3f operator -(Point3f pt) + { + return new Point3f(-pt.X, -pt.Y, -pt.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3f operator +(Point3f p1, Point3f p2) + { + return new Point3f(p1.X + p2.X, p1.Y + p2.Y, p1.Z + p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3f operator -(Point3f p1, Point3f p2) + { + return new Point3f(p1.X - p2.X, p1.Y - p2.Y, p1.Z - p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3f operator *(Point3f pt, double scale) + { + return new Point3f((float) (pt.X*scale), (float) (pt.Y*scale), (float) (pt.Z*scale)); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} z:{Z})"; + } + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Point3i.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3i.cs new file mode 100644 index 0000000..1ad811f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Point3i.cs @@ -0,0 +1,291 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Point3i : IEquatable + { + /// + /// + /// + public int X; + + /// + /// + /// + public int Y; + + /// + /// + /// + public int Z; + + /// + /// + /// + public const int SizeOf = sizeof (int) + sizeof (int) + sizeof (int); + + /// + /// + /// + /// + /// + /// + public Point3i(int x, int y, int z) + { + X = x; + Y = y; + Z = z; + } + + #region Cast + + /// + /// + /// + /// + /// + public static implicit operator Vec3i(Point3i point) + { + return new Vec3i(point.X, point.Y, point.Z); + } + + /// + /// + /// + /// + /// + public static implicit operator Point3i(Vec3i vec) + { + return new Point3i(vec.Item0, vec.Item1, vec.Item2); + } + + #endregion + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Point3i obj) + { + return (X == obj.X && Y == obj.Y && Z == obj.Z); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード。x,y座標値が等しければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the X and Y values of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Point3i lhs, Point3i rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード。x,y座標値が等しくなければtrueを返す + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false. +#endif + public static bool operator !=(Point3i lhs, Point3i rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// 単項プラス演算子 + /// + /// + /// +#else + /// + /// Unary plus operator + /// + /// + /// +#endif + public static Point3i operator +(Point3i pt) + { + return pt; + } + +#if LANG_JP + /// + /// 単項マイナス演算子 + /// + /// + /// +#else + /// + /// Unary minus operator + /// + /// + /// +#endif + public static Point3i operator -(Point3i pt) + { + return new Point3i(-pt.X, -pt.Y, -pt.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3i operator +(Point3i p1, Point3i p2) + { + return new Point3i(p1.X + p2.X, p1.Y + p2.Y, p1.Z + p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3i operator -(Point3i p1, Point3i p2) + { + return new Point3i(p1.X - p2.X, p1.Y - p2.Y, p1.Z - p2.Z); + } + +#if LANG_JP + /// + /// あるオフセットで点を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts point by a certain offset + /// + /// + /// + /// +#endif + public static Point3i operator *(Point3i pt, double scale) + { + return new Point3i((int) (pt.X*scale), (int) (pt.Y*scale), (int) (pt.Z*scale)); + } + + #endregion + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} z:{Z})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Range.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Range.cs new file mode 100644 index 0000000..e792803 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Range.cs @@ -0,0 +1,38 @@ +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [System.Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Range + { + /// + /// + /// + public int Start; + + /// + /// + /// + public int End; + + /// + /// + /// + /// + /// + public Range(int start, int end) + { + Start = start; + End = end; + } + + /// + /// + /// + public static Range All => new Range(int.MinValue, int.MaxValue); + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Rangef.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Rangef.cs new file mode 100644 index 0000000..41a3de6 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Rangef.cs @@ -0,0 +1,49 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// float Range class + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Rangef + { + /// + /// + /// + public float Start; + + /// + /// + /// + public float End; + + /// + /// Constructor + /// + /// + /// + public Rangef(float start, float end) + { + Start = start; + End = end; + } + + /// + /// Implicit operator (Range)this + /// + /// + /// + public static implicit operator Range(Rangef range) + { + return new Range((int)range.Start, (int)range.End); + } + + /// + /// Range(int.MinValue, int.MaxValue) + /// + public static Range All => new Range(int.MinValue, int.MaxValue); + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Rect.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect.cs new file mode 100644 index 0000000..ffd423c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect.cs @@ -0,0 +1,713 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// Stores a set of four integers that represent the location and size of a rectangle + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Rect : IEquatable + { + #region Field + + /// + /// + /// + public int X; + + /// + /// + /// + public int Y; + + /// + /// + /// + public int Width; + + /// + /// + /// + public int Height; + + /// + /// sizeof(Rect) + /// + public const int SizeOf = sizeof (int)*4; + +#if LANG_JP + /// + /// プロパティを初期化しない状態の Rect 構造体を表します。 + /// +#else + /// + /// Represents a Rect structure with its properties left uninitialized. + /// +#endif + public static readonly Rect Empty; + + #endregion + + /// + /// Initializes a new instance of the Rectangle class with the specified location and size. + /// + /// The x-coordinate of the upper-left corner of the rectangle. + /// The y-coordinate of the upper-left corner of the rectangle. + /// The width of the rectangle. + /// The height of the rectangle. + public Rect(int x, int y, int width, int height) + { + X = x; + Y = y; + Width = width; + Height = height; + } + + /// + /// Initializes a new instance of the Rectangle class with the specified location and size. + /// + /// A Point that represents the upper-left corner of the rectangular region. + /// A Size that represents the width and height of the rectangular region. + public Rect(Point location, Size size) + { + X = location.X; + Y = location.Y; + Width = size.Width; + Height = size.Height; + } + + /// + /// Creates a Rectangle structure with the specified edge locations. + /// + /// The x-coordinate of the upper-left corner of this Rectangle structure. + /// The y-coordinate of the upper-left corner of this Rectangle structure. + /// The x-coordinate of the lower-right corner of this Rectangle structure. + /// The y-coordinate of the lower-right corner of this Rectangle structure. +// ReSharper disable once InconsistentNaming + public static Rect FromLTRB(int left, int top, int right, int bottom) + { + var r = new Rect + { + X = left, + Y = top, + Width = right - left + 1, + Height = bottom - top + 1 + }; + + if (r.Width < 0) + throw new ArgumentException("right > left"); + if (r.Height < 0) + throw new ArgumentException("bottom > top"); + return r; + } + + #region Operators + + #region == / != + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Rect obj) + { + return (X == obj.X && Y == obj.Y && Width == obj.Width && Height == obj.Height); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two Rect objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Rect lhs, Rect rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two Rect objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Rect lhs, Rect rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region + / - + +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect operator +(Rect rect, Point pt) + { + return new Rect(rect.X + pt.X, rect.Y + pt.Y, rect.Width, rect.Height); + } + +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect operator -(Rect rect, Point pt) + { + return new Rect(rect.X - pt.X, rect.Y - pt.Y, rect.Width, rect.Height); + } + +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect operator +(Rect rect, Size size) + { + return new Rect(rect.X, rect.Y, rect.Width + size.Width, rect.Height + size.Height); + } + +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect operator -(Rect rect, Size size) + { + return new Rect(rect.X, rect.Y, rect.Width - size.Width, rect.Height - size.Height); + } + + #endregion + + #region & / | + +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect operator &(Rect a, Rect b) + { + return Intersect(a, b); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect structure that contains the union of two Rect structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect operator |(Rect a, Rect b) + { + return Union(a, b); + } + + #endregion + + #endregion + + #region Properties + +#if LANG_JP + /// + /// 上端のy座標 + /// +#else + /// + /// Gets the y-coordinate of the top edge of this Rect structure. + /// +#endif + public int Top + { + get { return Y; } + set { Y = value; } + } + +#if LANG_JP + /// + /// 下端のy座標 (Y + Height) + /// +#else + /// + /// Gets the y-coordinate that is the sum of the Y and Height property values of this Rect structure. + /// +#endif + public int Bottom + { + get { return Y + Height - 1; } + } + +#if LANG_JP + /// + /// 左端のx座標 + /// +#else + /// + /// Gets the x-coordinate of the left edge of this Rect structure. + /// +#endif + public int Left + { + get { return X; } + set { X = value; } + } + +#if LANG_JP + /// + /// 右端のx座標 (X + Width) + /// +#else + /// + /// Gets the x-coordinate that is the sum of X and Width property values of this Rect structure. + /// +#endif + public int Right + { + get { return X + Width - 1; } + } + +#if LANG_JP + /// + /// 矩形の左上頂点の位置 [Point(X, Y)] + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point(X, Y)] + /// +#endif + public Point Location + { + get { return new Point(X, Y); } + set + { + X = value.X; + Y = value.Y; + } + } + +#if LANG_JP + /// + /// 矩形の大きさ [CvSize(Width, Height)] + /// +#else + /// + /// Size of the rectangle [CvSize(Width, Height)] + /// +#endif + public Size Size + { + get { return new Size(Width, Height); } + set + { + Width = value.Width; + Height = value.Height; + } + } + +#if LANG_JP + /// + /// 左上の頂点 + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point(X, Y)] + /// +#endif + public Point TopLeft + { + get { return new Point(X, Y); } + } + +#if LANG_JP + /// + /// 右下の頂点 + /// +#else + /// + /// Coordinate of the right-most rectangle corner [Point(X+Width, Y+Height)] + /// +#endif + public Point BottomRight + { + get { return new Point(X + Width - 1, Y + Height - 1); } + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// x座標 + /// y座標 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// x-coordinate of the point + /// y-coordinate of the point + /// +#endif + public bool Contains(int x, int y) + { + return (X <= x && Y <= y && X + Width - 1 > x && Y + Height - 1 > y); + } + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// 点 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// point + /// +#endif + public bool Contains(Point pt) + { + return Contains(pt.X, pt.Y); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形に含まれているかどうかを判断する + /// + /// 矩形 + /// +#else + /// + /// Determines if the specified rectangle is contained within the rectangular region defined by this Rectangle. + /// + /// rectangle + /// +#endif + public bool Contains(Rect rect) + { + return X <= rect.X && + (rect.X + rect.Width) <= (X + Width) && + Y <= rect.Y && + (rect.Y + rect.Height) <= (Y + Height); + } + +#if LANG_JP + /// + /// このRectを指定の量だけ膨らませる + /// + /// 水平方向の膨張量 + /// 垂直方向の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. +#endif + public void Inflate(int width, int height) + { + X -= width; + Y -= height; + Width += (2*width); + Height += (2*height); + } + +#if LANG_JP + /// + /// このRectを指定の量だけ膨らませる + /// + /// この四角形の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this rectangle. +#endif + public void Inflate(Size size) + { + + Inflate(size.Width, size.Height); + } + +#if LANG_JP + /// + /// このRectを指定の量だけ膨らませる + /// + /// 対象の矩形 + /// 水平方向の膨張量 + /// 垂直方向の膨張量 + /// +#else + /// + /// Creates and returns an inflated copy of the specified Rect structure. + /// + /// The Rectangle with which to start. This rectangle is not modified. + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. + /// +#endif + public static Rect Inflate(Rect rect, int x, int y) + { + rect.Inflate(x, y); + return rect; + } + +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect Intersect(Rect a, Rect b) + { + var x1 = Math.Max(a.X, b.X); + var x2 = Math.Min(a.X + a.Width, b.X + b.Width); + var y1 = Math.Max(a.Y, b.Y); + var y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); + + if (x2 >= x1 && y2 >= y1) + return new Rect(x1, y1, x2 - x1, y2 - y1); + return Empty; + } + +#if LANG_JP + /// + /// 2 つの矩形の交差部分を表す矩形を取得する + /// + /// + /// +#else + /// + /// Determines the Rect structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// +#endif + public Rect Intersect(Rect rect) + { + return Intersect(this, rect); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形と交差するかどうか判定する + /// + /// 矩形 + /// +#else + /// + /// Determines if this rectangle intersects with rect. + /// + /// Rectangle + /// +#endif + public bool IntersectsWith(Rect rect) + { + return ( + (X < rect.X + rect.Width) && + (X + Width > rect.X) && + (Y < rect.Y + rect.Height) && + (Y + Height > rect.Y) + ); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// +#else + /// + /// Gets a Rect structure that contains the union of two Rect structures. + /// + /// A rectangle to union. + /// +#endif + public Rect Union(Rect rect) + { + return Union(this, rect); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect structure that contains the union of two Rect structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect Union(Rect a, Rect b) + { + var x1 = Math.Min(a.X, b.X); + var x2 = Math.Max(a.X + a.Width, b.X + b.Width); + var y1 = Math.Min(a.Y, b.Y); + var y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); + + return new Rect(x1, y1, x2 - x1, y2 - y1); + } + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Width.GetHashCode() ^ Height.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} width:{Width} height:{Height})"; + } + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2d.cs new file mode 100644 index 0000000..44df4a2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2d.cs @@ -0,0 +1,699 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Rect2d : IEquatable + { + #region Field + /// + /// + /// + public double X; + /// + /// + /// + public double Y; + /// + /// + /// + public double Width; + /// + /// + /// + public double Height; + /// + /// sizeof(Rect) + /// + public const int SizeOf = sizeof(double) * 4; + +#if LANG_JP + /// + /// プロパティを初期化しない状態の Rect2d 構造体を表します。 + /// +#else + /// + /// Represents a Rect2d structure with its properties left uninitialized. + /// +#endif + public static readonly Rect2d Empty; + + #endregion + + /// + /// + /// + /// + /// + /// + /// + public Rect2d(double x, double y, double width, double height) + { + X = x; + Y = y; + Width = width; + Height = height; + } + + /// + /// + /// + /// + /// + public Rect2d(Point2d location, Size2d size) + { + X = location.X; + Y = location.Y; + Width = size.Width; + Height = size.Height; + } + + /// + /// + /// + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public static Rect2d FromLTRB(double left, double top, double right, double bottom) + { + var r = new Rect2d + { + X = left, + Y = top, + Width = right - left + 1, + Height = bottom - top + 1 + }; + + if (r.Width < 0) + throw new ArgumentException("right > left"); + if (r.Height < 0) + throw new ArgumentException("bottom > top"); + return r; + } + + #region Operators + #region == / != +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Rect2d obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && + Math.Abs(Y - obj.Y) < 1e-9 && + Math.Abs(Width - obj.Width) < 1e-9 && + Math.Abs(Height - obj.Height) < 1e-9); + } +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two Rect2d objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Rect2d lhs, Rect2d rhs) + { + return lhs.Equals(rhs); + } +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two Rect2d objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Rect2d lhs, Rect2d rhs) + { + return !lhs.Equals(rhs); + } + #endregion + #region + / - +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect2d operator +(Rect2d rect, Point2d pt) + { + return new Rect2d(rect.X + pt.X, rect.Y + pt.Y, rect.Width, rect.Height); + } +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect2d operator -(Rect2d rect, Point2d pt) + { + return new Rect2d(rect.X - pt.X, rect.Y - pt.Y, rect.Width, rect.Height); + } + +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect2d operator +(Rect2d rect, Size2d size) + { + return new Rect2d(rect.X, rect.Y, rect.Width + size.Width, rect.Height + size.Height); + } +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect2d operator -(Rect2d rect, Size2d size) + { + return new Rect2d(rect.X, rect.Y, rect.Width - size.Width, rect.Height - size.Height); + } + #endregion + #region & / | +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect2d structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect2d operator &(Rect2d a, Rect2d b) + { + return Intersect(a, b); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect2d structure that contains the union of two Rect2d structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect2d operator |(Rect2d a, Rect2d b) + { + return Union(a, b); + } + #endregion + #endregion + + #region Properties +#if LANG_JP + /// + /// 上端のy座標 + /// +#else + /// + /// Gets the y-coordinate of the top edge of this Rect2d structure. + /// +#endif + public double Top + { + get { return Y; } + set { Y = value; } + } +#if LANG_JP + /// + /// 下端のy座標 (Y + Height) + /// +#else + /// + /// Gets the y-coordinate that is the sum of the Y and Height property values of this Rect2d structure. + /// +#endif + public double Bottom + { + get { return Y + Height - 1; } + } +#if LANG_JP + /// + /// 左端のx座標 + /// +#else + /// + /// Gets the x-coordinate of the left edge of this Rect2d structure. + /// +#endif + public double Left + { + get { return X; } + set { X = value; } + } +#if LANG_JP + /// + /// 右端のx座標 (X + Width) + /// +#else + /// + /// Gets the x-coordinate that is the sum of X and Width property values of this Rect2d structure. + /// +#endif + public double Right + { + get { return X + Width - 1; } + } + +#if LANG_JP + /// + /// 矩形の左上頂点の位置 [Point2d(X, Y)] + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point2d(X, Y)] + /// +#endif + public Point2d Location + { + get { return new Point2d(X, Y); } + set + { + X = value.X; + Y = value.Y; + } + } +#if LANG_JP + /// + /// 矩形の大きさ [CvSize(Width, Height)] + /// +#else + /// + /// Size of the rectangle [CvSize(Width, Height)] + /// +#endif + public Size2d Size + { + get { return new Size2d(Width, Height); } + set + { + Width = value.Width; + Height = value.Height; + } + } + +#if LANG_JP + /// + /// 左上の頂点 + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point2d(X, Y)] + /// +#endif + public Point2d TopLeft + { + get { return new Point2d(X, Y); } + } +#if LANG_JP + /// + /// 右下の頂点 + /// +#else + /// + /// Coordinate of the right-most rectangle corner [Point2d(X+Width, Y+Height)] + /// +#endif + public Point2d BottomRight + { + get { return new Point2d(X + Width - 1, Y + Height - 1); } + } + #endregion + + #region Methods + + /// + /// + /// + /// + public Rect ToRect() + { + return new Rect((int) X, (int) Y, (int) Width, (int) Height); + } + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// x座標 + /// y座標 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// x-coordinate of the point + /// y-coordinate of the point + /// +#endif + public bool Contains(double x, double y) + { + return (X <= x && Y <= y && X + Width - 1 > x && Y + Height - 1 > y); + } + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// 点 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// point + /// +#endif + public bool Contains(Point2d pt) + { + return Contains(pt.X, pt.Y); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形に含まれているかどうかを判断する + /// + /// 矩形 + /// +#else + /// + /// Determines if the specified rectangle is contained within the rectangular region defined by this Rectangle. + /// + /// rectangle + /// +#endif + public bool Contains(Rect2d rect) + { + return X <= rect.X && + (rect.X + rect.Width) <= (X + Width) && + Y <= rect.Y && + (rect.Y + rect.Height) <= (Y + Height); + } + +#if LANG_JP + /// + /// このRect2dを指定の量だけ膨らませる + /// + /// 水平方向の膨張量 + /// 垂直方向の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. +#endif + public void Inflate(double width, double height) + { + X -= width; + Y -= height; + Width += (2 * width); + Height += (2 * height); + } + +#if LANG_JP + /// + /// このRect2dを指定の量だけ膨らませる + /// + /// この四角形の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this rectangle. +#endif + public void Inflate(Size2d size) + { + + Inflate(size.Width, size.Height); + } + +#if LANG_JP + /// + /// このRect2dを指定の量だけ膨らませる + /// + /// 対象の矩形 + /// 水平方向の膨張量 + /// 垂直方向の膨張量 + /// +#else + /// + /// Creates and returns an inflated copy of the specified Rect2d structure. + /// + /// The Rectangle with which to start. This rectangle is not modified. + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. + /// +#endif + public static Rect Inflate(Rect rect, int x, int y) + { + rect.Inflate(x, y); + return rect; + } + +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect2d structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect2d Intersect(Rect2d a, Rect2d b) + { + var x1 = Math.Max(a.X, b.X); + var x2 = Math.Min(a.X + a.Width, b.X + b.Width); + var y1 = Math.Max(a.Y, b.Y); + var y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); + + if (x2 >= x1 && y2 >= y1) + return new Rect2d(x1, y1, x2 - x1, y2 - y1); + return Empty; + } + +#if LANG_JP + /// + /// 2 つの矩形の交差部分を表す矩形を取得する + /// + /// + /// +#else + /// + /// Determines the Rect2d structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// +#endif + public Rect2d Intersect(Rect2d rect) + { + return Intersect(this, rect); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形と交差するかどうか判定する + /// + /// 矩形 + /// +#else + /// + /// Determines if this rectangle intersects with rect. + /// + /// Rectangle + /// +#endif + public bool IntersectsWith(Rect2d rect) + { + return ( + (X < rect.X + rect.Width) && + (X + Width > rect.X) && + (Y < rect.Y + rect.Height) && + (Y + Height > rect.Y) + ); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// +#else + /// + /// Gets a Rect2d structure that contains the union of two Rect2d structures. + /// + /// A rectangle to union. + /// +#endif + public Rect2d Union(Rect2d rect) + { + return Union(this, rect); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect2d structure that contains the union of two Rect2d structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect2d Union(Rect2d a, Rect2d b) + { + var x1 = Math.Min(a.X, b.X); + var x2 = Math.Max(a.X + a.Width, b.X + b.Width); + var y1 = Math.Min(a.Y, b.Y); + var y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); + + return new Rect2d(x1, y1, x2 - x1, y2 - y1); + } + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Width.GetHashCode() ^ Height.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} width:{Width} height:{Height})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2f.cs new file mode 100644 index 0000000..3507ab0 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Rect2f.cs @@ -0,0 +1,696 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Rect2f : IEquatable + { + #region Field + /// + /// + /// + public float X; + /// + /// + /// + public float Y; + /// + /// + /// + public float Width; + /// + /// + /// + public float Height; + /// + /// sizeof(Rect) + /// + public const int SizeOf = sizeof(float) * 4; + +#if LANG_JP + /// + /// プロパティを初期化しない状態の Rect2f 構造体を表します。 + /// +#else + /// + /// Represents a Rect2f structure with its properties left uninitialized. + /// +#endif + public static readonly Rect2f Empty; + + #endregion + + /// + /// + /// + /// + /// + /// + /// + public Rect2f(float x, float y, float width, float height) + { + X = x; + Y = y; + Width = width; + Height = height; + } + + /// + /// + /// + /// + /// + public Rect2f(Point2f location, Size2f size) + { + X = location.X; + Y = location.Y; + Width = size.Width; + Height = size.Height; + } + + /// + /// + /// + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public static Rect2f FromLTRB(float left, float top, float right, float bottom) + { + var r = new Rect2f + { + X = left, + Y = top, + Width = right - left + 1, + Height = bottom - top + 1 + }; + + if (r.Width < 0) + throw new ArgumentException("right > left"); + if (r.Height < 0) + throw new ArgumentException("bottom > top"); + return r; + } + + #region Operators + #region == / != +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Rect2f obj) + { + return (Math.Abs(X - obj.X) < 1e-9 && + Math.Abs(Y - obj.Y) < 1e-9 && + Math.Abs(Width - obj.Width) < 1e-9 && + Math.Abs(Height - obj.Height) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two Rectf objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Rect2f lhs, Rect2f rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two Rectf objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Rect2f lhs, Rect2f rhs) + { + return !lhs.Equals(rhs); + } + #endregion + #region + / - +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect2f operator +(Rect2f rect, Point2f pt) + { + return new Rect2f(rect.X + pt.X, rect.Y + pt.Y, rect.Width, rect.Height); + } +#if LANG_JP + /// + /// あるオフセットで矩形を移動させる + /// + /// + /// + /// +#else + /// + /// Shifts rectangle by a certain offset + /// + /// + /// + /// +#endif + public static Rect2f operator -(Rect2f rect, Point2f pt) + { + return new Rect2f(rect.X - pt.X, rect.Y - pt.Y, rect.Width, rect.Height); + } + +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect2f operator +(Rect2f rect, Size2f size) + { + return new Rect2f(rect.X, rect.Y, rect.Width + size.Width, rect.Height + size.Height); + } +#if LANG_JP + /// + /// 指定したサイズ応じて、矩形を膨張または縮小する + /// + /// + /// + /// +#else + /// + /// Expands or shrinks rectangle by a certain amount + /// + /// + /// + /// +#endif + public static Rect2f operator -(Rect2f rect, Size2f size) + { + return new Rect2f(rect.X, rect.Y, rect.Width - size.Width, rect.Height - size.Height); + } + #endregion + #region & / | +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect2f structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect2f operator &(Rect2f a, Rect2f b) + { + return Intersect(a, b); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect2f structure that contains the union of two Rect2f structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect2f operator |(Rect2f a, Rect2f b) + { + return Union(a, b); + } + #endregion + #endregion + + #region Properties +#if LANG_JP + /// + /// 上端のy座標 + /// +#else + /// + /// Gets the y-coordinate of the top edge of this Rect2f structure. + /// +#endif + public float Top + { + get { return Y; } + set { Y = value; } + } + +#if LANG_JP + /// + /// 下端のy座標 (Y + Height) + /// +#else + /// + /// Gets the y-coordinate that is the sum of the Y and Height property values of this Rect2f structure. + /// +#endif + public float Bottom + { + get { return Y + Height - 1; } + } + +#if LANG_JP + /// + /// 左端のx座標 + /// +#else + /// + /// Gets the x-coordinate of the left edge of this Rect2f structure. + /// +#endif + public float Left + { + get { return X; } + set { X = value; } + } + +#if LANG_JP + /// + /// 右端のx座標 (X + Width) + /// +#else + /// + /// Gets the x-coordinate that is the sum of X and Width property values of this Rect2f structure. + /// +#endif + public float Right + { + get { return X + Width - 1; } + } + +#if LANG_JP + /// + /// 矩形の左上頂点の位置 [Point2f(X, Y)] + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point2f(X, Y)] + /// +#endif + public Point2f Location + { + get { return new Point2f(X, Y); } + set + { + X = value.X; + Y = value.Y; + } + } + +#if LANG_JP + /// + /// 矩形の大きさ [CvSize(Width, Height)] + /// +#else + /// + /// Size of the rectangle [CvSize(Width, Height)] + /// +#endif + public Size2f Size + { + get { return new Size2f(Width, Height); } + set + { + Width = value.Width; + Height = value.Height; + } + } + +#if LANG_JP + /// + /// 左上の頂点 + /// +#else + /// + /// Coordinate of the left-most rectangle corner [Point2f(X, Y)] + /// +#endif + public Point2f TopLeft + { + get { return new Point2f(X, Y); } + } + +#if LANG_JP + /// + /// 右下の頂点 + /// +#else + /// + /// Coordinate of the right-most rectangle corner [Point2f(X+Width, Y+Height)] + /// +#endif + public Point2f BottomRight + { + get { return new Point2f(X + Width - 1, Y + Height - 1); } + } + #endregion + + #region Methods + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// x座標 + /// y座標 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// x-coordinate of the point + /// y-coordinate of the point + /// +#endif + public bool Contains(float x, float y) + { + return (X <= x && Y <= y && X + Width - 1 > x && Y + Height - 1 > y); + } + +#if LANG_JP + /// + /// 指定した点がこの矩形に含まれているかどうかを判断する + /// + /// 点 + /// +#else + /// + /// Determines if the specified point is contained within the rectangular region defined by this Rectangle. + /// + /// point + /// +#endif + public bool Contains(Point2f pt) + { + return Contains(pt.X, pt.Y); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形に含まれているかどうかを判断する + /// + /// 矩形 + /// +#else + /// + /// Determines if the specified rectangle is contained within the rectangular region defined by this Rectangle. + /// + /// rectangle + /// +#endif + public bool Contains(Rect2f rect) + { + return X <= rect.X && + (rect.X + rect.Width) <= (X + Width) && + Y <= rect.Y && + (rect.Y + rect.Height) <= (Y + Height); + } + +#if LANG_JP + /// + /// このRect2fを指定の量だけ膨らませる + /// + /// 水平方向の膨張量 + /// 垂直方向の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. +#endif + public void Inflate(float width, float height) + { + X -= width; + Y -= height; + Width += (2 * width); + Height += (2 * height); + } + +#if LANG_JP + /// + /// このRect2fを指定の量だけ膨らませる + /// + /// この四角形の膨張量 +#else + /// + /// Inflates this Rect by the specified amount. + /// + /// The amount to inflate this rectangle. +#endif + public void Inflate(Size2f size) + { + + Inflate(size.Width, size.Height); + } + +#if LANG_JP + /// + /// このRect2fを指定の量だけ膨らませる + /// + /// 対象の矩形 + /// 水平方向の膨張量 + /// 垂直方向の膨張量 + /// +#else + /// + /// Creates and returns an inflated copy of the specified Rect2f structure. + /// + /// The Rectangle with which to start. This rectangle is not modified. + /// The amount to inflate this Rectangle horizontally. + /// The amount to inflate this Rectangle vertically. + /// +#endif + public static Rect Inflate(Rect rect, int x, int y) + { + rect.Inflate(x, y); + return rect; + } + +#if LANG_JP + /// + /// 2つの矩形の交差部分を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Determines the Rect2f structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// A rectangle to intersect. + /// +#endif + public static Rect2f Intersect(Rect2f a, Rect2f b) + { + var x1 = Math.Max(a.X, b.X); + var x2 = Math.Min(a.X + a.Width, b.X + b.Width); + var y1 = Math.Max(a.Y, b.Y); + var y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); + + if (x2 >= x1 && y2 >= y1) + return new Rect2f(x1, y1, x2 - x1, y2 - y1); + return Empty; + } + +#if LANG_JP + /// + /// 2 つの矩形の交差部分を表す矩形を取得する + /// + /// + /// +#else + /// + /// Determines the Rect2f structure that represents the intersection of two rectangles. + /// + /// A rectangle to intersect. + /// +#endif + public Rect2f Intersect(Rect2f rect) + { + return Intersect(this, rect); + } + +#if LANG_JP + /// + /// 指定した矩形がこの矩形と交差するかどうか判定する + /// + /// 矩形 + /// +#else + /// + /// Determines if this rectangle intersects with rect. + /// + /// Rectangle + /// +#endif + public bool IntersectsWith(Rect2f rect) + { + return ( + (X < rect.X + rect.Width) && + (X + Width > rect.X) && + (Y < rect.Y + rect.Height) && + (Y + Height > rect.Y) + ); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// +#else + /// + /// Gets a Rect2f structure that contains the union of two Rect2f structures. + /// + /// A rectangle to union. + /// +#endif + public Rect2f Union(Rect2f rect) + { + return Union(this, rect); + } + +#if LANG_JP + /// + /// 2つの矩形の和集合を表す矩形を取得する + /// + /// + /// + /// +#else + /// + /// Gets a Rect2f structure that contains the union of two Rect2f structures. + /// + /// A rectangle to union. + /// A rectangle to union. + /// +#endif + public static Rect2f Union(Rect2f a, Rect2f b) + { + var x1 = Math.Min(a.X, b.X); + var x2 = Math.Max(a.X + a.Width, b.X + b.Width); + var y1 = Math.Min(a.Y, b.Y); + var y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); + + return new Rect2f(x1, y1, x2 - x1, y2 - y1); + } + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return X.GetHashCode() ^ Y.GetHashCode() ^ Width.GetHashCode() ^ Height.GetHashCode(); + } +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(x:{X} y:{Y} width:{Width} height:{Height})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/RotatedRect.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/RotatedRect.cs new file mode 100644 index 0000000..58db96f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/RotatedRect.cs @@ -0,0 +1,86 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct RotatedRect + { + /// + /// sizeof(RotatedRect) + /// + public const int SizeOf = Point2f.SizeOf + Size2f.SizeOf + sizeof(float); + + /// + /// the rectangle mass center + /// + public Point2f Center; + + /// + /// width and height of the rectangle + /// + public Size2f Size; + + /// + /// the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. + /// + public float Angle; + + /// + /// + /// + /// + /// + /// + public RotatedRect(Point2f center, Size2f size, float angle) + { + Center = center; + Size = size; + Angle = angle; + } + + /// + /// returns 4 vertices of the rectangle + /// + /// + public Point2f[] Points() + { + var angle = Angle*Math.PI/180.0; + var b = (float) Math.Cos(angle)*0.5f; + var a = (float) Math.Sin(angle)*0.5f; + + var pt = new Point2f[4]; + pt[0].X = Center.X - a*Size.Height - b*Size.Width; + pt[0].Y = Center.Y + b*Size.Height - a*Size.Width; + pt[1].X = Center.X + a*Size.Height - b*Size.Width; + pt[1].Y = Center.Y - b*Size.Height - a*Size.Width; + pt[2].X = 2*Center.X - pt[0].X; + pt[2].Y = 2*Center.Y - pt[0].Y; + pt[3].X = 2*Center.X - pt[1].X; + pt[3].Y = 2*Center.Y - pt[1].Y; + return pt; + } + + /// + /// returns the minimal up-right rectangle containing the rotated rectangle + /// + /// + public Rect BoundingRect() + { + var pt = Points(); + var r = new Rect + { + X = (int)Math.Floor(Math.Min(Math.Min(Math.Min(pt[0].X, pt[1].X), pt[2].X), pt[3].X)), + Y = (int)Math.Floor(Math.Min(Math.Min(Math.Min(pt[0].Y, pt[1].Y), pt[2].Y), pt[3].Y)), + Width = (int)Math.Ceiling(Math.Max(Math.Max(Math.Max(pt[0].X, pt[1].X), pt[2].X), pt[3].X)), + Height = (int)Math.Ceiling(Math.Max(Math.Max(Math.Max(pt[0].Y, pt[1].Y), pt[2].Y), pt[3].Y)) + }; + r.Width -= r.X - 1; + r.Height -= r.Y - 1; + return r; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Scalar.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Scalar.cs new file mode 100644 index 0000000..e86e8cb --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Scalar.cs @@ -0,0 +1,1199 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// Template class for a 4-element vector derived from Vec. + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Scalar : IEquatable + { + #region Field + + /// + /// + /// + public double Val0; + + /// + /// + /// + public double Val1; + + /// + /// + /// + public double Val2; + + /// + /// + /// + public double Val3; + + /// + /// + /// + public double this[int i] + { + get + { + switch (i) + { + case 0: + return Val0; + case 1: + return Val1; + case 2: + return Val2; + case 3: + return Val3; + default: + throw new IndexOutOfRangeException(); + } + } + set + { + switch (i) + { + case 0: + Val0 = value; + break; + case 1: + Val1 = value; + break; + case 2: + Val2 = value; + break; + case 3: + Val3 = value; + break; + default: + throw new IndexOutOfRangeException(); + } + } + } + + #endregion + + #region Init + + /// + /// + /// + /// + public Scalar(double v0) + : this(v0, 0, 0, 0) + { + } + + /// + /// + /// + /// + /// + public Scalar(double v0, double v1) + : this(v0, v1, 0, 0) + { + } + + /// + /// + /// + /// + /// + /// + public Scalar(double v0, double v1, double v2) + : this(v0, v1, v2, 0) + { + } + + /// + /// + /// + /// + /// + /// + /// + public Scalar(double v0, double v1, double v2, double v3) + { + Val0 = v0; + Val1 = v1; + Val2 = v2; + Val3 = v3; + } + + /// + /// + /// + /// + /// + /// + public static Scalar FromRgb(int r, int g, int b) + { + return new Scalar(b, g, r); + } + + /// + /// + /// + public static Scalar RandomColor() + { + var buf = new byte[3]; + random.NextBytes(buf); + return new Scalar(buf[0], buf[1], buf[2]); + } + + private static readonly Random random = new Random(); + + #endregion + + #region Cast + + /// + /// + /// + /// + /// + public static explicit operator double(Scalar self) + { + return self.Val0; + } + + /// + /// + /// + /// + /// + public static implicit operator Scalar(double val) + { + return new Scalar(val); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(DMatch d) + { + return new Scalar(d.QueryIdx, d.TrainIdx, d.ImgIdx, d.Distance); + } + + /// + /// + /// + /// + /// + public static explicit operator DMatch(Scalar self) + { + return new DMatch((int) self.Val0, (int) self.Val1, (int) self.Val2, (float) self.Val3); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec3b v) + { + return new Scalar(v.Item0, v.Item1, v.Item2); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec3f v) + { + return new Scalar(v.Item0, v.Item1, v.Item2); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec4f v) + { + return new Scalar(v.Item0, v.Item1, v.Item2, v.Item3); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec6f v) + { + return new Scalar(v.Item0, v.Item1, v.Item2, v.Item3); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec3d v) + { + return new Scalar(v.Item0, v.Item1, v.Item2); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec4d v) + { + return new Scalar(v.Item0, v.Item1, v.Item2, v.Item3); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Vec6d v) + { + return new Scalar(v.Item0, v.Item1, v.Item2, v.Item3); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point p) + { + return new Scalar(p.X, p.Y); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point2f p) + { + return new Scalar(p.X, p.Y); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point2d p) + { + return new Scalar(p.X, p.Y); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point3i p) + { + return new Scalar(p.X, p.Y, p.Z); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point3f p) + { + return new Scalar(p.X, p.Y, p.Z); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Point3d p) + { + return new Scalar(p.X, p.Y, p.Z); + } + + /// + /// + /// + /// + /// + public static explicit operator Scalar(Rect p) + { + return new Scalar(p.X, p.Y, p.Width, p.Height); + } + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + var result = Val0.GetHashCode() ^ Val1.GetHashCode() ^ Val2.GetHashCode() ^ Val3.GetHashCode(); + return result; + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"[{Val0}, {Val1}, {Val2}, {Val3}]"; + } + + #endregion + + #region Operators + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Scalar s1, Scalar s2) + { + return s1.Equals(s2); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Scalar s1, Scalar s2) + { + return !s1.Equals(s2); + } + + #endregion + + #region Methods + + /// + /// + /// + /// + /// + public static Scalar All(double v) + { + return new Scalar(v, v, v, v); + } + + /// + /// + /// + /// + /// + /// + public Scalar Mul(Scalar it, double scale) + { + return new Scalar(Val0*it.Val0*scale, Val1*it.Val1*scale, + Val2*it.Val2*scale, Val3*it.Val3*scale); + } + + /// + /// + /// + /// + /// + public Scalar Mul(Scalar it) + { + return Mul(it, 1); + } + + /// + /// + /// + /// + public Scalar Conj() + { + return new Scalar(Val0, -Val1, -Val2, -Val3); + } + + /// + /// + /// + /// + public bool IsReal() + { + // ReSharper disable CompareOfFloatsByEqualityOperator + return Val1 == 0 && Val2 == 0 && Val3 == 0; + } + + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public readonly Vec3b ToVec3b() + { + return new Vec3b((byte)Val0, (byte)Val1, (byte)Val2); + } + + /// + /// + /// + /// + /// + public bool Equals(Scalar other) + { + return Math.Abs(Val0 - other.Val0) < 1e-9 && + Math.Abs(Val1 - other.Val1) < 1e-9 && + Math.Abs(Val2 - other.Val2) < 1e-9 && + Math.Abs(Val3 - other.Val3) < 1e-9; + } + + #endregion + + #region Existing Color Constants + + /// + /// #F0F8FF + /// + public static readonly Scalar AliceBlue = FromRgb(240, 248, 255); + + /// + /// #FAEBD7 + /// + public static readonly Scalar AntiqueWhite = FromRgb(250, 235, 215); + + /// + /// #00FFFF + /// + public static readonly Scalar Aqua = FromRgb(0, 255, 255); + + /// + /// #7FFFD4 + /// + public static readonly Scalar Aquamarine = FromRgb(127, 255, 212); + + /// + /// #F0FFFF + /// + public static readonly Scalar Azure = FromRgb(240, 255, 255); + + /// + /// #F5F5DC + /// + public static readonly Scalar Beige = FromRgb(245, 245, 220); + + /// + /// #FFE4C4 + /// + public static readonly Scalar Bisque = FromRgb(255, 228, 196); + + /// + /// #000000 + /// + public static readonly Scalar Black = FromRgb(0, 0, 0); + + /// + /// #FFEBCD + /// + public static readonly Scalar BlanchedAlmond = FromRgb(255, 235, 205); + + /// + /// #0000FF + /// + public static readonly Scalar Blue = FromRgb(0, 0, 255); + + /// + /// #8A2BE2 + /// + public static readonly Scalar BlueViolet = FromRgb(138, 43, 226); + + /// + /// #A52A2A + /// + public static readonly Scalar Brown = FromRgb(165, 42, 42); + + /// + /// #DEB887 + /// + public static readonly Scalar BurlyWood = FromRgb(222, 184, 135); + + /// + /// #5F9EA0 + /// + public static readonly Scalar CadetBlue = FromRgb(95, 158, 160); + + /// + /// #7FFF00 + /// + public static readonly Scalar Chartreuse = FromRgb(127, 255, 0); + + /// + /// #D2691E + /// + public static readonly Scalar Chocolate = FromRgb(210, 105, 30); + + /// + /// #FF7F50 + /// + public static readonly Scalar Coral = FromRgb(255, 127, 80); + + /// + /// #6495ED + /// + public static readonly Scalar CornflowerBlue = FromRgb(100, 149, 237); + + /// + /// #FFF8DC + /// + public static readonly Scalar Cornsilk = FromRgb(255, 248, 220); + + /// + /// #DC143C + /// + public static readonly Scalar Crimson = FromRgb(220, 20, 60); + + /// + /// #00FFFF + /// + public static readonly Scalar Cyan = FromRgb(0, 255, 255); + + /// + /// #00008B + /// + public static readonly Scalar DarkBlue = FromRgb(0, 0, 139); + + /// + /// #008B8B + /// + public static readonly Scalar DarkCyan = FromRgb(0, 139, 139); + + /// + /// #B8860B + /// + public static readonly Scalar DarkGoldenrod = FromRgb(184, 134, 11); + + /// + /// #A9A9A9 + /// + public static readonly Scalar DarkGray = FromRgb(169, 169, 169); + + /// + /// #006400 + /// + public static readonly Scalar DarkGreen = FromRgb(0, 100, 0); + + /// + /// #BDB76B + /// + public static readonly Scalar DarkKhaki = FromRgb(189, 183, 107); + + /// + /// #8B008B + /// + public static readonly Scalar DarkMagenta = FromRgb(139, 0, 139); + + /// + /// #556B2F + /// + public static readonly Scalar DarkOliveGreen = FromRgb(85, 107, 47); + + /// + /// #FF8C00 + /// + public static readonly Scalar DarkOrange = FromRgb(255, 140, 0); + + /// + /// #9932CC + /// + public static readonly Scalar DarkOrchid = FromRgb(153, 50, 204); + + /// + /// #8B0000 + /// + public static readonly Scalar DarkRed = FromRgb(139, 0, 0); + + /// + /// #E9967A + /// + public static readonly Scalar DarkSalmon = FromRgb(233, 150, 122); + + /// + /// #8FBC8F + /// + public static readonly Scalar DarkSeaGreen = FromRgb(143, 188, 139); + + /// + /// #483D8B + /// + public static readonly Scalar DarkSlateBlue = FromRgb(72, 61, 139); + + /// + /// #2F4F4F + /// + public static readonly Scalar DarkSlateGray = FromRgb(47, 79, 79); + + /// + /// #00CED1 + /// + public static readonly Scalar DarkTurquoise = FromRgb(0, 206, 209); + + /// + /// #9400D3 + /// + public static readonly Scalar DarkViolet = FromRgb(148, 0, 211); + + /// + /// #FF1493 + /// + public static readonly Scalar DeepPink = FromRgb(255, 20, 147); + + /// + /// #00BFFF + /// + public static readonly Scalar DeepSkyBlue = FromRgb(0, 191, 255); + + /// + /// #696969 + /// + public static readonly Scalar DimGray = FromRgb(105, 105, 105); + + /// + /// #1E90FF + /// + public static readonly Scalar DodgerBlue = FromRgb(30, 144, 255); + + /// + /// #B22222 + /// + public static readonly Scalar Firebrick = FromRgb(178, 34, 34); + + /// + /// #FFFAF0 + /// + public static readonly Scalar FloralWhite = FromRgb(255, 250, 240); + + /// + /// #228B22 + /// + public static readonly Scalar ForestGreen = FromRgb(34, 139, 34); + + /// + /// #FF00FF + /// + public static readonly Scalar Fuchsia = FromRgb(255, 0, 255); + + /// + /// #DCDCDC + /// + public static readonly Scalar Gainsboro = FromRgb(220, 220, 220); + + /// + /// #F8F8FF + /// + public static readonly Scalar GhostWhite = FromRgb(248, 248, 255); + + /// + /// #FFD700 + /// + public static readonly Scalar Gold = FromRgb(255, 215, 0); + + /// + /// #DAA520 + /// + public static readonly Scalar Goldenrod = FromRgb(218, 165, 32); + + /// + /// #808080 + /// + public static readonly Scalar Gray = FromRgb(128, 128, 128); + + /// + /// #008000 + /// + public static readonly Scalar Green = FromRgb(0, 128, 0); + + /// + /// #ADFF2F + /// + public static readonly Scalar GreenYellow = FromRgb(173, 255, 47); + + /// + /// #F0FFF0 + /// + public static readonly Scalar Honeydew = FromRgb(240, 255, 240); + + /// + /// #FF69B4 + /// + public static readonly Scalar HotPink = FromRgb(255, 105, 180); + + /// + /// #CD5C5C + /// + public static readonly Scalar IndianRed = FromRgb(205, 92, 92); + + /// + /// #4B0082 + /// + public static readonly Scalar Indigo = FromRgb(75, 0, 130); + + /// + /// #FFFFF0 + /// + public static readonly Scalar Ivory = FromRgb(255, 255, 240); + + /// + /// #F0E68C + /// + public static readonly Scalar Khaki = FromRgb(240, 230, 140); + + /// + /// #E6E6FA + /// + public static readonly Scalar Lavender = FromRgb(230, 230, 250); + + /// + /// #FFF0F5 + /// + public static readonly Scalar LavenderBlush = FromRgb(255, 240, 245); + + /// + /// #7CFC00 + /// + public static readonly Scalar LawnGreen = FromRgb(124, 252, 0); + + /// + /// #FFFACD + /// + public static readonly Scalar LemonChiffon = FromRgb(255, 250, 205); + + /// + /// #ADD8E6 + /// + public static readonly Scalar LightBlue = FromRgb(173, 216, 230); + + /// + /// #F08080 + /// + public static readonly Scalar LightCoral = FromRgb(240, 128, 128); + + /// + /// #E0FFFF + /// + public static readonly Scalar LightCyan = FromRgb(224, 255, 255); + + /// + /// #FAFAD2 + /// + public static readonly Scalar LightGoldenrodYellow = FromRgb(250, 250, 210); + + /// + /// #D3D3D3 + /// + public static readonly Scalar LightGray = FromRgb(211, 211, 211); + + /// + /// #90EE90 + /// + public static readonly Scalar LightGreen = FromRgb(144, 238, 144); + + /// + /// #FFB6C1 + /// + public static readonly Scalar LightPink = FromRgb(255, 182, 193); + + /// + /// #FFA07A + /// + public static readonly Scalar LightSalmon = FromRgb(255, 160, 122); + + /// + /// #20B2AA + /// + public static readonly Scalar LightSeaGreen = FromRgb(32, 178, 170); + + /// + /// #87CEFA + /// + public static readonly Scalar LightSkyBlue = FromRgb(135, 206, 250); + + /// + /// #778899 + /// + public static readonly Scalar LightSlateGray = FromRgb(119, 136, 153); + + /// + /// #B0C4DE + /// + public static readonly Scalar LightSteelBlue = FromRgb(176, 196, 222); + + /// + /// #FFFFE0 + /// + public static readonly Scalar LightYellow = FromRgb(255, 255, 224); + + /// + /// #00FF00 + /// + public static readonly Scalar Lime = FromRgb(0, 255, 0); + + /// + /// #32CD32 + /// + public static readonly Scalar LimeGreen = FromRgb(50, 205, 50); + + /// + /// #FAF0E6 + /// + public static readonly Scalar Linen = FromRgb(250, 240, 230); + + /// + /// #FF00FF + /// + public static readonly Scalar Magenta = FromRgb(255, 0, 255); + + /// + /// #800000 + /// + public static readonly Scalar Maroon = FromRgb(128, 0, 0); + + /// + /// #66CDAA + /// + public static readonly Scalar MediumAquamarine = FromRgb(102, 205, 170); + + /// + /// #0000CD + /// + public static readonly Scalar MediumBlue = FromRgb(0, 0, 205); + + /// + /// #BA55D3 + /// + public static readonly Scalar MediumOrchid = FromRgb(186, 85, 211); + + /// + /// #9370DB + /// + public static readonly Scalar MediumPurple = FromRgb(147, 112, 219); + + /// + /// #3CB371 + /// + public static readonly Scalar MediumSeaGreen = FromRgb(60, 179, 113); + + /// + /// #7B68EE + /// + public static readonly Scalar MediumSlateBlue = FromRgb(123, 104, 238); + + /// + /// #00FA9A + /// + public static readonly Scalar MediumSpringGreen = FromRgb(0, 250, 154); + + /// + /// #48D1CC + /// + public static readonly Scalar MediumTurquoise = FromRgb(72, 209, 204); + + /// + /// #C71585 + /// + public static readonly Scalar MediumVioletRed = FromRgb(199, 21, 133); + + /// + /// #191970 + /// + public static readonly Scalar MidnightBlue = FromRgb(25, 25, 112); + + /// + /// #F5FFFA + /// + public static readonly Scalar MintCream = FromRgb(245, 255, 250); + + /// + /// #FFE4E1 + /// + public static readonly Scalar MistyRose = FromRgb(255, 228, 225); + + /// + /// #FFE4B5 + /// + public static readonly Scalar Moccasin = FromRgb(255, 228, 181); + + /// + /// #FFDEAD + /// + public static readonly Scalar NavajoWhite = FromRgb(255, 222, 173); + + /// + /// #000080 + /// + public static readonly Scalar Navy = FromRgb(0, 0, 128); + + /// + /// #FDF5E6 + /// + public static readonly Scalar OldLace = FromRgb(253, 245, 230); + + /// + /// #808000 + /// + public static readonly Scalar Olive = FromRgb(128, 128, 0); + + /// + /// #6B8E23 + /// + public static readonly Scalar OliveDrab = FromRgb(107, 142, 35); + + /// + /// #FFA500 + /// + public static readonly Scalar Orange = FromRgb(255, 165, 0); + + /// + /// #FF4500 + /// + public static readonly Scalar OrangeRed = FromRgb(255, 69, 0); + + /// + /// #DA70D6 + /// + public static readonly Scalar Orchid = FromRgb(218, 112, 214); + + /// + /// #EEE8AA + /// + public static readonly Scalar PaleGoldenrod = FromRgb(238, 232, 170); + + /// + /// #98FB98 + /// + public static readonly Scalar PaleGreen = FromRgb(152, 251, 152); + + /// + /// #AFEEEE + /// + public static readonly Scalar PaleTurquoise = FromRgb(175, 238, 238); + + /// + /// #DB7093 + /// + public static readonly Scalar PaleVioletRed = FromRgb(219, 112, 147); + + /// + /// #FFEFD5 + /// + public static readonly Scalar PapayaWhip = FromRgb(255, 239, 213); + + /// + /// #FFDAB9 + /// + public static readonly Scalar PeachPuff = FromRgb(255, 218, 185); + + /// + /// #CD853F + /// + public static readonly Scalar Peru = FromRgb(205, 133, 63); + + /// + /// #FFC0CB + /// + public static readonly Scalar Pink = FromRgb(255, 192, 203); + + /// + /// #DDA0DD + /// + public static readonly Scalar Plum = FromRgb(221, 160, 221); + + /// + /// #B0E0E6 + /// + public static readonly Scalar PowderBlue = FromRgb(176, 224, 230); + + /// + /// #800080 + /// + public static readonly Scalar Purple = FromRgb(128, 0, 128); + + /// + /// #FF0000 + /// + public static readonly Scalar Red = FromRgb(255, 0, 0); + + /// + /// #BC8F8F + /// + public static readonly Scalar RosyBrown = FromRgb(188, 143, 143); + + /// + /// #4169E1 + /// + public static readonly Scalar RoyalBlue = FromRgb(65, 105, 225); + + /// + /// #8B4513 + /// + public static readonly Scalar SaddleBrown = FromRgb(139, 69, 19); + + /// + /// #FA8072 + /// + public static readonly Scalar Salmon = FromRgb(250, 128, 114); + + /// + /// #F4A460 + /// + public static readonly Scalar SandyBrown = FromRgb(244, 164, 96); + + /// + /// #2E8B57 + /// + public static readonly Scalar SeaGreen = FromRgb(46, 139, 87); + + /// + /// #FFF5EE + /// + public static readonly Scalar SeaShell = FromRgb(255, 245, 238); + + /// + /// #A0522D + /// + public static readonly Scalar Sienna = FromRgb(160, 82, 45); + + /// + /// #C0C0C0 + /// + public static readonly Scalar Silver = FromRgb(192, 192, 192); + + /// + /// #87CEEB + /// + public static readonly Scalar SkyBlue = FromRgb(135, 206, 235); + + /// + /// #6A5ACD + /// + public static readonly Scalar SlateBlue = FromRgb(106, 90, 205); + + /// + /// #708090 + /// + public static readonly Scalar SlateGray = FromRgb(112, 128, 144); + + /// + /// #FFFAFA + /// + public static readonly Scalar Snow = FromRgb(255, 250, 250); + + /// + /// #00FF7F + /// + public static readonly Scalar SpringGreen = FromRgb(0, 255, 127); + + /// + /// #4682B4 + /// + public static readonly Scalar SteelBlue = FromRgb(70, 130, 180); + + /// + /// #D2B48C + /// + public static readonly Scalar Tan = FromRgb(210, 180, 140); + + /// + /// #008080 + /// + public static readonly Scalar Teal = FromRgb(0, 128, 128); + + /// + /// #D8BFD8 + /// + public static readonly Scalar Thistle = FromRgb(216, 191, 216); + + /// + /// #FF6347 + /// + public static readonly Scalar Tomato = FromRgb(255, 99, 71); + + /// + /// #40E0D0 + /// + public static readonly Scalar Turquoise = FromRgb(64, 224, 208); + + /// + /// #EE82EE + /// + public static readonly Scalar Violet = FromRgb(238, 130, 238); + + /// + /// #F5DEB3 + /// + public static readonly Scalar Wheat = FromRgb(245, 222, 179); + + /// + /// #FFFFFF + /// + public static readonly Scalar White = FromRgb(255, 255, 255); + + /// + /// #F5F5F5 + /// + public static readonly Scalar WhiteSmoke = FromRgb(245, 245, 245); + + /// + /// #FFFF00 + /// + public static readonly Scalar Yellow = FromRgb(255, 255, 0); + + /// + /// #9ACD32 + /// + public static readonly Scalar YellowGreen = FromRgb(154, 205, 50); + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Size.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Size.cs new file mode 100644 index 0000000..5592a50 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Size.cs @@ -0,0 +1,157 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Size : IEquatable + { + /// + /// + /// + public int Width; + /// + /// + /// + public int Height; + + /// + /// + /// + /// + /// + public Size(int width, int height) + { + Width = width; + Height = height; + } + + /// + /// + /// + /// + /// + public Size(double width, double height) + { + Width = (int)width; + Height = (int)height; + } + + /// + /// Zero size + /// + public static readonly Size Zero; + + #region Operators +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Size obj) + { + return (Width == obj.Width && Height == obj.Height); + } +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Size lhs, Size rhs) + { + return lhs.Equals(rhs); + } +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Size lhs, Size rhs) + { + return !lhs.Equals(rhs); + } + #endregion + + #region Override +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return Width.GetHashCode() ^ Height.GetHashCode(); + } +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(width:{Width} height:{Height})"; + } + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Size2d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Size2d.cs new file mode 100644 index 0000000..41af72b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Size2d.cs @@ -0,0 +1,162 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Size2d : IEquatable + { + /// + /// + /// + public double Width; + + /// + /// + /// + public double Height; + + /// + /// + /// + /// + /// + public Size2d(float width, float height) + { + Width = width; + Height = height; + } + + /// + /// + /// + /// + /// + public Size2d(double width, double height) + { + Width = width; + Height = height; + } + + #region Operators + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Size2d obj) + { + return (Math.Abs(Width - obj.Width) < 1e-9 && + Math.Abs(Height - obj.Height) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Size2d lhs, Size2d rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Size2d lhs, Size2d rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return Width.GetHashCode() ^ Height.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(width:{Width} height:{Height})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Size2f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Size2f.cs new file mode 100644 index 0000000..bb41378 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Size2f.cs @@ -0,0 +1,168 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Size2f : IEquatable + { + /// + /// sizeof(Size2f) + /// + public const int SizeOf = sizeof(int) * 2; + + /// + /// + /// + public float Width; + + /// + /// + /// + public float Height; + + /// + /// + /// + /// + /// + public Size2f(float width, float height) + { + Width = width; + Height = height; + } + + /// + /// + /// + /// + /// + public Size2f(double width, double height) + { + Width = (float) width; + Height = (float) height; + } + + #region Operators + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(Size2f obj) + { + return (Math.Abs(Width - obj.Width) < 1e-9 && + Math.Abs(Height - obj.Height) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(Size2f lhs, Size2f rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(Size2f lhs, Size2f rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region Override + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return Width.GetHashCode() ^ Height.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"(width:{Width} height:{Height})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/TermCriteria.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/TermCriteria.cs new file mode 100644 index 0000000..a30473c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/TermCriteria.cs @@ -0,0 +1,52 @@ +namespace OpenCvSharp +{ + /// + /// The class defining termination criteria for iterative algorithms. + /// + public struct TermCriteria + { + /// + /// the type of termination criteria: COUNT, EPS or COUNT + EPS + /// + public CriteriaType Type; + + /// + /// the maximum number of iterations/elements + /// + public int MaxCount; + + /// + /// the desired accuracy + /// + public double Epsilon; + + /// + /// full constructor + /// + /// + /// + /// + public TermCriteria(CriteriaType type, int maxCount, double epsilon) + : this() + { + Type = type; + MaxCount = maxCount; + Epsilon = epsilon; + } + + /// + /// full constructor with both type (count | epsilon) + /// + /// + /// + public static TermCriteria Both(int maxCount, double epsilon) + { + return new TermCriteria + { + Type = CriteriaType.Count | CriteriaType.Eps, + MaxCount = maxCount, + Epsilon = epsilon, + }; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/IVec.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/IVec.cs new file mode 100644 index 0000000..1f04faf --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/IVec.cs @@ -0,0 +1,16 @@ +namespace OpenCvSharp +{ + /// + /// + /// + /// + public interface IVec where T : struct + { + /// + /// + /// + /// + /// + T this[int i] { get; set; } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2b.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2b.cs new file mode 100644 index 0000000..da1d768 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2b.cs @@ -0,0 +1,128 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of byte (System.Byte) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec2b : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public byte Item0; + + /// + /// The value of the second component of this object. + /// + public byte Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out byte item0, out byte item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2b(byte item0, byte item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public byte this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2b other) + { + return Item0 == other.Item0 && Item1 == other.Item1; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2b v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2b a, Vec2b b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2b a, Vec2b b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0.GetHashCode() * 397) ^ Item1.GetHashCode(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2d.cs new file mode 100644 index 0000000..a0f1140 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2d.cs @@ -0,0 +1,126 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of double (System.Double) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vec2d : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public double Item0; + /// + /// The value of the second component of this object. + /// + public double Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out double item0, out double item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2d(double item0, double item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public double this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2d other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2d v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2d a, Vec2d b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2d a, Vec2d b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0.GetHashCode() * 397) ^ Item1.GetHashCode(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2f.cs new file mode 100644 index 0000000..c06df23 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2f.cs @@ -0,0 +1,127 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of float (System.Single) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec2f : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public float Item0; + /// + /// The value of the second component of this object. + /// + public float Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out float item0, out float item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2f(float item0, float item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public float this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2f other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2f v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2f a, Vec2f b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2f a, Vec2f b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0.GetHashCode() * 397) ^ Item1.GetHashCode(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2i.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2i.cs new file mode 100644 index 0000000..e6f0210 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2i.cs @@ -0,0 +1,127 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of int (System.Int32) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec2i : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public int Item0; + /// + /// The value of the second component of this object. + /// + public int Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out int item0, out int item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2i(int item0, int item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public int this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2i other) + { + return Item0 == other.Item0 && Item1 == other.Item1; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2i v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2i a, Vec2i b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2i a, Vec2i b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0 * 397) ^ Item1; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2s.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2s.cs new file mode 100644 index 0000000..7cd6a38 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2s.cs @@ -0,0 +1,134 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of short (System.Int16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec2s : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public short Item0; + + /// + /// The value of the second component of this object. + /// + public short Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out short item0, out short item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2s(short item0, short item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public short this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2s other) + { + return Item0 == other.Item0 && Item1 == other.Item1; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2s v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2s a, Vec2s b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2s a, Vec2s b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0.GetHashCode() * 397) ^ Item1.GetHashCode(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2w.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2w.cs new file mode 100644 index 0000000..e3f7da6 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec2w.cs @@ -0,0 +1,134 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 2-Tuple of ushort (System.UInt16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec2w : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public ushort Item0; + + /// + /// The value of the second component of this object. + /// + public ushort Item1; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + public void Deconstruct(out ushort item0, out ushort item1) => (item0, item1) = (Item0, Item1); +#endif + + /// + /// Initializer + /// + /// + /// + public Vec2w(ushort item0, ushort item1) + { + Item0 = item0; + Item1 = item1; + } + + /// + /// Indexer + /// + /// + /// + public ushort this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec2w other) + { + return Item0 == other.Item0 && Item1 == other.Item1; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec2w w && Equals(w); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec2w a, Vec2w b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec2w a, Vec2w b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + return (Item0.GetHashCode() * 397) ^ Item1.GetHashCode(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3b.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3b.cs new file mode 100644 index 0000000..7749e8b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3b.cs @@ -0,0 +1,141 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of byte (System.Byte) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec3b : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public byte Item0; + + /// + /// The value of the second component of this object. + /// + public byte Item1; + + /// + /// The value of the third component of this object. + /// + public byte Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out byte item0, out byte item1, out byte item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3b(byte item0, byte item1, byte item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public byte this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3b other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3b b && Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3b a, Vec3b b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3b a, Vec3b b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3d.cs new file mode 100644 index 0000000..6f58b0d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3d.cs @@ -0,0 +1,140 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of double (System.Double) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vec3d : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public double Item0; + + /// + /// The value of the second component of this object. + /// + public double Item1; + + /// + /// The value of the third component of this object. + /// + public double Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out double item0, out double item1, out double item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3d(double item0, double item1, double item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public double this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3d other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3d v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3d a, Vec3d b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3d a, Vec3d b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3f.cs new file mode 100644 index 0000000..6014380 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3f.cs @@ -0,0 +1,141 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of float (System.Single) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec3f : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public float Item0; + + /// + /// The value of the second component of this object. + /// + public float Item1; + + /// + /// The value of the third component of this object. + /// + public float Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out float item0, out float item1, out float item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3f(float item0, float item1, float item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public float this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3f other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3f v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3f a, Vec3f b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3f a, Vec3f b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3i.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3i.cs new file mode 100644 index 0000000..cca8417 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3i.cs @@ -0,0 +1,141 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of int (System.Int32) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec3i : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public int Item0; + + /// + /// The value of the second component of this object. + /// + public int Item1; + + /// + /// The value of the third component of this object. + /// + public int Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out int item0, out int item1, out int item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3i(int item0, int item1, int item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public int this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3i other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3i v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3i a, Vec3i b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3i a, Vec3i b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0; + hashCode = (hashCode * 397) ^ Item1; + hashCode = (hashCode * 397) ^ Item2; + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3s.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3s.cs new file mode 100644 index 0000000..5e95360 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3s.cs @@ -0,0 +1,150 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of short (System.Int16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec3s : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public short Item0; + + /// + /// The value of the second component of this object. + /// + public short Item1; + + /// + /// The value of the third component of this object. + /// + public short Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out short item0, out short item1, out short item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3s(short item0, short item1, short item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public short this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3s other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3s v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3s a, Vec3s b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3s a, Vec3s b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3w.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3w.cs new file mode 100644 index 0000000..5fe3328 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec3w.cs @@ -0,0 +1,150 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 3-Tuple of ushort (System.UInt16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec3w : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public ushort Item0; + + /// + /// The value of the second component of this object. + /// + public ushort Item1; + + /// + /// The value of the third component of this object. + /// + public ushort Item2; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + public void Deconstruct(out ushort item0, out ushort item1, out ushort item2) => (item0, item1, item2) = (Item0, Item1, Item2); +#endif + + /// + /// Initializer + /// + /// + /// + /// + public Vec3w(ushort item0, ushort item1, ushort item2) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + } + + /// + /// Indexer + /// + /// + /// + public ushort this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec3w other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec3w v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec3w a, Vec3w b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec3w a, Vec3w b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4b.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4b.cs new file mode 100644 index 0000000..ef6367c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4b.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of byte (System.Byte) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec4b : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public byte Item0; + + /// + /// The value of the second component of this object. + /// + public byte Item1; + + /// + /// The value of the third component of this object. + /// + public byte Item2; + + /// + /// The value of the fourth component of this object. + /// + public byte Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out byte item0, out byte item1, out byte item2, out byte item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4b(byte item0, byte item1, byte item2, byte item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public byte this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4b other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4b v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4b a, Vec4b b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4b a, Vec4b b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4d.cs new file mode 100644 index 0000000..9e724cf --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4d.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of double (System.Double) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vec4d : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public double Item0; + + /// + /// The value of the second component of this object. + /// + public double Item1; + + /// + /// The value of the third component of this object. + /// + public double Item2; + + /// + /// The value of the fourth component of this object. + /// + public double Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out double item0, out double item1, out double item2, out double item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4d(double item0, double item1, double item2, double item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public double this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4d other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2) && Item3.Equals(other.Item3); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4d v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4d a, Vec4d b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4d a, Vec4d b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4f.cs new file mode 100644 index 0000000..157a5d8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4f.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of float (System.Single) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec4f : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public float Item0; + + /// + /// The value of the second component of this object. + /// + public float Item1; + + /// + /// The value of the third component of this object. + /// + public float Item2; + + /// + /// The value of the fourth component of this object. + /// + public float Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out float item0, out float item1, out float item2, out float item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4f(float item0, float item1, float item2, float item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public float this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4f other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2) && Item3.Equals(other.Item3); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4f v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4f a, Vec4f b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4f a, Vec4f b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4i.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4i.cs new file mode 100644 index 0000000..bb9b4a0 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4i.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of int (System.Int32) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec4i : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public int Item0; + + /// + /// The value of the second component of this object. + /// + public int Item1; + + /// + /// The value of the third component of this object. + /// + public int Item2; + + /// + /// The value of the fourth component of this object. + /// + public int Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out int item0, out int item1, out int item2, out int item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4i(int item0, int item1, int item2, int item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public int this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4i other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4i v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4i a, Vec4i b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4i a, Vec4i b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0; + hashCode = (hashCode * 397) ^ Item1; + hashCode = (hashCode * 397) ^ Item2; + hashCode = (hashCode * 397) ^ Item3; + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4s.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4s.cs new file mode 100644 index 0000000..ffea7c8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4s.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of short (System.Int16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec4s : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public short Item0; + + /// + /// The value of the second component of this object. + /// + public short Item1; + + /// + /// The value of the third component of this object. + /// + public short Item2; + + /// + /// The value of the fourth component of this object. + /// + public short Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out short item0, out short item1, out short item2, out short item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4s(short item0, short item1, short item2, short item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public short this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + case 3: + return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + case 3: + Item3 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4s other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4s v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4s a, Vec4s b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4s a, Vec4s b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4w.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4w.cs new file mode 100644 index 0000000..233cc42 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec4w.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of ushort (System.UInt16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec4w : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public ushort Item0; + + /// + /// The value of the second component of this object. + /// + public ushort Item1; + + /// + /// The value of the third component of this object. + /// + public ushort Item2; + + /// + /// The value of the fourth component of this object. + /// + public ushort Item3; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + public void Deconstruct(out ushort item0, out ushort item1, out ushort item2, out ushort item3) => (item0, item1, item2, item3) = (Item0, Item1, Item2, Item3); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + public Vec4w(ushort item0, ushort item1, ushort item2, ushort item3) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + } + + /// + /// Indexer + /// + /// + /// + public ushort this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + case 3: + return Item3; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + case 3: + Item3 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec4w other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec4w v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec4w a, Vec4w b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec4w a, Vec4w b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6b.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6b.cs new file mode 100644 index 0000000..be37fb6 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6b.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 6-Tuple of byte (System.Byte) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec6b : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public byte Item0; + + /// + /// The value of the second component of this object. + /// + public byte Item1; + + /// + /// The value of the third component of this object. + /// + public byte Item2; + + /// + /// The value of the fourth component of this object. + /// + public byte Item3; + + /// + /// The value of the fifth component of this object. + /// + public byte Item4; + + /// + /// The value of the sizth component of this object. + /// + public byte Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out byte item0, out byte item1, out byte item2, out byte item3, out byte item4, out byte item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6b(byte item0, byte item1, byte item2, byte item3, byte item4, byte item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public byte this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + case 4: return Item4; + case 5: return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + case 4: Item4 = value; break; + case 5: Item5 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6b other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3 && Item4 == other.Item4 && Item5 == other.Item5; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6b v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6b a, Vec6b b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6b a, Vec6b b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + hashCode = (hashCode * 397) ^ Item4.GetHashCode(); + hashCode = (hashCode * 397) ^ Item5.GetHashCode(); + return hashCode; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6d.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6d.cs new file mode 100644 index 0000000..45605e4 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6d.cs @@ -0,0 +1,173 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 6-Tuple of double (System.Double) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vec6d : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public double Item0; + + /// + /// The value of the second component of this object. + /// + public double Item1; + + /// + /// The value of the third component of this object. + /// + public double Item2; + + /// + /// The value of the fourth component of this object. + /// + public double Item3; + + /// + /// The value of the fifth component of this object. + /// + public double Item4; + + /// + /// The value of the sixth component of this object. + /// + public double Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out double item0, out double item1, out double item2, out double item3, out double item4, out double item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6d(double item0, double item1, double item2, double item3, double item4, double item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public double this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + case 4: return Item4; + case 5: return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + case 4: Item4 = value; break; + case 5: Item5 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6d other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2) && Item3.Equals(other.Item3) && Item4.Equals(other.Item4) && Item5.Equals(other.Item5); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6d v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6d a, Vec6d b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6d a, Vec6d b) + { + return !(a == b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + hashCode = (hashCode * 397) ^ Item4.GetHashCode(); + hashCode = (hashCode * 397) ^ Item5.GetHashCode(); + return hashCode; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6f.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6f.cs new file mode 100644 index 0000000..f9ce02d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6f.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 6-Tuple of float (System.Single) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec6f : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public float Item0; + + /// + /// The value of the second component of this object. + /// + public float Item1; + + /// + /// The value of the third component of this object. + /// + public float Item2; + + /// + /// The value of the fourth component of this object. + /// + public float Item3; + + /// + /// The value of the fifth component of this object. + /// + public float Item4; + + /// + /// The value of the sixth component of this object. + /// + public float Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out float item0, out float item1, out float item2, out float item3, out float item4, out float item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6f(float item0, float item1, float item2, float item3, float item4, float item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public float this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + case 4: return Item4; + case 5: return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + case 4: Item4 = value; break; + case 5: Item5 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6f other) + { + return Item0.Equals(other.Item0) && Item1.Equals(other.Item1) && Item2.Equals(other.Item2) && Item3.Equals(other.Item3) && Item4.Equals(other.Item4) && Item5.Equals(other.Item5); + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6f v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6f a, Vec6f b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6f a, Vec6f b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + hashCode = (hashCode * 397) ^ Item4.GetHashCode(); + hashCode = (hashCode * 397) ^ Item5.GetHashCode(); + return hashCode; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6i.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6i.cs new file mode 100644 index 0000000..9b6c05b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6i.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 6-Tuple of int (System.Int32) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec6i : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public int Item0; + + /// + /// The value of the second component of this object. + /// + public int Item1; + + /// + /// The value of the third component of this object. + /// + public int Item2; + + /// + /// The value of the fourth component of this object. + /// + public int Item3; + + /// + /// The value of the fourth component of this object. + /// + public int Item4; + + /// + /// The value of the sixth component of this object. + /// + public int Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out int item0, out int item1, out int item2, out int item3, out int item4, out int item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6i(int item0, int item1, int item2, int item3, int item4, int item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public int this[int i] + { + get + { + switch (i) + { + case 0: return Item0; + case 1: return Item1; + case 2: return Item2; + case 3: return Item3; + case 4: return Item4; + case 5: return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: Item0 = value; break; + case 1: Item1 = value; break; + case 2: Item2 = value; break; + case 3: Item3 = value; break; + case 4: Item4 = value; break; + case 5: Item5 = value; break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6i other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3 && Item4 == other.Item4 && Item5 == other.Item5; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6i v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6i a, Vec6i b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6i a, Vec6i b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0; + hashCode = (hashCode * 397) ^ Item1; + hashCode = (hashCode * 397) ^ Item2; + hashCode = (hashCode * 397) ^ Item3; + hashCode = (hashCode * 397) ^ Item4; + hashCode = (hashCode * 397) ^ Item5; + return hashCode; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6s.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6s.cs new file mode 100644 index 0000000..d134a78 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6s.cs @@ -0,0 +1,192 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 6-Tuple of short (System.Int16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec6s : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public short Item0; + + /// + /// The value of the second component of this object. + /// + public short Item1; + + /// + /// The value of the third component of this object. + /// + public short Item2; + + /// + /// The value of the fourth component of this object. + /// + public short Item3; + + /// + /// The value of the fifth component of this object. + /// + public short Item4; + + /// + /// The value of the sixth component of this object. + /// + public short Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out short item0, out short item1, out short item2, out short item3, out short item4, out short item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6s(short item0, short item1, short item2, short item3, short item4, short item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public short this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + case 3: + return Item3; + case 4: + return Item4; + case 5: + return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + case 3: + Item3 = value; + break; + case 4: + Item4 = value; + break; + case 5: + Item5 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6s other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3 && Item4 == other.Item4 && Item5 == other.Item5; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6s v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6s a, Vec6s b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6s a, Vec6s b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + hashCode = (hashCode * 397) ^ Item4.GetHashCode(); + hashCode = (hashCode * 397) ^ Item5.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6w.cs b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6w.cs new file mode 100644 index 0000000..366c37c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/core/Struct/Vec/Vec6w.cs @@ -0,0 +1,192 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// 4-Tuple of ushort (System.UInt16) + /// + [Serializable] + [StructLayout(LayoutKind.Sequential)] + // ReSharper disable once InconsistentNaming + public struct Vec6w : IVec, IEquatable + { + /// + /// The value of the first component of this object. + /// + public ushort Item0; + + /// + /// The value of the second component of this object. + /// + public ushort Item1; + + /// + /// The value of the third component of this object. + /// + public ushort Item2; + + /// + /// The value of the fourth component of this object. + /// + public ushort Item3; + + /// + /// The value of the fifth component of this object. + /// + public ushort Item4; + + /// + /// The value of the sixth component of this object. + /// + public ushort Item5; + +#if !DOTNET_FRAMEWORK + /// + /// Deconstructing a Vector + /// + /// + /// + /// + /// + /// + /// + public void Deconstruct(out ushort item0, out ushort item1, out ushort item2, out ushort item3, out ushort item4, out ushort item5) => (item0, item1, item2, item3, item4, item5) = (Item0, Item1, Item2, Item3, Item4, Item5); +#endif + + /// + /// Initializer + /// + /// + /// + /// + /// + /// + /// + public Vec6w(ushort item0, ushort item1, ushort item2, ushort item3, ushort item4, ushort item5) + { + Item0 = item0; + Item1 = item1; + Item2 = item2; + Item3 = item3; + Item4 = item4; + Item5 = item5; + } + + /// + /// Indexer + /// + /// + /// + public ushort this[int i] + { + get + { + switch (i) + { + case 0: + return Item0; + case 1: + return Item1; + case 2: + return Item2; + case 3: + return Item3; + case 4: + return Item4; + case 5: + return Item5; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + set + { + switch (i) + { + case 0: + Item0 = value; + break; + case 1: + Item1 = value; + break; + case 2: + Item2 = value; + break; + case 3: + Item3 = value; + break; + case 4: + Item4 = value; + break; + case 5: + Item5 = value; + break; + default: + throw new ArgumentOutOfRangeException(nameof(i)); + } + } + } + + /// + /// + /// + /// + /// + public bool Equals(Vec6w other) + { + return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2 && Item3 == other.Item3 && Item4 == other.Item4 && Item5 == other.Item5; + } + + /// + /// + /// + /// + /// + public override bool Equals(object? obj) + { + if (obj is null) return false; + return obj is Vec6w v && Equals(v); + } + + /// + /// + /// + /// + /// + /// + public static bool operator ==(Vec6w a, Vec6w b) + { + return a.Equals(b); + } + + /// + /// + /// + /// + /// + /// + public static bool operator !=(Vec6w a, Vec6w b) + { + return !a.Equals(b); + } + + /// + /// + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Item0.GetHashCode(); + hashCode = (hashCode * 397) ^ Item1.GetHashCode(); + hashCode = (hashCode * 397) ^ Item2.GetHashCode(); + hashCode = (hashCode * 397) ^ Item3.GetHashCode(); + hashCode = (hashCode * 397) ^ Item4.GetHashCode(); + hashCode = (hashCode * 397) ^ Item5.GetHashCode(); + return hashCode; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/dnn/CvDnn.cs b/OpenVinoOpenCvSharp/Modules/dnn/CvDnn.cs new file mode 100644 index 0000000..cbfaf6f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/dnn/CvDnn.cs @@ -0,0 +1,323 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; +// ReSharper disable UnusedMember.Global +// ReSharper disable InconsistentNaming +// ReSharper disable CommentTypo + +namespace OpenCvSharp.Dnn +{ + /// + /// cv::dnn functions + /// + public static class CvDnn + { + /// + /// Reads a network model stored in Darknet (https://pjreddie.com/darknet/) model files. + /// + /// path to the .cfg file with text description of the network architecture. + /// path to the .weights file with learned network. + /// Network object that ready to do forward, throw an exception in failure cases. + /// This is shortcut consisting from DarknetImporter and Net::populateNet calls. + public static Net ReadNetFromDarknet(string cfgFile, string? darknetModel = null) + { + return Net.ReadNetFromDarknet(cfgFile, darknetModel); + } + + /// + /// Reads a network model stored in Caffe model files. + /// + /// + /// + /// + /// This is shortcut consisting from createCaffeImporter and Net::populateNet calls. + // ReSharper disable once IdentifierTypo + public static Net ReadNetFromCaffe(string prototxt, string? caffeModel = null) + { + return Net.ReadNetFromCaffe(prototxt, caffeModel); + } + + /// + /// Reads a network model stored in Tensorflow model file. + /// + /// + /// + /// + /// This is shortcut consisting from createTensorflowImporter and Net::populateNet calls. + public static Net ReadNetFromTensorflow(string model, string? config = null) + { + return Net.ReadNetFromTensorflow(model, config); + } + + /// + /// Reads a network model stored in Torch model file. + /// + /// + /// + /// + /// This is shortcut consisting from createTorchImporter and Net::populateNet calls. + public static Net ReadNetFromTorch(string model, bool isBinary = true) + { + return Net.ReadNetFromTorch(model, isBinary); + } + + /// + /// Read deep learning network represented in one of the supported formats. + /// + /// This function automatically detects an origin framework of trained model + /// and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, + /// + /// Binary file contains trained weights. The following file + /// * extensions are expected for models from different frameworks: + /// * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) + /// * * `*.pb` (TensorFlow, https://www.tensorflow.org/) + /// * * `*.t7` | `*.net` (Torch, http://torch.ch/) + /// * * `*.weights` (Darknet, https://pjreddie.com/darknet/) + /// * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit) + /// Text file contains network configuration. It could be a + /// * file with the following extensions: + /// * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) + /// * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) + /// * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) + /// * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit) + /// Explicit framework name tag to determine a format. + /// + public static Net ReadNet(string model, string config = "", string framework = "") + { + return Net.ReadNet(model, config, framework); + } + + /// + /// Loads blob which was serialized as torch.Tensor object of Torch7 framework. + /// + /// + /// + /// + /// + /// This function has the same limitations as createTorchImporter(). + /// + public static Mat ReadTorchBlob(string fileName, bool isBinary = true) + { + if (fileName == null) + throw new ArgumentNullException(nameof(fileName)); + + var ptr = NativeMethods.dnn_readTorchBlob(fileName, isBinary ? 1 : 0); + return new Mat(ptr); + } + + /// + /// Creates blob from .pb file. + /// + /// path to the .pb file with input tensor. + /// + public static Mat? ReadTensorFromONNX(string path) + { + if (path == null) + throw new ArgumentNullException(nameof(path)); + + var p = NativeMethods.dnn_readTensorFromONNX(path); + return (p == IntPtr.Zero) ? null : new Mat(p); + } + + /// + /// Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, + /// subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. + /// + /// input image (with 1- or 3-channels). + /// multiplier for @p image values. + /// spatial size for output image + /// scalar with mean values which are subtracted from channels. Values are intended + /// to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + /// flag which indicates that swap first and last channels in 3-channel image is necessary. + /// flag which indicates whether image will be cropped after resize or not + /// 4-dimansional Mat with NCHW dimensions order. + /// if @p crop is true, input image is resized so one side after resize is equal to corresponing + /// dimension in @p size and another one is equal or larger.Then, crop from the center is performed. + /// If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + public static Mat BlobFromImage( + Mat image, double scaleFactor = 1.0, Size size = default, + Scalar mean = default, bool swapRB = true, bool crop = true) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + + var ptr = NativeMethods.dnn_blobFromImage(image.CvPtr, scaleFactor, size, mean, swapRB ? 1 : 0, crop ? 1 : 0); + return new Mat(ptr); + } + + /// + /// Creates 4-dimensional blob from series of images. Optionally resizes and + /// crops @p images from center, subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. + /// + /// input images (all with 1- or 3-channels). + /// multiplier for @p image values. + /// spatial size for output image + /// scalar with mean values which are subtracted from channels. Values are intended + /// to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + /// flag which indicates that swap first and last channels in 3-channel image is necessary. + /// flag which indicates whether image will be cropped after resize or not + /// 4-dimansional Mat with NCHW dimensions order. + /// if @p crop is true, input image is resized so one side after resize is equal to corresponing + /// dimension in @p size and another one is equal or larger.Then, crop from the center is performed. + /// If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + public static Mat BlobFromImages( + IEnumerable images, double scaleFactor, + Size size = default, Scalar mean = default, bool swapRB = true, bool crop = true) + { + if (images == null) + throw new ArgumentNullException(nameof(images)); + + var imagesPointers = EnumerableEx.SelectPtrs(images); + + var ptr = NativeMethods.dnn_blobFromImages( + imagesPointers, imagesPointers.Length, scaleFactor, size, mean, swapRB ? 1 : 0, crop ? 1 : 0); + return new Mat(ptr); + } + + /// + /// Convert all weights of Caffe network to half precision floating point. + /// + /// Path to origin model from Caffe framework contains single + /// precision floating point weights(usually has `.caffemodel` extension). + /// Path to destination model with updated weights. + /// + /// Shrinked model has no origin float32 weights so it can't be used + /// in origin Caffe framework anymore.However the structure of data + /// is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. + /// So the resulting model may be used there. + /// + public static void ShrinkCaffeModel(string src, string dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + + NativeMethods.dnn_shrinkCaffeModel(src, dst); + } + + /// + /// Create a text representation for a binary network stored in protocol buffer format. + /// + /// A path to binary network. + /// A path to output text file to be created. + public static void WriteTextGraph(string model, string output) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (output == null) + throw new ArgumentNullException(nameof(output)); + + NativeMethods.dnn_writeTextGraph(model, output); + } + + /// + /// Performs non maximum suppression given boxes and corresponding scores. + /// + /// a set of bounding boxes to apply NMS. + /// a set of corresponding confidences. + /// a threshold used to filter boxes by score. + /// a threshold used in non maximum suppression. + /// the kept indices of bboxes after NMS. + /// a coefficient in adaptive threshold formula + /// if `>0`, keep at most @p top_k picked indices. + // ReSharper disable once IdentifierTypo + public static void NMSBoxes(IEnumerable bboxes, IEnumerable scores, + float scoreThreshold, float nmsThreshold, + out int[] indices, + float eta = 1.0f, int topK = 0) + { + if (bboxes == null) + throw new ArgumentNullException(nameof(bboxes)); + if (scores == null) + throw new ArgumentNullException(nameof(scores)); + + // ReSharper disable once IdentifierTypo + using (var bboxesVec = new VectorOfRect(bboxes)) + using (var scoresVec = new VectorOfFloat(scores)) + using (var indicesVec = new VectorOfInt32()) + { + NativeMethods.dnn_NMSBoxes_Rect( + bboxesVec.CvPtr, scoresVec.CvPtr, scoreThreshold, nmsThreshold, + indicesVec.CvPtr, eta, topK); + indices = indicesVec.ToArray(); + } + } + + /// + /// Performs non maximum suppression given boxes and corresponding scores. + /// + /// a set of bounding boxes to apply NMS. + /// a set of corresponding confidences. + /// a threshold used to filter boxes by score. + /// a threshold used in non maximum suppression. + /// the kept indices of bboxes after NMS. + /// a coefficient in adaptive threshold formula + /// if `>0`, keep at most @p top_k picked indices. + // ReSharper disable once IdentifierTypo + public static void NMSBoxes(IEnumerable bboxes, IEnumerable scores, + float scoreThreshold, float nmsThreshold, + out int[] indices, + float eta = 1.0f, int topK = 0) + { + if (bboxes == null) + throw new ArgumentNullException(nameof(bboxes)); + if (scores == null) + throw new ArgumentNullException(nameof(scores)); + + // ReSharper disable once IdentifierTypo + using (var bboxesVec = new VectorOfRect2d(bboxes)) + using (var scoresVec = new VectorOfFloat(scores)) + using (var indicesVec = new VectorOfInt32()) + { + NativeMethods.dnn_NMSBoxes_Rect2d( + bboxesVec.CvPtr, scoresVec.CvPtr, scoreThreshold, nmsThreshold, + indicesVec.CvPtr, eta, topK); + indices = indicesVec.ToArray(); + } + } + + /// + /// Performs non maximum suppression given boxes and corresponding scores. + /// + /// a set of bounding boxes to apply NMS. + /// a set of corresponding confidences. + /// a threshold used to filter boxes by score. + /// a threshold used in non maximum suppression. + /// the kept indices of bboxes after NMS. + /// a coefficient in adaptive threshold formula + /// if `>0`, keep at most @p top_k picked indices. + // ReSharper disable once IdentifierTypo + public static void NMSBoxes(IEnumerable bboxes, IEnumerable scores, + float scoreThreshold, float nmsThreshold, + out int[] indices, + float eta = 1.0f, int topK = 0) + { + if (bboxes == null) + throw new ArgumentNullException(nameof(bboxes)); + if (scores == null) + throw new ArgumentNullException(nameof(scores)); + + // ReSharper disable once IdentifierTypo + using (var bboxesVec = new VectorOfRotatedRect(bboxes)) + using (var scoresVec = new VectorOfFloat(scores)) + using (var indicesVec = new VectorOfInt32()) + { + NativeMethods.dnn_NMSBoxes_RotatedRect( + bboxesVec.CvPtr, scoresVec.CvPtr, scoreThreshold, nmsThreshold, + indicesVec.CvPtr, eta, topK); + indices = indicesVec.ToArray(); + } + } + + /// + /// Release a Myriad device is binded by OpenCV. + /// + /// Single Myriad device cannot be shared across multiple processes which uses Inference Engine's Myriad plugin. + /// + public static void ResetMyriadDevice() + { + NativeMethods.dnn_resetMyriadDevice(); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/dnn/Net.cs b/OpenVinoOpenCvSharp/Modules/dnn/Net.cs new file mode 100644 index 0000000..2d46572 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/dnn/Net.cs @@ -0,0 +1,504 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; +// ReSharper disable UnusedMember.Global +// ReSharper disable IdentifierTypo +// ReSharper disable InconsistentNaming +// ReSharper disable CommentTypo + +namespace OpenCvSharp.Dnn +{ + /// + /// + /// This class allows to create and manipulate comprehensive artificial neural networks. + /// + /// + /// Neural network is presented as directed acyclic graph(DAG), where vertices are Layer instances, + /// and edges specify relationships between layers inputs and outputs. + /// + /// Each network layer has unique integer id and unique string name inside its network. + /// LayerId can store either layer name or layer id. + /// This class supports reference counting of its instances, i.e.copies point to the same instance. + /// + public class Net : DisposableCvObject + { + #region Init & Disposal + + /// + /// + /// Default constructor. + /// + public Net() + { + ptr = NativeMethods.dnn_Net_new(); + } + + /// + /// + /// + protected Net(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + protected override void DisposeUnmanaged() + { + NativeMethods.dnn_Net_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// Reads a network model stored in Darknet (https://pjreddie.com/darknet/) model files. + /// + /// path to the .cfg file with text description of the network architecture. + /// path to the .weights file with learned network. + /// Network object that ready to do forward, throw an exception in failure cases. + /// This is shortcut consisting from DarknetImporter and Net::populateNet calls. + public static Net ReadNetFromDarknet(string cfgFile, string? darknetModel = null) + { + if (cfgFile == null) + throw new ArgumentNullException(nameof(cfgFile)); + + var ptr = NativeMethods.dnn_readNetFromDarknet(cfgFile, darknetModel); + return new Net(ptr); + } + + /// + /// Reads a network model stored in Caffe model files. + /// + /// + /// + /// + /// This is shortcut consisting from createCaffeImporter and Net::populateNet calls. + public static Net ReadNetFromCaffe(string prototxt, string? caffeModel = null) + { + if (prototxt == null) + throw new ArgumentNullException(nameof(prototxt)); + + var ptr = NativeMethods.dnn_readNetFromCaffe(prototxt, caffeModel); + return new Net(ptr); + } + + /// + /// Reads a network model stored in Tensorflow model file. + /// + /// + /// + /// + /// This is shortcut consisting from createTensorflowImporter and Net::populateNet calls. + public static Net ReadNetFromTensorflow(string model, string? config = null) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + + var ptr = NativeMethods.dnn_readNetFromTensorflow(model, config); + return new Net(ptr); + } + + /// + /// Reads a network model stored in Torch model file. + /// + /// + /// + /// + /// This is shortcut consisting from createTorchImporter and Net::populateNet calls. + public static Net ReadNetFromTorch(string model, bool isBinary = true) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + + var ptr = NativeMethods.dnn_readNetFromTorch(model, isBinary ? 1 : 0); + return new Net(ptr); + } + + /// + /// Read deep learning network represented in one of the supported formats. + /// + /// This function automatically detects an origin framework of trained model + /// and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, + /// + /// Binary file contains trained weights. The following file + /// * extensions are expected for models from different frameworks: + /// * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) + /// * * `*.pb` (TensorFlow, https://www.tensorflow.org/) + /// * * `*.t7` | `*.net` (Torch, http://torch.ch/) + /// * * `*.weights` (Darknet, https://pjreddie.com/darknet/) + /// * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit) + /// Text file contains network configuration. It could be a + /// * file with the following extensions: + /// * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) + /// * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) + /// * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) + /// * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit) + /// Explicit framework name tag to determine a format. + /// + public static Net ReadNet(string model, string config = "", string framework = "") + { + if (string.IsNullOrEmpty(model)) + throw new ArgumentException("message is null or empty", nameof(model)); + config ??= ""; + framework ??= ""; + + var net = NativeMethods.dnn_readNet(model, config, framework); + return new Net(net); + } + + /// + /// Load a network from Intel's Model Optimizer intermediate representation. + /// Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine backend. + /// + /// XML configuration file with network's topology. + /// Binary file with trained weights. + /// + public static Net? ReadNetFromModelOptimizer(string xml, string bin) + { + if (xml == null) + throw new ArgumentNullException(nameof(xml)); + if (bin == null) + throw new ArgumentNullException(nameof(bin)); + + var p = NativeMethods.dnn_readNetFromModelOptimizer(xml, bin); + return (p == IntPtr.Zero) ? null : new Net(p); + } + + /// + /// Reads a network model ONNX https://onnx.ai/ + /// + /// path to the .onnx file with text description of the network architecture. + /// Network object that ready to do forward, throw an exception in failure cases. + // ReSharper disable once InconsistentNaming + public static Net? ReadNetFromONNX(string onnxFile) + { + if (onnxFile == null) + throw new ArgumentNullException(nameof(onnxFile)); + + var p = NativeMethods.dnn_readNetFromONNX(onnxFile); + return (p == IntPtr.Zero) ? null : new Net(p); + } + + #endregion + + #region Methods + + /// + /// Returns true if there are no layers in the network. + /// + /// + public bool Empty() + { + var ret = NativeMethods.dnn_Net_empty(ptr); + GC.KeepAlive(this); + return ret != 0; + } + + /// + /// Converts string name of the layer to the integer identifier. + /// + /// + /// id of the layer, or -1 if the layer wasn't found. + public int GetLayerId(string layer) + { + if (layer == null) + throw new ArgumentNullException(nameof(layer)); + + var ret = NativeMethods.dnn_Net_getLayerId(ptr, layer); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + public string?[] GetLayerNames() + { + using (var namesVec = new VectorOfString()) + { + NativeMethods.dnn_Net_getLayerNames(ptr, namesVec.CvPtr); + GC.KeepAlive(this); + return namesVec.ToArray(); + } + } + + /// + /// Connects output of the first layer to input of the second layer. + /// + /// descriptor of the first layer output. + /// descriptor of the second layer input. + public void Connect(string outPin, string inpPin) + { + if (outPin == null) + throw new ArgumentNullException(nameof(outPin)); + if (inpPin == null) + throw new ArgumentNullException(nameof(inpPin)); + + NativeMethods.dnn_Net_connect1(ptr, outPin, inpPin); + GC.KeepAlive(this); + } + + /// + /// Connects #@p outNum output of the first layer to #@p inNum input of the second layer. + /// + /// identifier of the first layer + /// identifier of the second layer + /// number of the first layer output + /// number of the second layer input + public void Connect(int outLayerId, int outNum, int inpLayerId, int inpNum) + { + NativeMethods.dnn_Net_connect2(ptr, outLayerId, outNum, inpLayerId, inpNum); + GC.KeepAlive(this); + } + + /// + /// Sets outputs names of the network input pseudo layer. + /// + /// + /// + /// * Each net always has special own the network input pseudo layer with id=0. + /// * This layer stores the user blobs only and don't make any computations. + /// * In fact, this layer provides the only way to pass user data into the network. + /// * As any other layer, this layer can label its outputs and this function provides an easy way to do this. + /// + public void SetInputsNames(IEnumerable inputBlobNames) + { + if (inputBlobNames == null) + throw new ArgumentNullException(nameof(inputBlobNames)); + + var inputBlobNamesArray = EnumerableEx.ToArray(inputBlobNames); + NativeMethods.dnn_Net_setInputsNames(ptr, inputBlobNamesArray, inputBlobNamesArray.Length); + GC.KeepAlive(this); + } + + /// + /// Runs forward pass to compute output of layer with name @p outputName. + /// By default runs forward pass for the whole network. + /// + /// name for layer which output is needed to get + /// blob for first output of specified layer. + public Mat Forward(string? outputName = null) + { + var ret = NativeMethods.dnn_Net_forward1(ptr, outputName); + GC.KeepAlive(this); + return new Mat(ret); + } + + /// + /// Runs forward pass to compute output of layer with name @p outputName. + /// + /// contains all output blobs for specified layer. + /// name for layer which output is needed to get. + /// If outputName is empty, runs forward pass for the whole network. + public void Forward(IEnumerable outputBlobs, string? outputName = null) + { + if (outputBlobs == null) + throw new ArgumentNullException(nameof(outputBlobs)); + + var outputBlobsPtrs = EnumerableEx.SelectPtrs(outputBlobs); + NativeMethods.dnn_Net_forward2(ptr, outputBlobsPtrs, outputBlobsPtrs.Length, outputName); + + GC.KeepAlive(outputBlobs); + GC.KeepAlive(this); + } + + /// + /// Runs forward pass to compute outputs of layers listed in @p outBlobNames. + /// + /// contains blobs for first outputs of specified layers. + /// names for layers which outputs are needed to get + public void Forward(IEnumerable outputBlobs, IEnumerable outBlobNames) + { + if (outputBlobs == null) + throw new ArgumentNullException(nameof(outputBlobs)); + if (outBlobNames == null) + throw new ArgumentNullException(nameof(outBlobNames)); + + var outputBlobsPtrs = EnumerableEx.SelectPtrs(outputBlobs); + var outBlobNamesArray = EnumerableEx.ToArray(outBlobNames); + NativeMethods.dnn_Net_forward3(ptr, outputBlobsPtrs, outputBlobsPtrs.Length, outBlobNamesArray, outBlobNamesArray.Length); + + GC.KeepAlive(outputBlobs); + GC.KeepAlive(this); + } + + /// + /// Compile Halide layers. + /// Schedule layers that support Halide backend. Then compile them for + /// specific target.For layers that not represented in scheduling file + /// or if no manual scheduling used at all, automatic scheduling will be applied. + /// + /// Path to YAML file with scheduling directives. + public void SetHalideScheduler(string scheduler) + { + ThrowIfDisposed(); + NativeMethods.dnn_Net_setHalideScheduler(ptr, scheduler); + GC.KeepAlive(this); + } + + /// + /// Ask network to use specific computation backend where it supported. + /// + /// backend identifier. + public void SetPreferableBackend(Backend backendId) + { + ThrowIfDisposed(); + NativeMethods.dnn_Net_setPreferableBackend(ptr, (int)backendId); + GC.KeepAlive(this); + } + + /// + /// Ask network to make computations on specific target device. + /// + /// target identifier. + public void SetPreferableTarget(Target targetId) + { + ThrowIfDisposed(); + NativeMethods.dnn_Net_setPreferableTarget(ptr, (int)targetId); + GC.KeepAlive(this); + } + + /// + /// Sets the new value for the layer output blob + /// + /// new blob. + /// descriptor of the updating layer output blob. + /// + /// connect(String, String) to know format of the descriptor. + /// If updating blob is not empty then @p blob must have the same shape, + /// because network reshaping is not implemented yet. + /// + public void SetInput(Mat blob, string name = "") + { + if (blob == null) + throw new ArgumentNullException(nameof(blob)); + + NativeMethods.dnn_Net_setInput(ptr, blob.CvPtr, name); + GC.KeepAlive(this); + } + + /// + /// Returns indexes of layers with unconnected outputs. + /// + /// + public int[] GetUnconnectedOutLayers() + { + ThrowIfDisposed(); + + try + { + using (var resultVec = new VectorOfInt32()) + { + NativeMethods.dnn_Net_getUnconnectedOutLayers(ptr, resultVec.CvPtr); + return resultVec.ToArray(); + } + } + finally + { + GC.KeepAlive(this); + } + } + + /// + /// Returns names of layers with unconnected outputs. + /// + /// + public string?[] GetUnconnectedOutLayersNames() + { + ThrowIfDisposed(); + + try + { + using (var resultVec = new VectorOfString()) + { + NativeMethods.dnn_Net_getUnconnectedOutLayersNames(ptr, resultVec.CvPtr); + return resultVec.ToArray(); + } + } + finally + { + GC.KeepAlive(this); + } + } + + /// + /// Enables or disables layer fusion in the network. + /// + /// true to enable the fusion, false to disable. The fusion is enabled by default. + public void EnableFusion(bool fusion) + { + ThrowIfDisposed(); + NativeMethods.dnn_Net_enableFusion(ptr, fusion ? 1 : 0); + GC.KeepAlive(this); + } + + /// + /// Returns overall time for inference and timings (in ticks) for layers. + /// Indexes in returned vector correspond to layers ids.Some layers can be fused with others, + /// in this case zero ticks count will be return for that skipped layers. + /// + /// vector for tick timings for all layers. + /// overall ticks for model inference. + public long GetPerfProfile(out double[] timings) + { + ThrowIfDisposed(); + + using (var timingsVec = new VectorOfDouble()) + { + var ret = NativeMethods.dnn_Net_getPerfProfile(ptr, timingsVec.CvPtr); + GC.KeepAlive(this); + + timings = timingsVec.ToArray(); + return ret; + } + } + + #endregion + + #region Enum + + /// + /// Enum of computation backends supported by layers. + /// + /// + /// DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if + /// OpenCV is built with Intel's Inference Engine library or + /// DNN_BACKEND_OPENCV otherwise. + /// + public enum Backend + { + //! DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if + //! OpenCV is built with Intel's Inference Engine library or + //! DNN_BACKEND_OPENCV otherwise. +#pragma warning disable CS1591 + // ReSharper disable once InconsistentNaming + DEFAULT, + HALIDE, + INFERENCE_ENGINE, + OPENCV, + VKCOM, + CUDA +#pragma warning restore CS1591 + } + + /// + /// Enum of target devices for computations. + /// + public enum Target + { +#pragma warning disable CS1591 + CPU, + OPENCL, + OPENCL_FP16, + MYRIAD, + VULKAN, + FPGA, + CUDA, + CUDA_FP16 +#pragma warning restore CS1591 + } + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/features2d/AKAZE.cs b/OpenVinoOpenCvSharp/Modules/features2d/AKAZE.cs new file mode 100644 index 0000000..c65ea07 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/AKAZE.cs @@ -0,0 +1,246 @@ +using System; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + +#if LANG_JP + /// + /// AKAZE 実装 + /// +#else + /// + /// Class implementing the AKAZE keypoint detector and descriptor extractor, + /// described in @cite ANB13 + /// + /// + /// AKAZE descriptors can only be used with KAZE or AKAZE keypoints. + /// Try to avoid using *extract* and *detect* instead of *operator()* due to performance reasons. + /// .. [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale + /// Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. + /// In British Machine Vision Conference (BMVC), Bristol, UK, September 2013. + /// +#endif + // ReSharper disable once InconsistentNaming + public class AKAZE : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected AKAZE(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// The AKAZE constructor + /// + /// + /// + /// + /// + /// + /// + /// + public static AKAZE Create( + AKAZEDescriptorType descriptorType = AKAZEDescriptorType.MLDB, + int descriptorSize = 0, + int descriptorChannels = 3, + float threshold = 0.001f, + int nOctaves = 4, + int nOctaveLayers = 4, + KAZEDiffusivityType diffusivity = KAZEDiffusivityType.DiffPmG2) + { + var ptr = NativeMethods.features2d_AKAZE_create( + (int) descriptorType, descriptorSize, descriptorChannels, + threshold, nOctaves, nOctaveLayers, (int) diffusivity); + return new AKAZE(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public AKAZEDescriptorType AKAZEDescriptorType // avoid name conflict + { + get + { + ThrowIfDisposed(); + var res = (AKAZEDescriptorType)NativeMethods.features2d_AKAZE_getDescriptorType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setDescriptorType(ptr, (int)value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + // ReSharper disable once InconsistentNaming + public int AKAZEDescriptorSize // avoid name conflict + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AKAZE_getDescriptorSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setDescriptorSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + // ReSharper disable once InconsistentNaming + public int AKAZEDescriptorChannels // avoid name conflict + { + get + { + ThrowIfDisposed(); + var res =NativeMethods.features2d_AKAZE_getDescriptorChannels(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setDescriptorChannels(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public double Threshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AKAZE_getThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int NOctaves + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AKAZE_getNOctaves(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setNOctaves(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int NOctaveLayers + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AKAZE_getNOctaveLayers(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setNOctaveLayers(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public KAZEDiffusivityType DiffusivityType + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AKAZE_getDiffusivity(ptr); + GC.KeepAlive(this); + return (KAZEDiffusivityType)res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AKAZE_setDiffusivity(ptr, (int)value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_AKAZE_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_AKAZE_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/AgastFeatureDetector.cs b/OpenVinoOpenCvSharp/Modules/features2d/AgastFeatureDetector.cs new file mode 100644 index 0000000..1467104 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/AgastFeatureDetector.cs @@ -0,0 +1,166 @@ +using System; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// AGAST 実装 + /// +#else + /// + /// Detects corners using the AGAST algorithm + /// +#endif + public class AgastFeatureDetector : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + +#pragma warning disable 1591 + public const int + THRESHOLD = 10000, + NONMAX_SUPPRESSION = 10001; +#pragma warning restore 1591 + + #region Init & Disposal + + /// + /// + /// + protected AgastFeatureDetector(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// The AgastFeatureDetector constructor + /// + /// threshold on difference between intensity of the central pixel + /// and pixels of a circle around this pixel. + /// if true, non-maximum suppression is applied to detected corners (keypoints). + /// + public static AgastFeatureDetector Create( + int threshold = 10, + bool nonmaxSuppression = true, + DetectorType type = DetectorType.OAST_9_16) + { + var ptr = NativeMethods.features2d_AgastFeatureDetector_create( + threshold, nonmaxSuppression ? 1 : 0, (int) type); + return new AgastFeatureDetector(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// threshold on difference between intensity of the central pixel and pixels of a circle around this pixel. + /// + public int Threshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AgastFeatureDetector_getThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AgastFeatureDetector_setThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// if true, non-maximum suppression is applied to detected corners (keypoints). + /// + public int NonmaxSuppression + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_AgastFeatureDetector_getNonmaxSuppression(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AgastFeatureDetector_setNonmaxSuppression(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// type one of the four neighborhoods as defined in the paper + /// + public DetectorType Type + { + get + { + ThrowIfDisposed(); + var res = (DetectorType)NativeMethods.features2d_AgastFeatureDetector_getType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_AgastFeatureDetector_setType(ptr, (int)value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_AgastFeatureDetector_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_AgastFeatureDetector_delete(ptr); + base.DisposeUnmanaged(); + } + } + +#pragma warning disable 1591 + + /// + /// AGAST type one of the four neighborhoods as defined in the paper + /// + public enum DetectorType + { + AGAST_5_8 = 0, + AGAST_7_12d = 1, + AGAST_7_12s = 2, + OAST_9_16 = 3, + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/BFMatcher.cs b/OpenVinoOpenCvSharp/Modules/features2d/BFMatcher.cs new file mode 100644 index 0000000..2b0c932 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/BFMatcher.cs @@ -0,0 +1,124 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Brute-force descriptor matcher. + /// For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. + /// + public class BFMatcher : DescriptorMatcher + { + private Ptr? detectorPtr; + + //internal override IntPtr PtrObj => detectorPtr.CvPtr; + + #region Init & Disposal + + /// + /// + /// + /// + /// + public BFMatcher(NormTypes normType = NormTypes.L2, bool crossCheck = false) + { + ptr = NativeMethods.features2d_BFMatcher_new((int) normType, crossCheck ? 1 : 0); + detectorPtr = null; + } + + /// + /// Creates instance by cv::Ptr<T> + /// + internal BFMatcher(Ptr detectorPtr) + { + this.detectorPtr = detectorPtr; + ptr = detectorPtr.Get(); + } + + /// + /// Creates instance by raw pointer T* + /// + internal BFMatcher(IntPtr rawPtr) + { + detectorPtr = null; + ptr = rawPtr; + } + + /// + /// Creates instance from cv::Ptr<T> . + /// ptr is disposed when the wrapper disposes. + /// + /// + internal new static BFMatcher FromPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Invalid cv::Ptr pointer"); + var ptrObj = new Ptr(ptr); + return new BFMatcher(ptrObj); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + if (detectorPtr != null) + { + detectorPtr.Dispose(); + detectorPtr = null; + ptr = IntPtr.Zero; + } + base.DisposeManaged(); + } + + /// + /// Releases managed resources + /// + protected override void DisposeUnmanaged() + { + if (detectorPtr == null && ptr != IntPtr.Zero) + NativeMethods.features2d_BFMatcher_delete(ptr); + ptr = IntPtr.Zero; + base.DisposeUnmanaged(); + } + + #endregion + + #region Methods + + /// + /// Return true if the matcher supports mask in match methods. + /// + /// + public override bool IsMaskSupported() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_BFMatcher_isMaskSupported(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + #endregion + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_BFMatcher_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_BFMatcher_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/BOWImgDescriptorExtractor.cs b/OpenVinoOpenCvSharp/Modules/features2d/BOWImgDescriptorExtractor.cs new file mode 100644 index 0000000..4ea7ac9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/BOWImgDescriptorExtractor.cs @@ -0,0 +1,187 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Brute-force descriptor matcher. + /// For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. + /// + public class BOWImgDescriptorExtractor : DisposableCvObject + { + /// + /// The constructor. + /// + /// Descriptor extractor that is used to compute descriptors for an input image and its keypoints. + /// Descriptor matcher that is used to find the nearest word of the trained vocabulary for each keypoint descriptor of the image. + public BOWImgDescriptorExtractor(Feature2D dextractor, DescriptorMatcher dmatcher) + { + if (dextractor == null) + throw new ArgumentNullException(nameof(dextractor)); + if (dmatcher == null) + throw new ArgumentNullException(nameof(dmatcher)); + + ptr = NativeMethods.features2d_BOWImgDescriptorExtractor_new1_RawPtr(dextractor.CvPtr, dmatcher.CvPtr); + + GC.KeepAlive(dextractor); + GC.KeepAlive(dmatcher); + } + + /// + /// The constructor. + /// + /// Descriptor matcher that is used to find the nearest word of the trained vocabulary for each keypoint descriptor of the image. + public BOWImgDescriptorExtractor(DescriptorMatcher dmatcher) + { + if (dmatcher == null) + throw new ArgumentNullException(nameof(dmatcher)); + + ptr = NativeMethods.features2d_BOWImgDescriptorExtractor_new2_RawPtr(dmatcher.CvPtr); + GC.KeepAlive(dmatcher); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_BOWImgDescriptorExtractor_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// Sets a visual vocabulary. + /// + /// Vocabulary (can be trained using the inheritor of BOWTrainer ). + /// Each row of the vocabulary is a visual word(cluster center). + public void SetVocabulary(Mat vocabulary) + { + ThrowIfDisposed(); + if (vocabulary == null) + throw new ArgumentNullException(nameof(vocabulary)); + NativeMethods.features2d_BOWImgDescriptorExtractor_setVocabulary(ptr, vocabulary.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(vocabulary); + } + + /// + /// Returns the set vocabulary. + /// + /// + public Mat GetVocabulary() + { + ThrowIfDisposed(); + var p = NativeMethods.features2d_BOWImgDescriptorExtractor_getVocabulary(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + /// + /// Computes an image descriptor using the set visual vocabulary. + /// + /// Image, for which the descriptor is computed. + /// Keypoints detected in the input image. + /// Computed output image descriptor. + /// 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, + out int[][] pointIdxsOfClusters, Mat? descriptors = null) + { + ThrowIfDisposed(); + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (imgDescriptor == null) + throw new ArgumentNullException(nameof(imgDescriptor)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + using (var pointIdxsOfClustersVec = new VectorOfVectorInt()) + { + NativeMethods.features2d_BOWImgDescriptorExtractor_compute11(ptr, image.CvPtr, keypointsVec.CvPtr, + imgDescriptor.CvPtr, pointIdxsOfClustersVec.CvPtr, Cv2.ToPtr(descriptors)); + keypoints = keypointsVec.ToArray(); + pointIdxsOfClusters = pointIdxsOfClustersVec.ToArray(); + } + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(imgDescriptor); + GC.KeepAlive(descriptors); + } + + /// + /// Computes an image descriptor using the set visual vocabulary. + /// + /// Computed descriptors to match with vocabulary. + /// 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) + { + ThrowIfDisposed(); + if (keypointDescriptors == null) + throw new ArgumentNullException(nameof(keypointDescriptors)); + if (imgDescriptor == null) + throw new ArgumentNullException(nameof(imgDescriptor)); + + using (var pointIdxsOfClustersVec = new VectorOfVectorInt()) + { + NativeMethods.features2d_BOWImgDescriptorExtractor_compute12( + ptr, keypointDescriptors.CvPtr, imgDescriptor.CvPtr, pointIdxsOfClustersVec.CvPtr); + pointIdxsOfClusters = pointIdxsOfClustersVec.ToArray(); + } + GC.KeepAlive(this); + GC.KeepAlive(keypointDescriptors); + GC.KeepAlive(imgDescriptor); + } + + /// + /// Computes an image descriptor using the set visual vocabulary. + /// + /// Image, for which the descriptor is computed. + /// Keypoints detected in the input image. + /// Computed output image descriptor. + public void Compute2(Mat image, ref KeyPoint[] keypoints, Mat imgDescriptor) + { + ThrowIfDisposed(); + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (imgDescriptor == null) + throw new ArgumentNullException(nameof(imgDescriptor)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_BOWImgDescriptorExtractor_compute2( + ptr, image.CvPtr, keypointsVec.CvPtr, imgDescriptor.CvPtr); + keypoints = keypointsVec.ToArray(); + } + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(imgDescriptor); + } + + /// + /// Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. + /// + /// + public int DescriptorSize() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_BOWImgDescriptorExtractor_descriptorSize(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// Returns an image descriptor type. + /// + /// + public int DescriptorType() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_BOWImgDescriptorExtractor_descriptorType(ptr); + GC.KeepAlive(this); + return res; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/BOWKMeansTrainer.cs b/OpenVinoOpenCvSharp/Modules/features2d/BOWKMeansTrainer.cs new file mode 100644 index 0000000..8d4a217 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/BOWKMeansTrainer.cs @@ -0,0 +1,65 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Brute-force descriptor matcher. + /// For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. + /// + public class BOWKMeansTrainer : BOWTrainer + { + /// + /// + /// + /// + /// + /// + /// + public BOWKMeansTrainer(int clusterCount, TermCriteria? termcrit = null, + int attempts = 3, KMeansFlags flags = KMeansFlags.PpCenters) + { + var termCritValue = termcrit.GetValueOrDefault(new TermCriteria()); + ptr = NativeMethods.features2d_BOWKMeansTrainer_new(clusterCount, termCritValue, attempts, (int)flags); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_BOWKMeansTrainer_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// Clusters train descriptors. + /// + /// + public override Mat Cluster() + { + ThrowIfDisposed(); + var p = NativeMethods.features2d_BOWKMeansTrainer_cluster1(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + /// + /// Clusters train descriptors. + /// + /// Descriptors to cluster. Each row of the descriptors matrix is a descriptor. Descriptors are not added to the inner train descriptor set. + /// The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first variant of the method, train descriptors stored in the object + /// are clustered.In the second variant, input descriptors are clustered. + /// + public override Mat Cluster(Mat descriptors) + { + ThrowIfDisposed(); + descriptors.ThrowIfDisposed(); + var p = NativeMethods.features2d_BOWKMeansTrainer_cluster2(ptr, descriptors.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(descriptors); + return new Mat(p); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/BOWTrainer.cs b/OpenVinoOpenCvSharp/Modules/features2d/BOWTrainer.cs new file mode 100644 index 0000000..b93c2c4 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/BOWTrainer.cs @@ -0,0 +1,76 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Brute-force descriptor matcher. + /// For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. + /// + public abstract class BOWTrainer : DisposableCvObject + { + /// + /// Adds descriptors to a training set. + /// + /// descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a descriptor. + /// The training set is clustered using clustermethod to construct the vocabulary. + public void Add(Mat descriptors) + { + if (descriptors == null) + throw new ArgumentNullException(nameof(descriptors)); + NativeMethods.features2d_BOWTrainer_add(ptr, descriptors.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(descriptors); + } + + /// + /// Returns a training set of descriptors. + /// + /// + public Mat[] GetDescriptors() + { + using (var descriptors = new VectorOfMat()) + { + NativeMethods.features2d_BOWTrainer_getDescriptors(ptr, descriptors.CvPtr); + GC.KeepAlive(this); + return descriptors.ToArray(); + } + } + + /// + /// Returns the count of all descriptors stored in the training set. + /// + /// + public int DescriptorsCount() + { + var res = NativeMethods.features2d_BOWTrainer_descriptorsCount(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + public virtual void Clear() + { + NativeMethods.features2d_BOWTrainer_clear(ptr); + GC.KeepAlive(this); + } + + /// + /// Clusters train descriptors. + /// + /// + public abstract Mat Cluster(); + + /// + /// Clusters train descriptors. + /// + /// Descriptors to cluster. Each row of the descriptors matrix is a descriptor. Descriptors are not added to the inner train descriptor set. + /// The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first variant of the method, train descriptors stored in the object + /// are clustered.In the second variant, input descriptors are clustered. + /// + public abstract Mat Cluster(Mat descriptors); + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/BRISK.cs b/OpenVinoOpenCvSharp/Modules/features2d/BRISK.cs new file mode 100644 index 0000000..754cbe1 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/BRISK.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + +#if LANG_JP + /// + /// BRISK 実装 + /// +#else + /// + /// BRISK implementation + /// +#endif + // ReSharper disable once InconsistentNaming + public class BRISK : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected BRISK() + { + } + + /// + /// + /// + /// + protected BRISK(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// + /// + /// + /// + /// + public static BRISK Create(int thresh = 30, int octaves = 3, float patternScale = 1.0f) + { + var p = NativeMethods.features2d_BRISK_create1(thresh, octaves, patternScale); + return new BRISK(p); + } + + /// + /// custom setup + /// + /// + /// + /// + /// + /// + /// + public static BRISK Create( + IEnumerable radiusList, IEnumerable numberList, + float dMax = 5.85f, float dMin = 8.2f, + IEnumerable? indexChange = null) + { + if (radiusList == null) + throw new ArgumentNullException(nameof(radiusList)); + if (numberList == null) + throw new ArgumentNullException(nameof(numberList)); + var radiusListArray = EnumerableEx.ToArray(radiusList); + var numberListArray = EnumerableEx.ToArray(numberList); + var indexChangeArray = (indexChange == null) ? null : EnumerableEx.ToArray(indexChange); + + var p = NativeMethods.features2d_BRISK_create2( + radiusListArray, radiusListArray.Length, + numberListArray, numberListArray.Length, + dMax, dMin, + indexChangeArray, indexChangeArray?.Length ?? 0); + return new BRISK(p); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Methods + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_BRISK_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_BRISK_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/DenseFeatureDetector.cs b/OpenVinoOpenCvSharp/Modules/features2d/DenseFeatureDetector.cs new file mode 100644 index 0000000..5a33f34 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/DenseFeatureDetector.cs @@ -0,0 +1,130 @@ +namespace OpenCvSharp +{ +#if false + /// + /// Class for generation of image features which are + /// distributed densely and regularly over the image. + /// + public class DenseFeatureDetector : FeatureDetector + { + private bool disposed; + private Ptr detectorPtr; + + #region Init & Disposal + /// + /// The detector generates several levels (in the amount of featureScaleLevels) of features. + /// Features of each level are located in the nodes of a regular grid over the image + /// (excluding the image boundary of given size). The level parameters (a feature scale, + /// a node size, a size of boundary) are multiplied by featureScaleMul with level index + /// growing depending on input flags, viz.: + /// + /// + /// + /// + /// + /// + /// The grid node size is multiplied if this is true. + /// Size of image boundary is multiplied if this is true. + public DenseFeatureDetector( float initFeatureScale=1.0f, int featureScaleLevels=1, + float featureScaleMul=0.1f, + int initXyStep=6, int initImgBound=0, + bool varyXyStepWithScale=true, + bool varyImgBoundWithScale=false ) + { + ptr = NativeMethods.features2d_DenseFeatureDetector_new( + initFeatureScale, featureScaleLevels, featureScaleMul,initXyStep, initImgBound, + varyXyStepWithScale ? 1 : 0, varyImgBoundWithScale ? 1 : 0); + } + + /// + /// Creates instance by cv::Ptr<cv::SURF> + /// + internal DenseFeatureDetector(Ptr detectorPtr) + { + this.detectorPtr = detectorPtr; + this.ptr = detectorPtr.Get(); + } + /// + /// Creates instance by raw pointer cv::SURF* + /// + internal DenseFeatureDetector(IntPtr rawPtr) + { + detectorPtr = null; + ptr = rawPtr; + } + /// + /// Creates instance from cv::Ptr<T> . + /// ptr is disposed when the wrapper disposes. + /// + /// + internal static new DenseFeatureDetector FromPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Invalid cv::Ptr pointer"); + var ptrObj = new Ptr(ptr); + return new DenseFeatureDetector(ptrObj); + } + +#if LANG_JP + /// + /// リソースの解放 + /// + /// + /// trueの場合は、このメソッドがユーザコードから直接が呼ばれたことを示す。マネージ・アンマネージ双方のリソースが解放される。 + /// falseの場合は、このメソッドはランタイムからファイナライザによって呼ばれ、もうほかのオブジェクトから参照されていないことを示す。アンマネージリソースのみ解放される。 + /// +#else + /// + /// Releases the resources + /// + /// + /// If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and unmanaged resources can be disposed. + /// If false, the method has been called by the runtime from inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed. + /// +#endif + protected override void Dispose(bool disposing) + { + if (!disposed) + { + try + { + // releases managed resources + if (disposing) + { + } + // releases unmanaged resources + if (detectorPtr != null) + { + detectorPtr.Dispose(); + detectorPtr = null; + } + else + { + if (ptr != IntPtr.Zero) + NativeMethods.features2d_DenseFeatureDetector_delete(ptr); + ptr = IntPtr.Zero; + } + disposed = true; + } + finally + { + base.Dispose(disposing); + } + } + } + #endregion + + /// + /// Pointer to algorithm information (cv::AlgorithmInfo*) + /// + /// + public override IntPtr InfoPtr + { + get + { + return NativeMethods.features2d_DenseFeatureDetector_info(ptr); + } + } + } +#endif +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/DescriptorMatcher.cs b/OpenVinoOpenCvSharp/Modules/features2d/DescriptorMatcher.cs new file mode 100644 index 0000000..9ab7439 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/DescriptorMatcher.cs @@ -0,0 +1,427 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class DescriptorMatcher : Algorithm + { + /// + /// + /// + private Ptr? detectorPtr; + + //internal virtual IntPtr PtrObj => detectorPtr.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected DescriptorMatcher() + { + detectorPtr = null; + ptr = IntPtr.Zero; + } + + /// + /// Create descriptor matcher by type name. + /// + /// + /// + public static DescriptorMatcher Create(string descriptorMatcherType) + { + if (string.IsNullOrEmpty(descriptorMatcherType)) + throw new ArgumentNullException(nameof(descriptorMatcherType)); + + switch (descriptorMatcherType) + { + case "FlannBased": + return new FlannBasedMatcher(); + + case "BruteForce": // L2 + // ReSharper disable once RedundantArgumentDefaultValue + return new BFMatcher(NormTypes.L2); + + case "BruteForce-SL2": // Squared L2 + return new BFMatcher(NormTypes.L2SQR); + + case "BruteForce-L1": + return new BFMatcher(NormTypes.L1); + + case "BruteForce-Hamming": + case "BruteForce-HammingLUT": + return new BFMatcher(NormTypes.Hamming); + + case "BruteForce-Hamming(2)": + return new BFMatcher(NormTypes.Hamming2); + + default: + throw new OpenCvSharpException("Unknown matcher name '{0}'", descriptorMatcherType); + } + /* + IntPtr ptr; + try + { + ptr = NativeMethods.features2d_FeatureDetector_create(descriptorMatcherType); + } + catch (OpenCvSharpException) + { + throw new OpenCvSharpException( + "matcher name '{0}' is not valid.", descriptorMatcherType); + } + return FromPtr(ptr);*/ + } + + /// + /// Creates instance from cv::Ptr<T> . + /// ptr is disposed when the wrapper disposes. + /// + /// + internal static DescriptorMatcher FromPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Invalid cv::Ptr pointer"); + var ptrObj = new Ptr(ptr); + var detector = new DescriptorMatcher + { + detectorPtr = ptrObj, + ptr = ptrObj.Get() + }; + return detector; + } + + /// + /// Creates instance from raw pointer T* + /// + /// + internal static DescriptorMatcher FromRawPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Invalid DescriptorMatcher pointer"); + var detector = new DescriptorMatcher + { + detectorPtr = null, + ptr = ptr + }; + return detector; + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + detectorPtr?.Dispose(); + detectorPtr = null; + base.DisposeManaged(); + } + + #endregion + + #region Methods + + /// + /// Add descriptors to train descriptor collection. + /// + /// Descriptors to add. Each descriptors[i] is a descriptors set from one image. + public virtual void Add(IEnumerable descriptors) + { + ThrowIfDisposed(); + if (descriptors == null) + throw new ArgumentNullException(nameof(descriptors)); + + var descriptorsArray = EnumerableEx.ToArray(descriptors); + if (descriptorsArray.Length == 0) + return; + + var descriptorsPtrs = EnumerableEx.SelectPtrs(descriptorsArray); + NativeMethods.features2d_DescriptorMatcher_add(ptr, descriptorsPtrs, descriptorsPtrs.Length); + GC.KeepAlive(this); + GC.KeepAlive(descriptorsArray); + } + + /// + /// Get train descriptors collection. + /// + /// + public Mat[] GetTrainDescriptors() + { + ThrowIfDisposed(); + using (var matVec = new VectorOfMat()) + { + NativeMethods.features2d_DescriptorMatcher_getTrainDescriptors(ptr, matVec.CvPtr); + GC.KeepAlive(this); + return matVec.ToArray(); + } + } + + /// + /// Clear train descriptors collection. + /// + public virtual void Clear() + { + ThrowIfDisposed(); + NativeMethods.features2d_DescriptorMatcher_clear(ptr); + GC.KeepAlive(this); + } + + /// + /// Return true if there are not train descriptors in collection. + /// + /// + public new virtual bool Empty() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_DescriptorMatcher_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Return true if the matcher supports mask in match methods. + /// + /// + public virtual bool IsMaskSupported() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_DescriptorMatcher_isMaskSupported(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Train matcher (e.g. train flann index). + /// In all methods to match the method train() is run every time before matching. + /// Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation + /// of this method, other matchers really train their inner structures + /// (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation + /// of train() should check the class object state and do traing/retraining + /// only if the state requires that (e.g. FlannBasedMatcher trains flann::Index + /// if it has not trained yet or if new descriptors have been added to the train collection). + /// + public virtual void Train() + { + ThrowIfDisposed(); + NativeMethods.features2d_DescriptorMatcher_train(ptr); + GC.KeepAlive(this); + } + + #region *Match + + /// + /// Find one best match for each query descriptor (if mask is empty). + /// + /// + /// + /// + /// + public DMatch[] Match(Mat queryDescriptors, Mat trainDescriptors, Mat? mask = null) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + if (trainDescriptors == null) + throw new ArgumentNullException(nameof(trainDescriptors)); + using (var matchesVec = new VectorOfDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_match1( + ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr, + matchesVec.CvPtr, Cv2.ToPtr(mask)); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(trainDescriptors); + GC.KeepAlive(mask); + return matchesVec.ToArray(); + } + } + + /// + /// Find k best matches for each query descriptor (in increasing order of distances). + /// compactResult is used when mask is not empty. If compactResult is false matches + /// vector will have the same size as queryDescriptors rows. If compactResult is true + /// matches vector will not contain matches for fully masked out query descriptors. + /// + /// + /// + /// + /// + /// + /// + public DMatch[][] KnnMatch(Mat queryDescriptors, Mat trainDescriptors, + int k, Mat? mask = null, bool compactResult = false) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + if (trainDescriptors == null) + throw new ArgumentNullException(nameof(trainDescriptors)); + using (var matchesVec = new VectorOfVectorDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_knnMatch1( + ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr, + matchesVec.CvPtr, k, Cv2.ToPtr(mask), compactResult ? 1 : 0); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(trainDescriptors); + GC.KeepAlive(mask); + return matchesVec.ToArray(); + } + } + + /// + /// Find best matches for each query descriptor which have distance less than + /// maxDistance (in increasing order of distances). + /// + /// + /// + /// + /// + /// + /// + public DMatch[][] RadiusMatch(Mat queryDescriptors, Mat trainDescriptors, + float maxDistance, Mat? mask = null, bool compactResult = false) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + if (trainDescriptors == null) + throw new ArgumentNullException(nameof(trainDescriptors)); + using (var matchesVec = new VectorOfVectorDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_radiusMatch1( + ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr, + matchesVec.CvPtr, maxDistance, Cv2.ToPtr(mask), compactResult ? 1 : 0); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(trainDescriptors); + GC.KeepAlive(mask); + return matchesVec.ToArray(); + } + } + + /// + /// Find one best match for each query descriptor (if mask is empty). + /// + /// + /// + /// + public DMatch[] Match(Mat queryDescriptors, Mat[]? masks = null) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + + var masksPtrs = new IntPtr[0]; + if (masks != null) + { + masksPtrs = EnumerableEx.SelectPtrs(masks); + } + + using (var matchesVec = new VectorOfDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_match2( + ptr, queryDescriptors.CvPtr, matchesVec.CvPtr, masksPtrs, masksPtrs.Length); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(masks); + return matchesVec.ToArray(); + } + } + + /// + /// Find k best matches for each query descriptor (in increasing order of distances). + /// compactResult is used when mask is not empty. If compactResult is false matches + /// vector will have the same size as queryDescriptors rows. If compactResult is true + /// matches vector will not contain matches for fully masked out query descriptors. + /// + /// + /// + /// + /// + /// + public DMatch[][] KnnMatch(Mat queryDescriptors, int k, Mat[]? masks = null, bool compactResult = false) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + + var masksPtrs = new IntPtr[0]; + if (masks != null) + { + masksPtrs = EnumerableEx.SelectPtrs(masks); + } + + using (var matchesVec = new VectorOfVectorDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_knnMatch2( + ptr, queryDescriptors.CvPtr, matchesVec.CvPtr, k, + masksPtrs, masksPtrs.Length, compactResult ? 1 : 0); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(masks); + return matchesVec.ToArray(); + } + } + + /// + /// Find best matches for each query descriptor which have distance less than + /// maxDistance (in increasing order of distances). + /// + /// + /// + /// + /// + /// + public DMatch[][] RadiusMatch(Mat queryDescriptors, float maxDistance, Mat[]? masks = null, bool compactResult = false) + { + ThrowIfDisposed(); + if (queryDescriptors == null) + throw new ArgumentNullException(nameof(queryDescriptors)); + + var masksPtrs = new IntPtr[0]; + if (masks != null) + { + masksPtrs = EnumerableEx.SelectPtrs(masks); + } + + using (var matchesVec = new VectorOfVectorDMatch()) + { + NativeMethods.features2d_DescriptorMatcher_radiusMatch2( + ptr, queryDescriptors.CvPtr, matchesVec.CvPtr, maxDistance, + masksPtrs, masksPtrs.Length, compactResult ? 1 : 0); + GC.KeepAlive(this); + GC.KeepAlive(queryDescriptors); + GC.KeepAlive(masks); + return matchesVec.ToArray(); + } + } + + #endregion + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_DescriptorMatcher_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_DescriptorMatcher_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Enum/AKAZEDescriptorType.cs b/OpenVinoOpenCvSharp/Modules/features2d/Enum/AKAZEDescriptorType.cs new file mode 100644 index 0000000..0e94d6a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Enum/AKAZEDescriptorType.cs @@ -0,0 +1,31 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + /// + /// cv::AKAZE descriptor type + /// + + public enum AKAZEDescriptorType + { + /// + /// Upright descriptors, not invariant to rotation + /// + KAZEUpright = 2, + + /// + /// + /// + KAZE = 3, + + /// + /// + /// + MLDBUpright = 4, + + /// + /// Upright descriptors, not invariant to rotation + /// + MLDB = 5 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Enum/DrawMatchesFlags.cs b/OpenVinoOpenCvSharp/Modules/features2d/Enum/DrawMatchesFlags.cs new file mode 100644 index 0000000..ab518bb --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Enum/DrawMatchesFlags.cs @@ -0,0 +1,39 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// + /// + [Flags] + public enum DrawMatchesFlags + { + /// + /// Output image matrix will be created (Mat::create), + /// i.e. existing memory of output image may be reused. + /// Two source image, matches and single keypoints will be drawn. + /// For each keypoint only the center point will be drawn (without + /// the circle around keypoint with keypoint size and orientation). + /// + Default = 0, + + /// + /// Output image matrix will not be created (Mat::create). + /// Matches will be drawn on existing content of output image. + /// + DrawOverOutImg = 1, + + /// + /// Single keypoints will not be drawn. + /// + NotDrawSinglePoints = 2, + + /// + /// For each keypoint the circle around keypoint with keypoint size and + /// orientation will be drawn. + /// + DrawRichKeypoints = 4 + } +} + + diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Enum/FASTType.cs b/OpenVinoOpenCvSharp/Modules/features2d/Enum/FASTType.cs new file mode 100644 index 0000000..4010387 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Enum/FASTType.cs @@ -0,0 +1,15 @@ +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming +#pragma warning disable 1591 + + /// + /// AGAST type one of the four neighborhoods as defined in the paper + /// + public enum FASTType + { + TYPE_5_8 = 0, + TYPE_7_12 = 1, + TYPE_9_16 = 2, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Enum/KAZEDiffusivityType.cs b/OpenVinoOpenCvSharp/Modules/features2d/Enum/KAZEDiffusivityType.cs new file mode 100644 index 0000000..ad74897 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Enum/KAZEDiffusivityType.cs @@ -0,0 +1,29 @@ +namespace OpenCvSharp +{ + /// + /// cv::KAZE diffusivity type + /// +// ReSharper disable once InconsistentNaming + public enum KAZEDiffusivityType + { + /// + /// + /// + DiffPmG1 = 0, + + /// + /// + /// + DiffPmG2 = 1, + + /// + /// + /// + DiffWeickert = 2, + + /// + /// + /// + DiffCharbonnier = 3, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Enum/ORBScoreType.cs b/OpenVinoOpenCvSharp/Modules/features2d/Enum/ORBScoreType.cs new file mode 100644 index 0000000..3750718 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Enum/ORBScoreType.cs @@ -0,0 +1,19 @@ +namespace OpenCvSharp +{ + /// + /// cv::ORB score flags + /// + // ReSharper disable once InconsistentNaming + public enum ORBScoreType + { + /// + /// + /// + Fast = 1, + + /// + /// + /// + Harris = 0, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/FastFeatureDetector.cs b/OpenVinoOpenCvSharp/Modules/features2d/FastFeatureDetector.cs new file mode 100644 index 0000000..a9478ed --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/FastFeatureDetector.cs @@ -0,0 +1,138 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// Detects corners using FAST algorithm by E. Rosten + /// +#else + /// + /// Detects corners using FAST algorithm by E. Rosten + /// +#endif + public class FastFeatureDetector : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected FastFeatureDetector(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// + /// + /// + /// + public static FastFeatureDetector Create(int threshold = 10, bool nonmaxSuppression = true) + { + var ptr = NativeMethods.features2d_FastFeatureDetector_create(threshold, nonmaxSuppression ? 1 : 0); + return new FastFeatureDetector(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int Threshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_FastFeatureDetector_getThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_FastFeatureDetector_setThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public bool NonmaxSuppression + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_FastFeatureDetector_getNonmaxSuppression(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_FastFeatureDetector_setNonmaxSuppression(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int Type + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_FastFeatureDetector_getType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_FastFeatureDetector_setType(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_FastFeatureDetector_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_FastFeatureDetector_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/Feature2D.cs b/OpenVinoOpenCvSharp/Modules/features2d/Feature2D.cs new file mode 100644 index 0000000..b38cfab --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/Feature2D.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// Abstract base class for 2D image feature detectors and descriptor extractors + /// + public class Feature2D : Algorithm + { + #region Init & Disposal + + /// + /// + /// + internal Feature2D() + { + } + + #endregion + + #region Properties + + /// + /// + /// + /// + public virtual int DescriptorSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_Feature2D_descriptorSize(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + /// + public virtual int DescriptorType + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_Feature2D_descriptorType(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + /// + public virtual int DefaultNorm + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_Feature2D_defaultNorm(ptr); + GC.KeepAlive(this); + return res; + } + } + + #endregion + + #region Methods + + /// + /// Return true if detector object is empty + /// + /// + public new virtual bool Empty() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_Feature2D_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Detect keypoints in an image. + /// + /// The image. + /// 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(Mat image, Mat? mask = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + ThrowIfDisposed(); + + image.ThrowIfDisposed(); + try + { + using (var keyPoints = new VectorOfKeyPoint()) + { + NativeMethods.features2d_Feature2D_detect_Mat1(ptr, image.CvPtr, keyPoints.CvPtr, Cv2.ToPtr(mask)); + return keyPoints.ToArray(); + } + } + finally + { + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(mask); + } + } + + /// + /// Detect keypoints in an image. + /// + /// The image. + /// 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, Mat? mask = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + ThrowIfDisposed(); + + image.ThrowIfDisposed(); + try + { + using (var keypoints = new VectorOfKeyPoint()) + { + NativeMethods.features2d_Feature2D_detect_InputArray(ptr, image.CvPtr, keypoints.CvPtr, + Cv2.ToPtr(mask)); + return keypoints.ToArray(); + } + } + finally + { + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(mask); + } + } + + /// + /// Detect keypoints in an image set. + /// + /// Image collection. + /// Masks for image set. masks[i] is a mask for images[i]. + /// Collection of keypoints detected in an input images. keypoints[i] is a set of keypoints detected in an images[i]. + public KeyPoint[][] Detect(IEnumerable images, IEnumerable? masks = null) + { + if (images == null) + throw new ArgumentNullException(nameof(images)); + ThrowIfDisposed(); + + var imagesArray = EnumerableEx.ToArray(images); + var imagesPtr = new IntPtr[imagesArray.Length]; + for (var i = 0; i < imagesArray.Length; i++) + imagesPtr[i] = imagesArray[i].CvPtr; + + using (var keypoints = new VectorOfVectorKeyPoint()) + { + if (masks == null) + { + NativeMethods.features2d_Feature2D_detect_Mat2( + ptr, imagesPtr, imagesArray.Length, keypoints.CvPtr, null); + } + else + { + var masksPtr = EnumerableEx.SelectPtrs(masks); + if (masksPtr.Length != imagesArray.Length) + throw new ArgumentException("masks.Length != images.Length"); + NativeMethods.features2d_Feature2D_detect_Mat2( + ptr, imagesPtr, imagesArray.Length, keypoints.CvPtr, masksPtr); + GC.KeepAlive(masks); + } + GC.KeepAlive(this); + GC.KeepAlive(imagesArray); + return keypoints.ToArray(); + } + } + + /// + /// Compute the descriptors for a set of keypoints in an image. + /// + /// The image. + /// The input keypoints. Keypoints for which a descriptor cannot be computed are removed. + /// Copmputed descriptors. Row i is the descriptor for keypoint i.param> + public virtual void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray descriptors) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + ThrowIfDisposed(); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_Feature2D_compute1(ptr, image.CvPtr, keypointsVec.CvPtr, descriptors.CvPtr); + keypoints = keypointsVec.ToArray(); + } + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(descriptors); + } + + /// + /// Compute the descriptors for a keypoints collection detected in image collection. + /// + /// Image collection. + /// Input keypoints collection. keypoints[i] is keypoints detected in images[i]. + /// Keypoints for which a descriptor cannot be computed are removed. + /// Descriptor collection. descriptors[i] are descriptors computed for set keypoints[i]. + public virtual void Compute(IEnumerable images, ref KeyPoint[][] keypoints, IEnumerable descriptors) + { + ThrowIfDisposed(); + if (images == null) + throw new ArgumentNullException(nameof(images)); + if (descriptors == null) + throw new ArgumentNullException(nameof(descriptors)); + + var imagesPtrs = EnumerableEx.SelectPtrs(images); + var descriptorsPtrs = EnumerableEx.SelectPtrs(descriptors); + + using (var keypointsVec = new VectorOfVectorKeyPoint(keypoints)) + { + NativeMethods.features2d_Feature2D_compute2( + ptr, imagesPtrs, imagesPtrs.Length, keypointsVec.CvPtr, + descriptorsPtrs, descriptorsPtrs.Length); + + keypoints = keypointsVec.ToArray(); + } + GC.KeepAlive(this); + GC.KeepAlive(images); + GC.KeepAlive(descriptors); + } + + /// + /// Detects keypoints and computes the descriptors + /// + /// + /// + /// + /// + /// + public virtual void DetectAndCompute( + InputArray image, + InputArray? mask, + out KeyPoint[] keypoints, + OutputArray descriptors, + bool useProvidedKeypoints = false) + { + ThrowIfDisposed(); + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (descriptors == null) + throw new ArgumentNullException(nameof(descriptors)); + image.ThrowIfDisposed(); + mask?.ThrowIfDisposed(); + + using (var keypointsVec = new VectorOfKeyPoint()) + { + NativeMethods.features2d_Feature2D_detectAndCompute( + ptr, image.CvPtr, Cv2.ToPtr(mask), keypointsVec.CvPtr, descriptors.CvPtr, useProvidedKeypoints ? 1 : 0); + keypoints = keypointsVec.ToArray(); + } + + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(mask); + descriptors.Fix(); + GC.KeepAlive(descriptors); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/FlannBasedMatcher.cs b/OpenVinoOpenCvSharp/Modules/features2d/FlannBasedMatcher.cs new file mode 100644 index 0000000..731a3ba --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/FlannBasedMatcher.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Flann; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Brute-force descriptor matcher. + /// For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. + /// + public class FlannBasedMatcher : DescriptorMatcher + { + private Ptr? detectorPtr; + private IndexParams? indexParams; + private SearchParams? searchParams; + + //internal override IntPtr PtrObj => detectorPtr.CvPtr; + + #region Init & Disposal + + /// + /// + /// + /// + /// + public FlannBasedMatcher(IndexParams? indexParams = null, SearchParams? searchParams = null) + { + indexParams?.ThrowIfDisposed(); + searchParams?.ThrowIfDisposed(); + + var indexParamsPtr = indexParams?.PtrObj?.CvPtr ?? IntPtr.Zero; + var searchParamsPtr = searchParams?.PtrObj?.CvPtr ?? IntPtr.Zero; + ptr = NativeMethods.features2d_FlannBasedMatcher_new(indexParamsPtr, searchParamsPtr); + this.indexParams = indexParams; + this.searchParams = searchParams; + } + + /// + /// Creates instance by cv::Ptr<T> + /// + internal FlannBasedMatcher(Ptr detectorPtr) + { + this.detectorPtr = detectorPtr; + ptr = detectorPtr.Get(); + } + + /// + /// Creates instance by raw pointer T* + /// + internal FlannBasedMatcher(IntPtr rawPtr) + { + detectorPtr = null; + ptr = rawPtr; + } + + /// + /// Creates instance from cv::Ptr<T> . + /// ptr is disposed when the wrapper disposes. + /// + /// + internal new static FlannBasedMatcher FromPtr(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Invalid cv::Ptr pointer"); + var ptrObj = new Ptr(ptr); + return new FlannBasedMatcher(ptrObj); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + if (detectorPtr != null) + { + detectorPtr.Dispose(); + detectorPtr = null; + ptr = IntPtr.Zero; + } + base.DisposeManaged(); + } + + /// + /// Releases managed resources + /// + protected override void DisposeUnmanaged() + { + if (detectorPtr == null && ptr != IntPtr.Zero) + NativeMethods.features2d_FlannBasedMatcher_delete(ptr); + indexParams = null; + searchParams = null; + ptr = IntPtr.Zero; + base.DisposeUnmanaged(); + } + + #endregion + + #region Methods + + /// + /// Return true if the matcher supports mask in match methods. + /// + /// + public override bool IsMaskSupported() + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_FlannBasedMatcher_isMaskSupported(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Add descriptors to train descriptor collection. + /// + /// Descriptors to add. Each descriptors[i] is a descriptors set from one image. + public override void Add(IEnumerable descriptors) + { + ThrowIfDisposed(); + if (descriptors == null) + throw new ArgumentNullException(nameof(descriptors)); + + var descriptorsArray = EnumerableEx.ToArray(descriptors); + if (descriptorsArray.Length == 0) + return; + + var descriptorsPtrs = EnumerableEx.SelectPtrs(descriptorsArray); + NativeMethods.features2d_DescriptorMatcher_add(ptr, descriptorsPtrs, descriptorsPtrs.Length); + GC.KeepAlive(descriptorsArray); + } + + /// + /// Clear train descriptors collection. + /// + public override void Clear() + { + ThrowIfDisposed(); + NativeMethods.features2d_FlannBasedMatcher_clear(ptr); + GC.KeepAlive(this); + } + + /// + /// Train matcher (e.g. train flann index). + /// In all methods to match the method train() is run every time before matching. + /// Some descriptor matchers (e.g. BruteForceMatcher) have empty implementation + /// of this method, other matchers really train their inner structures + /// (e.g. FlannBasedMatcher trains flann::Index). So nonempty implementation + /// of train() should check the class object state and do traing/retraining + /// only if the state requires that (e.g. FlannBasedMatcher trains flann::Index + /// if it has not trained yet or if new descriptors have been added to the train collection). + /// + public override void Train() + { + ThrowIfDisposed(); + NativeMethods.features2d_FlannBasedMatcher_train(ptr); + GC.KeepAlive(this); + } + + #endregion + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_FlannBasedMatcher_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_FlannBasedMatcher_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/GFTTDetector.cs b/OpenVinoOpenCvSharp/Modules/features2d/GFTTDetector.cs new file mode 100644 index 0000000..3fa935e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/GFTTDetector.cs @@ -0,0 +1,206 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// Good Features To Track Detector + /// + public class GFTTDetector : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static GFTTDetector Create( + int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 1, + int blockSize = 3, bool useHarrisDetector = false, double k = 0.04) + { + var ptr = NativeMethods.features2d_GFTTDetector_create( + maxCorners, qualityLevel, minDistance, + blockSize, useHarrisDetector ? 1 : 0, k); + return new GFTTDetector(ptr); + } + + /// + /// + /// + /// + protected GFTTDetector(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int MaxFeatures + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getMaxFeatures(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setMaxFeatures(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public double QualityLevel + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getQualityLevel(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setQualityLevel(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public double MinDistance + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getMinDistance(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setMinDistance(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int BlockSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getBlockSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setBlockSize(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public bool HarrisDetector + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getHarrisDetector(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setHarrisDetector(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public double K + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_GFTTDetector_getK(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_GFTTDetector_setK(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_GFTTDetector_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_GFTTDetector_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/KAZE.cs b/OpenVinoOpenCvSharp/Modules/features2d/KAZE.cs new file mode 100644 index 0000000..bcbbfba --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/KAZE.cs @@ -0,0 +1,213 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + +#if LANG_JP + /// + /// KAZE 実装 + /// +#else + /// + /// Class implementing the KAZE keypoint detector and descriptor extractor + /// +#endif + // ReSharper disable once InconsistentNaming + public class KAZE : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected KAZE(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// The KAZE constructor + /// + /// Set to enable extraction of extended (128-byte) descriptor. + /// Set to enable use of upright descriptors (non rotation-invariant). + /// Detector response threshold to accept point + /// Maximum octave evolution of the image + /// Default number of sublevels per scale level + /// Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or DIFF_CHARBONNIER + public static KAZE Create( + bool extended = false, bool upright = false, float threshold = 0.001f, + int nOctaves = 4, int nOctaveLayers = 4, KAZEDiffusivityType diffusivity = KAZEDiffusivityType.DiffPmG2) + { + var ptr = NativeMethods.features2d_KAZE_create( + extended, upright, threshold, + nOctaves, nOctaveLayers, (int) diffusivity); + return new KAZE(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public KAZEDiffusivityType Diffusivity + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getDiffusivity(ptr); + GC.KeepAlive(this); + return (KAZEDiffusivityType)res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setDiffusivity(ptr, (int)value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public bool Extended + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getExtended(ptr); + GC.KeepAlive(this); + return res != 0; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setExtended(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int NOctaveLayers + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getNOctaveLayers(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setNOctaveLayers(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int NOctaves + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getNOctaves(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setNOctaves(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public double Threshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public bool Upright + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_KAZE_getUpright(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_KAZE_setUpright(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_KAZE_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_KAZE_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/KeyPointsFilter.cs b/OpenVinoOpenCvSharp/Modules/features2d/KeyPointsFilter.cs new file mode 100644 index 0000000..5b98828 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/KeyPointsFilter.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + + /// + /// A class filters a vector of keypoints. + /// + public static class KeyPointsFilter + { + /// + /// Remove keypoints within borderPixels of an image edge. + /// + /// + /// + /// + /// + public static KeyPoint[] RunByImageBorder(IEnumerable keypoints, Size imageSize, int borderSize) + { + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_KeyPointsFilter_runByImageBorder( + keypointsVec.CvPtr, imageSize, borderSize); + return keypointsVec.ToArray(); + } + } + + /// + /// Remove keypoints of sizes out of range. + /// + /// + /// + /// + /// + public static KeyPoint[] RunByKeypointSize(IEnumerable keypoints, float minSize, + float maxSize = float.MaxValue) + { + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_KeyPointsFilter_runByKeypointSize( + keypointsVec.CvPtr, minSize, maxSize); + return keypointsVec.ToArray(); + } + } + + /// + /// Remove keypoints from some image by mask for pixels of this image. + /// + /// + /// + /// + public static KeyPoint[] RunByPixelsMask(IEnumerable keypoints, Mat mask) + { + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + if (mask == null) + throw new ArgumentNullException(nameof(mask)); + mask.ThrowIfDisposed(); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_KeyPointsFilter_runByPixelsMask( + keypointsVec.CvPtr, mask.CvPtr); + GC.KeepAlive(mask); + return keypointsVec.ToArray(); + } + } + + /// + /// Remove duplicated keypoints. + /// + /// + /// + public static KeyPoint[] RemoveDuplicated(IEnumerable keypoints) + { + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_KeyPointsFilter_removeDuplicated(keypointsVec.CvPtr); + return keypointsVec.ToArray(); + } + } + + /// + /// Retain the specified number of the best keypoints (according to the response) + /// + /// + /// + /// + public static KeyPoint[] RetainBest(IEnumerable keypoints, int npoints) + { + if (keypoints == null) + throw new ArgumentNullException(nameof(keypoints)); + + using (var keypointsVec = new VectorOfKeyPoint(keypoints)) + { + NativeMethods.features2d_KeyPointsFilter_retainBest( + keypointsVec.CvPtr, npoints); + return keypointsVec.ToArray(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/MSER.cs b/OpenVinoOpenCvSharp/Modules/features2d/MSER.cs new file mode 100644 index 0000000..da73c5d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/MSER.cs @@ -0,0 +1,224 @@ +using System; + +namespace OpenCvSharp +{ +// ReSharper disable once InconsistentNaming + +#if LANG_JP + /// + /// MSER (Maximal Stable Extremal Regions) 抽出機 + /// +#else + /// + /// Maximal Stable Extremal Regions class + /// +#endif + // ReSharper disable once InconsistentNaming + public class MSER : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// Creates instance by raw pointer cv::MSER* + /// + protected MSER(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + +#if LANG_JP + /// + /// MSERのパラメータを生成する + /// + /// delta, in the code, it compares (size_{i}-size_{i-delta})/size_{i-delta} + /// prune the area which smaller than min_area + /// prune the area which bigger than max_area + /// prune the area have simliar size to its children + /// trace back to cut off mser with diversity < min_diversity + /// for color image, the evolution steps + /// the area threshold to cause re-initialize + /// ignore too small margin + /// the aperture size for edge blur +#else + /// + /// Creates MSER parameters + /// + /// delta, in the code, it compares (size_{i}-size_{i-delta})/size_{i-delta} + /// prune the area which smaller than min_area + /// prune the area which bigger than max_area + /// prune the area have simliar size to its children + /// trace back to cut off mser with diversity < min_diversity + /// for color image, the evolution steps + /// the area threshold to cause re-initialize + /// ignore too small margin + /// the aperture size for edge blur +#endif + public static MSER Create( + int delta = 5, + int minArea = 60, + int maxArea = 14400, + double maxVariation = 0.25, + double minDiversity = 0.2, + int maxEvolution = 200, + double areaThreshold = 1.01, + double minMargin = 0.003, + int edgeBlurSize = 5) + { + var ptr = NativeMethods.features2d_MSER_create(delta, minArea, maxArea, maxVariation, minDiversity, + maxEvolution, areaThreshold, minMargin, edgeBlurSize); + return new MSER(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int Delta + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_MSER_getDelta(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_MSER_setDelta(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int MinArea + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_MSER_getMinArea(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_MSER_setMinArea(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public int MaxArea + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_MSER_getMaxArea(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_MSER_setMaxArea(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public bool Pass2Only + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_MSER_getPass2Only(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_MSER_setPass2Only(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// + /// + /// + /// + /// + public virtual void DetectRegions( + InputArray image, out Point[][] msers, out Rect[] bboxes) + { + ThrowIfDisposed(); + if (image == null) + throw new ArgumentNullException(nameof(image)); + image.ThrowIfDisposed(); + + using (var msersVec = new VectorOfVectorPoint()) + using (var bboxesVec = new VectorOfRect()) + { + NativeMethods.features2d_MSER_detectRegions( + ptr, image.CvPtr, msersVec.CvPtr, bboxesVec.CvPtr); + GC.KeepAlive(this); + msers = msersVec.ToArray(); + bboxes = bboxesVec.ToArray(); + } + + GC.KeepAlive(image); + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_MSER_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_MSER_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/ORB.cs b/OpenVinoOpenCvSharp/Modules/features2d/ORB.cs new file mode 100644 index 0000000..2f0930b --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/ORB.cs @@ -0,0 +1,286 @@ +using System; + +namespace OpenCvSharp +{ + // ReSharper disable once InconsistentNaming + +#if LANG_JP + /// + /// ORB 実装 + /// +#else + /// + /// Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor + /// + /// + /// described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, + /// selects the strongest features using FAST or Harris response, finds their orientation + /// using first-order moments and computes the descriptors using BRIEF (where the coordinates + /// of random point pairs (or k-tuples) are rotated according to the measured orientation). + /// +#endif + // ReSharper disable once InconsistentNaming + public class ORB : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + #region Init & Disposal + + /// + /// + /// + protected ORB(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static ORB Create( + int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, + int edgeThreshold = 31, int firstLevel = 0, int wtaK = 2, + ORBScoreType scoreType = ORBScoreType.Harris, int patchSize = 31) + { + var ptr = NativeMethods.features2d_ORB_create( + nFeatures, scaleFactor, nLevels, edgeThreshold, + firstLevel, wtaK, (int)scoreType, patchSize); + return new ORB(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// + /// + public int MaxFeatures + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getMaxFeatures(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setMaxFeatures(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// + /// + public double ScaleFactor + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getScaleFactor(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setScaleFactor(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int NLevels + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getNLevels(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setNLevels(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int EdgeThreshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getEdgeThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setEdgeThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int FirstLevel + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getFirstLevel(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setFirstLevel(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + // ReSharper disable once InconsistentNaming + public int WTA_K + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getWTA_K(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setWTA_K(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public ORBScoreType ScoreType + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getScoreType(ptr); + GC.KeepAlive(this); + return (ORBScoreType)res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setScoreType(ptr, (int)value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int PatchSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getPatchSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setPatchSize(ptr, value); + GC.KeepAlive(this); + } + } + + + /// + /// + /// + public int FastThreshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.features2d_ORB_getFastThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.features2d_ORB_setFastThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_ORB_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_ORB_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/features2d/SimpleBlobDetector.cs b/OpenVinoOpenCvSharp/Modules/features2d/SimpleBlobDetector.cs new file mode 100644 index 0000000..f36de0d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/features2d/SimpleBlobDetector.cs @@ -0,0 +1,252 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// Class for extracting blobs from an image. + /// + public class SimpleBlobDetector : Feature2D + { + private Ptr? ptrObj; + + //internal override IntPtr PtrObj => ptrObj.CvPtr; + + /// + /// SimpleBlobDetector parameters + /// + public class Params + { + internal WParams Data; + + /// + /// + /// + public Params() + { + Data = new WParams + { + thresholdStep = 10, + minThreshold = 50, + maxThreshold = 220, + minRepeatability = 2, + minDistBetweenBlobs = 10, + filterByColor = 1, + blobColor = 0, + filterByArea = 1, + minArea = 25, + maxArea = 5000, + filterByCircularity = 0, + minCircularity = 0.8f, + maxCircularity = float.MaxValue, + filterByInertia = 1, + minInertiaRatio = 0.1f, + maxInertiaRatio = float.MaxValue, + filterByConvexity = 1, + minConvexity = 0.95f, + maxConvexity = float.MaxValue + }; + } + +#pragma warning disable 1591 + public float ThresholdStep + { + get => Data.thresholdStep; + set => Data.thresholdStep = value; + } + + public float MinThreshold + { + get => Data.minThreshold; + set => Data.minThreshold = value; + } + + public float MaxThreshold + { + get => Data.maxThreshold; + set => Data.maxThreshold = value; + } + + public uint MinRepeatability + { + get => Data.minRepeatability; + set => Data.minRepeatability = value; + } + + public float MinDistBetweenBlobs + { + get => Data.minDistBetweenBlobs; + set => Data.minDistBetweenBlobs = value; + } + + public bool FilterByColor + { + get => Data.filterByColor != 0; + set => Data.filterByColor = (value ? 1 : 0); + } + + public byte BlobColor + { + get => Data.blobColor; + set => Data.blobColor = value; + } + + public bool FilterByArea + { + get => Data.filterByArea != 0; + set => Data.filterByArea = (value ? 1 : 0); + } + + public float MinArea + { + get => Data.minArea; + set => Data.minArea = value; + } + + public float MaxArea + { + get => Data.maxArea; + set => Data.maxArea = value; + } + + public bool FilterByCircularity + { + get => Data.filterByCircularity != 0; + set => Data.filterByCircularity = (value ? 1 : 0); + } + + public float MinCircularity + { + get => Data.minCircularity; + set => Data.minCircularity = value; + } + + public float MaxCircularity + { + get => Data.maxCircularity; + set => Data.maxCircularity = value; + } + + public bool FilterByInertia + { + get => Data.filterByInertia != 0; + set => Data.filterByInertia = (value ? 1 : 0); + } + + public float MinInertiaRatio + { + get => Data.minInertiaRatio; + set => Data.minInertiaRatio = value; + } + + public float MaxInertiaRatio + { + get => Data.maxInertiaRatio; + set => Data.maxInertiaRatio = value; + } + + public bool FilterByConvexity + { + get => Data.filterByConvexity != 0; + set => Data.filterByConvexity = (value ? 1 : 0); + } + + public float MinConvexity + { + get => Data.minConvexity; + set => Data.minConvexity = value; + } + + public float MaxConvexity + { + get => Data.maxConvexity; + set => Data.maxConvexity = value; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct WParams + { + public float thresholdStep; + public float minThreshold; + public float maxThreshold; + public uint minRepeatability; // size_t + public float minDistBetweenBlobs; + + public int filterByColor; + public byte blobColor; + + public int filterByArea; + public float minArea, maxArea; + + public int filterByCircularity; + public float minCircularity, maxCircularity; + + public int filterByInertia; + public float minInertiaRatio, maxInertiaRatio; + + public int filterByConvexity; + public float minConvexity, maxConvexity; +#pragma warning restore 1591 + } + + #region Init & Disposal + + /// + /// + /// + protected SimpleBlobDetector(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// + /// + /// + public static SimpleBlobDetector Create(Params? parameters = null) + { + if (parameters == null) + parameters = new Params(); + var ptr = NativeMethods.features2d_SimpleBlobDetector_create(ref parameters.Data); + return new SimpleBlobDetector(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Methods + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.features2d_Ptr_SimpleBlobDetector_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.features2d_Ptr_SimpleBlobDetector_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/FlannCentersInit.cs b/OpenVinoOpenCvSharp/Modules/flann/FlannCentersInit.cs new file mode 100644 index 0000000..adf73ff --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/FlannCentersInit.cs @@ -0,0 +1,57 @@ +// ReSharper disable InconsistentNaming +// ReSharper disable CommentTypo +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// k-means クラスタリングの初期中心を選択するアルゴリズム. + /// +#else + /// + /// The algorithm to use for selecting the initial centers when performing a k-means clustering step. + /// +#endif + public enum FlannCentersInit + { +#if LANG_JP + /// + /// ランダムに初期クラスタ中心を選択 + /// [flann_centers_init_t::CENTERS_RANDOM] + /// +#else + /// + /// picks the initial cluster centers randomly + /// [flann_centers_init_t::CENTERS_RANDOM] + /// +#endif + Random = 0, + +#if LANG_JP + /// + /// Gonzalesのアルゴリズムを用いて初期クラスタ中心を選択 + /// [flann_centers_init_t::CENTERS_GONZALES] + /// +#else + /// + /// picks the initial centers using Gonzales’ algorithm + /// [flann_centers_init_t::CENTERS_GONZALES] + /// +#endif + Gonzales = 1, + +#if LANG_JP + /// + /// arthur_kmeanspp_2007 で提案されたアルゴリズムを用いて初期クラスタ中心を選択 + /// [flann_centers_init_t::CENTERS_KMEANSPP] + /// +#else + /// + /// picks the initial centers using the algorithm suggested in [arthur_kmeanspp_2007] + /// [flann_centers_init_t::CENTERS_KMEANSPP] + /// +#endif + KMeansPP = 2 + } +} + + diff --git a/OpenVinoOpenCvSharp/Modules/flann/FlannDistance.cs b/OpenVinoOpenCvSharp/Modules/flann/FlannDistance.cs new file mode 100644 index 0000000..7994540 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/FlannDistance.cs @@ -0,0 +1,25 @@ +namespace OpenCvSharp.Flann +{ +#pragma warning disable 1591 +// ReSharper disable InconsistentNaming + + /// + /// + /// + public enum FlannDistance + { + Euclidean = 1, + L2 = 1, + Manhattan = 2, + L1 = 2, + Minkowski = 3, + Max = 4, + HistIntersect = 5, + Hellinger = 6, + ChiSquare = 7, + CS = 7, + KullbackLeibler = 8, + KL = 8, + Hamming = 9, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/Index.cs b/OpenVinoOpenCvSharp/Modules/flann/Index.cs new file mode 100644 index 0000000..5265f51 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/Index.cs @@ -0,0 +1,343 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// FLANN 最近傍インデックスクラス + /// +#else + /// + /// The FLANN nearest neighbor index class. + /// +#endif + public class Index : DisposableCvObject + { + #region Init & Disposal + +#if LANG_JP + /// + /// 与えられたデータセットの最近傍探索インデックスを作成します. + /// + /// インデックス作成対象となる特徴(点)が格納された, CV_32F 型の行列.この行列のサイズは matrix is num _ features x feature _ dimensionality となります + /// params – インデックスパラメータを含む構造体.作成されるインデックスの種類は,このパラメータの種類に依存します + /// +#else + /// + /// Constructs a nearest neighbor search index for a given dataset. + /// + /// 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. + /// +#endif + public Index(InputArray features, IndexParams @params, FlannDistance distType = FlannDistance.L2) + { + if (features == null) + throw new ArgumentNullException(nameof(features)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + + ptr = NativeMethods.flann_Index_new(features.CvPtr, @params.CvPtr, (int)distType); + GC.KeepAlive(features); + GC.KeepAlive(@params); + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException("Failed to create Index"); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Index_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Methods + #region KnnSearch +#if LANG_JP + /// + /// 複数のクエリ点に対するk-近傍探索を行います. + /// + /// クエリ点 + /// 求められた最近傍のインデックス + /// 求められた最近傍までの距離 + /// この個数分の最近傍を求めます + /// 探索パラメータ +#else + /// + /// Performs a K-nearest neighbor search for multiple query points. + /// + /// The query points, one per row + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// Search parameters +#endif + public void KnnSearch(float[] queries, out int[] indices, out float[] dists, int knn, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + if (queries.Length == 0) + throw new ArgumentException(); + if (knn < 1) + throw new ArgumentOutOfRangeException(nameof(knn)); + + indices = new int[knn]; + dists = new float[knn]; + + NativeMethods.flann_Index_knnSearch1(ptr, queries, queries.Length, indices, dists, knn, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(@params); + } +#if LANG_JP + /// + /// 複数のクエリ点に対するk-近傍探索を行います. + /// + /// クエリ点.1行が1つの点を表します + /// 求められた最近傍のインデックス + /// 求められた最近傍までの距離 + /// この個数分の最近傍を求めます + /// 探索パラメータ +#else + /// + /// Performs a K-nearest neighbor search for multiple query points. + /// + /// The query points, one per row + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// Search parameters +#endif + public void KnnSearch(Mat queries, Mat indices, Mat dists, int knn, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (indices == null) + throw new ArgumentNullException(nameof(indices)); + if (dists == null) + throw new ArgumentNullException(nameof(dists)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + + NativeMethods.flann_Index_knnSearch2(ptr, queries.CvPtr, indices.CvPtr, dists.CvPtr, knn, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(queries); + GC.KeepAlive(indices); + GC.KeepAlive(dists); + GC.KeepAlive(@params); + } +#if LANG_JP + /// + /// 複数のクエリ点に対するk-近傍探索を行います. + /// + /// クエリ点.1行が1つの点を表します + /// 求められた最近傍のインデックス + /// 求められた最近傍までの距離 + /// この個数分の最近傍を求めます + /// 探索パラメータ +#else + /// + /// Performs a K-nearest neighbor search for multiple query points. + /// + /// The query points, one per row + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// Search parameters +#endif + public void KnnSearch(Mat queries, out int[] indices, out float[] dists, int knn, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + if (knn < 1) + throw new ArgumentOutOfRangeException(nameof(knn)); + + indices = new int[knn]; + dists = new float[knn]; + + NativeMethods.flann_Index_knnSearch3(ptr, queries.CvPtr, indices, dists, knn, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(queries); + GC.KeepAlive(@params); + } + #endregion + #region RadiusSearch +#if LANG_JP + /// + /// 与えられたクエリ点に対するradius 最近傍探索を行います. + /// + /// クエリ点.1行が1つの点を表します [入力] + /// 求められた最近傍のインデックス [出力] + /// 求められた最近傍までの距離 [出力] + /// 探索範囲 + /// + /// 探索パラメータ +#else + /// + /// Performs a radius nearest neighbor search for a given query point. + /// + /// The query point + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// + /// Search parameters +#endif + public void RadiusSearch(float[] queries, int[] indices, float[] dists, float radius, int maxResults, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (indices == null) + throw new ArgumentNullException(nameof(indices)); + if (dists == null) + throw new ArgumentNullException(nameof(dists)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + + NativeMethods.flann_Index_radiusSearch1(ptr, queries, queries.Length, indices, indices.Length, dists, dists.Length, radius, maxResults, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(@params); + } +#if LANG_JP + /// + /// 与えられたクエリ点に対するradius 最近傍探索を行います. + /// + /// クエリ点.1行が1つの点を表します [入力] + /// 求められた最近傍のインデックス [出力] + /// 求められた最近傍までの距離 [出力] + /// 探索範囲 + /// + /// 探索パラメータ +#else + /// + /// Performs a radius nearest neighbor search for a given query point. + /// + /// The query point + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// + /// Search parameters +#endif + public void RadiusSearch(Mat queries, Mat indices, Mat dists, float radius, int maxResults, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (indices == null) + throw new ArgumentNullException(nameof(indices)); + if (dists == null) + throw new ArgumentNullException(nameof(dists)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + + NativeMethods.flann_Index_radiusSearch2(ptr, queries.CvPtr, indices.CvPtr, dists.CvPtr, radius, maxResults, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(queries); + GC.KeepAlive(indices); + GC.KeepAlive(dists); + GC.KeepAlive(@params); + } +#if LANG_JP + /// + /// 与えられたクエリ点に対するradius 最近傍探索を行います. + /// + /// クエリ点.1行が1つの点を表します [入力] + /// 求められた最近傍のインデックス [出力] + /// 求められた最近傍までの距離 [出力] + /// 探索範囲 + /// + /// 探索パラメータ +#else + /// + /// Performs a radius nearest neighbor search for a given query point. + /// + /// The query point + /// Indices of the nearest neighbors found + /// Distances to the nearest neighbors found + /// Number of nearest neighbors to search for + /// + /// Search parameters +#endif + public void RadiusSearch(Mat queries, int[] indices, float[] dists, float radius, int maxResults, SearchParams @params) + { + if (queries == null) + throw new ArgumentNullException(nameof(queries)); + if (indices == null) + throw new ArgumentNullException(nameof(indices)); + if (dists == null) + throw new ArgumentNullException(nameof(dists)); + if (@params == null) + throw new ArgumentNullException(nameof(@params)); + + NativeMethods.flann_Index_radiusSearch3(ptr, queries.CvPtr, indices, indices.Length, dists, dists.Length, radius, maxResults, @params.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(queries); + GC.KeepAlive(@params); + } + #endregion + #region Save +#if LANG_JP + /// + /// インデックスをファイルに保存します. + /// + /// インデックスを保存するファイル名 +#else + /// + /// Saves the index to a file. + /// + /// The file to save the index to +#endif + public void Save(string filename) + { + if (string.IsNullOrEmpty(filename)) + throw new ArgumentNullException(nameof(filename)); + NativeMethods.flann_Index_save(ptr, filename); + GC.KeepAlive(this); + } + #endregion + /* + #region VecLen +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + public int VecLen() + { + return FlannInvoke.flann_Index_veclen(ptr); + } + #endregion + #region Size +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + public int Size() + { + return FlannInvoke.flann_Index_size(ptr); + } + #endregion + //*/ + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/AutotunedIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/AutotunedIndexParams.cs new file mode 100644 index 0000000..8dfe36a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/AutotunedIndexParams.cs @@ -0,0 +1,82 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// 階層型 k-means tree で表現されるインデックス. + /// +#else + /// + /// hierarchical k-means tree. + /// +#endif + public class AutotunedIndexParams : IndexParams + { +#if LANG_JP + /// + /// + /// + /// どれだけ厳密な最近傍を返すかという,最近傍探索の近似の割合を指定する 0から1の間の値.このパラメータが大きくなると,より正確な結果が得られますが,探索時間が長くなります.最適な値は,アプリケーションに依存します + /// 最近傍探索時間に対するインデックスの構築時間の重要度を指定します. + /// その後のインデックス探索時間が高速になるならば,インデックスの構築時間が長くても良いというアプリケーションが存在する一方で,インデックスの探索時間が多少長くなっても,できるだけ高速にインデックスを構築する必要があるアプリケーションもあります + /// これは,(インデックスの構築時間と探索時間)とインデックスの占有メモリとの,トレードオフを指定するのに利用されます. + /// 1より小さい値は消費時間を重要視し,1より大きい値はメモリ使用量を重要視します + /// パラメータの自動設定アルゴリズムにおけるデータ集合の比率を示す,0から1の間の値. + /// 全データ集合を用いてアルゴリズムを実行すると,最も正確な結果が得られますが,巨大なデータ集合に対しては長い計算時間がかかります. + /// このような場合,データをある比率分だけ使うことでアルゴリズムを高速化し,なおかつ,最適なパラメータの良い近似となる結果を得ることができます +#else + /// + /// + /// + /// Is a number between 0 and 1 specifying the percentage of the approximate nearest-neighbor searches that return the exact nearest-neighbor. + /// Using a higher value for this parameter gives more accurate results, but the search takes longer. The optimum value usually depends on the application. + /// Specifies the importance of the index build time raported to the nearest-neighbor search time. + /// In some applications it’s acceptable for the index build step to take a long time if the subsequent searches in the index can be performed very fast. + /// In other applications it’s required that the index be build as fast as possible even if that leads to slightly longer search times. + /// Is used to specify the tradeoff between time (index build time and search time) and memory used by the index. + /// A value less than 1 gives more importance to the time spent and a value greater than 1 gives more importance to the memory usage. + /// Is a number between 0 and 1 indicating what fraction of the dataset to use in the automatic parameter configuration algorithm. + /// Running the algorithm on the full dataset gives the most accurate results, but for very large datasets can take longer than desired. + /// In such case using just a fraction of the data helps speeding up this algorithm while still giving good approximations of the optimum parameters. +#endif + public AutotunedIndexParams(float targetPrecision = 0.9f, float buildWeight = 0.01f, float memoryWeight = 0, float sampleFraction = 0.1f) + : base(null) + { + var p = NativeMethods.flann_Ptr_AutotunedIndexParams_new(targetPrecision, buildWeight, memoryWeight, sampleFraction); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(AutotunedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected AutotunedIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_AutotunedIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_AutotunedIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/CompositeIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/CompositeIndexParams.cs new file mode 100644 index 0000000..efeabb4 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/CompositeIndexParams.cs @@ -0,0 +1,75 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// ランダム kd-tree と 階層的 k-means tree の組み合わせでインデックスが表現されます. + /// +#else + /// + /// When using a parameters object of this type the index created combines the randomized kd-trees and the hierarchical k-means tree. + /// +#endif + public class CompositeIndexParams : IndexParams + { +#if LANG_JP + /// + /// + /// + /// 並列な kd-tree の個数.[1..16] の範囲が適切な値です + /// 階層型 k-means tree で利用される branching ファクタ + /// k-means tree を作成する際の,k-means クラスタリングステージでの反復数の上限.ここで -1 は,k-means クラスタリングが収束するまで続けられることを意味します + /// k-means クラスタリングの初期中心を選択するアルゴリズム. + /// このパラメータ(クラスタ境界インデックス)は,階層的 k-means tree の探索方法に影響を与えます. cb_index が0の場合,最も近い中心のクラスタが,次に探索される k-means 領域になります.0より大きい値の場合も,領域サイズが考慮されます +#else + /// + /// + /// + /// The number of parallel kd-trees to use. Good values are in the range [1..16] + /// The branching factor to use for the hierarchical k-means tree + /// The maximum number of iterations to use in the k-means clustering stage when building the k-means tree. A value of -1 used here means that the k-means clustering should be iterated until convergence + /// The algorithm to use for selecting the initial centers when performing a k-means clustering step. + /// This parameter (cluster boundary index) influences the way exploration is performed in the hierarchical kmeans tree. When cb_index is zero the next kmeans domain to be explored is choosen to be the one with the closest center. A value greater then zero also takes into account the size of the domain. +#endif + public CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, + FlannCentersInit centersInit = FlannCentersInit.Random, float cbIndex = 0.2f) + : base(null) + { + var p = NativeMethods.flann_Ptr_CompositeIndexParams_new(trees, branching, iterations, centersInit, cbIndex); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(AutotunedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected CompositeIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_CompositeIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_CompositeIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/IndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/IndexParams.cs new file mode 100644 index 0000000..44bfa57 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/IndexParams.cs @@ -0,0 +1,200 @@ +using System; +using System.Text; + +namespace OpenCvSharp.Flann +{ + /// + /// + /// + public class IndexParams : DisposableCvObject + { + internal OpenCvSharp.Ptr? PtrObj { get; set; } + + /// + /// + /// + public IndexParams() + { + var p = NativeMethods.flann_Ptr_IndexParams_new(); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(IndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected IndexParams(OpenCvSharp.Ptr? ptrObj) + { + PtrObj = ptrObj; + ptr = PtrObj?.Get() ?? IntPtr.Zero; + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + PtrObj?.Dispose(); + PtrObj = null; + base.DisposeManaged(); + } + + #region Methods + #region Get** + /// + /// + /// + /// + /// + /// + public string GetString(string key, string? defaultVal) + { + var sb = new StringBuilder(1024); + NativeMethods.flann_IndexParams_getString(ptr, key, defaultVal, sb); + GC.KeepAlive(this); + return sb.ToString(); + } + /// + /// + /// + /// + /// + public string GetString(string key) + { + return GetString(key, null); + } + + /// + /// + /// + /// + /// + /// + public int GetInt(string key, int defaultVal) + { + var ret = NativeMethods.flann_IndexParams_getInt(ptr, key, defaultVal); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + /// + public int GetInt(string key) + { + return GetInt(key, -1); + } + + /// + /// + /// + /// + /// + /// + public double GetDouble(string key, double defaultVal) + { + var ret = NativeMethods.flann_IndexParams_getDouble(ptr, key, defaultVal); + GC.KeepAlive(this); + return ret; + } + + /// + /// + /// + /// + /// + public double GetDouble(string key) + { + return GetDouble(key, -1); + } + + #endregion + #region Set** + /// + /// + /// + /// + /// + public void SetString(string key, string value) + { + NativeMethods.flann_IndexParams_setString(ptr, key, value); + GC.KeepAlive(this); + } + /// + /// + /// + /// + /// + public void SetInt(string key, int value) + { + NativeMethods.flann_IndexParams_setInt(ptr, key, value); + GC.KeepAlive(this); + } + /// + /// + /// + /// + /// + public void SetDouble(string key, double value) + { + NativeMethods.flann_IndexParams_setDouble(ptr, key, value); + GC.KeepAlive(this); + } + /// + /// + /// + /// + /// + public void SetFloat(string key, float value) + { + NativeMethods.flann_IndexParams_setFloat(ptr, key, value); + GC.KeepAlive(this); + } + /// + /// + /// + /// + /// + public void SetBool(string key, bool value) + { + NativeMethods.flann_IndexParams_setBool(ptr, key, value ? 1 : 0); + GC.KeepAlive(this); + } + /// + /// + /// + /// + public void SetAlgorithm(int value) + { + NativeMethods.flann_IndexParams_setAlgorithm(ptr, value); + GC.KeepAlive(this); + } + #endregion + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_IndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_IndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KDTreeIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KDTreeIndexParams.cs new file mode 100644 index 0000000..716b1e3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KDTreeIndexParams.cs @@ -0,0 +1,68 @@ +using System; +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// ランダム kd-tree の集合でインデックスが表現され,これは並列に探索されます. + /// +#else + /// + /// When passing an object of this type the index constructed will consist of a set + /// of randomized kd-trees which will be searched in parallel. + /// +#endif + public class KDTreeIndexParams : IndexParams + { +#if LANG_JP + /// + /// + /// + /// 並列な kd-tree の個数.[1..16] の範囲が適切な値です +#else + /// + /// + /// + /// The number of parallel kd-trees to use. Good values are in the range [1..16] +#endif + public KDTreeIndexParams(int trees = 4) + : base(null) + { + var p = NativeMethods.flann_Ptr_KDTreeIndexParams_new(trees); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(AutotunedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected KDTreeIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_KDTreeIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_KDTreeIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KMeansIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KMeansIndexParams.cs new file mode 100644 index 0000000..f4eb38a --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/KMeansIndexParams.cs @@ -0,0 +1,72 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// 階層型 k-means tree でインデックスが表現されます. + /// +#else + /// + /// When passing an object of this type the index constructed will be a hierarchical k-means tree. + /// +#endif + public class KMeansIndexParams : IndexParams + { +#if LANG_JP + /// + /// + /// + /// 階層型 k-means tree で利用される branching ファクタ + /// k-means tree を作成する際の,k-means クラスタリングステージでの反復数の上限.ここで -1 は,k-means クラスタリングが収束するまで続けられることを意味します + /// k-means クラスタリングの初期中心を選択するアルゴリズム. + /// このパラメータ(クラスタ境界インデックス)は,階層的 k-means tree の探索方法に影響を与えます. cb_index が0の場合,最も近い中心のクラスタが,次に探索される k-means 領域になります.0より大きい値の場合も,領域サイズが考慮されます +#else + /// + /// + /// + /// The branching factor to use for the hierarchical k-means tree + /// The maximum number of iterations to use in the k-means clustering stage when building the k-means tree. A value of -1 used here means that the k-means clustering should be iterated until convergence + /// The algorithm to use for selecting the initial centers when performing a k-means clustering step. + /// This parameter (cluster boundary index) influences the way exploration is performed in the hierarchical kmeans tree. When cb_index is zero the next kmeans domain to be explored is choosen to be the one with the closest center. A value greater then zero also takes into account the size of the domain. +#endif + public KMeansIndexParams(int branching = 32, int iterations = 11, FlannCentersInit centersInit = FlannCentersInit.Random, float cbIndex = 0.2f) + : base(null) + { + var p = NativeMethods.flann_Ptr_KMeansIndexParams_new(branching, iterations, centersInit, cbIndex); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(AutotunedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected KMeansIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_KMeansIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_KMeansIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LinearIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LinearIndexParams.cs new file mode 100644 index 0000000..6e12ae8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LinearIndexParams.cs @@ -0,0 +1,58 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// 線形のブルートフォース探索が行われます + /// +#else + /// + /// the index will perform a linear, brute-force search. + /// +#endif + public class LinearIndexParams : IndexParams + { + /// + /// + /// + public LinearIndexParams() + : base(null) + { + var p = NativeMethods.flann_Ptr_LinearIndexParams_new(); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(LinearIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected LinearIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_LinearIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_LinearIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LshIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LshIndexParams.cs new file mode 100644 index 0000000..f4b0fc1 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/LshIndexParams.cs @@ -0,0 +1,70 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// Multi-Probe LSH を使用したインデックスが表現されます. + /// +#else + /// + /// When using a parameters object of this type the index created uses multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007) + /// +#endif + public class LshIndexParams : IndexParams + { +#if LANG_JP + /// + /// + /// + /// 使用するハッシュテーブルの数 (通常、10 から 30) + /// ビットで表現されるハッシュキーのサイズ (通常、10 から 20) + /// 近接するバケツのチェックのためにシフトするビットの数 (0 は LSH の標準、推奨は 2) +#else + /// + /// + /// + /// The number of hash tables to use (between 10 and 30 usually). + /// The size of the hash key in bits (between 10 and 20 usually). + /// The number of bits to shift to check for neighboring buckets (0 is regular LSH, 2 is recommended). +#endif + public LshIndexParams(int tableNumber, int keySize, int multiProbeLevel) + : base(null) + { + var p = NativeMethods.flann_Ptr_LshIndexParams_new(tableNumber, keySize, multiProbeLevel); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(AutotunedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected LshIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_LshIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_LshIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SavedIndexParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SavedIndexParams.cs new file mode 100644 index 0000000..89e970f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SavedIndexParams.cs @@ -0,0 +1,62 @@ +using System; + +namespace OpenCvSharp.Flann +{ +#if LANG_JP + /// + /// ディスクにあらかじめ保存されたデータを読み出すために利用されます. + /// +#else + /// + /// This object type is used for loading a previously saved index from the disk. + /// +#endif + public class SavedIndexParams : IndexParams + { + /// + /// + /// + /// + public SavedIndexParams(string fileName) + : base(null) + { + if (string.IsNullOrEmpty(fileName)) + throw new ArgumentNullException(nameof(fileName)); + + var p = NativeMethods.flann_Ptr_SavedIndexParams_new(fileName); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(SavedIndexParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected SavedIndexParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_SavedIndexParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_SavedIndexParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SearchParams.cs b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SearchParams.cs new file mode 100644 index 0000000..3aa36b7 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/flann/IndexParams/SearchParams.cs @@ -0,0 +1,55 @@ +using System; + +namespace OpenCvSharp.Flann +{ + /// + /// + /// + public class SearchParams : IndexParams + { + /// + /// + /// + /// + /// + /// + public SearchParams(int checks = 32, float eps = 0.0f, bool sorted = true) + : base(null) + { + var p = NativeMethods.flann_Ptr_SearchParams_new(checks, eps, sorted ? 1 : 0); + if (p == IntPtr.Zero) + throw new OpenCvSharpException($"Failed to create {nameof(SearchParams)}"); + + PtrObj = new Ptr(p); + ptr = PtrObj.Get(); + } + + /// + /// + /// + protected SearchParams(OpenCvSharp.Ptr ptrObj) + : base(ptrObj) + { + } + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.flann_Ptr_SearchParams_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.flann_Ptr_SearchParams_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ConvertImageModes.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ConvertImageModes.cs new file mode 100644 index 0000000..59a738e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ConvertImageModes.cs @@ -0,0 +1,24 @@ + +namespace OpenCvSharp +{ + /// + /// + /// + public enum ConvertImageModes + { + /// + /// + /// + None = 0, + + /// + /// + /// + Flip = 1, + + /// + /// + /// + SwapRB = 2 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImreadModes.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImreadModes.cs new file mode 100644 index 0000000..5deb8a3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImreadModes.cs @@ -0,0 +1,118 @@ +using System; +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvLoadImageで用いる読み込みフラグ . + /// +#else + /// + /// Specifies colorness and Depth of the loaded image + /// +#endif + [Flags] + public enum ImreadModes + { + #if LANG_JP + /// + /// 8 ビット,カラーまたはグレースケール [CV_LOAD_IMAGE_UNCHANGED] + /// +#else + /// + /// If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). + /// +#endif + Unchanged = -1, + + +#if LANG_JP + /// + /// 8 ビット,グレースケール [CV_LOAD_IMAGE_GRAYSCALE] + /// +#else + /// + /// If set, always convert image to the single channel grayscale image. + /// +#endif + Grayscale = 0, + + +#if LANG_JP + /// + /// AnyDepth と併用されない限り 8 ビット,カラー [CV_LOAD_IMAGE_COLOR] + /// +#else + /// + /// If set, always convert image to the 3 channel BGR color image. + /// +#endif + Color = 1, + + +#if LANG_JP + /// + ///任意のデプス,グレー [CV_LOAD_IMAGE_ANYDEPTH] + /// +#else + /// + /// If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. + /// +#endif + AnyDepth = 2, + + +#if LANG_JP + /// + /// 8 ビット,カラーまたはグレースケール [CV_LOAD_IMAGE_ANYCOLOR]. + /// AnyDepth と併用可能. + /// +#else + /// + /// If set, the image is read in any possible color format. + /// +#endif + AnyColor = 4, + + /// + /// If set, use the gdal driver for loading the image. + /// + LoadGdal = 8, + + /// + /// If set, always convert image to the single channel grayscale image and the image size reduced 1/2. + /// + ReducedGrayscale2 = 16, + + /// + /// If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. + /// + ReducedColor2 = 17, + + /// + /// If set, always convert image to the single channel grayscale image and the image size reduced 1/4. + /// + ReducedGrayscale4 = 32, + + /// + /// If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. + /// + ReducedColor4 = 33, + + /// + /// If set, always convert image to the single channel grayscale image and the image size reduced 1/8. + /// + ReducedGrayscale8 = 64, + + /// + /// If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. + /// + ReducedColor8 = 65, + + /// + /// If set, do not rotate the image according to EXIF's orientation flag. + /// + IgnoreOrientation = 128 + }; +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteEXRTypeFlags.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteEXRTypeFlags.cs new file mode 100644 index 0000000..9c9dff8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteEXRTypeFlags.cs @@ -0,0 +1,24 @@ +// ReSharper disable UnusedMember.Global +// ReSharper disable IdentifierTypo +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp +{ + /// + /// + /// + public enum ImwriteEXRTypeFlags + { + /*IMWRITE_EXR_TYPE_UNIT = 0, //!< not supported */ + + /// + /// store as HALF (FP16) + /// + TypeHalf = 1, + + /// + /// store as FP32 (default) + /// + TypeFloat = 2 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteFlags.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteFlags.cs new file mode 100644 index 0000000..88aa85d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwriteFlags.cs @@ -0,0 +1,114 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::imwrite, cv::inencode で用いるエンコードの種類 + /// +#else + /// + /// The format type IDs for cv::imwrite and cv::inencode + /// +#endif + public enum ImwriteFlags + { +#if LANG_JP + /// + /// JPEGの場合のフラグ。0から100の値を取る(大きいほど高品質)。デフォルト値は95。 + /// +#else + /// + /// For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. + /// +#endif + JpegQuality = 1, + + /// + /// Enable JPEG features, 0 or 1, default is False. + /// + JpegProgressive = 2, + + /// + /// Enable JPEG features, 0 or 1, default is False. + /// + JpegOptimize = 3, + + /// + /// JPEG restart interval, 0 - 65535, default is 0 - no restart. + /// + JpegRstInterval = 4, + + /// + /// Separate luma quality level, 0 - 100, default is 0 - don't use. + /// + JpegLumaQuality = 5, + + /// + /// Separate chroma quality level, 0 - 100, default is 0 - don't use. + /// + JpegChromaQuality = 6, + +#if LANG_JP + /// + /// PNGの場合のフラグ。圧縮レベルを0から9の値で指定する(大きいほど高圧縮率で、かつ圧縮に時間を要する)。デフォルト値は3。 + /// +#else + /// + /// For PNG, it can be the compression level from 0 to 9. + /// A higher value means a smaller size and longer compression time. Default value is 3. + /// +#endif + PngCompression = 16, + + /// + /// One of cv::ImwritePNGFlags, default is IMWRITE_PNG_StrategyDEFAULT. + /// + PngStrategy = 17, + + /// + /// Binary level PNG, 0 or 1, default is 0. + /// + PngBilevel = 18, + +#if LANG_JP + /// + /// PPM, PGM, PBMの場合のフラグ。フォーマットをバイナリ(1)かアスキー(0)かで指定する。デフォルト値は1。 + /// +#else + /// + /// For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. + /// +#endif + PxmBinary = 32, + + /// + /// [48] override EXR storage type (FLOAT (FP32) is default) + /// + ExrType = (3 << 4) + 0, /* 48 */ //!< override EXR storage type (FLOAT (FP32) is default) + + /// + /// For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. + /// + WebPQuality = 64, + + /// + /// For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format + /// + PamTupleType = 128, + + /// + /// For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values + /// + TiffResUnit = 256, + + /// + /// For TIFF, use to specify the X direction DPI + /// + TiffXDpi = 257, + + /// + /// For TIFF, use to specify the Y direction DPI + /// + TiffYDpi = 258 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePAMFlags.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePAMFlags.cs new file mode 100644 index 0000000..3cae456 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePAMFlags.cs @@ -0,0 +1,21 @@ +// ReSharper disable CommentTypo + +namespace OpenCvSharp +{ + /// + /// Imwrite PAM specific tupletype flags used to define the 'TUPETYPE' field of a PAM file. + /// + // ReSharper disable once IdentifierTypo + // ReSharper disable once UnusedMember.Global + // ReSharper disable once InconsistentNaming + public enum ImwritePAMFlags + { +#pragma warning disable CS1591 + FormatNull = 0, + FormatBlackAndWhite = 1, + FormatGrayscale = 2, + FormatGrayscaleAlpha = 3, + FormatRgb = 4, + FormatRgbAlpha = 5, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePNGFlags.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePNGFlags.cs new file mode 100644 index 0000000..12722e3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/Enum/ImwritePNGFlags.cs @@ -0,0 +1,47 @@ +// ReSharper disable UnusedMember.Global +// ReSharper disable CommentTypo +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp +{ + /// + /// Imwrite PNG specific flags used to tune the compression algorithm. + /// + /// These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. + /// The effect of IMWRITE_PNG_StrategyFILTERED is to force more Huffman coding and less string matching; it is somewhat + /// intermediate between IMWRITE_PNG_StrategyDEFAULT and IMWRITE_PNG_StrategyHUFFMAN_ONLY. + /// IMWRITE_PNG_StrategyRLE is designed to be almost as fast as IMWRITE_PNG_StrategyHUFFMAN_ONLY, but give better compression for PNG + /// image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even + /// if it is not set appropriately. IMWRITE_PNG_StrategyFIXED prevents the use of dynamic Huffman codes, allowing for a simpler + /// decoder for special applications. + /// + // ReSharper disable once IdentifierTypo + public enum ImwritePNGFlags + { + /// + /// Use this value for normal data. + /// + StrategyDefault = 0, + + /// + /// Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat + /// random distribution. In this case, the compression algorithm is tuned to compress them better. + /// + StrategyFiltered = 1, + + /// + /// Use this value to force Huffman encoding only (no string match). + /// + StrategyHuffmanOnly = 2, + + /// + /// Use this value to limit match distances to one (run-length encoding). + /// + StrategyRLE = 3, + + /// + /// Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. + /// + StrategyFixed = 4 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgcodecs/ImageEncodingParam.cs b/OpenVinoOpenCvSharp/Modules/imgcodecs/ImageEncodingParam.cs new file mode 100644 index 0000000..cd091fc --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgcodecs/ImageEncodingParam.cs @@ -0,0 +1,59 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::imwrite, cv::imencode で用いるエンコードパラメータ + /// +#else + /// + /// The format-specific save parameters for cv::imwrite and cv::imencode + /// +#endif + [Serializable] + public class ImageEncodingParam + { +#if LANG_JP + /// + /// エンコードの種類 + /// +#else + /// + /// format type ID + /// +#endif + public ImwriteFlags EncodingId { get; set; } + +#if LANG_JP + /// + /// パラメータの値 + /// +#else + /// + /// value of parameter + /// +#endif + public int Value { get; set; } + + +#if LANG_JP + /// + /// 初期化 + /// + /// エンコードの種類 + /// パラメータの値 +#else + /// + /// Constructor + /// + /// format type ID + /// value of parameter +#endif + public ImageEncodingParam(ImwriteFlags id, int value) + { + EncodingId = id; + Value = value; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/CLAHE.cs b/OpenVinoOpenCvSharp/Modules/imgproc/CLAHE.cs new file mode 100644 index 0000000..2b210d9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/CLAHE.cs @@ -0,0 +1,169 @@ +using System; + +// ReSharper disable InconsistentNaming +// ReSharper disable IdentifierTypo +// ReSharper disable CommentTypo + +namespace OpenCvSharp +{ + /// + /// Contrast Limited Adaptive Histogram Equalization + /// + public sealed class CLAHE : Algorithm + { + /// + /// cv::Ptr<CLAHE> + /// + private Ptr? ptrObj; + + /// + /// + /// + private CLAHE(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates a predefined CLAHE object + /// + /// + /// + /// + public static CLAHE Create(double clipLimit = 40.0, Size? tileGridSize = null) + { + var ptr = NativeMethods.imgproc_createCLAHE( + clipLimit, tileGridSize.GetValueOrDefault(new Size(8, 8))); + return new CLAHE(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + /// + /// + /// + /// + /// + public void Apply(InputArray src, OutputArray dst) + { + ThrowIfDisposed(); + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + src.ThrowIfDisposed(); + dst.ThrowIfNotReady(); + + NativeMethods.imgproc_CLAHE_apply(ptr, src.CvPtr, dst.CvPtr); + + dst.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(src); + GC.KeepAlive(dst); + } + + /// + /// + /// + /// + public void SetClipLimit(double clipLimit) + { + ThrowIfDisposed(); + NativeMethods.imgproc_CLAHE_setClipLimit(ptr, clipLimit); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + public double GetClipLimit() + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_CLAHE_getClipLimit(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + public double ClipLimit + { + get => GetClipLimit(); + set => SetClipLimit(value); + } + + /// + /// + /// + /// + public void SetTilesGridSize(Size tileGridSize) + { + ThrowIfDisposed(); + NativeMethods.imgproc_CLAHE_setTilesGridSize(ptr, tileGridSize); + GC.KeepAlive(this); + } + + /// + /// + /// + /// + public Size GetTilesGridSize() + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_CLAHE_getTilesGridSize(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + public Size TilesGridSize + { + get => GetTilesGridSize(); + set => SetTilesGridSize(value); + } + + + /// + /// + /// + public void CollectGarbage() + { + ThrowIfDisposed(); + NativeMethods.imgproc_CLAHE_collectGarbage(ptr); + GC.KeepAlive(this); + } + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.imgproc_Ptr_CLAHE_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.imgproc_Ptr_CLAHE_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/ConnectedComponent.cs b/OpenVinoOpenCvSharp/Modules/imgproc/ConnectedComponent.cs new file mode 100644 index 0000000..04f9e59 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/ConnectedComponent.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// connected components that is returned from Cv2.ConnectedComponentsEx + /// + public class ConnectedComponents + { + /// + /// All blobs + /// + public ReadOnlyCollection Blobs { get; internal set; } + + /// + /// destination labeled value + /// + public int[,] Labels { get; internal set; } + + /// + /// The number of labels -1 + /// + public int LabelCount { get; internal set; } + + /// + /// Constructor + /// + /// + /// + /// + internal ConnectedComponents(IList blobs, int[,] labels, int labelCount) + { + Blobs = new ReadOnlyCollection(blobs); + Labels = labels; + LabelCount = labelCount; + } + + /// + /// Filter a image with the specified label value. + /// + /// Source image. + /// Destination image. + /// Label value. + /// Filtered image. + public Mat FilterByLabel(Mat src, Mat dst, int labelValue) + { + return FilterByLabels(src, dst, new[] { labelValue }); + } + + /// + /// Filter a image with the specified label values. + /// + /// Source image. + /// Destination image. + /// Label values. + /// Filtered image. + public Mat FilterByLabels(Mat src, Mat dst, IEnumerable labelValues) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (labelValues == null) + throw new ArgumentNullException(nameof(labelValues)); + var labelArray = EnumerableEx.ToArray(labelValues); + if (labelArray.Length == 0) + throw new ArgumentException("empty labelValues"); + + foreach (var labelValue in labelArray) + { + if (labelValue < 0 || labelValue >= LabelCount) + throw new ArgumentException("0 <= x < LabelCount"); + } + + // マスク用Matを用意し、Andで切り抜く + using (var mask = GetLabelMask(labelArray[0])) + { + for (var i = 1; i < labelArray.Length; i++) + { + using (var maskI = GetLabelMask(labelArray[i])) + { + Cv2.BitwiseOr(mask, maskI, mask); + } + } + src.CopyTo(dst, mask); + return dst; + } + } + + /// + /// Filter a image with the specified blob object. + /// + /// Source image. + /// Destination image. + /// Blob value. + /// Filtered image. + public Mat FilterByBlob(Mat src, Mat dst, Blob blob) + { + return FilterByLabels(src, dst, new[] { blob.Label }); + } + + /// + /// Filter a image with the specified blob objects. + /// + /// Source image. + /// Destination image. + /// Blob values. + /// Filtered image. + public Mat FilterBlobs(Mat src, Mat dst, IEnumerable blobs) + { + return FilterByLabels(src, dst, EnumerableEx.Select(blobs, b => b.Label)); + } + + /// + /// Draws all blobs to the specified image. + /// + /// The target image to be drawn. + public void RenderBlobs(Mat img) + { + if (img == null) + throw new ArgumentNullException(nameof(img)); + /* + if (img.Empty()) + throw new ArgumentException("img is empty"); + if (img.Type() != MatType.CV_8UC3) + throw new ArgumentException("img must be CV_8UC3");*/ + if (Blobs == null || Blobs.Count == 0) + throw new OpenCvSharpException("Blobs is empty"); + if (Labels == null) + throw new OpenCvSharpException("Labels is empty"); + + var height = Labels.GetLength(0); + var width = Labels.GetLength(1); + img.Create(new Size(width, height), MatType.CV_8UC3); + + var colors = new Scalar[Blobs.Count]; + colors[0] = Scalar.All(0); + for (var i = 1; i < Blobs.Count; i++) + { + colors[i] = Scalar.RandomColor(); + } + + using (var imgt = new Mat(img)) + { + var indexer = imgt.GetIndexer(); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var labelValue = Labels[y, x]; + indexer[y, x] = colors[labelValue].ToVec3b(); + } + } + } + } + + /// + /// Find the largest blob. + /// + /// the largest blob + public Blob GetLargestBlob() + { + if (Blobs == null || Blobs.Count <= 1) + throw new OpenCvSharpException("Blobs is empty"); + + var max = Blobs[1]; + for (var i = 2; i < Blobs.Count; i++) + { + if (max.Area < Blobs[i].Area) + max = Blobs[i]; + } + return max; + } + + /// + /// 指定したラベル値のところのみを非0で残したマスク画像を返す + /// + /// + /// + private Mat GetLabelMask(int label) + { + var rows = Labels.GetLength(0); + var cols = Labels.GetLength(1); + using (var labels = new Mat(rows, cols, MatType.CV_32SC1, Labels)) + using (var cmp = new Mat(rows, cols, MatType.CV_32SC1, Scalar.All(label))) + { + var result = new Mat(); + Cv2.Compare(labels, cmp, result, CmpTypes.EQ); + return result; + } + } + + /// + /// One blob + /// + public class Blob + { + /// + /// Label value + /// + public int Label { get; internal set; } + + /// + /// Floating point centroid (x,y) + /// + public Point2d Centroid { get; internal set; } + + /// + /// The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal direction. + /// + public int Left { get; internal set; } + + /// + /// The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical direction. + /// + public int Top { get; internal set; } + + /// + /// The horizontal size of the bounding box. + /// + public int Width { get; internal set; } + + /// + /// The vertical size of the bounding box. + /// + public int Height { get; internal set; } + + /// + /// The bounding box. + /// + public Rect Rect => new Rect(Left, Top, Width, Height); + + /// + /// The total area (in pixels) of the connected component. + /// + public int Area { get; internal set; } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/AdaptiveThresholdTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/AdaptiveThresholdTypes.cs new file mode 100644 index 0000000..99b0933 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/AdaptiveThresholdTypes.cs @@ -0,0 +1,38 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 適応的閾値処理で使用するアルゴリズムの種類 + /// +#else + /// + /// Adaptive thresholding algorithms + /// +#endif + public enum AdaptiveThresholdTypes + { +#if LANG_JP + /// + /// 注目ピクセルの block_size × block_size 隣接領域の平均から,param1 を引いた値を閾値とする. + /// +#else + /// + /// It is a mean of block_size × block_size pixel neighborhood, subtracted by param1. + /// +#endif + MeanC = 0, + + +#if LANG_JP + /// + /// 注目ピクセルの block_size × block_size 隣接領域の重み付き総和(ガウシアン)から param1 を引いた値を閾値とする. + /// +#else + /// + /// it is a weighted sum (Gaussian) of block_size × block_size pixel neighborhood, subtracted by param1. + /// +#endif + GaussianC = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/BorderTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/BorderTypes.cs new file mode 100644 index 0000000..3a0efe6 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/BorderTypes.cs @@ -0,0 +1,71 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvCopyMakeBorderで指定する, 境界線のタイプ + /// +#else + /// + /// Type of the border to create around the copied source image rectangle + /// +#endif + public enum BorderTypes + { +#if LANG_JP + /// + /// 境界はこの関数の最後のパラメータとして渡された定数 value で埋められる. + /// `iiiiii|abcdefgh|iiiiiii` with some specified `i` + /// +#else + /// + /// Border is filled with the fixed value, passed as last parameter of the function. + /// `iiiiii|abcdefgh|iiiiiii` with some specified `i` + /// +#endif + Constant = 0, + +#if LANG_JP + /// + /// 画像の最も上/下の行と最も左/右の列(画像領域の一番外側の値)を用いて境界線を生成する. + /// `aaaaaa|abcdefgh|hhhhhhh` + /// +#else + /// + /// The pixels from the top and bottom rows, the left-most and right-most columns are replicated to fill the border. + /// `aaaaaa|abcdefgh|hhhhhhh` + /// +#endif + Replicate = 1, + + /// + /// `fedcba|abcdefgh|hgfedcb` + /// + Reflect = 2, + + /// + /// `cdefgh|abcdefgh|abcdefg` + /// + Wrap = 3, + + /// + /// `gfedcb|abcdefgh|gfedcba` + /// + Reflect101 = 4, + + /// + /// `uvwxyz|absdefgh|ijklmno` + /// + Transparent = 5, + + /// + /// same as BORDER_REFLECT_101 + /// + Default = Reflect101, + + /// + /// do not look outside of ROI + /// + Isolated = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColorConversionCodes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColorConversionCodes.cs new file mode 100644 index 0000000..4864a5f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColorConversionCodes.cs @@ -0,0 +1,272 @@ + +#pragma warning disable 1591 +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 色空間の変換の方法 + /// +#else + /// + /// Color conversion operation for cv::cvtColor + /// +#endif + public enum ColorConversionCodes + { + BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image + RGB2RGBA = BGR2BGRA, + + BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image + RGBA2RGB = BGRA2BGR, + + BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) + RGB2BGRA = BGR2RGBA, + + RGBA2BGR = 3, + BGRA2RGB = RGBA2BGR, + + BGR2RGB = 4, + RGB2BGR = BGR2RGB, + + BGRA2RGBA = 5, + RGBA2BGRA = BGRA2RGBA, + + BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref convert_rgb_gray "color conversions" + RGB2GRAY = 7, + GRAY2BGR = 8, + GRAY2RGB = GRAY2BGR, + GRAY2BGRA = 9, + GRAY2RGBA = GRAY2BGRA, + BGRA2GRAY = 10, + RGBA2GRAY = 11, + + BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) + RGB2BGR565 = 13, + BGR5652BGR = 14, + BGR5652RGB = 15, + BGRA2BGR565 = 16, + RGBA2BGR565 = 17, + BGR5652BGRA = 18, + BGR5652RGBA = 19, + + GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) + BGR5652GRAY = 21, + + BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) + RGB2BGR555 = 23, + BGR5552BGR = 24, + BGR5552RGB = 25, + BGRA2BGR555 = 26, + RGBA2BGR555 = 27, + BGR5552BGRA = 28, + BGR5552RGBA = 29, + + GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) + BGR5552GRAY = 31, + + BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref convert_rgb_xyz "color conversions" + RGB2XYZ = 33, + XYZ2BGR = 34, + XYZ2RGB = 35, + + BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref convert_rgb_ycrcb "color conversions" + RGB2YCrCb = 37, + YCrCb2BGR = 38, + YCrCb2RGB = 39, + + BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value), @ref convert_rgb_hsv "color conversions" + RGB2HSV = 41, + + BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref convert_rgb_lab "color conversions" + RGB2Lab = 45, + + BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref convert_rgb_luv "color conversions" + RGB2Luv = 51, + BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation), @ref convert_rgb_hls "color conversions" + RGB2HLS = 53, + + HSV2BGR = 54, //!< backward conversions to RGB/BGR + HSV2RGB = 55, + + Lab2BGR = 56, + Lab2RGB = 57, + Luv2BGR = 58, + Luv2RGB = 59, + HLS2BGR = 60, + HLS2RGB = 61, + + BGR2HSV_FULL = 66, //!< + RGB2HSV_FULL = 67, + BGR2HLS_FULL = 68, + RGB2HLS_FULL = 69, + + HSV2BGR_FULL = 70, + HSV2RGB_FULL = 71, + HLS2BGR_FULL = 72, + HLS2RGB_FULL = 73, + + LBGR2Lab = 74, + LRGB2Lab = 75, + LBGR2Luv = 76, + LRGB2Luv = 77, + + Lab2LBGR = 78, + Lab2LRGB = 79, + Luv2LBGR = 80, + Luv2LRGB = 81, + + BGR2YUV = 82, //!< convert between RGB/BGR and YUV + RGB2YUV = 83, + YUV2BGR = 84, + YUV2RGB = 85, + + //! YUV 4:2:0 family to RGB + YUV2RGB_NV12 = 90, + YUV2BGR_NV12 = 91, + YUV2RGB_NV21 = 92, + YUV2BGR_NV21 = 93, + YUV420sp2RGB = YUV2RGB_NV21, + YUV420sp2BGR = YUV2BGR_NV21, + + YUV2RGBA_NV12 = 94, + YUV2BGRA_NV12 = 95, + YUV2RGBA_NV21 = 96, + YUV2BGRA_NV21 = 97, + YUV420sp2RGBA = YUV2RGBA_NV21, + YUV420sp2BGRA = YUV2BGRA_NV21, + + YUV2RGB_YV12 = 98, + YUV2BGR_YV12 = 99, + YUV2RGB_IYUV = 100, + YUV2BGR_IYUV = 101, + YUV2RGB_I420 = YUV2RGB_IYUV, + YUV2BGR_I420 = YUV2BGR_IYUV, + YUV420p2RGB = YUV2RGB_YV12, + YUV420p2BGR = YUV2BGR_YV12, + + YUV2RGBA_YV12 = 102, + YUV2BGRA_YV12 = 103, + YUV2RGBA_IYUV = 104, + YUV2BGRA_IYUV = 105, + YUV2RGBA_I420 = YUV2RGBA_IYUV, + YUV2BGRA_I420 = YUV2BGRA_IYUV, + YUV420p2RGBA = YUV2RGBA_YV12, + YUV420p2BGRA = YUV2BGRA_YV12, + + YUV2GRAY_420 = 106, + YUV2GRAY_NV21 = YUV2GRAY_420, + YUV2GRAY_NV12 = YUV2GRAY_420, + YUV2GRAY_YV12 = YUV2GRAY_420, + YUV2GRAY_IYUV = YUV2GRAY_420, + YUV2GRAY_I420 = YUV2GRAY_420, + YUV420sp2GRAY = YUV2GRAY_420, + YUV420p2GRAY = YUV2GRAY_420, + + //! YUV 4:2:2 family to RGB + YUV2RGB_UYVY = 107, + YUV2BGR_UYVY = 108, + //YUV2RGB_VYUY = 109, + //YUV2BGR_VYUY = 110, + YUV2RGB_Y422 = YUV2RGB_UYVY, + YUV2BGR_Y422 = YUV2BGR_UYVY, + YUV2RGB_UYNV = YUV2RGB_UYVY, + YUV2BGR_UYNV = YUV2BGR_UYVY, + + YUV2RGBA_UYVY = 111, + YUV2BGRA_UYVY = 112, + //YUV2RGBA_VYUY = 113, + //YUV2BGRA_VYUY = 114, + YUV2RGBA_Y422 = YUV2RGBA_UYVY, + YUV2BGRA_Y422 = YUV2BGRA_UYVY, + YUV2RGBA_UYNV = YUV2RGBA_UYVY, + YUV2BGRA_UYNV = YUV2BGRA_UYVY, + + YUV2RGB_YUY2 = 115, + YUV2BGR_YUY2 = 116, + YUV2RGB_YVYU = 117, + YUV2BGR_YVYU = 118, + YUV2RGB_YUYV = YUV2RGB_YUY2, + YUV2BGR_YUYV = YUV2BGR_YUY2, + YUV2RGB_YUNV = YUV2RGB_YUY2, + YUV2BGR_YUNV = YUV2BGR_YUY2, + + YUV2RGBA_YUY2 = 119, + YUV2BGRA_YUY2 = 120, + YUV2RGBA_YVYU = 121, + YUV2BGRA_YVYU = 122, + YUV2RGBA_YUYV = YUV2RGBA_YUY2, + YUV2BGRA_YUYV = YUV2BGRA_YUY2, + YUV2RGBA_YUNV = YUV2RGBA_YUY2, + YUV2BGRA_YUNV = YUV2BGRA_YUY2, + + YUV2GRAY_UYVY = 123, + YUV2GRAY_YUY2 = 124, + //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, + YUV2GRAY_Y422 = YUV2GRAY_UYVY, + YUV2GRAY_UYNV = YUV2GRAY_UYVY, + YUV2GRAY_YVYU = YUV2GRAY_YUY2, + YUV2GRAY_YUYV = YUV2GRAY_YUY2, + YUV2GRAY_YUNV = YUV2GRAY_YUY2, + + //! alpha premultiplication + RGBA2mRGBA = 125, + mRGBA2RGBA = 126, + + //! RGB to YUV 4:2:0 family + RGB2YUV_I420 = 127, + BGR2YUV_I420 = 128, + RGB2YUV_IYUV = RGB2YUV_I420, + BGR2YUV_IYUV = BGR2YUV_I420, + + RGBA2YUV_I420 = 129, + BGRA2YUV_I420 = 130, + RGBA2YUV_IYUV = RGBA2YUV_I420, + BGRA2YUV_IYUV = BGRA2YUV_I420, + RGB2YUV_YV12 = 131, + BGR2YUV_YV12 = 132, + RGBA2YUV_YV12 = 133, + BGRA2YUV_YV12 = 134, + + //! Demosaicing + BayerBG2BGR = 46, + BayerGB2BGR = 47, + BayerRG2BGR = 48, + BayerGR2BGR = 49, + + BayerBG2RGB = BayerRG2BGR, + BayerGB2RGB = BayerGR2BGR, + BayerRG2RGB = BayerBG2BGR, + BayerGR2RGB = BayerGB2BGR, + + BayerBG2GRAY = 86, + BayerGB2GRAY = 87, + BayerRG2GRAY = 88, + BayerGR2GRAY = 89, + + //! Demosaicing using Variable Number of Gradients + BayerBG2BGR_VNG = 62, + BayerGB2BGR_VNG = 63, + BayerRG2BGR_VNG = 64, + BayerGR2BGR_VNG = 65, + + BayerBG2RGB_VNG = BayerRG2BGR_VNG, + BayerGB2RGB_VNG = BayerGR2BGR_VNG, + BayerRG2RGB_VNG = BayerBG2BGR_VNG, + BayerGR2RGB_VNG = BayerGB2BGR_VNG, + + //! Edge-Aware Demosaicing + BayerBG2BGR_EA = 135, + BayerGB2BGR_EA = 136, + BayerRG2BGR_EA = 137, + BayerGR2BGR_EA = 138, + + BayerBG2RGB_EA = BayerRG2BGR_EA, + BayerGB2RGB_EA = BayerGR2BGR_EA, + BayerRG2RGB_EA = BayerBG2BGR_EA, + BayerGR2RGB_EA = BayerGB2BGR_EA, + + COLORCVT_MAX = 139 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColormapTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColormapTypes.cs new file mode 100644 index 0000000..3fe2f2f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ColormapTypes.cs @@ -0,0 +1,31 @@ +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + /// + /// GNU Octave/MATLAB equivalent colormaps + /// + public enum ColormapTypes + { + Autumn = 0, + Bone = 1, + Jet = 2, + Winter = 3, + Rainbow = 4, + Ocean = 5, + Summer = 6, + Spring = 7, + Cool = 8, + Hsv = 9, + Pink = 10, + Hot = 11, + Parula = 12, + Magma = 13, + Inferno = 14, + Plasma = 15, + Viridis = 16, + Cividis = 17, + Twilight = 18, + TwilightShifted = 19 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ConnectedComponentsTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ConnectedComponentsTypes.cs new file mode 100644 index 0000000..e0cbd6e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ConnectedComponentsTypes.cs @@ -0,0 +1,35 @@ +namespace OpenCvSharp +{ + /// + /// components algorithm output formats + /// + public enum ConnectedComponentsTypes + { + /// + /// The leftmost (x) coordinate which is the inclusive start of the bounding + /// box in the horizontal direction. + /// + Left = 0, + + /// + /// The topmost (y) coordinate which is the inclusive start of the bounding + /// box in the vertical direction. + /// + Top = 1, + + /// + /// The horizontal size of the bounding box + /// + Width = 2, + + /// + /// The vertical size of the bounding box + /// + Height = 3, + + /// + /// The total area (in pixels) of the connected component + /// + Area = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ContourApproximationModes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ContourApproximationModes.cs new file mode 100644 index 0000000..18efeb8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ContourApproximationModes.cs @@ -0,0 +1,64 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 輪郭の近似手法 + /// +#else + /// + /// Approximation method (for all the modes, except CV_RETR_RUNS, which uses built-in approximation). + /// +#endif + public enum ContourApproximationModes + { +#if LANG_JP + /// + /// [CHAIN_APPROX_NONE] + /// +#else + /// + /// CHAIN_APPROX_NONE - translate all the points from the chain code into points; + /// +#endif + ApproxNone = 1, + + +#if LANG_JP + /// + /// 水平・垂直・斜めの線分を圧縮し,それらの端点のみを残します.例えば,まっすぐな矩形の輪郭線は,4つの点にエンコードされます. [CV_CHAIN_APPROX_SIMPLE] + /// +#else + /// + /// CHAIN_APPROX_SIMPLE - compress horizontal, vertical, and diagonal segments, that is, the function leaves only their ending points; + /// +#endif + ApproxSimple = 2, + + +#if LANG_JP + /// + /// Teh-Chinチェーン近似アルゴリズムの1つを適用します. TehChin89 を参照してください. [CV_CHAIN_APPROX_TC89_L1] + /// +#else + /// + /// CHAIN_APPROX_TC89_L1 - apply one of the flavors of Teh-Chin chain approximation algorithm. + /// +#endif +// ReSharper disable once InconsistentNaming + ApproxTC89L1 = 3, + + +#if LANG_JP + /// + /// Teh-Chinチェーン近似アルゴリズムの1つを適用します. TehChin89 を参照してください. [CV_CHAIN_APPROX_TC89_KCOS] + /// +#else + /// + /// CHAIN_APPROX_TC89_KCOS - apply one of the flavors of Teh-Chin chain approximation algorithm. + /// +#endif +// ReSharper disable once InconsistentNaming + ApproxTC89KCOS = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceMaskSize.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceMaskSize.cs new file mode 100644 index 0000000..ad902bf --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceMaskSize.cs @@ -0,0 +1,32 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 距離変換 (distance transform) のマスクサイズ + /// +#else + /// + /// Mask size for distance transform + /// +#endif + [Flags] + public enum DistanceMaskSize + { + /// + /// 3 + /// + Mask3 = 3, + + /// + /// 5 + /// + Mask5 = 5, + + /// + /// + /// + Precise = 0, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTransformLabelTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTransformLabelTypes.cs new file mode 100644 index 0000000..dd73313 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTransformLabelTypes.cs @@ -0,0 +1,20 @@ +namespace OpenCvSharp +{ + /// + /// distanceTransform algorithm flags + /// + public enum DistanceTransformLabelTypes + { + /// + /// each connected component of zeros in src + /// (as well as all the non-zero pixels closest to the connected component) + /// will be assigned the same label + /// + CComp = 0, + + /// + /// each zero pixel (and all the non-zero pixels closest to it) gets its own label. + /// + Pixel = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTypes.cs new file mode 100644 index 0000000..5db85e8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/DistanceTypes.cs @@ -0,0 +1,55 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvDistTransformで指定する距離の種類 + /// +#else + /// + /// Type of distance for cvDistTransform + /// +#endif + public enum DistanceTypes + { + /// + /// User defined distance [CV_DIST_USER] + /// + User = -1, + + /// + /// distance = |x1-x2| + |y1-y2| [CV_DIST_L1] + /// + L1 = 1, + + /// + /// the simple euclidean distance [CV_DIST_L2] + /// + L2 = 2, + + /// + /// distance = max(|x1-x2|,|y1-y2|) [CV_DIST_C] + /// + C = 3, + + /// + /// L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) [CV_DIST_L12] + /// + L12 = 4, + + /// + /// distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 [CV_DIST_FAIR] + /// + Fair = 5, + + /// + /// distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 [CV_DIST_WELSCH] + /// + Welsch = 6, + + /// + /// distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 [CV_DIST_HUBER] + /// + Huber = 7, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FlipMode.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FlipMode.cs new file mode 100644 index 0000000..28ea6cf --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FlipMode.cs @@ -0,0 +1,51 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 配列の反転方法 + /// +#else + /// + /// Specifies how to flip the array + /// +#endif + public enum FlipMode + { +#if LANG_JP + /// + /// x軸周りでの反転 + /// +#else + /// + /// means flipping around x-axis + /// +#endif + X = 0, + + +#if LANG_JP + /// + /// y軸周りでの反転 + /// +#else + /// + /// means flipping around y-axis + /// +#endif + Y = 1, + + +#if LANG_JP + /// + /// 両軸周りでの反転 + /// +#else + /// + /// means flipping around both axises + /// +#endif + // ReSharper disable once InconsistentNaming + XY = -1 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FloodFillFlags.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FloodFillFlags.cs new file mode 100644 index 0000000..1898c89 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/FloodFillFlags.cs @@ -0,0 +1,70 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// floodFillの処理フラグ + /// +#else + /// + /// floodFill 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. Upper bits can be 0 or a combination of the following flags: + /// +#endif + [Flags] + public enum FloodFillFlags + { +#if LANG_JP + /// + /// 4連結による線分 + /// [= 4] + /// +#else + /// + /// 4-connected line. + /// [= 4] + /// +#endif + Link4 = 4, + +#if LANG_JP + /// + /// 8連結による線分 + /// [= 8] + /// +#else + /// + /// 8-connected line. + /// [= 8] + /// +#endif + Link8 = 8, + +#if LANG_JP + /// + /// If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference between neighbor pixels is considered (that is, the range is floating). + /// [CV_FLOODFILL_FIXED_RANGE] + /// +#else + /// + /// If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference between neighbor pixels is considered (that is, the range is floating). + /// [CV_FLOODFILL_FIXED_RANGE] + /// +#endif + FixedRange = 1 << 16, + + +#if LANG_JP + /// + /// If set, the function does not change the image ( newVal is ignored), but fills the mask. The flag can be used for the second variant only. + /// [CV_FLOODFILL_MASK_ONLY] + /// +#else + /// + /// If set, the function does not change the image ( newVal is ignored), but fills the mask. The flag can be used for the second variant only. + /// [CV_FLOODFILL_MASK_ONLY] + /// +#endif + MaskOnly = 1 << 17, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutClasses.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutClasses.cs new file mode 100644 index 0000000..84d7968 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutClasses.cs @@ -0,0 +1,29 @@ +// ReSharper disable InconsistentNaming +namespace OpenCvSharp +{ + /// + /// class of the pixel in GrabCut algorithm + /// + public enum GrabCutClasses + { + /// + /// an obvious background pixels + /// + BGD = 0, + + /// + /// an obvious foreground (object) pixel + /// + FGD = 1, + + /// + /// a possible background pixel + /// + PR_BGD = 2, + + /// + /// a possible foreground pixel + /// + PR_FGD = 3 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutModes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutModes.cs new file mode 100644 index 0000000..029f90d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/GrabCutModes.cs @@ -0,0 +1,59 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// GrabCutの処理フラグ + /// +#else + /// + /// GrabCut algorithm flags + /// +#endif + [Flags] + public enum GrabCutModes + { +#if LANG_JP + /// + /// 与えられた矩形を用いて,状態とマスクを初期化します. + /// その後,アルゴリズムが iterCount 回繰り返されます. + /// +#else + /// + /// The function initializes the state and the mask using the provided rectangle. + /// After that it runs iterCount iterations of the algorithm. + /// +#endif + InitWithRect = 0, + + +#if LANG_JP + /// + /// 与えられたマスクを用いて状態を初期化します. + /// GC_INIT_WITH_RECT と GC_INIT_WITH_MASK は,一緒に使うことができる + /// ことに注意してください.そして,ROIの外側の全ピクセルは自動的に + /// GC_BGD として初期化されます. + /// +#else + /// + /// The function initializes the state using the provided mask. + /// Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. + /// Then, all the pixels outside of the ROI are automatically initialized with GC_BGD . + /// +#endif + InitWithMask = 1, + + +#if LANG_JP + /// + /// アルゴリズムがすぐに再開することを意味する値. + /// +#else + /// + /// The value means that the algorithm should just resume. + /// +#endif + Eval = 2, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HistCompMethods.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HistCompMethods.cs new file mode 100644 index 0000000..34bdbe9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HistCompMethods.cs @@ -0,0 +1,80 @@ +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvCompareHistで用いる、CvHistogramの比較方法 + /// +#else + /// + /// Comparison methods for cvCompareHist + /// +#endif + public enum HistCompMethods + { +#if LANG_JP + /// + /// 相関 [CV_COMP_CORREL] + /// +#else + /// + /// Correlation [CV_COMP_CORREL] + /// +#endif + Correl = 0, + + +#if LANG_JP + /// + /// カイ二乗 [CV_COMP_CHISQR] + /// +#else + /// + /// Chi-Square [CV_COMP_CHISQR] + /// +#endif + Chisqr = 1, + + +#if LANG_JP + /// + /// 交差 [CV_COMP_INTERSECT] + /// +#else + /// + /// Intersection [CV_COMP_INTERSECT] + /// +#endif + Intersect = 2, + + +#if LANG_JP + /// + /// Bhattacharyya距離 [CV_COMP_BHATTACHARYYA]. 正規化されたヒストグラムでのみ実行可能である. + /// +#else + /// + /// Bhattacharyya distance [CV_COMP_BHATTACHARYYA] + /// +#endif + Bhattacharyya = 3, + + /// + /// Synonym for HISTCMP_BHATTACHARYYA + /// + Hellinger = Bhattacharyya, + + /// + /// Alternative Chi-Square + /// \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] + /// This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 + /// + ChisqrAlt = 4, + + /// + /// Kullback-Leibler divergence + /// \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] + /// +// ReSharper disable once InconsistentNaming + KLDiv = 5 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HoughMethods.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HoughMethods.cs new file mode 100644 index 0000000..d4c01d8 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/HoughMethods.cs @@ -0,0 +1,44 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// ハフ変換の種類 + /// +#else + /// + /// Variants of a Hough transform + /// +#endif + public enum HoughMethods + { + /* */ + /// + /// classical or standard Hough transform. + /// Every line is represented by two floating-point numbers \f$(\rho, \theta)\f$ , + /// where \f$\rho\f$ is a distance between (0,0) point and the line, + /// and \f$\theta\f$ is the angle between x-axis and the normal to the line. + /// Thus, the matrix must be (the created sequence will be) of CV_32FC2 type + /// + Standard = 0, + + /// + /// probabilistic Hough transform (more efficient in case if the picture contains + /// a few long linear segments). It returns line segments rather than the whole line. + /// Each segment is represented by starting and ending points, and the matrix must be + /// (the created sequence will be) of the CV_32SC4 type. + /// + Probabilistic = 1, + + /// + /// multi-scale variant of the classical Hough transform. + /// The lines are encoded the same way as HOUGH_STANDARD. + /// + MultiScale = 2, + + /// + /// basically *21HT*, described in @cite Yuen90 + /// + Gradient = 3 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/InterpolationFlags.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/InterpolationFlags.cs new file mode 100644 index 0000000..bc574fc --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/InterpolationFlags.cs @@ -0,0 +1,95 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 画像の補間方法 + /// +#else + /// + /// Interpolation algorithm + /// +#endif + [Flags] + public enum InterpolationFlags + { +#if LANG_JP + /// + /// 最近隣接補間 + /// +#else + /// + /// Nearest-neighbor interpolation, + /// +#endif + Nearest = 0, + +#if LANG_JP + /// + /// バイリニア補間 + /// +#else + /// + /// Bilinear interpolation (used by default) + /// +#endif + Linear = 1, + +#if LANG_JP + /// + /// バイキュービック補間 + /// +#else + /// + /// Bicubic interpolation. + /// +#endif + Cubic = 2, + +#if LANG_JP + /// + /// ピクセル領域の関係を用いてリサンプリングする.画像縮小の際は,モアレの無い処理結果を得ることができる手法である.拡大の際は,CV_INTER_NN と同様 . + /// +#else + /// + /// Resampling using pixel area relation. It is the preferred method for image decimation that gives moire-free results. In case of zooming it is similar to CV_INTER_NN method. + /// +#endif + Area = 3, + + /// + /// Lanczos interpolation over 8x8 neighborhood + /// + Lanczos4 = 4, + + /// + /// mask for interpolation codes + /// + Max = 7, + +#if LANG_JP + /// + /// 出力画像の全ピクセルの値を埋める.対応ピクセルが入力画像外であるようなピクセルである場合は, fillvalがセットされる + /// +#else + /// + /// Fill all the destination image pixels. If some of them correspond to outliers in the source image, they are set to fillval. + /// +#endif + WarpFillOutliers = 8, + +#if LANG_JP + /// + /// このフラグは map_matrixが出力画像から入力画像への逆変換のための行列であることを意味するので,直接ピクセル補間に用いることができる. + /// これがセットされていない場合,この関数は map_matrix を使って逆変換を計算する. + /// +#else + /// + /// Indicates that matrix is inverse transform from destination image to source and, + /// thus, can be used directly for pixel interpolation. Otherwise, the function finds the inverse transform from map_matrix. + /// +#endif + WarpInverseMap = 16, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/LineTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/LineTypes.cs new file mode 100644 index 0000000..b90c040 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/LineTypes.cs @@ -0,0 +1,30 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 線分の種類 + /// +#else + /// + /// Type of the line + /// +#endif + public enum LineTypes + { + /// + /// 8-connected line. + /// + Link8 = 8, + + /// + /// 4-connected line. + /// + Link4 = 4, + + /// + /// Anti-aliased line. + /// + AntiAlias = 16 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MarkerStyle.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MarkerStyle.cs new file mode 100644 index 0000000..feab8ef --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MarkerStyle.cs @@ -0,0 +1,125 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// Mat.DrawMarkerで用いるマーカーの形状 + /// +#else + /// + /// Marker styles for Mat.DrawMarker + /// +#endif + public enum MarkerStyle + { +#if LANG_JP + /// + /// 円(線のみ) + /// +#else + /// + /// A circle polyline + /// +#endif + CircleLine, + +#if LANG_JP + /// + /// 円(塗りつぶし) + /// +#else + /// + /// A filled circle + /// +#endif + CircleFilled, + +#if LANG_JP + /// + /// 十字 + /// +#else + /// + /// A cross + /// +#endif + Cross, + +#if LANG_JP + /// + /// バツ + /// +#else + /// + /// A tilted cross + /// +#endif + TiltedCross, + +#if LANG_JP + /// + /// 円と十字 + /// +#else + /// + /// A circle and a cross + /// +#endif + CircleAndCross, + +#if LANG_JP + /// + /// 円とバツ + /// +#else + /// + /// A circle and a tilted cross + /// +#endif + CircleAndTiltedCross, + +#if LANG_JP + /// + /// 菱形(線のみ) + /// +#else + /// + /// A diamond polyline + /// +#endif + DiamondLine, + +#if LANG_JP + /// + /// 菱形(塗りつぶし) + /// +#else + /// + /// A filled diamond + /// +#endif + DiamondFilled, + +#if LANG_JP + /// + /// 正方形(線のみ) + /// +#else + /// + /// A square polyline + /// +#endif + SquareLine, + +#if LANG_JP + /// + /// 正方形(塗りつぶし) + /// +#else + /// + /// A filledsquare + /// +#endif + SquareFilled, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphShapes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphShapes.cs new file mode 100644 index 0000000..5db0ddb --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphShapes.cs @@ -0,0 +1,50 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 構造要素の形状 + /// +#else + /// + /// Shape of the structuring element + /// +#endif + public enum MorphShapes + { +#if LANG_JP + /// + /// 矩形 + /// +#else + /// + /// A rectangular element + /// +#endif + Rect = 0, + + +#if LANG_JP + /// + /// 十字型 + /// +#else + /// + /// A cross-shaped element + /// +#endif + Cross = 1, + + +#if LANG_JP + /// + /// 楕円 + /// +#else + /// + /// An elliptic element + /// +#endif + Ellipse = 2, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphTypes.cs new file mode 100644 index 0000000..8d186f9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/MorphTypes.cs @@ -0,0 +1,96 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// モルフォロジー演算の種類 + /// +#else + /// + /// Type of morphological operation + /// +#endif + [Flags] + public enum MorphTypes + { + /// + /// + /// + Erode = 0, + + /// + /// + /// + Dilate = 1, + +#if LANG_JP + /// + /// オープニング [CV_MOP_OPEN]. + /// dst=open(src,element)=dilate(erode(src,element),element) + /// +#else + /// + /// an opening operation + /// +#endif + Open = 2, + + +#if LANG_JP + /// + /// クロージング [CV_MOP_CLOSE]. + /// dst=close(src,element)=erode(dilate(src,element),element) + /// +#else + /// + /// a closing operation + /// +#endif + Close = 3, + + +#if LANG_JP + /// + /// モルフォロジー勾配(エッジ検出) [CV_MOP_GRADIENT]. + /// dst=morph_grad(src,element)=dilate(src,element)-erode(src,element) + /// +#else + /// + /// Morphological gradient + /// +#endif + Gradient = 4, + + +#if LANG_JP + /// + /// トップハット変換(top hat) [CV_MOP_TOPHAT]. + /// dst=tophat(src,element)=src-open(src,element) + /// +#else + /// + /// "Top hat" + /// +#endif + TopHat = 5, + + +#if LANG_JP + /// + /// ブラックハット変換(black hat) [CV_MOP_BLACKHAT] + /// dst=blackhat(src,element)=close(src,element)-src + /// +#else + /// + /// "Black hat" + /// +#endif + BlackHat = 6, + + /// + /// "hit and miss" + /// + HitMiss = 7 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/PixelConnectivity.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/PixelConnectivity.cs new file mode 100644 index 0000000..8687e3c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/PixelConnectivity.cs @@ -0,0 +1,38 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// CvLineIteratorにおける、走査した線分の接続性 + /// +#else + /// + /// PixelConnectivity for LineIterator + /// +#endif + public enum PixelConnectivity + { +#if LANG_JP + /// + /// 周囲4方向(上下左右) + /// +#else + /// + /// Connectivity 4 (N,S,E,W) + /// +#endif + Connectivity4 = 4, + + +#if LANG_JP + /// + /// 周囲8方向 + /// +#else + /// + /// Connectivity 8 (N,S,E,W,NE,SE,SW,NW) + /// +#endif + Connectivity8 = 8, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ProjectionType.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ProjectionType.cs new file mode 100644 index 0000000..8c1c024 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ProjectionType.cs @@ -0,0 +1,23 @@ +namespace OpenCvSharp +{ + /// + /// cv::initWideAngleProjMap flags + /// + public enum ProjectionType + { + /// + /// + /// + None = 0, + + /// + /// + /// + SphericalOrtho = 0, + + /// + /// + /// + SphericalEqRect = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RectanglesIntersectTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RectanglesIntersectTypes.cs new file mode 100644 index 0000000..23ab71f --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RectanglesIntersectTypes.cs @@ -0,0 +1,23 @@ +namespace OpenCvSharp +{ + /// + /// types of intersection between rectangles + /// + public enum RectanglesIntersectTypes + { + /// + /// No intersection + /// + None = 0, + + /// + /// There is a partial intersection + /// + Partial = 1, + + /// + /// One of the rectangle is fully enclosed in the other + /// + Full = 2 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RetrievalModes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RetrievalModes.cs new file mode 100644 index 0000000..6562a5e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/RetrievalModes.cs @@ -0,0 +1,80 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 輪郭の抽出モード + /// +#else + /// + /// mode of the contour retrieval algorithm + /// +#endif + public enum RetrievalModes + { +#if LANG_JP + /// + /// 最も外側の輪郭のみ抽出 + /// +#else + /// + /// retrieves only the extreme outer contours. + /// It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for all the contours. + /// +#endif + External = 0, + +#if LANG_JP + /// + /// 全ての輪郭を抽出し,リストに追加 + /// [CV_RETR_LIST] + /// +#else + /// + /// retrieves all of the contours without establishing any hierarchical relationships. + /// +#endif + List = 1, + + +#if LANG_JP + /// + /// 全ての輪郭を抽出し,二つのレベルを持つ階層構造を構成する.1番目のレベルは連結成分の外側の境界線,2番目のレベルは穴(連結成分の内側に存在する)の境界線 + /// +#else + /// + /// retrieves all of the contours and organizes them into a two-level hierarchy. + /// At the top level, there are external boundaries of the components. + /// At the second level, there are boundaries of the holes. If there is another + /// contour inside a hole of a connected component, it is still put at the top level. + /// +#endif + CComp = 2, + + +#if LANG_JP + /// + /// 全ての輪郭を抽出し,枝分かれした輪郭を完全に表現する階層構造を構成する + /// +#else + /// + /// retrieves all of the contours and reconstructs a full hierarchy + /// of nested contours. + /// +#endif + Tree = 3, + + +#if LANG_JP + /// + /// + /// [CV_RETR_FLOODFILL] + /// +#else + /// + /// + /// +#endif + FloodFill = 4, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ShapeMatchModes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ShapeMatchModes.cs new file mode 100644 index 0000000..4484147 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ShapeMatchModes.cs @@ -0,0 +1,30 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cv::matchShapesで用いる比較手法 + /// +#else + /// + /// Comparison methods for cv::matchShapes + /// +#endif + public enum ShapeMatchModes + { + /// + /// \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] + /// + I1 = 1, + + /// + /// \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] + /// + I2 = 2, + + /// + /// \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] + /// + I3 = 3, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/TemplateMatchModes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/TemplateMatchModes.cs new file mode 100644 index 0000000..68581eb --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/TemplateMatchModes.cs @@ -0,0 +1,47 @@ + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// テンプレートマッチングの方法 + /// +#else + /// + /// Specifies the way the template must be compared with image regions + /// +#endif + public enum TemplateMatchModes + { + /// + /// \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] + /// + SqDiff = 0, + + /// + /// \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + /// + SqDiffNormed = 1, + + /// + /// \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] + /// + CCorr = 2, + + /// + /// \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + /// + CCorrNormed = 3, + + /// + /// \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] + /// where + /// \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] + /// + CCoeff = 4, + + /// + /// \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\f] + /// + CCoeffNormed = 5, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ThresholdTypes.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ThresholdTypes.cs new file mode 100644 index 0000000..c7757f9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Enum/ThresholdTypes.cs @@ -0,0 +1,57 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 閾値処理の種類 + /// +#else + /// + /// Thresholding type + /// +#endif + [Flags] + public enum ThresholdTypes + { + /// + /// \f[\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] + /// + Binary = 0, + + /// + /// \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] + /// + BinaryInv = 1, + + /// + /// \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + /// + Trunc = 2, + + /// + /// \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] + /// + Tozero = 3, + + /// + /// \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + /// + TozeroInv = 4, + + /// + /// + /// + Mask = 7, + + /// + /// flag, use Otsu algorithm to choose the optimal threshold value + /// + Otsu = 8, + + /// + /// flag, use Triangle algorithm to choose the optimal threshold value + /// + Triangle = 16 + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHough.cs b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHough.cs new file mode 100644 index 0000000..015ab63 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHough.cs @@ -0,0 +1,238 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// finds arbitrary template in the grayscale image using Generalized Hough Transform + /// + public abstract class GeneralizedHough : Algorithm + { + /// + /// Canny low threshold. + /// + /// + public int CannyLowThresh + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.imgproc_GeneralizedHough_getCannyLowThresh(ptr); + GC.KeepAlive(this); + return res; + } + set + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + NativeMethods.imgproc_GeneralizedHough_setCannyLowThresh(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Canny high threshold. + /// + /// + public int CannyHighThresh + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.imgproc_GeneralizedHough_getCannyHighThresh(ptr); + GC.KeepAlive(this); + return res; + } + set + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + NativeMethods.imgproc_GeneralizedHough_setCannyHighThresh(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Minimum distance between the centers of the detected objects. + /// + /// + public double MinDist + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.imgproc_GeneralizedHough_getMinDist(ptr); + GC.KeepAlive(this); + return res; + } + set + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + NativeMethods.imgproc_GeneralizedHough_setMinDist(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Inverse ratio of the accumulator resolution to the image resolution. + /// + /// + public double Dp + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.imgproc_GeneralizedHough_getDp(ptr); + GC.KeepAlive(this); + return res; + } + set + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + NativeMethods.imgproc_GeneralizedHough_setDp(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Maximal size of inner buffers. + /// + /// + public int MaxBufferSize + { + get + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.imgproc_GeneralizedHough_getMaxBufferSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + NativeMethods.imgproc_GeneralizedHough_setMaxBufferSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// set template to search + /// + /// + /// + public void SetTemplate(InputArray templ, Point? templCenter = null) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (templ == null) + throw new ArgumentNullException(nameof(templ)); + templ.ThrowIfDisposed(); + var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); + + NativeMethods.imgproc_GeneralizedHough_setTemplate1(ptr, templ.CvPtr, templCenterValue); + GC.KeepAlive(this); + GC.KeepAlive(templ); + } + + /// + /// set template to search + /// + /// + /// + /// + /// + public virtual void SetTemplate(InputArray edges, InputArray dx, InputArray dy, Point? templCenter = null) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (edges == null) + throw new ArgumentNullException(nameof(edges)); + if (dx == null) + throw new ArgumentNullException(nameof(dx)); + if (dy == null) + throw new ArgumentNullException(nameof(dy)); + edges.ThrowIfDisposed(); + dx.ThrowIfDisposed(); + dy.ThrowIfDisposed(); + var templCenterValue = templCenter.GetValueOrDefault(new Point(-1, -1)); + + NativeMethods.imgproc_GeneralizedHough_setTemplate2( + ptr, edges.CvPtr, dx.CvPtr, dy.CvPtr, templCenterValue); + GC.KeepAlive(this); + GC.KeepAlive(edges); + GC.KeepAlive(dx); + GC.KeepAlive(dy); + } + + /// + /// find template on image + /// + /// + /// + /// + public virtual void Detect( + InputArray image, OutputArray positions, OutputArray? votes = null) + { + if (image == null) + throw new ArgumentNullException(nameof(image)); + if (positions == null) + throw new ArgumentNullException(nameof(positions)); + image.ThrowIfDisposed(); + positions.ThrowIfNotReady(); + votes?.ThrowIfNotReady(); + + NativeMethods.imgproc_GeneralizedHough_detect1( + ptr, image.CvPtr, positions.CvPtr, Cv2.ToPtr(votes)); + GC.KeepAlive(this); + GC.KeepAlive(image); + GC.KeepAlive(positions); + GC.KeepAlive(votes); + positions.Fix(); + votes?.Fix(); + } + + /// + /// find template on image + /// + /// + /// + /// + /// + /// + public virtual void Detect( + InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray? votes = null) + { + if (edges == null) + throw new ArgumentNullException(nameof(edges)); + if (dx == null) + throw new ArgumentNullException(nameof(dx)); + if (dy == null) + throw new ArgumentNullException(nameof(dy)); + if (positions == null) + throw new ArgumentNullException(nameof(positions)); + edges.ThrowIfDisposed(); + dx.ThrowIfDisposed(); + dy.ThrowIfDisposed(); + positions.ThrowIfNotReady(); + votes?.ThrowIfNotReady(); + + NativeMethods.imgproc_GeneralizedHough_detect2( + ptr, edges.CvPtr, dx.CvPtr, dy.CvPtr, positions.CvPtr, Cv2.ToPtr(votes)); + GC.KeepAlive(this); + GC.KeepAlive(edges); + GC.KeepAlive(dx); + GC.KeepAlive(dy); + GC.KeepAlive(positions); + GC.KeepAlive(votes); + positions.Fix(); + votes?.Fix(); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughBallard.cs b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughBallard.cs new file mode 100644 index 0000000..7f8123e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughBallard.cs @@ -0,0 +1,109 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. + /// Pattern Recognition 13 (2): 111-122. + /// Detects position only without traslation and rotation + /// + public class GeneralizedHoughBallard : GeneralizedHough + { + /// + /// cv::Ptr<T> object + /// + private Ptr? ptrObj; + + /// + /// + /// + private GeneralizedHoughBallard(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates a predefined GeneralizedHoughBallard object + /// + /// + public static GeneralizedHoughBallard Create() + { + var ptr = NativeMethods.imgproc_createGeneralizedHoughBallard(); + return new GeneralizedHoughBallard(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + /// + /// R-Table levels. + /// + /// + public int Levels + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughBallard_getLevels(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughBallard_setLevels(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// The accumulator threshold for the template centers at the detection stage. + /// The smaller it is, the more false positions may be detected. + /// + /// + public int VotesThreshold + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughBallard_getVotesThreshold(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughBallard_setVotesThreshold(ptr, value); + GC.KeepAlive(this); + } + } + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.imgproc_Ptr_GeneralizedHoughBallard_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.imgproc_Ptr_GeneralizedHoughBallard_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughGuil.cs b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughGuil.cs new file mode 100644 index 0000000..278dcf4 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/GeneralizedHoughGuil.cs @@ -0,0 +1,319 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). + /// Bidimensional shape detection using an invariant approach. + /// Pattern Recognition 32 (6): 1025-1038. + /// Detects position, traslation and rotation + /// + public class GeneralizedHoughGuil : GeneralizedHough + { + /// + /// cv::Ptr<T> object + /// + private Ptr? ptrObj; + + /// + /// + /// + private GeneralizedHoughGuil(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates a predefined GeneralizedHoughBallard object + /// + /// + public static GeneralizedHoughGuil Create() + { + var ptr = NativeMethods.imgproc_createGeneralizedHoughGuil(); + return new GeneralizedHoughGuil(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + /// + /// Angle difference in degrees between two points in feature. + /// + /// + public double Xi + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getXi(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setXi(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Feature table levels. + /// + /// + public int Levels + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getLevels(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setLevels(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Maximal difference between angles that treated as equal. + /// + /// + public double AngleEpsilon + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getAngleEpsilon(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setAngleEpsilon(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Minimal rotation angle to detect in degrees. + /// + /// + public double MinAngle + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getMinAngle(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setMinAngle(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Maximal rotation angle to detect in degrees. + /// + /// + public double MaxAngle + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getMaxAngle(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setMaxAngle(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Angle step in degrees. + /// + /// + public double AngleStep + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getAngleStep(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setAngleStep(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Angle votes threshold. + /// + /// + public int AngleThresh + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getAngleThresh(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setAngleThresh(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Minimal scale to detect. + /// + /// + public double MinScale + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getMinScale(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setMinScale(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Maximal scale to detect. + /// + /// + public double MaxScale + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getMaxScale(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setMaxScale(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Scale step. + /// + /// + public double ScaleStep + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getScaleStep(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setScaleStep(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Scale votes threshold. + /// + /// + public int ScaleThresh + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getScaleThresh(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setScaleThresh(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Position votes threshold. + /// + /// + public int PosThresh + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_GeneralizedHoughGuil_getPosThresh(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.imgproc_GeneralizedHoughGuil_setPosThresh(ptr, value); + GC.KeepAlive(this); + } + } + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.imgproc_Ptr_GeneralizedHoughGuil_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.imgproc_Ptr_GeneralizedHoughBallard_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/LineIterator.cs b/OpenVinoOpenCvSharp/Modules/imgproc/LineIterator.cs new file mode 100644 index 0000000..00d1f1e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/LineIterator.cs @@ -0,0 +1,301 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// Contrast Limited Adaptive Histogram Equalization + /// + public sealed class LineIterator : DisposableCvObject, IEnumerable + { + private readonly Mat img; + private readonly Point pt1; + private readonly Point pt2; + private readonly PixelConnectivity connectivity; + private readonly bool leftToRight; + + /// + /// Constructor + /// + /// + /// + /// + /// + /// + /// + public LineIterator( + Mat img, + Point pt1, + Point pt2, + PixelConnectivity connectivity = PixelConnectivity.Connectivity8, + bool leftToRight = false) + { + this.img = img ?? throw new ArgumentNullException(nameof(img)); + this.pt1 = pt1; + this.pt2 = pt2; + this.connectivity = connectivity; + this.leftToRight = leftToRight; + } + + /// + /// Initializes the iterator + /// + /// + private void Initialize() + { + if (ptr != IntPtr.Zero) + throw new OpenCvSharpException("invalid state"); + img.ThrowIfDisposed(); + + ptr = NativeMethods.imgproc_LineIterator_new( + img.CvPtr, pt1, pt2, (int)connectivity, leftToRight ? 1 : 0); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.imgproc_LineIterator_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// + /// + /// + public IEnumerator GetEnumerator() + { + //if (disposed) + // throw new ObjectDisposedException(GetType().Name); + Dispose(); + Initialize(); + + var count = NativeMethods.imgproc_LineIterator_count_get(ptr); + for (var i = 0; i < count; i++) + { + var pos = NativeMethods.imgproc_LineIterator_pos(ptr); + var value = NativeMethods.imgproc_LineIterator_operatorEntity(ptr); + GC.KeepAlive(this); + yield return new Pixel(pos, value); + + NativeMethods.imgproc_LineIterator_operatorPP(ptr); + GC.KeepAlive(this); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #region Properties + + /// + /// + /// + public IntPtr Ptr + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_ptr_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public IntPtr Ptr0 + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_ptr0_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Step + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_step_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int ElemSize + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_elemSize_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Err + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_err_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Count + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_count_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int MinusDelta + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_minusDelta_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int PlusDelta + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_plusDelta_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int MinusStep + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_minusStep_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int PlusStep + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_LineIterator_plusStep_get(ptr); + GC.KeepAlive(this); + return res; + } + } + + #endregion + + /// + /// LineIterator pixel data + /// + public class Pixel + { + /// + /// + /// + public unsafe byte* ValuePointer { get; } + + /// + /// + /// + public Point Pos { get; } + + /// + /// + /// + public IntPtr Value + { + get + { + unsafe + { + return new IntPtr(ValuePointer); + } + } + } + + /// + /// + /// + /// + /// + public T GetValue() where T : struct + { + return MarshalHelper.PtrToStructure(Value); + } + + /// + /// + /// + /// + /// + /// + public void SetValue(T value) where T : struct + { + Marshal.StructureToPtr(value, Value, false); + } + + /// + /// Constructor + /// + /// + /// + internal unsafe Pixel(Point pos, IntPtr value) + { + Pos = pos; + ValuePointer = (byte*)value.ToPointer(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/CircleSegment.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/CircleSegment.cs new file mode 100644 index 0000000..ee32eb3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/CircleSegment.cs @@ -0,0 +1,176 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvHoughCirclesで得られる、円のデータ(中心と半径) + /// +#else + /// + /// circle structure retrieved from cvHoughCircle + /// +#endif + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct CircleSegment : IEquatable + { + #region Fields +#if LANG_JP + /// + /// 円の中心 + /// +#else + /// + /// Center coordinate of the circle + /// +#endif + public Point2f Center; +#if LANG_JP + /// + /// 半径 + /// +#else + /// + /// Radius + /// +#endif + public float Radius; + #endregion + + #region Init +#if LANG_JP + /// + /// 初期化 + /// + /// 円の中心 + /// 半径 +#else + /// + /// Constructor + /// + /// center + /// radius +#endif + public CircleSegment(Point2f center, float radius) + { + Center = center; + Radius = radius; + } + #endregion + + #region Operators +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(CircleSegment obj) + { + return (Center == obj.Center && + Math.Abs(Radius - obj.Radius) < 1e-9); + } +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(CircleSegment lhs, CircleSegment rhs) + { + return lhs.Equals(rhs); + } +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(CircleSegment lhs, CircleSegment rhs) + { + return !lhs.Equals(rhs); + } + #endregion + + #region Overrided Methods + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return Center.GetHashCode() + Radius.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"CvCircleSegment (Center:{Center} Radius:{Radius})"; + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/HierarchyIndex.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/HierarchyIndex.cs new file mode 100644 index 0000000..3dcb9d2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/HierarchyIndex.cs @@ -0,0 +1,81 @@ +namespace OpenCvSharp +{ + /// + /// Information about the image topology for cv::findContours + /// + public class HierarchyIndex + { + /// + /// + /// + public int Next { get; set; } + + /// + /// + /// + public int Previous { get; set; } + + /// + /// + /// + public int Child { get; set; } + + /// + /// + /// + public int Parent { get; set; } + + /// + /// + /// + public HierarchyIndex() + { + Next = 0; + Previous = 0; + Child = 0; + Parent = 0; + } + + /// + /// + /// + /// + /// + /// + /// + public HierarchyIndex(int next, int previous, int child, int parent) + { + Next = next; + Previous = previous; + Child = child; + Parent = parent; + } + + /// + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public static HierarchyIndex FromVec4i(Vec4i vec) + { + return new HierarchyIndex + { + Next = vec.Item0, + Previous = vec.Item1, + Child = vec.Item2, + Parent = vec.Item3 + }; + } + + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public Vec4i ToVec4i() + { + return new Vec4i(Next, Previous, Child, Parent); + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line2D.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line2D.cs new file mode 100644 index 0000000..de16e93 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line2D.cs @@ -0,0 +1,219 @@ +using System; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// 始点と変化量であらわされる、2次元の直線を表すオブジェクト + /// +#else + /// + /// 2-dimentional line vector + /// +#endif + public class Line2D + { + #region Properties +#if LANG_JP + /// + /// 直線に乗るように正規化された方向ベクトル (x成分) + /// +#else + /// + /// The X component of the normalized vector collinear to the line + /// +#endif + public double Vx { get; set; } +#if LANG_JP + /// + /// 直線に乗るように正規化された方向ベクトル (y成分) + /// +#else + /// + /// The Y component of the normalized vector collinear to the line + /// +#endif + public double Vy { get; set; } +#if LANG_JP + /// + /// 直線上の点のx座標 + /// +#else + /// + /// X-coordinate of some point on the line + /// +#endif + public double X1 { get; set; } +#if LANG_JP + /// + /// 直線上の点のy座標 + /// +#else + /// + /// Y-coordinate of some point on the line + /// +#endif + public double Y1 { get; set; } + #endregion + + #region Init +#if LANG_JP + /// + /// 初期化 + /// + /// 直線に乗るように正規化された方向ベクトル (x成分) + /// 直線に乗るように正規化された方向ベクトル (y成分) + /// 直線上の点のx座標 + /// 直線上の点のy座標 +#else + /// + /// Initializes this object + /// + /// The X component of the normalized vector collinear to the line + /// The Y component of the normalized vector collinear to the line + /// Z-coordinate of some point on the line + /// Z-coordinate of some point on the line +#endif + public Line2D(double vx, double vy, double x1, double y1) + { + Vx = vx; + Vy = vy; + X1 = x1; + Y1 = y1; + } +#if LANG_JP + /// + /// cvFitLineの出力(float[4])から初期化 + /// + /// cvFitLineの出力結果 +#else + /// + /// Initializes by cvFitLine output + /// + /// The returned value from cvFitLineparam> +#endif + public Line2D(float[] line) + : this(line[0], line[1], line[2], line[3]) + { + } + #endregion + + #region Methods + + /// + /// + /// + /// + public double GetVectorRadian() + { + return Math.Atan2(Vy, Vx); + } + /// + /// + /// + /// + public double GetVectorAngle() + { + return GetVectorRadian() * 180 / Math.PI; + } + +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// +#endif + public double Distance(Point point) + { + return Distance(point.X, point.Y); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// +#endif + public double Distance(Point2f point) + { + return Distance(point.X, point.Y); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// +#endif + public double Distance(Point2d point) + { + return Distance(point.X, point.Y); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// + /// +#endif + public double Distance(double x, double y) + { + // 公式で + var m = Vy / Vx; + var n = Y1 - m * X1; + return Math.Abs(y - m * x - n) / Math.Sqrt(1 + m * m); + } + +#if LANG_JP + /// + /// 指定したサイズに直線を合わせて、その端点を返す (描画用途) + /// + /// 合わせこむサイズの幅 + /// 合わせこむサイズの高さ + /// 端点1つ目 + /// 端点2つ目 +#else + /// + /// Fits this line to the specified size (for drawing) + /// + /// Width of fit size + /// Height of fit size + /// 1st edge point of fitted line + /// 2nd edge point of fitted line +#endif + public void FitSize(int width, int height, out Point pt1, out Point pt2) + { + double t = (width + height); + pt1 = new Point + { + X = (int)Math.Round(X1 - Vx*t), + Y = (int)Math.Round(Y1 - Vy * t) + }; + pt2 = new Point + { + X = (int)Math.Round(X1 + Vx * t), + Y = (int)Math.Round(Y1 + Vy * t) + }; + } + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line3D.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line3D.cs new file mode 100644 index 0000000..aa8bc25 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/Line3D.cs @@ -0,0 +1,294 @@ +using System; + +namespace OpenCvSharp +{ + +#if LANG_JP + /// + /// 3次元空間上の直線 + /// +#else + /// + /// A 3-dimensional line object + /// +#endif + public class Line3D + { + #region Properties +#if LANG_JP + /// + /// 直線に乗るように正規化された方向ベクトル (x成分) + /// +#else + /// + /// The X component of the normalized vector collinear to the line + /// +#endif + public double Vx { get; set; } +#if LANG_JP + /// + /// 直線に乗るように正規化された方向ベクトル (y成分) + /// +#else + /// + /// The Y component of the normalized vector collinear to the line + /// +#endif + public double Vy { get; set; } +#if LANG_JP + /// + /// 直線に乗るように正規化された方向ベクトル (z成分) + /// +#else + /// + /// The Z component of the normalized vector collinear to the line + /// +#endif + public double Vz { get; set; } +#if LANG_JP + /// + /// 直線上の点のx座標 + /// +#else + /// + /// X-coordinate of some point on the line + /// +#endif + public double X1 { get; set; } +#if LANG_JP + /// + /// 直線上の点のy座標 + /// +#else + /// + /// Y-coordinate of some point on the line + /// +#endif + public double Y1 { get; set; } +#if LANG_JP + /// + /// 直線上の点のz座標 + /// +#else + /// + /// Z-coordinate of some point on the line + /// +#endif + public double Z1 { get; set; } + #endregion + + #region Initialization +#if LANG_JP + /// + /// 初期化 + /// + /// 直線に乗るように正規化された方向ベクトル (x成分) + /// 直線に乗るように正規化された方向ベクトル (y成分) + /// 直線に乗るように正規化された方向ベクトル (z成分) + /// 直線上の点のx座標 + /// 直線上の点のy座標 + /// 直線上の点のz座標 +#else + /// + /// Initializes this object + /// + /// The X component of the normalized vector collinear to the line + /// The Y component of the normalized vector collinear to the line + /// The Z component of the normalized vector collinear to the line + /// Z-coordinate of some point on the line + /// Z-coordinate of some point on the line + /// Z-coordinate of some point on the line +#endif + public Line3D(double vx, double vy, double vz, double x1, double y1, double z1) + { + Vx = vx; + Vy = vy; + Vz = vz; + X1 = x1; + Y1 = y1; + Z1 = z1; + } +#if LANG_JP + /// + /// cvFitLineの出力(float[6])から初期化 + /// + /// cvFitLineの出力結果 +#else + /// + /// Initializes by cvFitLine output + /// + /// The returned value from cvFitLineparam> +#endif + public Line3D(float[] line) + : this(line[0], line[1], line[2], line[3], line[4], line[5]) + { + } + #endregion + + #region Methods +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + public Point3d PerpendicularFoot(Point3f point) + { + return PerpendicularFoot(point.X, point.Y, point.Z); + } +#if LANG_JP + /// + /// + /// + /// +#else + /// + /// + /// + /// +#endif + public Point3d PerpendicularFoot(Point3d point) + { + return PerpendicularFoot(point.X, point.Y, point.Z); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// + /// + /// +#endif + public Point3d PerpendicularFoot(double x, double y, double z) + { + var xa = X1; + var ya = Y1; + var za = Z1; + var xb = X1 + Vx; + var yb = Y1 + Vy; + var zb = Z1 + Vz; + + var k = ((x - xa)*(xb - xa) + (y - ya)*(yb - ya) + (z - za)*(zb - za))/ + (Math.Pow(xb - xa, 2) + Math.Pow(yb - ya, 2) + Math.Pow(zb - za, 2)); + + var hx = k*xb+(1-k)*xa; + var hy = k*yb+(1-k)*ya; + var hz = k*zb+(1-k)*za; + return new Point3d(hx, hy, hz); + } + + +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// +#endif + public double Distance(Point3f point) + { + return Distance(point.X, point.Y, point.Z); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// +#endif + public double Distance(Point3d point) + { + return Distance(point.X, point.Y, point.Z); + } +#if LANG_JP + /// + /// 指定した点と直線の距離を返す + /// + /// + /// + /// +#else + /// + /// Returns the distance between this line and the specified point + /// + /// + /// + /// +#endif + public double Distance(double x, double y, double z) + { + var p = new Point3d(x, y, z); + var a = new Point3d(X1, Y1, Z1); + var b = new Point3d(X1 + Vx, Y1 + Vy, Z1 + Vz); + var ab = new Point3d { X = b.X - a.X, Y = b.Y - a.Y, Z = b.Z - a.Z }; + var ap = new Point3d { X = p.X - a.X, Y = p.Y - a.Y, Z = p.Z - a.Z }; + + // AB, APを外積 -> 平行四辺形Dの面積 + var d = VectorLength(CrossProduct(ab, ap)); + // AB間の距離 + var l = VertexDistance(a, b); + // 平行四辺形の高さ(垂線) + var h = d / l; + return h; + } + + /// + /// ベクトルの外積 + /// + /// + /// + /// + private Point3d CrossProduct(Point3d vl, Point3d vr) + { + var ret = new Point3d + { + X = (vl.Y*vr.Z) - (vl.Z*vr.Y), + Y = (vl.Z*vr.X) - (vl.X*vr.Z), + Z = (vl.X*vr.Y) - (vl.Y*vr.X) + }; + return ret; + } + /// + /// ベクトルの長さ(原点からの距離) + /// + /// + /// + private double VectorLength(Point3d v) + { + return Math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z); + } + /// + /// 2点間(2ベクトル)の距離 + /// + /// + /// + /// + private double VertexDistance(Point3d p1, Point3d p2) + { + return Math.Sqrt((p2.X - p1.X) * (p2.X - p1.X) + + (p2.Y - p1.Y) * (p2.Y - p1.Y) + + (p2.Z - p1.Z) * (p2.Z - p1.Z)); + } + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPoint.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPoint.cs new file mode 100644 index 0000000..ad95eae --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPoint.cs @@ -0,0 +1,487 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvHoughLines2で得られる、両端の点で表現される線分 + /// +#else + /// + /// Line segment structure retrieved from cvHoughLines2 + /// +#endif + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct LineSegmentPoint : IEquatable + { + #region Fields + +#if LANG_JP + /// + /// 1つ目の点 + /// +#else + /// + /// 1st Point + /// +#endif + public Point P1; + +#if LANG_JP + /// + /// 2つ目の点 + /// +#else + /// + /// 2nd Point + /// +#endif + public Point P2; + + #endregion + + #region Init + +#if LANG_JP + /// + /// 初期化 + /// + /// 1つ目の点 + /// 2つ目の点 +#else + /// + /// Constructor + /// + /// 1st Point + /// 2nd Point +#endif + public LineSegmentPoint(Point p1, Point p2) + { + P1 = p1; + P2 = p2; + } + + #endregion + + #region Operators + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(LineSegmentPoint obj) + { + return (P1 == obj.P1 && P2 == obj.P2); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(LineSegmentPoint lhs, LineSegmentPoint rhs) + { + return lhs.Equals(rhs); + } + +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(LineSegmentPoint lhs, LineSegmentPoint rhs) + { + return !lhs.Equals(rhs); + } + + #endregion + + #region Overrided methods + +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } + +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return P1.GetHashCode() + P2.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"CvLineSegmentPoint (P1:{P1} P2:{P2})"; + } + + #endregion + + #region Methods + + #region Line and Line + +#if LANG_JP + /// + /// 2直線の交点を求める (線分としてではなく直線として) + /// + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two lines + /// + /// + /// + /// +#endif + public static Point? LineIntersection(LineSegmentPoint line1, LineSegmentPoint line2) + { + var x1 = line1.P1.X; + var y1 = line1.P1.Y; + var f1 = line1.P2.X - line1.P1.X; + var g1 = line1.P2.Y - line1.P1.Y; + var x2 = line2.P1.X; + var y2 = line2.P1.Y; + var f2 = line2.P2.X - line2.P1.X; + var g2 = line2.P2.Y - line2.P1.Y; + + double det = f2*g1 - f1*g2; + if (Math.Abs(det) < 1e-9) + { + return null; + } + + var dx = x2 - x1; + var dy = y2 - y1; + var t1 = (f2*dy - g2*dx)/det; + //var t2 = (f1*dy - g1*dx)/det; + + return new Point + { + X = (int) Math.Round(x1 + (f1*t1)), + Y = (int) Math.Round(y1 + (g1*t1)) + }; + } + +#if LANG_JP + /// + /// 2直線の交点を求める (線分としてではなく直線として) + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two lines + /// + /// + /// +#endif + public Point? LineIntersection(LineSegmentPoint line) + { + return LineIntersection(this, line); + } + + #endregion + + #region Segment and Segment + +#if LANG_JP + /// + /// 線分同士の交点を求める + /// + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two segments + /// + /// + /// + /// +#endif + public static Point? SegmentIntersection(LineSegmentPoint seg1, LineSegmentPoint seg2) + { + if (IntersectedSegments(seg1, seg2)) + return LineIntersection(seg1, seg2); + else + return null; + } + +#if LANG_JP + /// + /// 線分同士の交点を求める + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two segments + /// + /// + /// +#endif + public Point? SegmentIntersection(LineSegmentPoint seg) + { + return SegmentIntersection(this, seg); + } + +#if LANG_JP + /// + /// 2つの線分が交差しているかどうかを返す + /// + /// + /// + /// +#else + /// + /// Returns a boolean value indicating whether the specified two segments intersect. + /// + /// + /// + /// +#endif + public static bool IntersectedSegments(LineSegmentPoint seg1, LineSegmentPoint seg2) + { + var p1 = seg1.P1; + var p2 = seg1.P2; + var p3 = seg2.P1; + var p4 = seg2.P2; + + checked + { + if (p1.X >= p2.X) + { + if ((p1.X < p3.X && p1.X < p4.X) || (p2.X > p3.X && p2.X > p4.X)) + return false; + } + else + { + if ((p2.X < p3.X && p2.X < p4.X) || (p1.X > p3.X && p1.X > p4.X)) + return false; + } + if (p1.Y >= p2.Y) + { + if ((p1.Y < p3.Y && p1.Y < p4.Y) || (p2.Y > p3.Y && p2.Y > p4.Y)) + return false; + } + else + { + if ((p2.Y < p3.Y && p2.Y < p4.Y) || (p1.Y > p3.Y && p1.Y > p4.Y)) + return false; + } + + if (((long) (p1.X - p2.X)*(p3.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p3.X))* + ((long) (p1.X - p2.X)*(p4.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p4.X)) > 0) + return false; + if (((long) (p3.X - p4.X)*(p1.Y - p3.Y) + (long) (p3.Y - p4.Y)*(p3.X - p1.X))* + ((long) (p3.X - p4.X)*(p2.Y - p3.Y) + (long) (p3.Y - p4.Y)*(p3.X - p2.X)) > 0) + return false; + } + return true; + } + +#if LANG_JP + /// + /// 2つの線分が交差しているかどうかを返す + /// + /// + /// +#else + /// + /// Returns a boolean value indicating whether the specified two segments intersect. + /// + /// + /// +#endif + public bool IntersectedSegments(LineSegmentPoint seg) + { + return IntersectedSegments(this, seg); + } + + #endregion + + #region Line and Segment + +#if LANG_JP + /// + /// 直線と線分が交差しているかを調べる + /// + /// 線分 + /// 直線 + /// +#else + /// + /// Returns a boolean value indicating whether a line and a segment intersect. + /// + /// Line + /// Segment + /// +#endif + public static bool IntersectedLineAndSegment(LineSegmentPoint line, LineSegmentPoint seg) + { + var p1 = line.P1; + var p2 = line.P2; + var p3 = seg.P1; + var p4 = seg.P2; + if (((long) (p1.X - p2.X)*(p3.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p3.X))* + ((long) (p1.X - p2.X)*(p4.Y - p1.Y) + (long) (p1.Y - p2.Y)*(p1.X - p4.X)) > 0) + { + return false; + } + return true; + } + +#if LANG_JP + /// + /// 直線と線分の交点を求める + /// + /// + /// + /// +#else + /// + /// Calculates a intersection of a line and a segment + /// + /// + /// + /// +#endif + public static Point? LineAndSegmentIntersection(LineSegmentPoint line, LineSegmentPoint seg) + { + if (IntersectedLineAndSegment(line, seg)) + return LineIntersection(line, seg); + else + return null; + } + + #endregion + +#if LANG_JP + /// + /// 2点間の距離を求める + /// + /// + /// +#else + /// + /// + /// + /// + /// +#endif + public double Length(LineSegmentPoint s) + { + return P1.DistanceTo(P2); + } + +#if LANG_JP + /// + /// この CvLineSegmentPoint を指定の量だけ平行移動する + /// + /// x 座標のオフセット量 + /// y 座標のオフセット量 + /// +#else + /// + /// Translates the Point by the specified amount. + /// + /// The amount to offset the x-coordinate. + /// The amount to offset the y-coordinate. + /// +#endif + public void Offset(int x, int y) + { + P1.X += x; + P1.Y += y; + P2.X += x; + P2.Y += y; + } + +#if LANG_JP + /// + /// この CvLineSegmentPoint を指定の量だけ平行移動する + /// + /// オフセットに使用する CvPoint + /// +#else + /// + /// Translates the Point by the specified amount. + /// + /// The Point used offset this CvPoint. + /// +#endif + public void Offset(Point p) + { + Offset(p.X, p.Y); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPolar.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPolar.cs new file mode 100644 index 0000000..3849760 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Model/LineSegmentPolar.cs @@ -0,0 +1,340 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// cvHoughLines2で得られる、極座標系で表現される線分 + /// +#else + /// + /// Polar line segment retrieved from cvHoughLines2 + /// +#endif + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct LineSegmentPolar : IEquatable + { + #region Fields +#if LANG_JP + /// + /// 線分の長さ + /// +#else + /// + /// Length of the line + /// +#endif + public float Rho; +#if LANG_JP + /// + /// 線分の角度(ラジアン) + /// +#else + /// + /// Angle of the line (radian) + /// +#endif + public float Theta; + #endregion + + #region Init +#if LANG_JP + /// + /// 初期化 + /// + /// 線分の長さ + /// 線分の角度(ラジアン) +#else + /// + /// Constructor + /// + /// Length of the line + /// Angle of the line (radian) +#endif + public LineSegmentPolar(float rho, float theta) + { + Rho = rho; + Theta = theta; + } + #endregion + + #region Operators + +#if LANG_JP + /// + /// 指定したオブジェクトと等しければtrueを返す + /// + /// 比較するオブジェクト + /// 型が同じで、メンバの値が等しければtrue +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public bool Equals(LineSegmentPolar obj) + { + return (Math.Abs(Rho - obj.Rho) < 1e-9 && + Math.Abs(Theta - obj.Theta) < 1e-9); + } + +#if LANG_JP + /// + /// == 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are equal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are equal; otherwise, false. +#endif + public static bool operator ==(LineSegmentPolar lhs, LineSegmentPolar rhs) + { + return lhs.Equals(rhs); + } +#if LANG_JP + /// + /// != 演算子のオーバーロード + /// + /// 左辺値 + /// 右辺値 + /// 等しくなければtrue +#else + /// + /// Compares two CvPoint objects. The result specifies whether the members of each object are unequal. + /// + /// A Point to compare. + /// A Point to compare. + /// This operator returns true if the members of left and right are unequal; otherwise, false. +#endif + public static bool operator !=(LineSegmentPolar lhs, LineSegmentPolar rhs) + { + return !lhs.Equals(rhs); + } + #endregion + + #region Overrided methods +#if LANG_JP + /// + /// Equalsのオーバーライド + /// + /// 比較するオブジェクト + /// +#else + /// + /// Specifies whether this object contains the same members as the specified Object. + /// + /// The Object to test. + /// This method returns true if obj is the same type as this object and has the same members as this object. +#endif + public override bool Equals(object? obj) + { + return base.Equals(obj); + } +#if LANG_JP + /// + /// GetHashCodeのオーバーライド + /// + /// このオブジェクトのハッシュ値を指定する整数値。 +#else + /// + /// Returns a hash code for this object. + /// + /// An integer value that specifies a hash value for this object. +#endif + public override int GetHashCode() + { + return Rho.GetHashCode() + Theta.GetHashCode(); + } +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// 文字列形式 +#else + /// + /// Converts this object to a human readable string. + /// + /// A string that represents this object. +#endif + public override string ToString() + { + return $"CvLineSegmentPolar (Rho:{Rho} Theta:{Theta})"; + } + #endregion + + #region Methods +#if LANG_JP + /// + /// 2直線の交点を求める + /// + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two lines + /// + /// + /// + /// +#endif + public static Point? LineIntersection(LineSegmentPolar line1, LineSegmentPolar line2) + { + var seg1 = line1.ToSegmentPoint(5000); + var seg2 = line2.ToSegmentPoint(5000); + return LineSegmentPoint.LineIntersection(seg1, seg2); + } + +#if LANG_JP + /// + /// 2直線の交点を求める (線分としてではなく直線として) + /// + /// + /// +#else + /// + /// Calculates a intersection of the specified two lines + /// + /// + /// +#endif + public Point? LineIntersection(LineSegmentPolar line) + { + return LineIntersection(this, line); + } + +#if LANG_JP + /// + /// LineSegmentPointに変換する + /// + /// + /// +#else + /// + /// Convert To LineSegmentPoint + /// + /// + /// +#endif + public LineSegmentPoint ToSegmentPoint(double scale) + { + var cos = Math.Cos(Theta); + var sin = Math.Sin(Theta); + var x0 = cos * Rho; + var y0 = sin * Rho; + var p1 = new Point { X = (int)Math.Round(x0 + scale * -sin), Y = (int)Math.Round(y0 + scale * cos) }; + var p2 = new Point { X = (int)Math.Round(x0 - scale * -sin), Y = (int)Math.Round(y0 - scale * cos) }; + return new LineSegmentPoint(p1, p2); + } + +#if LANG_JP + /// + /// 指定したx座標を両端とするような線分に変換する + /// + /// + /// + /// +#else + /// + /// Converts to a line segment with the specified x coordinates at both ends + /// + /// + /// + /// +#endif + public LineSegmentPoint ToSegmentPointX(int x1, int x2) + { + if (x1 > x2) + throw new ArgumentOutOfRangeException(); + + var y1 = YPosOfLine(x1); + var y2 = YPosOfLine(x2); + if (!y1.HasValue || !y2.HasValue) + throw new Exception(); + + var p1 = new Point(x1, y1.Value); + var p2 = new Point(x2, y2.Value); + return new LineSegmentPoint(p1, p2); + } + +#if LANG_JP + /// + /// 指定したy座標を両端とするような線分に変換する + /// + /// + /// + /// +#else + /// + /// Converts to a line segment with the specified y coordinates at both ends + /// + /// + /// + /// +#endif + public LineSegmentPoint ToSegmentPointY(int y1, int y2) + { + if (y1 > y2) + throw new ArgumentOutOfRangeException(); + + var x1 = XPosOfLine(y1); + var x2 = XPosOfLine(y2); + if (!x1.HasValue || !x2.HasValue) + throw new Exception(); + + var p1 = new Point(x1.Value, y1); + var p2 = new Point(x2.Value, y2); + return new LineSegmentPoint(p1, p2); + } + +#if LANG_JP + /// + /// 指定したy座標を通るときのx座標を求める + /// + /// + /// +#else + /// + /// + /// + /// + /// +#endif + public int? XPosOfLine(int y) + { + var axis = new LineSegmentPolar(y, (float)(Math.PI / 2)); // 垂線90度 = x軸に平行 + var node = LineIntersection(axis); + return node?.X; + } + +#if LANG_JP + /// + /// 指定したx座標を通るときのy座標を求める + /// + /// + /// +#else + /// + /// + /// + /// + /// +#endif + public int? YPosOfLine(int x) + { + var axis = new LineSegmentPolar(x, 0); // 垂線0度 = y軸に平行 + var node = LineIntersection(axis); + return node?.Y; + } +#endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Moments.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Moments.cs new file mode 100644 index 0000000..a9f084c --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Moments.cs @@ -0,0 +1,268 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// Raster image moments + /// + public class Moments + { + /// + /// spatial moments + /// + public double M00, M10, M01, M20, M11, M02, M30, M21, M12, M03; + + /// + /// central moments + /// + public double Mu20, Mu11, Mu02, Mu30, Mu21, Mu12, Mu03; + + /// + /// central normalized moments + /// + public double Nu20, Nu11, Nu02, Nu30, Nu21, Nu12, Nu03; + + #region Init & Disposal + /// + /// Default constructor. + /// All moment values are set to 0. + /// + public Moments() + { + M00 = M10 = M01 = M20 = M11 = M02 = M30 = M21 = M12 = M03 = + Mu20 = Mu11 = Mu02 = Mu30 = Mu21 = Mu12 = Mu03 = + Nu20 = Nu11 = Nu02 = Nu30 = Nu21 = Nu12 = Nu03 = 0.0; + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public Moments(double m00, double m10, double m01, double m20, double m11, + double m02, double m30, double m21, double m12, double m03) + { + Initialize(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (single-channel, 8-bit or floating-point + /// 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) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + array.ThrowIfDisposed(); + InitializeFromInputArray(array, binaryImage); + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (8-bit) 2D array + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public Moments(byte[,] array, bool binaryImage = false) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + var rows = array.GetLength(0); + var cols = array.GetLength(1); + using (var arrayMat = new Mat(rows, cols, MatType.CV_8UC1, array)) + { + InitializeFromInputArray(arrayMat, binaryImage); + } + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (floating-point) 2D array + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public Moments(float[,] array, bool binaryImage = false) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + var rows = array.GetLength(0); + var cols = array.GetLength(1); + using (var arrayMat = new Mat(rows, cols, MatType.CV_32FC1, array)) + { + InitializeFromInputArray(arrayMat, binaryImage); + } + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// Array of 2D points + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public Moments(IEnumerable array, bool binaryImage = false) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + var points = EnumerableEx.ToArray(array); + using (var pointsMat = new Mat(points.Length, 1, MatType.CV_32SC2, points)) + { + InitializeFromInputArray(pointsMat, binaryImage); + } + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// Array of 2D points + /// If it is true, then all the non-zero image pixels are treated as 1’s + /// + public Moments(IEnumerable array, bool binaryImage = false) + { + if (array == null) + throw new ArgumentNullException(nameof(array)); + var points = EnumerableEx.ToArray(array); + using (var pointsMat = new Mat(points.Length, 1, MatType.CV_32FC2, points)) + { + InitializeFromInputArray(pointsMat, binaryImage); + } + } + + /// + /// Calculates all of the moments + /// up to the third order of a polygon or rasterized shape. + /// + /// A raster image (single-channel, 8-bit or floating-point + /// 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) + { + var m = NativeMethods.imgproc_moments(array.CvPtr, binaryImage ? 1 : 0); + GC.KeepAlive(array); + Initialize(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void Initialize(double m00, double m10, double m01, double m20, double m11, + double m02, double m30, double m21, double m12, double m03) + { + M00 = m00; + M10 = m10; + M01 = m01; + M20 = m20; + M11 = m11; + M02 = m02; + M30 = m30; + M21 = m21; + M12 = m12; + M03 = m03; + + double cx = 0, cy = 0, invM00 = 0; + if (Math.Abs(M00) > double.Epsilon) + { + invM00 = 1.0 / M00; + cx = M10 * invM00; + cy = M01 * invM00; + } + + Mu20 = M20 - M10 * cx; + Mu11 = M11 - M10 * cy; + Mu02 = M02 - M01 * cy; + + Mu30 = M30 - cx * (3 * Mu20 + cx * M10); + Mu21 = M21 - cx * (2 * Mu11 + cx * M01) - cy * Mu20; + Mu12 = M12 - cy * (2 * Mu11 + cy * M10) - cx * Mu02; + Mu03 = M03 - cy * (3 * Mu02 + cy * M01); + + var invSqrtM00 = Math.Sqrt(Math.Abs(invM00)); + var s2 = invM00 * invM00; + var s3 = s2 * invSqrtM00; + + Nu20 = Mu20 * s2; + Nu11 = Mu11 * s2; + Nu02 = Mu02 * s2; + Nu30 = Mu30 * s3; + Nu21 = Mu21 * s3; + Nu12 = Mu12 * s3; + Nu03 = Mu03 * s3; + } + + #endregion + + #region Methods + /// + /// computes 7 Hu invariants from the moments + /// + /// + public double[] HuMoments() + { + var hu = new double[7]; + var t0 = Nu30 + Nu12; + var t1 = Nu21 + Nu03; + + double q0 = t0 * t0, q1 = t1 * t1; + + var n4 = 4 * Nu11; + var s = Nu20 + Nu02; + var d = Nu20 - Nu02; + + hu[0] = s; + hu[1] = d * d + n4 * Nu11; + hu[3] = q0 + q1; + hu[5] = d * (q0 - q1) + n4 * t0 * t1; + + t0 *= q0 - 3 * q1; + t1 *= 3 * q0 - q1; + + q0 = Nu30 - 3 * Nu12; + q1 = 3 * Nu21 - Nu03; + + hu[2] = q0 * q0 + q1 * q1; + hu[4] = q0 * t0 + q1 * t1; + hu[6] = q1 * t0 - q0 * t1; + return hu; + } + + #endregion + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] +#pragma warning disable 1591 + public struct NativeStruct + { + public double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; /* spatial moments */ + public double mu20, mu11, mu02, mu30, mu21, mu12, mu03; /* central moments */ + public double inv_sqrt_m00; /* m00 != 0 ? 1/sqrt(m00) : 0 */ + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/imgproc/Subdiv2D.cs b/OpenVinoOpenCvSharp/Modules/imgproc/Subdiv2D.cs new file mode 100644 index 0000000..2594f3e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/imgproc/Subdiv2D.cs @@ -0,0 +1,392 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; +// ReSharper disable InconsistentNaming +// ReSharper disable IdentifierTypo + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// + /// +#else + /// + /// + /// +#endif + public class Subdiv2D : DisposableCvObject + { + #region Init and Disposal + +#if LANG_JP + /// + /// デフォルトのパラメータで初期化. + /// 実際は numberOfDisparities だけは指定する必要がある. + /// +#else + /// + /// Default constructor + /// +#endif + public Subdiv2D() + { + ptr = NativeMethods.imgproc_Subdiv2D_new1(); + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException(); + } + +#if LANG_JP + /// + /// Subdiv2D コンストラクタ + /// + /// +#else + /// + /// Subdiv2D Constructor + /// + /// +#endif + public Subdiv2D(Rect rect) + { + ptr = NativeMethods.imgproc_Subdiv2D_new2(rect); + if (ptr == IntPtr.Zero) + throw new OpenCvSharpException(); + } + +#if LANG_JP + /// + /// リソースの解放 + /// +#else + /// + /// Clean up any resources being used. + /// +#endif + public void Release() + { + Dispose(); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.imgproc_Subdiv2D_delete(ptr); + base.DisposeUnmanaged(); + } + + #endregion + + #region Constants + /// + /// + /// + public const int + PTLOC_ERROR = -2, + PTLOC_OUTSIDE_RECT = -1, + PTLOC_INSIDE = 0, + PTLOC_VERTEX = 1, + PTLOC_ON_EDGE = 2; + /// + /// + /// + public const int + NEXT_AROUND_ORG = 0x00, + NEXT_AROUND_DST = 0x22, + PREV_AROUND_ORG = 0x11, + PREV_AROUND_DST = 0x33, + NEXT_AROUND_LEFT = 0x13, + NEXT_AROUND_RIGHT = 0x31, + PREV_AROUND_LEFT = 0x20, + PREV_AROUND_RIGHT = 0x02; + #endregion + + #region Methods + #region InitDelaunay + /// + /// + /// + /// + public void InitDelaunay(Rect rect) + { + ThrowIfDisposed(); + NativeMethods.imgproc_Subdiv2D_initDelaunay(ptr, rect); + GC.KeepAlive(this); + } + #endregion + #region Insert + /// + /// + /// + /// + /// + public int Insert(Point2f pt) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_insert1(ptr, pt); + GC.KeepAlive(this); + return res; + } + /// + /// + /// + /// + public void Insert(Point2f[] ptvec) + { + ThrowIfDisposed(); + if (ptvec == null) + throw new ArgumentNullException(nameof(ptvec)); + NativeMethods.imgproc_Subdiv2D_insert2(ptr, ptvec, ptvec.Length); + GC.KeepAlive(this); + } + /// + /// + /// + /// + public void Insert(IEnumerable ptvec) + { + if (ptvec == null) + throw new ArgumentNullException(nameof(ptvec)); + Insert(new List(ptvec).ToArray()); + } + #endregion + #region Locate + /// + /// + /// + /// + /// + /// + /// + public int Locate(Point2f pt, out int edge, out int vertex) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_locate(ptr, pt, out edge, out vertex); + GC.KeepAlive(this); + return res; + } + #endregion + #region FindNearest + /// + /// + /// + /// + /// + public int FindNearest(Point2f pt) + { + return FindNearest(pt, out _); + } + /// + /// + /// + /// + /// + /// + public int FindNearest(Point2f pt, out Point2f nearestPt) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_findNearest(ptr, pt, out nearestPt); + GC.KeepAlive(this); + return res; + } + #endregion + #region GetEdgeList + /// + /// + /// + /// + public Vec4f[] GetEdgeList() + { + ThrowIfDisposed(); + NativeMethods.imgproc_Subdiv2D_getEdgeList(ptr, out var p); + GC.KeepAlive(this); + using (var vec = new VectorOfVec4f(p)) + { + return vec.ToArray(); + } + } + #endregion + #region GetTriangleList + /// + /// + /// + /// + public Vec6f[] GetTriangleList() + { + ThrowIfDisposed(); + NativeMethods.imgproc_Subdiv2D_getTriangleList(ptr, out var p); + GC.KeepAlive(this); + using (var vec = new VectorOfVec6f(p)) + { + return vec.ToArray(); + } + } + #endregion + #region GetVoronoiFacetList + /// + /// + /// + /// + /// + /// + public void GetVoronoiFacetList(IEnumerable idx, out Point2f[][] facetList, out Point2f[] facetCenters) + { + ThrowIfDisposed(); + + IntPtr facetListPtr, facetCentersPtr; + if (idx == null) + { + NativeMethods.imgproc_Subdiv2D_getVoronoiFacetList(ptr, IntPtr.Zero, 0, out facetListPtr, out facetCentersPtr); + } + else + { + var idxArray = EnumerableEx.ToArray(idx); + NativeMethods.imgproc_Subdiv2D_getVoronoiFacetList(ptr, idxArray, idxArray.Length, out facetListPtr, out facetCentersPtr); + } + GC.KeepAlive(this); + + using (var facetListVec = new VectorOfVectorPoint2f(facetListPtr)) + { + facetList = facetListVec.ToArray(); + } + using (var facetCentersVec = new VectorOfPoint2f(facetCentersPtr)) + { + facetCenters = facetCentersVec.ToArray(); + } + } + #endregion + #region GetVertex + /// + /// + /// + /// + /// + public Point2f GetVertex(int vertex) + { + return GetVertex(vertex, out _); + } + /// + /// + /// + /// + /// + /// + public Point2f GetVertex(int vertex, out int firstEdge) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_getVertex(ptr, vertex, out firstEdge); + GC.KeepAlive(this); + return res; + } + #endregion + #region GetEdge + /// + /// + /// + /// + /// + /// + public int GetEdge(int edge, int nextEdgeType) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_getEdge(ptr, edge, nextEdgeType); + GC.KeepAlive(this); + return res; + } + #endregion + #region NextEdge + /// + /// + /// + /// + /// + public int NextEdge(int edge) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_nextEdge(ptr, edge); + GC.KeepAlive(this); + return res; + } + #endregion + #region RotateEdge + /// + /// + /// + /// + /// + /// + public int RotateEdge(int edge, int rotate) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_rotateEdge(ptr, edge, rotate); + GC.KeepAlive(this); + return res; + } + #endregion + #region SymEdge + /// + /// + /// + /// + /// + public int SymEdge(int edge) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_symEdge(ptr, edge); + GC.KeepAlive(this); + return res; + } + #endregion + #region EdgeOrg + /// + /// + /// + /// + /// + public int EdgeOrg(int edge) + { + return EdgeOrg(edge, out _); + } + /// + /// + /// + /// + /// + /// + public int EdgeOrg(int edge, out Point2f orgpt) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_edgeOrg(ptr, edge, out orgpt); + GC.KeepAlive(this); + return res; + } + #endregion + #region EdgeDst + /// + /// + /// + /// + /// + public int EdgeDst(int edge) + { + return EdgeDst(edge, out _); + } + /// + /// + /// + /// + /// + /// + public int EdgeDst(int edge, out Point2f dstpt) + { + ThrowIfDisposed(); + var res = NativeMethods.imgproc_Subdiv2D_edgeDst(ptr, edge, out dstpt); + GC.KeepAlive(this); + return res; + } + #endregion + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/ANN_MLP.cs b/OpenVinoOpenCvSharp/Modules/ml/ANN_MLP.cs new file mode 100644 index 0000000..d5be49e --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/ANN_MLP.cs @@ -0,0 +1,366 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// MLPモデルクラス + /// +#else + /// + /// Artificial Neural Networks - Multi-Layer Perceptrons. + /// +#endif + // ReSharper disable once InconsistentNaming + public class ANN_MLP : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + /// + /// Creates instance by raw pointer cv::ml::ANN_MLP* + /// + protected ANN_MLP(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model. + /// + /// + public static ANN_MLP Create() + { + var ptr = NativeMethods.ml_ANN_MLP_create(); + return new ANN_MLP(ptr); + } + + /// + /// Loads and creates a serialized ANN from a file. + /// Use ANN::save to serialize and store an ANN to disk. + /// Load the ANN from this file again, by calling this function with the path to the file. + /// + /// + /// + public static ANN_MLP Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_ANN_MLP_load(filePath); + return new ANN_MLP(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static ANN_MLP LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_ANN_MLP_loadFromString(strModel); + return new ANN_MLP(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Termination criteria of the training algorithm. + /// + public TermCriteria TermCriteria + { + get + { + var res = NativeMethods.ml_ANN_MLP_getTermCriteria(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setTermCriteria(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Strength of the weight gradient term. + /// The recommended value is about 0.1. Default value is 0.1. + /// + public double BackpropWeightScale + { + get + { + var res = NativeMethods.ml_ANN_MLP_getBackpropWeightScale(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setBackpropWeightScale(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Strength of the momentum term (the difference between weights on the 2 previous iterations). + /// This parameter provides some inertia to smooth the random fluctuations of the weights. + /// It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or + /// so is good enough. Default value is 0.1. + /// + public double BackpropMomentumScale + { + get + { + var res = NativeMethods.ml_ANN_MLP_getBackpropMomentumScale(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setBackpropMomentumScale(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Initial value Delta_0 of update-values Delta_{ij}. Default value is 0.1. + /// +// ReSharper disable once InconsistentNaming + public double RpropDW0 + { + get + { + var res = NativeMethods.ml_ANN_MLP_getRpropDW0(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setRpropDW0(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Increase factor eta^+. + /// It must be >1. Default value is 1.2. + /// +// ReSharper disable once InconsistentNaming + public double RpropDWPlus + { + get + { + var res = NativeMethods.ml_ANN_MLP_getRpropDWPlus(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setRpropDWPlus(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Decrease factor eta^-. + /// It must be \>1. Default value is 0.5. + /// +// ReSharper disable once InconsistentNaming + public double RpropDWMinus + { + get + { + var res = NativeMethods.ml_ANN_MLP_getRpropDWPlus(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setRpropDWPlus(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Update-values lower limit Delta_{min}. + /// It must be positive. Default value is FLT_EPSILON. + /// +// ReSharper disable once InconsistentNaming + public double RpropDWMin + { + get + { + var res = NativeMethods.ml_ANN_MLP_getRpropDWMin(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setRpropDWMin(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Update-values upper limit Delta_{max}. + /// It must be >1. Default value is 50. + /// +// ReSharper disable once InconsistentNaming + public double RpropDWMax + { + get + { + var res = NativeMethods.ml_ANN_MLP_getRpropDWMax(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_ANN_MLP_setRpropDWMax(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Integer vector specifying the number of neurons in each layer including the input and output layers. + /// The very first element specifies the number of elements in the input layer. + /// The last element - number of elements in the output layer.Default value is empty Mat. + /// + /// + public virtual void SetLayerSizes(InputArray layerSizes) + { + ThrowIfDisposed(); + if (layerSizes == null) + throw new ArgumentNullException(nameof(layerSizes)); + NativeMethods.ml_ANN_MLP_setLayerSizes(ptr, layerSizes.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(layerSizes); + } + + /// + /// Integer vector specifying the number of neurons in each layer including the input and output layers. + /// The very first element specifies the number of elements in the input layer. + /// The last element - number of elements in the output layer. + /// + /// + public virtual Mat GetLayerSizes() + { + ThrowIfDisposed(); + var p = NativeMethods.ml_ANN_MLP_getLayerSizes(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + #endregion + + #region Types + + /// + /// possible activation functions + /// + public enum ActivationFunctions + { + /// + /// Identity function: $f(x)=x + /// + Identity = 0, + + /// + /// Symmetrical sigmoid: f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x} + /// + SigmoidSym = 1, + + /// + /// Gaussian function: f(x)=\beta e^{-\alpha x*x} + /// + Gaussian = 2 + } + + /// + /// Train options + /// + [Flags] + public enum TrainFlags + { + /// + /// Update the network weights, rather than compute them from scratch. + /// In the latter case the weights are initialized using the Nguyen-Widrow algorithm. + /// + UpdateWeights = 1, + + /* */ + /// + /// Do not normalize the input vectors. + /// If this flag is not set, the training algorithm normalizes each input feature + /// independently, shifting its mean value to 0 and making the standard deviation + /// equal to 1. If the network is assumed to be updated frequently, the new + /// training data could be much different from original one. In this case, + /// you should take care of proper normalization. + /// + NoInputScale = 2, + + /// + /// Do not normalize the output vectors. If the flag is not set, + /// the training algorithm normalizes each output feature independently, + /// by transforming it to the certain range depending on the used activation function. + /// + NoOutputScale = 4 + } + + /// + /// Available training methods + /// + public enum TrainingMethods + { + /// + /// The back-propagation algorithm. + /// + BackProp = 0, + + /// + /// The RPROP algorithm. See @cite RPROP93 for details. + /// + RProp = 1 + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_ANN_MLP_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_ANN_MLP_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/ml/Boost.cs b/OpenVinoOpenCvSharp/Modules/ml/Boost.cs new file mode 100644 index 0000000..b067191 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/Boost.cs @@ -0,0 +1,193 @@ +using System; + +namespace OpenCvSharp.ML +{ + /// + /// Boosted tree classifier derived from DTrees + /// + public class Boost : DTrees + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::Boost* + /// + protected Boost(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model. + /// + /// + public new static Boost Create() + { + var ptr = NativeMethods.ml_Boost_create(); + return new Boost(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public new static Boost Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_Boost_load(filePath); + return new Boost(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public new static Boost LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_Boost_loadFromString(strModel); + return new Boost(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Type of the boosting algorithm. + /// See Boost::Types. Default value is Boost::REAL. + /// + public Types BoostType + { + get + { + ThrowIfDisposed(); + var res = (Types) NativeMethods.ml_Boost_getBoostType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_Boost_setBoostType(ptr, (int) value); + GC.KeepAlive(this); + } + } + + /// + /// The number of weak classifiers. + /// Default value is 100. + /// + public int WeakCount + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.ml_Boost_getWeakCount(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_Boost_setWeakCount(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// A threshold between 0 and 1 used to save computational time. + /// Samples with summary weight \f$\leq 1 - weight_trim_rate + /// do not participate in the *next* iteration of training. + /// Set this parameter to 0 to turn off this functionality. Default value is 0.95. + /// + public double WeightTrimRate + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.ml_Boost_getWeightTrimRate(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_Boost_setWeightTrimRate(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Types + + /// + /// Boosting type. + /// Gentle AdaBoost and Real AdaBoost are often the preferable choices. + /// + public enum Types + { + /// + /// Discrete AdaBoost. + /// + Discrete = 0, + + /// + /// Real AdaBoost. It is a technique that utilizes confidence-rated predictions + /// and works well with categorical data. + /// + Real = 1, + + /// + /// LogitBoost. It can produce good regression fits. + /// + Logit = 2, + + /// + /// Gentle AdaBoost. It puts less weight on outlier data points and for that + /// reason is often good with regression data. + /// + Gentle = 3 + }; + + #endregion + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_Boost_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_Boost_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/DTrees.cs b/OpenVinoOpenCvSharp/Modules/ml/DTrees.cs new file mode 100644 index 0000000..c881b33 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/DTrees.cs @@ -0,0 +1,444 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// 決定木クラス + /// +#else + /// + /// Decision tree + /// +#endif + public class DTrees : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// + /// + protected DTrees() + { + ptrObj = null; + } + + /// + /// Creates instance by raw pointer cv::ml::SVM* + /// + protected DTrees(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model. + /// + /// + public static DTrees Create() + { + var ptr = NativeMethods.ml_DTrees_create(); + return new DTrees(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public static DTrees Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_DTrees_load(filePath); + return new DTrees(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static DTrees LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_DTrees_loadFromString(strModel); + return new DTrees(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Cluster possible values of a categorical variable into + /// K < =maxCategories clusters to find a suboptimal split. + /// + public int MaxCategories + { + get + { + var res = NativeMethods.ml_DTrees_getMaxCategories(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setMaxCategories(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// The maximum possible depth of the tree. + /// + public int MaxDepth + { + get + { + var res = NativeMethods.ml_DTrees_getMaxDepth(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setMaxDepth(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// If the number of samples in a node is less than this parameter then the + /// node will not be split. Default value is 10. + /// + public int MinSampleCount + { + get + { + var res = NativeMethods.ml_DTrees_getMinSampleCount(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setMinSampleCount(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold + /// cross-validation procedure where K is equal to CVFolds. Default value is 10. + /// +// ReSharper disable once InconsistentNaming + public int CVFolds + { + get + { + var res = NativeMethods.ml_DTrees_getCVFolds(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setCVFolds(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// If true then surrogate splits will be built. + /// These splits allow to work with missing data and compute variable + /// importance correctly. Default value is false. + /// + public bool UseSurrogates + { + get + { + var res = NativeMethods.ml_DTrees_getUseSurrogates(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setUseSurrogates(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// If true then a pruning will be harsher. + /// This will make a tree more compact and more resistant to the training + /// data noise but a bit less accurate. Default value is true. + /// +// ReSharper disable once InconsistentNaming + public bool Use1SERule + { + get + { + var res = NativeMethods.ml_DTrees_getUse1SERule(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setUse1SERule(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// If true then pruned branches are physically removed from the tree. + /// Otherwise they are retained and it is possible to get results from the + /// original unpruned (or pruned less aggressively) tree. Default value is true. + /// + public bool TruncatePrunedTree + { + get + { + var res = NativeMethods.ml_DTrees_getTruncatePrunedTree(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setTruncatePrunedTree(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// Termination criteria for regression trees. + /// If all absolute differences between an estimated value in a node and + /// values of train samples in this node are less than this parameter + /// then the node will not be split further. Default value is 0.01f. + /// + public float RegressionAccuracy + { + get + { + var res = NativeMethods.ml_DTrees_getRegressionAccuracy(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_DTrees_setRegressionAccuracy(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// The array of a priori class probabilities, sorted by the class label value. + /// + public Mat Priors + { + get + { + var p = NativeMethods.ml_DTrees_getPriors(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + set + { + NativeMethods.ml_DTrees_setPriors(ptr, value.CvPtr); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Returns indices of root nodes + /// + /// + public int[] GetRoots() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + using (var vector = new VectorOfInt32()) + { + NativeMethods.ml_DTrees_getRoots(ptr, vector.CvPtr); + GC.KeepAlive(this); + return vector.ToArray(); + } + } + + /// + /// Returns all the nodes. + /// all the node indices are indices in the returned vector + /// + public Node[] GetNodes() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + using (var vector = new VectorOfDTreesNode()) + { + NativeMethods.ml_DTrees_getNodes(ptr, vector.CvPtr); + GC.KeepAlive(this); + return vector.ToArray(); + } + } + + /// + /// Returns all the splits. + /// all the split indices are indices in the returned vector + /// + /// + public Split[] GetSplits() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + using (var vector = new VectorOfDTreesSplit()) + { + NativeMethods.ml_DTrees_getSplits(ptr, vector.CvPtr); + GC.KeepAlive(this); + return vector.ToArray(); + } + } + + /// + /// Returns all the bitsets for categorical splits. + /// Split::subsetOfs is an offset in the returned vector + /// + /// + public int[] GetSubsets() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + + using (var vector = new VectorOfInt32()) + { + NativeMethods.ml_DTrees_getSubsets(ptr, vector.CvPtr); + GC.KeepAlive(this); + return vector.ToArray(); + } + } + + #endregion + + #region Types + + /// + /// The class represents a decision tree node. + /// + public struct Node + { + /// + /// Value at the node: a class label in case of classification or estimated + /// function value in case of regression. + /// + public double Value; + + /// + /// Class index normalized to 0..class_count-1 range and assigned to the + /// node. It is used internally in classification trees and tree ensembles. + /// + public int ClassIdx; + + /// + /// Index of the parent node + /// + public int Parent; + + /// + /// Index of the left child node + /// + public int Left; + + /// + /// Index of right child node + /// + public int Right; + + /// + /// Default direction where to go (-1: left or +1: right). It helps in the + /// case of missing values. + /// + public int DefaultDir; + + /// + /// Index of the first split + /// + public int Split; + } + + /// + /// The class represents split in a decision tree. + /// + public struct Split + { + /// + /// Index of variable on which the split is created. + /// + public int VarIdx; + + /// + /// If not 0, then the inverse split rule is used (i.e. left and right + /// branches are exchanged in the rule expressions below). + /// + public int Inversed; + + /// + /// The split quality, a positive number. It is used to choose the best split. + /// + public float Quality; + + /// + /// Index of the next split in the list of splits for the node + /// + public int Next; + + /// + /// The threshold value in case of split on an ordered variable. + /// + public float C; + + /// + /// Offset of the bitset used by the split on a categorical variable. + /// + public int SubsetOfs; + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_DTrees_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_DTrees_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/EM.cs b/OpenVinoOpenCvSharp/Modules/ml/EM.cs new file mode 100644 index 0000000..94296dc --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/EM.cs @@ -0,0 +1,516 @@ +using System; + +// ReSharper disable once InconsistentNaming + +namespace OpenCvSharp +{ +#if LANG_JP + /// + /// EMモデルクラス + /// +#else + /// + /// The class implements the Expectation Maximization algorithm. + /// +#endif + public class EM : Algorithm + { + private Ptr? ptrObj; + + #region Constants + +#pragma warning disable 1591 + // ReSharper disable InconsistentNaming + public const int DEFAULT_NCLUSTERS = 5; + public const int DEFAULT_MAX_ITERS = 100; + // ReSharper restore InconsistentNaming +#pragma warning restore 1591 + + #endregion + + #region Init and Disposal + + /// + /// Creates instance by pointer cv::Ptr<EM> + /// + protected EM(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates empty EM model. + /// + /// + public static EM Create() + { + var ptr = NativeMethods.ml_EM_create(); + return new EM(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public static EM Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_EM_load(filePath); + return new EM(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static EM LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_EM_loadFromString(strModel); + return new EM(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// The number of mixture components in the Gaussian mixture model. + /// Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. + /// Some of EM implementation could determine the optimal number of mixtures + /// within a specified value range, but that is not the case in ML yet. + /// + public int ClustersNumber + { + get + { + var res = NativeMethods.ml_EM_getClustersNumber(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_EM_setClustersNumber(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Constraint on covariance matrices which defines type of matrices. + /// + public int CovarianceMatrixType + { + get + { + var res = NativeMethods.ml_EM_getCovarianceMatrixType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_EM_setCovarianceMatrixType(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// The termination criteria of the %EM algorithm. + /// The EM algorithm can be terminated by the number of iterations + /// termCrit.maxCount (number of M-steps) or when relative change of likelihood + /// logarithm is less than termCrit.epsilon. + /// Default maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. + /// + public TermCriteria TermCriteria + { + get + { + var res = NativeMethods.ml_EM_getTermCriteria(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_EM_setTermCriteria(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Returns weights of the mixtures. + /// Returns vector with the number of elements equal to the number of mixtures. + /// + /// + public Mat GetWeights() + { + ThrowIfDisposed(); + var p = NativeMethods.ml_EM_getWeights(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + /// + /// Returns the cluster centers (means of the Gaussian mixture). + /// Returns matrix with the number of rows equal to the number of mixtures and + /// number of columns equal to the space dimensionality. + /// + /// + public Mat GetMeans() + { + ThrowIfDisposed(); + var p = NativeMethods.ml_EM_getMeans(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + /// + /// Returns covariation matrices. + /// Returns vector of covariation matrices. Number of matrices is the number of + /// gaussian mixtures, each matrix is a square floating-point matrix NxN, where N is the space dimensionality. + /// + public Mat[] GetCovs() + { + ThrowIfDisposed(); + + using (var vec = new VectorOfMat()) + { + NativeMethods.ml_EM_getCovs(ptr, vec.CvPtr); + GC.KeepAlive(this); + return vec.ToArray(); + } + } + + /// + /// Estimates Gaussian mixture parameters from the sample set + /// + /// + /// + /// + /// + /// + // ReSharper disable once InconsistentNaming + public virtual bool TrainEM( + InputArray samples, + OutputArray? logLikelihoods = null, + OutputArray? labels = null, + OutputArray? probs = null) + { + ThrowIfDisposed(); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + samples.ThrowIfDisposed(); + + logLikelihoods?.ThrowIfNotReady(); + labels?.ThrowIfNotReady(); + probs?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_EM_trainEM( + ptr, + samples.CvPtr, + Cv2.ToPtr(logLikelihoods), + Cv2.ToPtr(labels), + Cv2.ToPtr(probs)); + + logLikelihoods?.Fix(); + labels?.Fix(); + probs?.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(logLikelihoods); + GC.KeepAlive(labels); + GC.KeepAlive(probs); + return ret != 0; + } + +#if LANG_JP + /// + /// サンプル集合からガウス混合パラメータを推定する + /// + /// + /// + /// + /// + /// + /// + /// +#else + /// + /// Estimates Gaussian mixture parameters from the sample set + /// + /// + /// + /// + /// + /// + /// + /// +#endif + public virtual bool TrainE( + InputArray samples, + InputArray means0, + InputArray? covs0 = null, + InputArray? weights0 = null, + OutputArray? logLikelihoods = null, + OutputArray? labels = null, + OutputArray? probs = null) + { + ThrowIfDisposed(); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (means0 == null) + throw new ArgumentNullException(nameof(means0)); + samples.ThrowIfDisposed(); + means0.ThrowIfDisposed(); + + logLikelihoods?.ThrowIfNotReady(); + covs0?.ThrowIfDisposed(); + weights0?.ThrowIfDisposed(); + labels?.ThrowIfNotReady(); + probs?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_EM_trainE( + ptr, + samples.CvPtr, + means0.CvPtr, + Cv2.ToPtr(covs0), + Cv2.ToPtr(weights0), + Cv2.ToPtr(logLikelihoods), + Cv2.ToPtr(labels), + Cv2.ToPtr(probs)); + + logLikelihoods?.Fix(); + labels?.Fix(); + probs?.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(means0); + GC.KeepAlive(covs0); + GC.KeepAlive(weights0); + GC.KeepAlive(logLikelihoods); + GC.KeepAlive(labels); + GC.KeepAlive(probs); + return ret != 0; + } + +#if LANG_JP + /// + /// サンプル集合からガウス混合パラメータを推定する + /// + /// + /// + /// + /// + /// +#else + /// + /// Estimates Gaussian mixture parameters from the sample set + /// + /// + /// + /// + /// + /// +#endif + public virtual bool TrainM( + InputArray samples, + InputArray probs0, + OutputArray? logLikelihoods = null, + OutputArray? labels = null, + OutputArray? probs = null) + { + ThrowIfDisposed(); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (probs0 == null) + throw new ArgumentNullException(nameof(probs0)); + samples.ThrowIfDisposed(); + probs0.ThrowIfDisposed(); + + logLikelihoods?.ThrowIfNotReady(); + labels?.ThrowIfNotReady(); + probs?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_EM_trainM( + ptr, + samples.CvPtr, + probs0.CvPtr, + Cv2.ToPtr(logLikelihoods), + Cv2.ToPtr(labels), + Cv2.ToPtr(probs)); + + logLikelihoods?.Fix(); + labels?.Fix(); + probs?.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(probs0); + GC.KeepAlive(logLikelihoods); + GC.KeepAlive(labels); + GC.KeepAlive(probs); + + return ret != 0; + } + +#if LANG_JP + /// + /// サンプルに対する応答を予測する + /// + /// + /// +#else + /// + /// Predicts the response for sample + /// + /// + /// +#endif + public virtual Vec2d Predict2(InputArray sample, OutputArray? probs = null) + { + ThrowIfDisposed(); + if (sample == null) + throw new ArgumentNullException(nameof(sample)); + sample.ThrowIfDisposed(); + probs?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_EM_predict2(ptr, sample.CvPtr, Cv2.ToPtr(probs)); + probs?.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(sample); + GC.KeepAlive(probs); + return ret; + } + + #endregion + + #region Types + + /// + /// Type of covariation matrices + /// + public enum Types + { + /// + /// A scaled identity matrix \f$\mu_k * I\f$. + /// There is the only parameter \f$\mu_k\f$ to be estimated for each matrix. + /// The option may be used in special cases, when the constraint is relevant, + /// or as a first step in the optimization (for example in case when the data is + /// preprocessed with PCA). The results of such preliminary estimation may be + /// passed again to the optimization procedure, this time with covMatType=EM::COV_MAT_DIAGONAL. + /// + CovMatSpherical = 0, + + /// + /// A diagonal matrix with positive diagonal elements. + /// The number of free parameters is d for each matrix. + /// This is most commonly used option yielding good estimation results. + /// + CovMatDiagonal = 1, + + /// + /// A symmetric positively defined matrix. The number of free parameters in each + /// matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless + /// there is pretty accurate initial estimation of the parameters and/or a huge number + /// of training samples. + /// + CovMatGeneric = 2, + + /// + /// + /// + CovMatDefault = CovMatSpherical, + } + +#if LANG_JP + /// + /// アルゴリズムをスタートする最初のステップ + /// +#else + /// + /// The initial step the algorithm starts from + /// +#endif + public enum StartStep + { +#if LANG_JP + /// + /// アルゴリズムはE-stepでスタートする. 少なくとも平均ベクトルの初期値 CvEMParams.Means が渡されなければならない. + /// オプションとして,ユーザは重み(CvEMParams.Weights)と/または共変動行列(CvEMParams.Covs)を与えることもできる. + /// [CvEM::START_E_STEP] + /// +#else + /// + /// The algorithm starts with E-step. + /// At least, the initial values of mean vectors, CvEMParams.Means must be passed. + /// Optionally, the user may also provide initial values for weights (CvEMParams.Weights) + /// and/or covariation matrices (CvEMParams.Covs). + /// [CvEM::START_E_STEP] + /// +#endif + E = 1, +#if LANG_JP + /// + /// アルゴリズムはM-stepでスタートする.初期確率 p_i,k が与えられなければならない. + /// [CvEM::START_M_STEP] + /// +#else + /// + /// The algorithm starts with M-step. The initial probabilities p_i,k must be provided. + /// [CvEM::START_M_STEP] + /// +#endif + M = 2, +#if LANG_JP + /// + /// ユーザから必要な値が指定されない場合,k-meansアルゴリズムが混合分布パラメータの初期値推定に用いられる. + /// [CvEM::START_AUTO_STEP] + /// +#else + /// + /// No values are required from the user, k-means algorithm is used to estimate initial mixtures parameters. + /// [CvEM::START_AUTO_STEP] + /// +#endif + Auto = 0, + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_EM_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_EM_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/Enum/SampleTypes.cs b/OpenVinoOpenCvSharp/Modules/ml/Enum/SampleTypes.cs new file mode 100644 index 0000000..2cf94be --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/Enum/SampleTypes.cs @@ -0,0 +1,19 @@ + +namespace OpenCvSharp.ML +{ + /// + /// Sample types + /// + public enum SampleTypes + { + /// + /// each training sample is a row of samples + /// + RowSample = 0, + + /// + /// each training sample occupies a column of samples + /// + ColSample = 1, + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/KNearest.cs b/OpenVinoOpenCvSharp/Modules/ml/KNearest.cs new file mode 100644 index 0000000..11dd3fe --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/KNearest.cs @@ -0,0 +1,231 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// K近傍法モデルクラス + /// +#else + /// + /// K nearest neighbors classifier + /// +#endif + public class KNearest : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::KNearest* + /// + protected KNearest(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model + /// + /// + public static KNearest Create() + { + var ptr = NativeMethods.ml_KNearest_create(); + return new KNearest(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public static KNearest Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_KNearest_load(filePath); + return new KNearest(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static KNearest LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_KNearest_loadFromString(strModel); + return new KNearest(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Default number of neighbors to use in predict method. + /// + public int DefaultK + { + get + { + var res = NativeMethods.ml_KNearest_getDefaultK(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_KNearest_setDefaultK(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Whether classification or regression model should be trained. + /// + public new bool IsClassifier + { + get + { + var res = NativeMethods.ml_KNearest_getIsClassifier(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_KNearest_setIsClassifier(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// Parameter for KDTree implementation + /// + public int Emax + { + get + { + var res = NativeMethods.ml_KNearest_getEmax(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_KNearest_setEmax(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Algorithm type, one of KNearest::Types. + /// + public Types AlgorithmType + { + get + { + var res = (Types)NativeMethods.ml_KNearest_getAlgorithmType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_KNearest_setAlgorithmType(ptr, (int)value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Finds the neighbors and predicts responses for input vectors. + /// + /// Input samples stored by rows. + /// It is a single-precision floating-point matrix of `[number_of_samples] * k` size. + /// Number of used nearest neighbors. Should be greater than 1. + /// Vector with results of prediction (regression or classification) for each + /// input sample. It is a single-precision floating-point vector with `[number_of_samples]` elements. + /// neighborResponses Optional output values for corresponding neighbors. + /// It is a single-precision floating-point matrix of `[number_of_samples] * k` size. + /// 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) + { + ThrowIfDisposed(); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (results == null) + throw new ArgumentNullException(nameof(results)); + samples.ThrowIfDisposed(); + results.ThrowIfNotReady(); + + var ret = NativeMethods.ml_KNearest_findNearest( + ptr, + samples.CvPtr, k, results.CvPtr, + Cv2.ToPtr(neighborResponses), Cv2.ToPtr(dist)); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(results); + GC.KeepAlive(neighborResponses); + GC.KeepAlive(dist); + results.Fix(); + neighborResponses?.Fix(); + dist?.Fix(); + return ret; + } + + #endregion + + #region Types + + /// + /// Implementations of KNearest algorithm + /// + public enum Types + { +#pragma warning disable 1591 + BruteForce = 1, + KdTree = 2 +#pragma warning restore 1591 + }; + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_KNearest_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_KNearest_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/LogisticRegression.cs b/OpenVinoOpenCvSharp/Modules/ml/LogisticRegression.cs new file mode 100644 index 0000000..15fb41d --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/LogisticRegression.cs @@ -0,0 +1,291 @@ +using System; + +namespace OpenCvSharp.ML +{ + /// + /// Implements Logistic Regression classifier. + /// + public class LogisticRegression : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::LogisticRegression* + /// + protected LogisticRegression(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model. + /// + /// + public static LogisticRegression Create() + { + var ptr = NativeMethods.ml_LogisticRegression_create(); + return new LogisticRegression(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public static LogisticRegression Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_LogisticRegression_load(filePath); + return new LogisticRegression(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static LogisticRegression LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_LogisticRegression_loadFromString(strModel); + return new LogisticRegression(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Learning rate + /// + public double LearningRate + { + get + { + var res = NativeMethods.ml_LogisticRegression_getLearningRate(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setLearningRate(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Number of iterations. + /// + public int Iterations + { + get + { + var res = NativeMethods.ml_LogisticRegression_getIterations(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setIterations(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Kind of regularization to be applied. See LogisticRegression::RegKinds. + /// + public RegKinds Regularization + { + get + { + var res = (RegKinds)NativeMethods.ml_LogisticRegression_getRegularization(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setRegularization(ptr, (int)value); + GC.KeepAlive(this); + } + } + + /// + /// Kind of training method used. See LogisticRegression::Methods. + /// + public Methods TrainMethod + { + get + { + var res = (Methods)NativeMethods.ml_LogisticRegression_getTrainMethod(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setTrainMethod(ptr, (int)value); + GC.KeepAlive(this); + } + } + + /// + /// Specifies the number of training samples taken in each step of Mini-Batch Gradient. + /// Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. + /// It has to take values less than the total number of training samples. + /// + public int MiniBatchSize + { + get + { + var res = NativeMethods.ml_LogisticRegression_getMiniBatchSize(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setMiniBatchSize(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Termination criteria of the training algorithm. + /// + public TermCriteria TermCriteria + { + get + { + var res = NativeMethods.ml_LogisticRegression_getTermCriteria(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_LogisticRegression_setTermCriteria(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Predicts responses for input samples and returns a float type. + /// + /// The input data for the prediction algorithm. Matrix [m x n], + /// where each row contains variables (features) of one object being classified. + /// Should have data type CV_32F. + /// Predicted labels as a column matrix of type CV_32S. + /// Not used. + /// + public float Predict(InputArray samples, OutputArray? results = null, int flags = 0) + { + ThrowIfDisposed(); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + samples.ThrowIfDisposed(); + results?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_LogisticRegression_predict(ptr, samples.CvPtr, Cv2.ToPtr(results), flags); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(results); + results?.Fix(); + + return ret; + } + + /// + /// This function returns the trained paramters arranged across rows. + /// For a two class classifcation problem, it returns a row matrix. + /// It returns learnt paramters of the Logistic Regression as a matrix of type CV_32F. + /// + /// + public Mat GetLearntThetas() + { + ThrowIfDisposed(); + + var p = NativeMethods.ml_LogisticRegression_get_learnt_thetas(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + #endregion + + #region Types + + /// + /// Regularization kinds + /// + public enum RegKinds + { + /// + /// Regularization disabled + /// + RegDisable = -1, + + /// + /// L1 norm + /// + RegL1 = 0, + + /// + /// L2 norm + /// + RegL2 = 1 + } + + /// + /// Training methods + /// + public enum Methods + { + /// + /// + /// + Batch = 0, + + /// + /// Set MiniBatchSize to a positive integer when using this method. + /// + MiniBatch = 1 + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_LogisticRegression_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_LogisticRegression_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Modules/ml/NormalBayesClassifier.cs b/OpenVinoOpenCvSharp/Modules/ml/NormalBayesClassifier.cs new file mode 100644 index 0000000..a908982 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/NormalBayesClassifier.cs @@ -0,0 +1,145 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// 正規分布データに対するベイズ分類器クラス + /// +#else + /// + /// Bayes classifier for normally distributed data + /// +#endif + public class NormalBayesClassifier : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::NormalBayesClassifier* + /// + protected NormalBayesClassifier(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates empty model. + /// Use StatModel::train to train the model after creation. + /// + /// + public static NormalBayesClassifier Create() + { + var ptr = NativeMethods.ml_NormalBayesClassifier_create(); + return new NormalBayesClassifier(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public static NormalBayesClassifier Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_NormalBayesClassifier_load(filePath); + return new NormalBayesClassifier(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public static NormalBayesClassifier LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_NormalBayesClassifier_loadFromString(strModel); + return new NormalBayesClassifier(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + #endregion + + #region Methods + + /// + /// Predicts the response for sample(s). + /// + /// + /// + /// + /// + /// + /// + /// The method estimates the most probable classes for input vectors. Input vectors (one or more) + /// are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one + /// 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) + { + ThrowIfDisposed(); + if (inputs == null) + throw new ArgumentNullException(nameof(inputs)); + if (outputs == null) + throw new ArgumentNullException(nameof(outputs)); + if (outputProbs == null) + throw new ArgumentNullException(nameof(outputProbs)); + + inputs.ThrowIfDisposed(); + outputs.ThrowIfNotReady(); + outputProbs.ThrowIfNotReady(); + + var result = NativeMethods.ml_NormalBayesClassifier_predictProb( + ptr, inputs.CvPtr, outputs.CvPtr, outputProbs.CvPtr, flags); + outputs.Fix(); + outputProbs.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(inputs); + GC.KeepAlive(outputs); + GC.KeepAlive(outputProbs); + return result; + } + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_NormalBayesClassifier_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_NormalBayesClassifier_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/ParamGrid.cs b/OpenVinoOpenCvSharp/Modules/ml/ParamGrid.cs new file mode 100644 index 0000000..399de87 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/ParamGrid.cs @@ -0,0 +1,43 @@ +namespace OpenCvSharp.ML +{ + /// + /// The structure represents the logarithmic grid range of statmodel parameters. + /// + public struct ParamGrid + { + /// + /// Minimum value of the statmodel parameter. Default value is 0. + /// + public double MinVal; + + /// + /// Maximum value of the statmodel parameter. Default value is 0. + /// + public double MaxVal; + + /// + /// Logarithmic step for iterating the statmodel parameter. + /// + /// + /// The grid determines the following iteration sequence of the statmodel parameter values: + /// \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] + /// where \f$n\f$ is the maximal index satisfying + /// \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] + /// The grid is logarithmic, so logStep must always be greater then 1. Default value is 1. + /// + public double LogStep; + + /// + /// Constructor with parameters + /// + /// + /// + /// + public ParamGrid(double minVal, double maxVal, double logStep) + { + MinVal = minVal; + MaxVal = maxVal; + LogStep = logStep; + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/RTrees.cs b/OpenVinoOpenCvSharp/Modules/ml/RTrees.cs new file mode 100644 index 0000000..29438bd --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/RTrees.cs @@ -0,0 +1,182 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// ランダムツリークラス + /// +#else + /// + /// The class implements the random forest predictor. + /// +#endif + public class RTrees : DTrees + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::RTrees* + /// + protected RTrees(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates the empty model. + /// + /// + public new static RTrees Create() + { + var ptr = NativeMethods.ml_RTrees_create(); + return new RTrees(ptr); + } + + /// + /// Loads and creates a serialized model from a file. + /// + /// + /// + public new static RTrees Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_RTrees_load(filePath); + return new RTrees(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// he string variable containing the model you want to load. + /// + public new static RTrees LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_RTrees_loadFromString(strModel); + return new RTrees(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// If true then variable importance will be calculated and then + /// it can be retrieved by RTrees::getVarImportance. Default value is false. + /// + public bool CalculateVarImportance + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.ml_RTrees_getCalculateVarImportance(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_RTrees_setCalculateVarImportance(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// The size of the randomly selected subset of features at each tree node + /// and that are used to find the best split(s). + /// + public bool ActiveVarCount + { + get + { + ThrowIfDisposed(); + var res =NativeMethods.ml_RTrees_getActiveVarCount(ptr) != 0; + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_RTrees_setActiveVarCount(ptr, value ? 1 : 0); + GC.KeepAlive(this); + } + } + + /// + /// The termination criteria that specifies when the training algorithm stops. + /// + public TermCriteria TermCriteria + { + get + { + ThrowIfDisposed(); + var res = NativeMethods.ml_RTrees_getTermCriteria(ptr); + GC.KeepAlive(this); + return res; + } + set + { + ThrowIfDisposed(); + NativeMethods.ml_RTrees_setTermCriteria(ptr, value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Returns the variable importance array. + /// The method returns the variable importance vector, computed at the training + /// stage when CalculateVarImportance is set to true. If this flag was set to false, + /// the empty matrix is returned. + /// + /// + public Mat GetVarImportance() + { + ThrowIfDisposed(); + var p = NativeMethods.ml_RTrees_getVarImportance(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + #endregion + + internal new class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_RTrees_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_RTrees_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/SVM.cs b/OpenVinoOpenCvSharp/Modules/ml/SVM.cs new file mode 100644 index 0000000..9ab5b98 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/SVM.cs @@ -0,0 +1,532 @@ +using System; + +namespace OpenCvSharp.ML +{ + // ReSharper disable InconsistentNaming + +#if LANG_JP + /// + /// SVM model classifier + /// +#else + /// + /// Support Vector Machines + /// +#endif + + public class SVM : StatModel + { + private Ptr? ptrObj; + + #region Init and Disposal + + /// + /// Creates instance by raw pointer cv::ml::SVM* + /// + protected SVM(IntPtr p) + { + ptrObj = new Ptr(p); + ptr = ptrObj.Get(); + } + + /// + /// Creates empty model. + /// Use StatModel::Train to train the model. + /// Since %SVM has several parameters, you may want to find the best + /// parameters for your problem, it can be done with SVM::TrainAuto. + /// + /// + public static SVM Create() + { + var ptr = NativeMethods.ml_SVM_create(); + return new SVM(ptr); + } + + /// + /// Loads and creates a serialized svm from a file. + /// Use SVM::save to serialize and store an SVM to disk. + /// Load the SVM from this file again, by calling this function with the path to the file. + /// + /// + /// + public static SVM Load(string filePath) + { + if (filePath == null) + throw new ArgumentNullException(nameof(filePath)); + var ptr = NativeMethods.ml_SVM_load(filePath); + return new SVM(ptr); + } + + /// + /// Loads algorithm from a String. + /// + /// The string variable containing the model you want to load. + /// + public static SVM LoadFromString(string strModel) + { + if (strModel == null) + throw new ArgumentNullException(nameof(strModel)); + var ptr = NativeMethods.ml_SVM_loadFromString(strModel); + return new SVM(ptr); + } + + /// + /// Releases managed resources + /// + protected override void DisposeManaged() + { + ptrObj?.Dispose(); + ptrObj = null; + base.DisposeManaged(); + } + + #endregion + + #region Properties + + /// + /// Type of a %SVM formulation. + /// Default value is SVM::C_SVC. + /// + public Types Type + { + get + { + var res = (Types)NativeMethods.ml_SVM_getType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setType(ptr, (int)value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter gamma of a kernel function. + /// For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. + /// + public double Gamma + { + get + { + var res = NativeMethods.ml_SVM_getGamma(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setGamma(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter coef0 of a kernel function. + /// For SVM::POLY or SVM::SIGMOID. Default value is 0. + /// + public double Coef0 + { + get + { + var res = NativeMethods.ml_SVM_getCoef0(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setCoef0(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter degree of a kernel function. + /// For SVM::POLY. Default value is 0. + /// + public double Degree + { + get + { + var res = NativeMethods.ml_SVM_getDegree(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setDegree(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter C of a %SVM optimization problem. + /// For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. + /// + public double C + { + get + { + var res = NativeMethods.ml_SVM_getC(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setC(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter nu of a %SVM optimization problem. + /// For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. + /// + public double Nu + { + get + { + var res = NativeMethods.ml_SVM_getNu(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setNu(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Parameter epsilon of a %SVM optimization problem. + /// For SVM::EPS_SVR. Default value is 0. + /// + public double P + { + get + { + var res = NativeMethods.ml_SVM_getP(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setP(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Optional weights in the SVM::C_SVC problem, assigned to particular classes. + /// + /// + /// They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. + /// Thus these weights affect the misclassification penalty for different classes. + /// The larger weight, the larger penalty on misclassification of data from the + /// corresponding class. Default value is empty Mat. + /// + public Mat ClassWeights + { + get + { + var p = NativeMethods.ml_SVM_getClassWeights(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + set + { + NativeMethods.ml_SVM_setClassWeights(ptr, value.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(value); + } + } + + /// + /// Termination criteria of the iterative SVM training procedure + /// which solves a partial case of constrained quadratic optimization problem. + /// + /// + /// You can specify tolerance and/or the maximum number of iterations. + /// Default value is `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; + /// + public TermCriteria TermCriteria + { + get + { + var res = NativeMethods.ml_SVM_getTermCriteria(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setTermCriteria(ptr, value); + GC.KeepAlive(this); + } + } + + /// + /// Type of a %SVM kernel. See SVM::KernelTypes. Default value is SVM::RBF. + /// + public KernelTypes KernelType + { + get + { + var res = (KernelTypes)NativeMethods.ml_SVM_getKernelType(ptr); + GC.KeepAlive(this); + return res; + } + set + { + NativeMethods.ml_SVM_setKernel(ptr, (int)value); + GC.KeepAlive(this); + } + } + + #endregion + + #region Methods + + /// + /// Initialize with custom kernel. + /// + /// + public void SetCustomKernel(Kernel kernel) + { + throw new NotImplementedException(); + } + + /// + /// Trains an %SVM with optimal parameters. + /// + /// the training data that can be constructed using + /// TrainData::create or TrainData::loadFromCSV. + /// Cross-validation parameter. The training set is divided into kFold subsets. + /// One subset is used to test the model, the others form the train set. So, the %SVM algorithm is + /// executed kFold times. + /// grid for C + /// grid for gamma + /// grid for p + /// grid for nu + /// grid for coeff + /// grid for degree + /// If true and the problem is 2-class classification then the method creates + /// more balanced cross-validation subsets that is proportions between classes in subsets are close + /// to such proportion in the whole train dataset. + /// + public bool TrainAuto(TrainData data, int kFold = 10, + ParamGrid? cGrid = null, + ParamGrid? gammaGrid = null, + ParamGrid? pGrid = null, + ParamGrid? nuGrid = null, + ParamGrid? coeffGrid = null, + ParamGrid? degreeGrid = null, + bool balanced = false) + { + throw new NotImplementedException(); + /* + var cGridValue = cGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.C)); + var gammaGridValue = gammaGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.Gamma)); + var pGridValue = pGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.P)); + var nuGridValue = nuGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.Nu)); + var coeffGridValue = coeffGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.Coef)); + var degreeGridValue = degreeGrid.GetValueOrDefault(GetDefaultGrid(ParamTypes.Degree));*/ + } + + /// + /// Retrieves all the support vectors + /// + /// + public Mat GetSupportVectors() + { + ThrowIfDisposed(); + var p = NativeMethods.ml_SVM_getSupportVectors(ptr); + GC.KeepAlive(this); + return new Mat(p); + } + + /// + /// Retrieves the decision function + /// + /// i the index of the decision function. + /// If the problem solved is regression, 1-class or 2-class classification, then + /// there will be just one decision function and the index should always be 0. + /// Otherwise, in the case of N-class classification, there will be N(N-1)/2 decision functions. + /// alpha the optional output vector for weights, corresponding to + /// different support vectors. In the case of linear %SVM all the alpha's will be 1's. + /// the optional output vector of indices of support vectors + /// 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) + { + ThrowIfDisposed(); + if (alpha == null) + throw new ArgumentNullException(nameof(alpha)); + if (svidx == null) + throw new ArgumentNullException(nameof(svidx)); + + alpha.ThrowIfNotReady(); + svidx.ThrowIfNotReady(); + var ret = NativeMethods.ml_SVM_getDecisionFunction(ptr, i, alpha.CvPtr, svidx.CvPtr); + alpha.Fix(); + svidx.Fix(); + GC.KeepAlive(this); + GC.KeepAlive(alpha); + GC.KeepAlive(svidx); + return ret; + } + + /// + /// Generates a grid for SVM parameters. + /// + /// SVM parameters IDs that must be one of the SVM::ParamTypes. + /// The grid is generated for the parameter with this ID. + /// + public static ParamGrid GetDefaultGrid(ParamTypes paramId) + { + return NativeMethods.ml_SVM_getDefaultGrid((int)paramId); + } + + #endregion + + #region Types + + /// + /// + /// + public class Kernel + { + /// + /// + /// + public Kernel() + { + throw new NotImplementedException(); + } + } + + /// + /// SVM type + /// + public enum Types + { + /// + /// C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), + /// allows imperfect separation of classes with penalty multiplier C for outliers. + /// + CSvc = 100, + + /// + /// nu-Support Vector Classification. n-class classification with possible + /// imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger + /// the value, the smoother the decision boundary) is used instead of C. + /// + NuSvc = 101, + + /// + /// Distribution Estimation (One-class %SVM). All the training data are from + /// the same class, %SVM builds a boundary that separates the class from the + /// rest of the feature space. + /// + OneClass = 102, + + /// + /// epsilon-Support Vector Regression. + /// The distance between feature vectors from the training set and the fitting + /// hyper-plane must be less than p. For outliers the penalty multiplier C is used. + /// + EpsSvr = 103, + + /// + /// nu-Support Vector Regression. \f$\nu\f$ is used instead of p. + /// See @cite LibSVM for details. + /// + NuSvr = 104 + } + + /// + /// SVM kernel type + /// + public enum KernelTypes + { + /// + /// Returned by SVM::getKernelType in case when custom kernel has been set + /// + Custom = -1, + + /// + /// Linear kernel. No mapping is done, linear discrimination (or regression) is + /// done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. + /// + Linear = 0, + + /// + /// Polynomial kernel: + /// \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. + /// + Poly = 1, + + /// + /// Radial basis function (RBF), a good choice in most cases. + /// \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. + /// + Rbf = 2, + + /// + /// Sigmoid kernel: + /// \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. + /// + Sigmoid = 3, + + /// + /// Exponential Chi2 kernel, similar to the RBF kernel: + /// \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. + /// + Chi2 = 4, + + /// + /// Histogram intersection kernel. + /// A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. + /// + Inter = 5 + } + + /// + /// SVM params type + /// + public enum ParamTypes + { +#pragma warning disable 1591 + C = 0, + Gamma = 1, + P = 2, + Nu = 3, + Coef = 4, + Degree = 5 +#pragma warning restore 1591 + }; + + #endregion + + internal class Ptr : OpenCvSharp.Ptr + { + public Ptr(IntPtr ptr) : base(ptr) + { + } + + public override IntPtr Get() + { + var res = NativeMethods.ml_Ptr_SVM_get(ptr); + GC.KeepAlive(this); + return res; + } + + protected override void DisposeUnmanaged() + { + NativeMethods.ml_Ptr_SVM_delete(ptr); + base.DisposeUnmanaged(); + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/StatModel.cs b/OpenVinoOpenCvSharp/Modules/ml/StatModel.cs new file mode 100644 index 0000000..3159f21 --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/StatModel.cs @@ -0,0 +1,190 @@ +using System; + +namespace OpenCvSharp.ML +{ +#if LANG_JP + /// + /// ML 統計モデルのための基本クラス + /// +#else + /// + /// Base class for statistical models in ML + /// +#endif + public abstract class StatModel : Algorithm + { + #region Init and Disposal + +#if LANG_JP + /// + /// 初期化 + /// +#else + /// + /// Default constructor + /// +#endif + protected StatModel() + { + } + + #endregion + + #region Methods + + /// + /// Returns the number of variables in training samples + /// + /// + public virtual int GetVarCount() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.ml_StatModel_getVarCount(ptr); + GC.KeepAlive(this); + return res; + } + + /// + /// + /// + /// + public new virtual bool Empty() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.ml_StatModel_empty(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Returns true if the model is trained + /// + /// + public virtual bool IsTrained() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.ml_StatModel_isTrained(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Returns true if the model is classifier + /// + /// + public virtual bool IsClassifier() + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + var res = NativeMethods.ml_StatModel_isClassifier(ptr) != 0; + GC.KeepAlive(this); + return res; + } + + /// + /// Trains the statistical model + /// + /// training data that can be loaded from file using TrainData::loadFromCSV + /// or created with TrainData::create. + /// optional flags, depending on the model. Some of the models can be updated with the + /// new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). + /// + public virtual bool Train(TrainData trainData, int flags = 0) + { + throw new NotImplementedException(); + } + + /// + /// Trains the statistical model + /// + /// training samples + /// SampleTypes value + /// vector of responses associated with the training samples. + /// + public virtual bool Train(InputArray samples, SampleTypes layout, InputArray responses) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + if (responses == null) + throw new ArgumentNullException(nameof(responses)); + samples.ThrowIfDisposed(); + responses.ThrowIfDisposed(); + + var ret = NativeMethods.ml_StatModel_train2(ptr, samples.CvPtr, (int)layout, responses.CvPtr); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(responses); + return ret != 0; + } + + /// + /// Computes error on the training or test dataset + /// + /// the training data + /// if true, the error is computed over the test subset of the data, + /// otherwise it's computed over the training subset of the data. Please note that if you + /// loaded a completely different dataset to evaluate already trained classifier, you will + /// probably want not to set the test subset at all with TrainData::setTrainTestSplitRatio + /// and specify test=false, so that the error is computed for the whole new set. Yes, this + /// sounds a bit confusing. + /// the optional output responses. + /// + public virtual float CalcError(TrainData data, bool test, OutputArray resp) + { + throw new NotImplementedException(); + } + + /// + /// Predicts response(s) for the provided sample(s) + /// + /// The input samples, floating-point matrix + /// The optional output matrix of results. + /// The optional flags, model-dependent. + /// + public virtual float Predict(InputArray samples, OutputArray? results = null, Flags flags = 0) + { + if (ptr == IntPtr.Zero) + throw new ObjectDisposedException(GetType().Name); + if (samples == null) + throw new ArgumentNullException(nameof(samples)); + samples.ThrowIfDisposed(); + results?.ThrowIfNotReady(); + + var ret = NativeMethods.ml_StatModel_predict( + ptr, samples.CvPtr, Cv2.ToPtr(results), (int)flags); + GC.KeepAlive(this); + GC.KeepAlive(samples); + GC.KeepAlive(results); + results?.Fix(); + return ret; + } + + #endregion + + #region Types + + /// + /// Predict options + /// + [FlagsAttribute] + public enum Flags + { +#pragma warning disable 1591 + UpdateModel = 1, + /// + /// makes the method return the raw results (the sum), not the class label + /// + RawOutput = 1, + CompressedInput = 2, + PreprocessedInput = 4 +#pragma warning restore 1591 + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Modules/ml/TrainData.cs b/OpenVinoOpenCvSharp/Modules/ml/TrainData.cs new file mode 100644 index 0000000..a2ef5ae --- /dev/null +++ b/OpenVinoOpenCvSharp/Modules/ml/TrainData.cs @@ -0,0 +1,18 @@ +using System; + +namespace OpenCvSharp.ML +{ + /// + /// + /// + public class TrainData + { + /// + /// + /// + public TrainData() + { + throw new NotImplementedException(); + } + } +} diff --git a/OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj b/OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj new file mode 100644 index 0000000..2cad91b --- /dev/null +++ b/OpenVinoOpenCvSharp/OpenVinoOpenCvSharp.csproj @@ -0,0 +1,21 @@ + + + + netstandard2.1 + true + true + OpenCvSharp + OpenVinoOpenCvSharp + false + false + false + Debug;Release + 8 + enable + + + + TRACE;DOTNETCORE;WINRT + + + diff --git a/OpenVinoOpenCvSharp/PInvoke/NativeMethods.cs b/OpenVinoOpenCvSharp/PInvoke/NativeMethods.cs new file mode 100644 index 0000000..cd63db6 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/NativeMethods.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +#if DOTNET_FRAMEWORK +using System.Security; +using System.Security.Permissions; +#endif +using OpenCvSharp.Util; + +// ReSharper disable InconsistentNaming +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + /// + /// P/Invoke methods of OpenCV 2.x C++ interface + /// +#if DOTNET_FRAMEWORK && !net20 + [SuppressUnmanagedCodeSecurity] +#endif + public static partial class NativeMethods + { + public const string DllExtern = "OpenVinoOpenCvSharpExtern"; + + /// + /// Is tried P/Invoke once + /// + private static bool tried; + + /// + /// Static constructor + /// +#if DOTNET_FRAMEWORK + [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] +#endif + static NativeMethods() + { + LoadLibraries(WindowsLibraryLoader.Instance.AdditionalPaths); + + // call cv to enable redirecting + TryPInvoke(); + } + + /// + /// Load DLL files dynamically using Win32 LoadLibrary + /// + /// + public static void LoadLibraries(IEnumerable? additionalPaths = null) + { + if (IsUnix()) + return; + + var ap = (additionalPaths == null) ? new string[0] : EnumerableEx.ToArray(additionalPaths); + + WindowsLibraryLoader.Instance.LoadLibrary(DllExtern, ap); + + // Redirection of error occurred in native library + var zero = IntPtr.Zero; + var current = redirectError(ErrorHandlerThrowException, zero, ref zero); + GC.KeepAlive(current); + } + + /// + /// Checks whether PInvoke functions can be called + /// + public static void TryPInvoke() + { + if (tried) + return; + tried = true; + + try + { + core_Mat_sizeof(); + } + catch (DllNotFoundException e) + { + var exception = PInvokeHelper.CreateException(e); + try { Console.WriteLine(exception.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + try { Debug.WriteLine(exception.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + throw exception; + } + catch (BadImageFormatException e) + { + var exception = PInvokeHelper.CreateException(e); + try { Console.WriteLine(exception.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + try { Debug.WriteLine(exception.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + throw exception; + } + catch (Exception e) + { + var ex = e.InnerException ?? e; + try { Console.WriteLine(ex.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + try { Debug.WriteLine(ex.Message); } + // ReSharper disable once EmptyGeneralCatchClause + catch { } + throw; + } + } + + /// + /// Returns whether the OS is Windows or not + /// + /// + public static bool IsWindows() + { + return !IsUnix(); + } + + /// + /// Returns whether the OS is *nix or not + /// + /// + public static bool IsUnix() + { +#if DOTNET_FRAMEWORK + var p = Environment.OSVersion.Platform; + return (p == PlatformID.Unix || + p == PlatformID.MacOSX || + (int)p == 128); +#elif uap10 + return false; +#else + return RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || + RuntimeInformation.IsOSPlatform(OSPlatform.OSX); +#endif + } + + /// + /// Returns whether the runtime is Mono or not + /// + /// + public static bool IsMono() + { + return (Type.GetType("Mono.Runtime") != null); + } + + #region Error redirection + + /// + /// Custom error handler to be thrown by OpenCV + /// + public static readonly CvErrorCallback ErrorHandlerThrowException = + (status, funcName, errMsg, fileName, line, userdata) => + { + try + { + //cvSetErrStatus(CvStatus.StsOk); + return 0; + } + finally + { + throw new OpenCVException(status, funcName, errMsg, fileName, line); + } + }; + + /// + /// Custom error handler to ignore all OpenCV errors + /// + public static readonly CvErrorCallback ErrorHandlerIgnorance = + (status, funcName, errMsg, fileName, line, userdata) => 0; + + /// + /// Default error handler + /// + public static CvErrorCallback? ErrorHandlerDefault; + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/NativeMethods_flann.cs b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_flann.cs new file mode 100644 index 0000000..69a507d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_flann.cs @@ -0,0 +1,200 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; +using OpenCvSharp.Flann; + +#pragma warning disable 1591 +#pragma warning disable CA1401 // P/Invokes should not be visible + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + #region Index + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Index_new(IntPtr features, IntPtr @params, int distType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_knnSearch1(IntPtr obj, [In] float[] queries, int queriesLength, [Out] int[] indices, [Out] float[] dists, int knn, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_knnSearch2(IntPtr obj, IntPtr queries, IntPtr indices, IntPtr dists, int knn, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_knnSearch3(IntPtr obj, IntPtr queries, [Out] int[] indices, [Out] float[] dists, int knn, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_radiusSearch1(IntPtr obj, [In] float[] queries, int queriesLength, [Out] int[] indices, int indicesLength, [Out] float[] dists, int distsLength, float radius, int maxResults, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_radiusSearch2(IntPtr obj, IntPtr queries, IntPtr indices, IntPtr dists, float radius, int maxResults, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Index_radiusSearch3(IntPtr obj, IntPtr queries, [Out] int[] indices, int indicesLength, [Out] float[] dists, int distsLength, float radius, int maxResults, IntPtr @params); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_Index_save(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string filename); + //[DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + //public static extern int flann_Index_veclen(IntPtr obj); + //[DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + //public static extern int flann_Index_size(IntPtr obj); + #endregion + #region IndexParams + #region IndexParams + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_IndexParams_new(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_IndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_IndexParams_new(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_IndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_IndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_getString(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string? defaultVal, [MarshalAs(UnmanagedType.LPStr)] StringBuilder result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int flann_IndexParams_getInt(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, int defaultVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern double flann_IndexParams_getDouble(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, double defaultVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_setString(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_setInt(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, int value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_setDouble(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, double value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_setFloat(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, float value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void flann_IndexParams_setBool(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string key, int value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_IndexParams_setAlgorithm(IntPtr obj, int value); + #endregion + #region LinearIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_LinearIndexParams_new(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_LinearIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_LinearIndexParams_new(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_LinearIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_LinearIndexParams_delete(IntPtr obj); + + #endregion + #region KDTreeIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_KDTreeIndexParams_new(int trees); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_KDTreeIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_KDTreeIndexParams_new(int trees); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_KDTreeIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_KDTreeIndexParams_delete(IntPtr obj); + + #endregion + #region KMeansIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_KMeansIndexParams_new( + int branching, int iterations, [MarshalAs(UnmanagedType.I4)] FlannCentersInit centersInit, float cbIndex); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_KMeansIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_KMeansIndexParams_new( + int branching, int iterations, [MarshalAs(UnmanagedType.I4)] FlannCentersInit centersInit, float cbIndex); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_KMeansIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_KMeansIndexParams_delete(IntPtr obj); + + #endregion + #region LshIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_LshIndexParams_new( + int tableNumber, int keySize, int multiProbeLevel); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_LshIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_LshIndexParams_new( + int tableNumber, int keySize, int multiProbeLevel); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_LshIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_LshIndexParams_delete(IntPtr obj); + + #endregion + #region CompositeIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_CompositeIndexParams_new(int trees, int branching, int iterations, FlannCentersInit centersInit, float cbIndex); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_CompositeIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_CompositeIndexParams_new(int trees, int branching, int iterations, FlannCentersInit centersInit, float cbIndex); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_CompositeIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_CompositeIndexParams_delete(IntPtr obj); + + #endregion + #region AutotunedIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_AutotunedIndexParams_new(float targetPrecision, float buildWeight, float memoryWeight, float sampleFraction); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_AutotunedIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_AutotunedIndexParams_new(float targetPrecision, float buildWeight, float memoryWeight, float sampleFraction); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_AutotunedIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_AutotunedIndexParams_delete(IntPtr obj); + + #endregion + #region SavedIndexParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern IntPtr flann_SavedIndexParams_new([MarshalAs(UnmanagedType.LPStr)] string filename); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_SavedIndexParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_SavedIndexParams_new([MarshalAs(UnmanagedType.LPStr)] string filename); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_SavedIndexParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_SavedIndexParams_delete(IntPtr obj); + + #endregion + #region SearchParams + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_SearchParams_new(int checks, float eps, int sorted); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_SearchParams_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_SearchParams_new(int checks, float eps, int sorted); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr flann_Ptr_SearchParams_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void flann_Ptr_SearchParams_delete(IntPtr obj); + + #endregion + + #endregion + + //[DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + //public static extern int flann_hierarchicalClustering(IntPtr features, IntPtr centers, IntPtr @params); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/NativeMethods_imgcodecs.cs b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_imgcodecs.cs new file mode 100644 index 0000000..d535d61 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_imgcodecs.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern IntPtr imgcodecs_imread(string filename, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_imreadmulti([MarshalAs(UnmanagedType.LPStr)] string filename, IntPtr mats, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_imwrite([MarshalAs(UnmanagedType.LPStr)] string filename, IntPtr img, [In] int[] @params, int paramsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_imwrite_multi([MarshalAs(UnmanagedType.LPStr)] string filename, IntPtr img, [In] int[] @params, int paramsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgcodecs_imdecode_Mat(IntPtr buf, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgcodecs_imdecode_vector(byte[] buf, IntPtr bufLength, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgcodecs_imdecode_InputArray(IntPtr buf, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_imencode_vector([MarshalAs(UnmanagedType.LPStr)] string ext, IntPtr img, IntPtr buf, [In] int[] @params, int paramsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_haveImageReader([MarshalAs(UnmanagedType.LPStr)] string fileName); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int imgcodecs_haveImageWriter([MarshalAs(UnmanagedType.LPStr)] string fileName); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdstring.cs b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdstring.cs new file mode 100644 index 0000000..50ac55d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdstring.cs @@ -0,0 +1,25 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr string_new1(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, CharSet = CharSet.Ansi)] + public static extern IntPtr string_new2([MarshalAs(UnmanagedType.LPStr)] string str); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void string_delete(IntPtr s); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe sbyte* string_c_str(IntPtr s); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr string_size(IntPtr s); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdvector.cs b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdvector.cs new file mode 100644 index 0000000..9414110 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/NativeMethods_stdvector.cs @@ -0,0 +1,467 @@ +using System; +using System.Runtime.InteropServices; +using OpenCvSharp.ML; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + #region uchar + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_uchar_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_uchar_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_uchar_new3([In] byte[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_uchar_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_uchar_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_uchar_copy(IntPtr vector, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_uchar_delete(IntPtr vector); + #endregion + #region char + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_char_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_char_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_char_new3([In] sbyte[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_char_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_char_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_char_copy(IntPtr vector, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_char_delete(IntPtr vector); + #endregion + #region int + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_int32_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_int32_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_int32_new3([In] int[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_int32_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_int32_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_int32_delete(IntPtr vector); + #endregion + #region float + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_float_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_float_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_float_new3([In] float[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_float_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_float_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_float_delete(IntPtr vector); + #endregion + #region double + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_double_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_double_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_double_new3([In] double[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_double_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_double_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_double_delete(IntPtr vector); + #endregion + #region cv::Vec2f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec2f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec2f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec2f_new3([In] Vec2f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec2f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec2f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec2f_delete(IntPtr vector); + #endregion + #region cv::Vec3f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec3f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec3f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec3f_new3([In] Vec3f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec3f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec3f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec3f_delete(IntPtr vector); + #endregion + #region cv::Vec4f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4f_new3([In] Vec4f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec4f_delete(IntPtr vector); + #endregion + #region cv::Vec4i + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4i_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4i_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4i_new3([In] Vec4i[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4i_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec4i_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec4i_delete(IntPtr vector); + #endregion + #region cv::Vec6f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6f_new3([In] Vec6f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec6f_delete(IntPtr vector); + #endregion + #region cv::Vec6d + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6d_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6d_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6d_new3([In] Vec6d[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6d_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Vec6d_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Vec6d_delete(IntPtr vector); + #endregion + #region cv::Point2i + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2i_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2i_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2i_new3([In] Point[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2i_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2i_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Point2i_delete(IntPtr vector); + #endregion + #region cv::Point2f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2f_new3([In] Point2f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point2f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Point2f_delete(IntPtr vector); + #endregion + #region cv::Point3f + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point3f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point3f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point3f_new3([In] Point3f[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point3f_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Point3f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Point3f_delete(IntPtr vector); + #endregion + #region cv::Rect + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect_new3([In] Rect[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Rect_delete(IntPtr vector); + #endregion + #region cv::Rect2d + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect2d_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect2d_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect2d_new3([In] Rect2d[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect2d_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Rect2d_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Rect2d_delete(IntPtr vector); + #endregion + #region cv::RotatedRect + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_RotatedRect_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_RotatedRect_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_RotatedRect_new3([In] RotatedRect[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_RotatedRect_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_RotatedRect_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_RotatedRect_delete(IntPtr vector); + #endregion + #region cv::KeyPoint + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_KeyPoint_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_KeyPoint_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_KeyPoint_new3([In]KeyPoint[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_KeyPoint_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_KeyPoint_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_KeyPoint_delete(IntPtr vector); + #endregion + #region cv::KeyPoint + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DMatch_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DMatch_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DMatch_new3([In] DMatch[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DMatch_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DMatch_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_DMatch_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_int_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_int_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_int_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_int_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_int_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_int_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_int_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_float_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_float_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_float_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_float_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_float_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_float_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_float_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_double_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_double_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_double_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_double_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_double_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_double_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_double_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_KeyPoint_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_KeyPoint_new2(IntPtr size); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_KeyPoint_new3( + IntPtr[] values, int size1, int[] size2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_KeyPoint_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_KeyPoint_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_KeyPoint_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_KeyPoint_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_KeyPoint_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_DMatch_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_DMatch_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_DMatch_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_DMatch_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_DMatch_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_DMatch_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_DMatch_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point2f_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point2f_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point2f_getSize1(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point2f_getSize2(IntPtr vector, [In, Out] IntPtr[] size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_vector_Point2f_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point2f_copy(IntPtr vec, IntPtr[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_vector_Point2f_delete(IntPtr vector); + #endregion + #region vector + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_string_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_string_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_string_getSize(IntPtr vec); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_string_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe sbyte* vector_string_elemAt(IntPtr vector, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_string_delete(IntPtr vector); + #endregion + #region cv::Mat + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Mat_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Mat_new2(uint size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Mat_new3(IntPtr[] data, uint dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Mat_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_Mat_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Mat_delete(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Mat_assignToArray(IntPtr vector, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] arr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_Mat_addref(IntPtr vector); + + #endregion + + #region cv::ml::DTrees::Node + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Node_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Node_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Node_new3([In]DTrees.Node[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Node_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Node_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_DTrees_Node_delete(IntPtr vector); + + #endregion + + #region cv::ml::DTrees::Split + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Split_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Split_new2(IntPtr size); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Split_new3([In]DTrees.Split[] data, IntPtr dataLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Split_getSize(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr vector_DTrees_Split_getPointer(IntPtr vector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void vector_DTrees_Split_delete(IntPtr vector); + + #endregion + + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/StdString.cs b/OpenVinoOpenCvSharp/PInvoke/StdString.cs new file mode 100644 index 0000000..b46e98b --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/StdString.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp +{ + /// + /// + /// C++ std::string + /// + public class StdString : DisposableCvObject + { + /// + /// + /// + public StdString() + { + ptr = NativeMethods.string_new1(); + } + + /// + /// + /// + public StdString(IntPtr ptr) + { + if (ptr == IntPtr.Zero) + throw new ArgumentException("null pointer", nameof(ptr)); + this.ptr = ptr; + } + + /// + /// + /// + /// + public StdString(string str) + { + if (str == null) + throw new ArgumentNullException(nameof(str)); + ptr = NativeMethods.string_new2(str); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.string_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// string.size() + /// + public int Size + { + get + { + var ret = NativeMethods.string_size(ptr).ToInt32(); + GC.KeepAlive(this); + return ret; + } + } + + /// + /// Converts std::string to managed string + /// + /// + public new string ToString() + { + unsafe + { + var stringPointer = NativeMethods.string_c_str(ptr); +#if DOTNET_FRAMEWORK + var ret = new string(stringPointer); +#else + var ret = Marshal.PtrToStringAnsi(new IntPtr(stringPointer)) ?? ""; +#endif + GC.KeepAlive(this); + return ret; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/Win32API.cs b/OpenVinoOpenCvSharp/PInvoke/Win32API.cs new file mode 100644 index 0000000..9f5bbeb --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/Win32API.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +// ReSharper disable IdentifierTypo +// ReSharper disable InconsistentNaming +// ReSharper disable CommentTypo +#pragma warning disable CA1401 // P/Invokes should not be visible +#pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments + +namespace OpenCvSharp +{ + /// + /// Win32API Wrapper + /// + public static class Win32Api + { + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string lpFileName); + [DllImport("kernel32")] + public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + [DllImport("kernel32")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool FreeLibrary(IntPtr hLibModule); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/WindowsLibraryLoader.cs b/OpenVinoOpenCvSharp/PInvoke/WindowsLibraryLoader.cs new file mode 100644 index 0000000..5eeadff --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/WindowsLibraryLoader.cs @@ -0,0 +1,379 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; + +namespace OpenCvSharp +{ + /// + /// Handles loading embedded dlls into memory, based on http://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-sharp-dll. + /// + /// This code is based on https://github.com/charlesw/tesseract + public sealed class WindowsLibraryLoader + { + #region Singleton pattern + + /// + /// + /// + public static WindowsLibraryLoader Instance { get; } = new WindowsLibraryLoader(); + + #endregion + + /// + /// The default base directory name to copy the assemblies too. + /// + private const string ProcessorArchitecture = "PROCESSOR_ARCHITECTURE"; + private const string DllFileExtension = ".dll"; + private const string DllDirectory = "dll"; + + private readonly List loadedAssemblies = new List(); + + /// + /// Map processor + /// + private readonly Dictionary processorArchitecturePlatforms = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + {"x86", "x86"}, + {"AMD64", "x64"}, + {"IA64", "Itanium"}, + {"ARM", "WinCE"} + }; + + /// + /// Used as a sanity check for the returned processor architecture to double check the returned value. + /// + private readonly Dictionary processorArchitectureAddressWidthPlatforms = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + {"x86", 4}, + {"AMD64", 8}, + {"IA64", 8}, + {"ARM", 4} + }; + + /// + /// Additional user-defined DLL paths + /// + public List AdditionalPaths { get; } + + private readonly object syncLock = new object(); + + /// + /// constructor + /// + private WindowsLibraryLoader() + { + AdditionalPaths = new List(); + } + + /// + /// + /// + /// + /// + public bool IsLibraryLoaded(string dllName) + { + lock (syncLock) + { + return loadedAssemblies.Contains(dllName); + } + } + + /// + /// + /// + /// + public bool IsCurrentPlatformSupported() + { +#if DOTNET_FRAMEWORK + return Environment.OSVersion.Platform == PlatformID.Win32NT || + Environment.OSVersion.Platform == PlatformID.Win32Windows; +#else + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); +#endif + } + + /// + /// + /// + /// + /// + public void LoadLibrary(string dllName, IEnumerable? additionalPaths = null) + { + if (!IsCurrentPlatformSupported()) + { + return; + } + + if (additionalPaths == null) + additionalPaths = new string[0]; + + try + { + lock (syncLock) + { + if (loadedAssemblies.Contains(dllName)) + { + return; + } + + var processArch = GetProcessArchitecture(); + IntPtr dllHandle; + + // Try loading from user-defined paths + foreach (var path in additionalPaths) + { + // baseDirectory = Path.GetFullPath(path); + dllHandle = LoadLibraryRaw(dllName, path); + if (dllHandle != IntPtr.Zero) return; + } + + // Try loading from executing assembly domain +#if DOTNET_FRAMEWORK + var executingAssembly = Assembly.GetExecutingAssembly(); +#else + var executingAssembly = GetType().GetTypeInfo().Assembly; +#endif + var baseDirectory = Path.GetDirectoryName(executingAssembly.Location) ?? ""; + dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch); + if (dllHandle != IntPtr.Zero) return; + + // Fallback to current app domain + // TODO +#if DOTNET_FRAMEWORK + baseDirectory = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory); + dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch); + if (dllHandle != IntPtr.Zero) return; +#endif + + // Gets the pathname of the base directory that the assembly resolver uses to probe for assemblies. + // https://github.com/dotnet/corefx/issues/2221 +#if !NET20 && !NET40 + baseDirectory = AppContext.BaseDirectory; + dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch); + if (dllHandle != IntPtr.Zero) return; +#endif + + // Finally try the working directory + baseDirectory = Path.GetFullPath(Directory.GetCurrentDirectory()); + dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch); + if (dllHandle != IntPtr.Zero) return; + + // ASP.NET hack, requires an active context +#if DOTNET_FRAMEWORK + if (System.Web.HttpContext.Current != null) + { + var server = System.Web.HttpContext.Current.Server; + baseDirectory = Path.GetFullPath(server.MapPath("bin")); + dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch); + if (dllHandle != IntPtr.Zero) return; + } +#endif + + var errorMessage = new StringBuilder(); + errorMessage.AppendFormat("Failed to find dll \"{0}\", for processor architecture {1}.", dllName, + processArch.Architecture); + if (processArch.HasWarnings) + { + // include process detection warnings + errorMessage.AppendFormat("\r\nWarnings: \r\n{0}", processArch.WarningText()); + } + throw new Exception(errorMessage.ToString()); + } + } + catch (Exception e) + { + Debug.WriteLine(e.Message); + } + } + + /// + /// Get's the current process architecture while keeping track of any assumptions or possible errors. + /// + /// + private ProcessArchitectureInfo GetProcessArchitecture() + { + // BUGBUG: Will this always be reliable? + var processArchitecture = Environment.GetEnvironmentVariable(ProcessorArchitecture); + + var processInfo = new ProcessArchitectureInfo(); + if (!string.IsNullOrEmpty(processArchitecture)) + { + // Sanity check + processInfo.Architecture = processArchitecture; + } + else + { + processInfo.AddWarning("Failed to detect processor architecture, falling back to x86."); + processInfo.Architecture = (IntPtr.Size == 8) ? "x64" : "x86"; + } + + var addressWidth = processorArchitectureAddressWidthPlatforms[processInfo.Architecture]; + if (addressWidth != IntPtr.Size) + { + if (string.Equals(processInfo.Architecture, "AMD64", StringComparison.OrdinalIgnoreCase) && IntPtr.Size == 4) + { + // fall back to x86 if detected x64 but has an address width of 32 bits. + processInfo.Architecture = "x86"; + processInfo.AddWarning("Expected the detected processing architecture of {0} to have an address width of {1} Bytes but was {2} Bytes, falling back to x86.", processInfo.Architecture, addressWidth, IntPtr.Size); + } + else + { + // no fallback possible + processInfo.AddWarning("Expected the detected processing architecture of {0} to have an address width of {1} Bytes but was {2} Bytes.", processInfo.Architecture, addressWidth, IntPtr.Size); + } + } + + return processInfo; + } + + private IntPtr LoadLibraryInternal(string dllName, string baseDirectory, ProcessArchitectureInfo processArchInfo) + { + //IntPtr libraryHandle = IntPtr.Zero; + var platformName = GetPlatformName(processArchInfo.Architecture) ?? ""; + var expectedDllDirectory = Path.Combine( + Path.Combine(baseDirectory, DllDirectory), platformName); + //var fileName = FixUpDllFileName(Path.Combine(expectedDllDirectory, dllName)); + + return LoadLibraryRaw(dllName, expectedDllDirectory); + } + + private IntPtr LoadLibraryRaw(string dllName, string baseDirectory) + { + var libraryHandle = IntPtr.Zero; + var fileName = FixUpDllFileName(Path.Combine(baseDirectory, dllName)); + +#if WINRT && false + // MP! Note: This is a hack, needs refinement. We don't need to carry payload of both binaries for WinRT because the appx is platform specific. + ProcessArchitectureInfo processInfo = GetProcessArchitecture(); + + string cpu = "x86"; + if (processInfo.Architecture == "AMD64") + cpu = "x64"; + + string dllpath = baseDirectory.Replace($"dll\\{cpu}", ""); + fileName = $"{dllpath}{dllName}.dll"; + + // Show where we're trying to load the file from + Debug.WriteLine($"Trying to load native library \"{fileName}\"..."); +#endif + + if (File.Exists(fileName)) + { + // Attempt to load dll + try + { + libraryHandle = Win32LoadLibrary(fileName); + if (libraryHandle != IntPtr.Zero) + { + // library has been loaded + Debug.WriteLine($"Successfully loaded native library \"{fileName}\"."); + loadedAssemblies.Add(dllName); + } + else + { + Debug.WriteLine($"Failed to load native library \"{fileName}\".\r\nCheck windows event log."); + } + } + catch (Exception e) + { + // ReSharper disable once RedundantAssignment + var lastError = Marshal.GetLastWin32Error(); + Debug.WriteLine( + $"Failed to load native library \"{fileName}\".\r\nLast Error:{lastError}\r\nCheck inner exception and\\or windows event log.\r\nInner Exception: {e}"); + } + } + else + { + Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, + "The native library \"{0}\" does not exist.", + fileName)); + } + + return libraryHandle; + } + + /// + /// Determines if the dynamic link library file name requires a suffix + /// and adds it if necessary. + /// + private string FixUpDllFileName(string fileName) + { + if (!string.IsNullOrEmpty(fileName)) + { +#if DOTNET_FRAMEWORK + var platformId = Environment.OSVersion.Platform; + if ((platformId == PlatformID.Win32S) || + (platformId == PlatformID.Win32Windows) || + (platformId == PlatformID.Win32NT) || + (platformId == PlatformID.WinCE)) +#else + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) +#endif + { + if (!fileName.EndsWith(DllFileExtension, + StringComparison.OrdinalIgnoreCase)) + { + return fileName + DllFileExtension; + } + } + } + + return fileName; + } + + /// + /// Given the processor architecture, returns the name of the platform. + /// + private string? GetPlatformName(string processorArchitecture) + { + if (string.IsNullOrEmpty(processorArchitecture)) + return null; + + if (processorArchitecturePlatforms.TryGetValue(processorArchitecture, out var platformName)) + return platformName; + + return null; + } + + private class ProcessArchitectureInfo + { + public string Architecture { get; set; } + private List Warnings { get; } + + public ProcessArchitectureInfo() + { + Architecture = ""; + Warnings = new List(); + } + + public bool HasWarnings => Warnings.Count > 0; + + public void AddWarning(string format, params object[] args) + { + Warnings.Add(string.Format(format, args)); + } + + public string WarningText() + { + return string.Join("\r\n", Warnings.ToArray()); + } + } + +#if DOTNET_FRAMEWORK + private const CharSet DefaultCharSet = CharSet.Auto; +#else + private const CharSet DefaultCharSet = CharSet.Unicode; +#endif + + [DllImport("kernel32", EntryPoint = "LoadLibrary", CallingConvention = CallingConvention.Winapi, + SetLastError = true, CharSet = DefaultCharSet, BestFitMapping = false, ThrowOnUnmappableChar = true)] + private static extern IntPtr Win32LoadLibrary(string dllPath); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d.cs b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d.cs new file mode 100644 index 0000000..b3efe5d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d.cs @@ -0,0 +1,441 @@ + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_Rodrigues(IntPtr src, IntPtr dst, IntPtr jacobian); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_Rodrigues_VecToMat(IntPtr vector, IntPtr matrix, IntPtr jacobian); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_Rodrigues_MatToVec(IntPtr vector, IntPtr matrix, IntPtr jacobian); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findHomography_InputArray(IntPtr srcPoints, IntPtr dstPoints, + int method, double ransacReprojThreshold, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findHomography_vector(Point2d[] srcPoints, int srcPointsLength, + Point2d[] dstPoints, int dstPointsLength, int method, double ransacReprojThreshold, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_RQDecomp3x3_InputArray(IntPtr src, IntPtr mtxR, + IntPtr mtxQ, IntPtr qx, IntPtr qy, IntPtr qz, out Vec3d outVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_RQDecomp3x3_Mat(IntPtr src, IntPtr mtxR, IntPtr mtxQ, + IntPtr qx, IntPtr qy, IntPtr qz, out Vec3d outVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_decomposeProjectionMatrix_InputArray(IntPtr projMatrix, + IntPtr cameraMatrix, IntPtr rotMatrix, IntPtr transVect, IntPtr rotMatrixX, + IntPtr rotMatrixY, IntPtr rotMatrixZ, IntPtr eulerAngles); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_decomposeProjectionMatrix_Mat(IntPtr projMatrix, + IntPtr cameraMatrix, IntPtr rotMatrix, IntPtr transVect, IntPtr rotMatrixX, + IntPtr rotMatrixY, IntPtr rotMatrixZ, IntPtr eulerAngles); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_matMulDeriv(IntPtr a, IntPtr b, + IntPtr dABdA, IntPtr dABdB); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_composeRT_InputArray(IntPtr rvec1, IntPtr tvec1, + IntPtr rvec2, IntPtr tvec2, + IntPtr rvec3, IntPtr tvec3, + IntPtr dr3dr1, IntPtr dr3dt1, + IntPtr dr3dr2, IntPtr dr3dt2, + IntPtr dt3dr1, IntPtr dt3dt1, + IntPtr dt3dr2, IntPtr dt3dt2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_composeRT_Mat(IntPtr rvec1, IntPtr tvec1, + IntPtr rvec2, IntPtr tvec2, + IntPtr rvec3, IntPtr tvec3, + IntPtr dr3dr1, IntPtr dr3dt1, + IntPtr dr3dr2, IntPtr dr3dt2, + IntPtr dt3dr1, IntPtr dt3dt1, + IntPtr dt3dr2, IntPtr dt3dt2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_projectPoints_InputArray(IntPtr objectPoints, + IntPtr rvec, IntPtr tvec, + IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr imagePoints, IntPtr jacobian, + double aspectRatio); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_projectPoints_Mat(IntPtr objectPoints, + IntPtr rvec, IntPtr tvec, + IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr imagePoints, IntPtr jacobian, + double aspectRatio); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_solvePnP_InputArray(IntPtr selfectPoints, IntPtr imagePoints, IntPtr cameraMatrix, + IntPtr distCoeffs, IntPtr rvec, IntPtr tvec, int useExtrinsicGuess, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_solvePnP_vector(Point3f[] objectPoints, int objectPointsLength, + Point2f[] imagePoints, int imagePointsLength, + double* cameraMatrix, double[] distCoeffs, int distCoeffsLength, + [Out] double[] rvec, [Out] double[] tvec, int useExtrinsicGuess, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_solvePnPRansac_InputArray(IntPtr objectPoints, IntPtr imagePoints, + IntPtr cameraMatrix, IntPtr distCoeffs, IntPtr rvec, IntPtr tvec, + int useExtrinsicGuess, int iterationsCount, float reprojectionError, double confidence, + IntPtr inliers, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_solvePnPRansac_vector(Point3f[] objectPoints, int objectPointsLength, + Point2f[] imagePoints, int imagePointsLength, double* cameraMatrix, double[] distCoeffs, int distCoeffsLength, + [Out] double[] rvec, [Out] double[] tvec, int useExtrinsicGuess, int iterationsCount, float reprojectionError, + double confidence, IntPtr inliers, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_initCameraMatrix2D_Mat(IntPtr[] objectPoints, int objectPointsLength, + IntPtr[] imagePoints, int imagePointsLength, + Size imageSize, double aspectRatio); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_initCameraMatrix2D_array(IntPtr[] objectPoints, int opSize1, int[] opSize2, + IntPtr[] imagePoints, int ipSize1, int[] ipSize2, + Size imageSize, double aspectRatio); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findChessboardCorners_InputArray(IntPtr image, Size patternSize, + IntPtr corners, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findChessboardCorners_vector(IntPtr image, Size patternSize, + IntPtr corners, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_checkChessboard(IntPtr img, Size size); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findChessboardCornersSB_OutputArray( + IntPtr image, Size patternSize, IntPtr corners, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findChessboardCornersSB_vector( + IntPtr image, Size patternSize, IntPtr corners, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_find4QuadCornerSubpix_InputArray(IntPtr img, IntPtr corners, Size regionSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_find4QuadCornerSubpix_vector(IntPtr img, IntPtr corners, Size regionSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_drawChessboardCorners_InputArray(IntPtr image, Size patternSize, + IntPtr corners, int patternWasFound); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_drawChessboardCorners_array(IntPtr image, Size patternSize, + Point2f[] corners, int cornersLength, int patternWasFound); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_drawFrameAxes( + IntPtr image, IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr rvec, IntPtr tvec, float length, int thickness); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findCirclesGrid_InputArray(IntPtr image, Size patternSize, + IntPtr centers, int flags, IntPtr blobDetector); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_findCirclesGrid_vector(IntPtr image, Size patternSize, + IntPtr centers, int flags, IntPtr blobDetector); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double calib3d_calibrateCamera_InputArray( + IntPtr[] objectPoints, int objectPointsSize, + IntPtr[] imagePoints, int imagePointsSize, + Size imageSize, + IntPtr cameraMatrix,IntPtr distCoeffs, + IntPtr rvecs, IntPtr tvecs, + int flags, TermCriteria criteria); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe double calib3d_calibrateCamera_vector( + IntPtr[] objectPoints, int opSize1, int[] opSize2, + IntPtr[] imagePoints, int ipSize1, int[] ipSize2, + Size imageSize, + double* cameraMatrix, + [In, Out] double[] distCoeffs, int distCoeffsSize, + IntPtr rvecs, IntPtr tvecs, + int flags, TermCriteria criteria); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_calibrationMatrixValues_InputArray( + IntPtr cameraMatrix, + Size imageSize, double apertureWidth, double apertureHeight, out double fovx, out double fovy, + out double focalLength, out Point2d principalPoint, out double aspectRatio); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_calibrationMatrixValues_array( + double* cameraMatrix, Size imageSize, + double apertureWidth, double apertureHeight, out double fovx, out double fovy, out double focalLength, + out Point2d principalPoint, out double aspectRatio); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double calib3d_stereoCalibrate_InputArray( + IntPtr[] objectPoints, int opSize, + IntPtr[] imagePoints1, int ip1Size, + IntPtr[] imagePoints2, int ip2Size, + IntPtr cameraMatrix1, + IntPtr distCoeffs1, + IntPtr cameraMatrix2, + IntPtr distCoeffs2, + Size imageSize, + IntPtr R, IntPtr T, + IntPtr E, IntPtr F, + int flags, TermCriteria criteria); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe double calib3d_stereoCalibrate_array( + IntPtr[] objectPoints, int opSize1, int[] opSizes2, + IntPtr[] imagePoints1, int ip1Size1, int[] ip1Sizes2, + IntPtr[] imagePoints2, int ip2Size1, int[] ip2Sizes2, + double* cameraMatrix1, + [In, Out] double[] distCoeffs1, int dc1Size, + double* cameraMatrix2, + [In, Out] double[] distCoeffs2, int dc2Size, + Size imageSize, + IntPtr R, IntPtr T, + IntPtr E, IntPtr F, + int flags, TermCriteria criteria); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_stereoRectify_InputArray( + IntPtr cameraMatrix1, IntPtr distCoeffs1, + IntPtr cameraMatrix2, IntPtr distCoeffs2, + Size imageSize, IntPtr R, IntPtr T, + IntPtr R1, IntPtr R2, + IntPtr P1, IntPtr P2, + IntPtr Q, int flags, + double alpha, Size newImageSize, + out Rect validPixROI1, out Rect validPixROI2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_stereoRectify_array( + double* cameraMatrix1, + double[] distCoeffs1, int dc1Size, + double* cameraMatrix2, + double[] distCoeffs2, int dc2Size, + Size imageSize, + double* R, double[] T, + double* R1, double* R2, double* P1, double* P2, + double* Q, int flags, double alpha, Size newImageSize, + out Rect validPixROI1, out Rect validPixROI2); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_stereoRectifyUncalibrated_InputArray( + IntPtr points1, IntPtr points2, + IntPtr F, Size imgSize, + IntPtr H1, IntPtr H2, + double threshold); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int calib3d_stereoRectifyUncalibrated_array( + Point2d[] points1, int points1Size, + Point2d[] points2, int points2Size, + double* F, Size imgSize, + double* H1, double* H2, + double threshold); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float calib3d_rectify3Collinear_InputArray( + IntPtr cameraMatrix1, IntPtr distCoeffs1, + IntPtr cameraMatrix2, IntPtr distCoeffs2, + IntPtr cameraMatrix3, IntPtr distCoeffs3, + IntPtr[] imgpt1, int imgpt1Size, + IntPtr[] imgpt3, int imgpt3Size, + Size imageSize, IntPtr R12, IntPtr T12, + IntPtr R13, IntPtr T13, + IntPtr R1, IntPtr R2, IntPtr R3, + IntPtr P1, IntPtr P2, IntPtr P3, + IntPtr Q, double alpha, Size newImgSize, + out Rect roi1, out Rect roi2, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_getOptimalNewCameraMatrix_InputArray( + IntPtr cameraMatrix, IntPtr distCoeffs, + Size imageSize, double alpha, Size newImgSize, + out Rect validPixROI, int centerPrincipalPoint); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe IntPtr calib3d_getOptimalNewCameraMatrix_array( + double* cameraMatrix, + [In] double[] distCoeffs, int distCoeffsSize, + Size imageSize, double alpha, Size newImgSize, + out Rect validPixROI, int centerPrincipalPoint); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsToHomogeneous_InputArray( + IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsToHomogeneous_array1( + [In] Vec2f[] src, [In, Out] Vec3f[] dst, int length); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsToHomogeneous_array2( + [In] Vec3f[] src, [In, Out] Vec4f[] dst, int length); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsFromHomogeneous_InputArray( + IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsFromHomogeneous_array1( + [In] Vec3f[] src, [In, Out] Vec2f[] dst, int length); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsFromHomogeneous_array2( + [In] Vec4f[] src, [In, Out] Vec3f[] dst, int length); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_convertPointsHomogeneous( + IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findFundamentalMat_InputArray( + IntPtr points1, IntPtr points2, + int method, double param1, double param2, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findFundamentalMat_array( + Point2d[] points1, int points1Size, + Point2d[] points2, int points2Size, + int method, double param1, double param2, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_computeCorrespondEpilines_InputArray( + IntPtr points, int whichImage, IntPtr F, IntPtr lines); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_computeCorrespondEpilines_array2d( + [In] Point2d[] points, int pointsSize, + int whichImage, double* F, [In, Out] Point3f[] lines); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_computeCorrespondEpilines_array3d( + [In] Point3d[] points, int pointsSize, + int whichImage, double* F, [In, Out] Point3f[] lines); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_triangulatePoints_InputArray( + IntPtr projMatr1, IntPtr projMatr2, + IntPtr projPoints1, IntPtr projPoints2, + IntPtr points4D); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_triangulatePoints_array( + double* projMatr1, double* projMatr2, + [In] Point2d[] projPoints1, int projPoints1Size, + [In] Point2d[] projPoints2, int projPoints2Size, + [In, Out] Vec4d[] points4D); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_correctMatches_InputArray( + IntPtr F, IntPtr points1, IntPtr points2, + IntPtr newPoints1, IntPtr newPoints2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void calib3d_correctMatches_array( + double* F, Point2d[] points1, int points1Size, + Point2d[] points2, int points2Size, + Point2d[] newPoints1, Point2d[] newPoints2); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_filterSpeckles(IntPtr img, double newVal, int maxSpeckleSize, + double maxDiff, IntPtr buf); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect calib3d_getValidDisparityROI(Rect roi1, Rect roi2, + int minDisparity, int numberOfDisparities, int SADWindowSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_validateDisparity(IntPtr disparity, IntPtr cost, + int minDisparity, int numberOfDisparities, int disp12MaxDisp); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_reprojectImageTo3D(IntPtr disparity, IntPtr _3dImage, + IntPtr Q, int handleMissingValues, int ddepth); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_estimateAffine3D(IntPtr src, IntPtr dst, + IntPtr outVal, IntPtr inliers, double ransacThreshold, double confidence); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double calib3d_sampsonDistance_InputArray(IntPtr pt1, IntPtr pt2, IntPtr F); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe double calib3d_sampsonDistance_Point3d(Point3d pt1, Point3d pt2, double* F); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_estimateAffine2D( + IntPtr from, IntPtr to, IntPtr inliers, + int method, double ransacReprojThreshold, + ulong maxIters, double confidence, ulong refineIters); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_estimateAffinePartial2D( + IntPtr from, IntPtr to, IntPtr inliers, + int method, double ransacReprojThreshold, + ulong maxIters, double confidence, ulong refineIters); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_decomposeHomographyMat( + IntPtr H, + IntPtr K, + IntPtr rotations, + IntPtr translations, + IntPtr normals); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_filterHomographyDecompByVisibleRefpoints( + IntPtr rotations, + IntPtr normals, + IntPtr beforePoints, + IntPtr afterPoints, + IntPtr possibleSolutions, + IntPtr pointsMask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_undistort( + IntPtr src, IntPtr dst, + IntPtr cameraMatrix, IntPtr distCoeffs, IntPtr newCameraMatrix); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_initUndistortRectifyMap( + IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr R, IntPtr newCameraMatrix, + Size size, int m1type, IntPtr map1, IntPtr map2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float calib3d_initWideAngleProjMap( + IntPtr cameraMatrix, IntPtr distCoeffs, + Size imageSize, int destImageWidth, + int m1type, IntPtr map1, IntPtr map2, + int projType, double alpha); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_getDefaultNewCameraMatrix( + IntPtr cameraMatrix, Size imgsize, int centerPrincipalPoint); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_undistortPoints( + IntPtr src, IntPtr dst, + IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr R, IntPtr P); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_undistortPointsIter( + IntPtr src, IntPtr dst, + IntPtr cameraMatrix, IntPtr distCoeffs, + IntPtr R, IntPtr P, TermCriteria criteria); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_recoverPose_InputArray1( + IntPtr E, IntPtr points1, IntPtr points2, + IntPtr cameraMatrix, + IntPtr R, IntPtr P, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_recoverPose_InputArray2( + IntPtr E, IntPtr points1, IntPtr points2, + IntPtr R, IntPtr P, double focal, IntPtr pp, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_recoverPose_InputArray3( + IntPtr E, IntPtr points1, IntPtr points2, + IntPtr cameraMatrix, + IntPtr R, IntPtr P, double distanceTresh, IntPtr mask, IntPtr triangulatedPoints); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findEssentialMat_InputArray1( + IntPtr points1, IntPtr points2, + IntPtr cameraMatrix, + int method, double prob, double threshold, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_findEssentialMat_InputArray2( + IntPtr points1, IntPtr points2, + double focal, IntPtr pp, + int method, double prob, double threshold, IntPtr mask); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoBM.cs b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoBM.cs new file mode 100644 index 0000000..1539276 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoBM.cs @@ -0,0 +1,71 @@ + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_Ptr_StereoBM_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_Ptr_StereoBM_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_StereoBM_create(int numDisparities, int blockSize); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getPreFilterType(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setPreFilterType(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getPreFilterSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setPreFilterSize(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getPreFilterCap(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setPreFilterCap(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getTextureThreshold(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setTextureThreshold(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getUniquenessRatio(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setUniquenessRatio(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoBM_getSmallerBlockSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setSmallerBlockSize(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect calib3d_StereoBM_getROI1(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setROI1(IntPtr obj, Rect value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect calib3d_StereoBM_getROI2(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoBM_setROI2(IntPtr obj, Rect value); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoMatcher.cs b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoMatcher.cs new file mode 100644 index 0000000..00e6bb1 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoMatcher.cs @@ -0,0 +1,54 @@ + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_compute( + IntPtr obj, IntPtr left, IntPtr right, IntPtr disparity); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getMinDisparity(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setMinDisparity(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getNumDisparities(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setNumDisparities(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getBlockSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setBlockSize(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getSpeckleWindowSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setSpeckleWindowSize(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getSpeckleRange(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setSpeckleRange(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoMatcher_getDisp12MaxDiff(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoMatcher_setDisp12MaxDiff(IntPtr obj, int value); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoSGBM.cs b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoSGBM.cs new file mode 100644 index 0000000..41cb0d9 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_StereoSGBM.cs @@ -0,0 +1,56 @@ + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_Ptr_StereoSGBM_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_Ptr_StereoSGBM_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr calib3d_StereoSGBM_create( + int minDisparity, int numDisparities, int blockSize, + int P1, int P2, int disp12MaxDiff, + int preFilterCap, int uniquenessRatio, + int speckleWindowSize, int speckleRange, int mode); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoSGBM_getPreFilterCap(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoSGBM_setPreFilterCap(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoSGBM_getUniquenessRatio(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoSGBM_setUniquenessRatio(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoSGBM_getP1(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoSGBM_setP1(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoSGBM_getP2(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoSGBM_setP2(IntPtr obj, int value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int calib3d_StereoSGBM_getMode(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_StereoSGBM_setMode(IntPtr obj, int value); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_fisheye.cs b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_fisheye.cs new file mode 100644 index 0000000..518d676 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/calib3d/NativeMethods_calib3d_fisheye.cs @@ -0,0 +1,80 @@ + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + // TODO + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_projectPoints1( + IntPtr objectPoints, IntPtr imagePoints, IntPtr affine, + IntPtr K, IntPtr D, double alpha, IntPtr jacobian); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_projectPoints2( + IntPtr objectPoints, IntPtr imagePoints, IntPtr rvec, IntPtr tvec, + IntPtr K, IntPtr D, double alpha, IntPtr jacobian); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_distortPoints( + IntPtr undistorted, IntPtr distorted, IntPtr K, IntPtr D, double alpha); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_undistortPoints( + IntPtr distorted, IntPtr undistorted, + IntPtr K, IntPtr D, IntPtr R, IntPtr P); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_initUndistortRectifyMap( + IntPtr K, IntPtr D, IntPtr R, IntPtr P, + Size size, int m1type, IntPtr map1, IntPtr map2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_undistortImage( + IntPtr distorted, IntPtr undistorted, + IntPtr K, IntPtr D, IntPtr Knew, Size newSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_estimateNewCameraMatrixForUndistortRectify( + IntPtr K, IntPtr D, Size image_size, IntPtr R, + IntPtr P, double balance, Size newSize, double fov_scale); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double calib3d_fisheye_calibrate( + IntPtr objectPoints, IntPtr imagePoints, + Size imageSize, + IntPtr K, + IntPtr D, + IntPtr rvecs, + IntPtr tvecs, + int flags, + TermCriteria criteria); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void calib3d_fisheye_stereoRectify( + IntPtr K1, IntPtr D1, IntPtr K2, IntPtr D2, Size imageSize, IntPtr R, IntPtr tvec, + IntPtr R1, IntPtr R2, IntPtr P1, IntPtr P2, IntPtr Q, int flags, Size newImageSize, + double balance, double fov_scale); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double calib3d_fisheye_stereoCalibrate( + IntPtr objectPoints, + IntPtr imagePoints1, + IntPtr imagePoints2, + IntPtr K1, + IntPtr D1, + IntPtr K2, + IntPtr D2, + Size imageSize, + IntPtr R, + IntPtr T, + int flags, + TermCriteria criteria); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core.cs new file mode 100644 index 0000000..e21903d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core.cs @@ -0,0 +1,337 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + #region Miscellaneous + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_setNumThreads(int nthreads); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getNumThreads(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getThreadNum(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_getBuildInformation([MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int maxLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern int core_getBuildInformation_length(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_getVersionString([MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int maxLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getVersionMajor(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getVersionMinor(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getVersionRevision(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern long core_getTickCount(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_getTickFrequency(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern long core_getCPUTickCount(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_checkHardwareSupport(int feature); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_getHardwareFeatureName(int feature, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int bufLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_getCPUFeaturesLine([MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int bufLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getNumberOfCPUs(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_fastMalloc(IntPtr bufSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_fastFree(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_setUseOptimized(int onoff); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_useOptimized(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_glob([MarshalAs(UnmanagedType.LPStr)] string pattern, IntPtr result, int recursive); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_setBreakOnError(int flag); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr redirectError(CvErrorCallback errCallback, IntPtr userdata, ref IntPtr prevUserdata); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern unsafe sbyte* core_format(IntPtr mtx, int fmt); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe void core_char_delete(sbyte* buf); + + #endregion + + #region Array Operations + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_add(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask, int dtype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_subtract_InputArray2(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_subtract_InputArrayScalar(IntPtr src1, Scalar src2, IntPtr dst, IntPtr mask, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_subtract_ScalarInputArray(Scalar src1, IntPtr src2, IntPtr dst, IntPtr mask, int dtype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_multiply(IntPtr src1, IntPtr src2, IntPtr dst, double scale, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_divide1(double scale, IntPtr src2, IntPtr dst, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_divide2(IntPtr src1, IntPtr src2, IntPtr dst, double scale, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_scaleAdd(IntPtr src1, double alpha, IntPtr src2,IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_addWeighted(IntPtr src1, double alpha, IntPtr src2, + double beta, double gamma, IntPtr dst, int dtype); + + #endregion + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_borderInterpolate(int p, int len, int borderType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_copyMakeBorder(IntPtr src, IntPtr dst, int top, int bottom, int left, + int right, int borderType, Scalar value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_convertScaleAbs(IntPtr src, IntPtr dst, double alpha, double beta); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LUT(IntPtr src, IntPtr lut, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Scalar core_sum(IntPtr src); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_countNonZero(IntPtr src); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_findNonZero(IntPtr src, IntPtr idx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Scalar core_mean(IntPtr src, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_meanStdDev_OutputArray( + IntPtr src, IntPtr mean, IntPtr stddev, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_meanStdDev_Scalar( + IntPtr src, out Scalar mean, out Scalar stddev, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_norm1(IntPtr src1, int normType, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_norm2(IntPtr src1, IntPtr src2, + int normType, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_batchDistance(IntPtr src1, IntPtr src2, + IntPtr dist, int dtype, IntPtr nidx, + int normType, int k, IntPtr mask, + int update, int crosscheck); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_normalize(IntPtr src, IntPtr dst, double alpha, double beta, + int normType, int dtype, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_minMaxLoc1(IntPtr src, out double minVal, out double maxVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_minMaxLoc2(IntPtr src, out double minVal, out double maxVal, + out Point minLoc, out Point maxLoc, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_minMaxIdx1(IntPtr src, out double minVal, out double maxVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_minMaxIdx2(IntPtr src, out double minVal, out double maxVal, + [MarshalAs(UnmanagedType.LPArray)] int[] minIdx, [MarshalAs(UnmanagedType.LPArray)] int[] maxIdx, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_reduce(IntPtr src, IntPtr dst, int dim, int rtype, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_merge([MarshalAs(UnmanagedType.LPArray)] IntPtr[] mv, uint count, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_split(IntPtr src, out IntPtr mv); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_mixChannels(IntPtr[] src, uint nsrcs, + IntPtr[] dst, uint ndsts, int[] fromTo, uint npairs); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_extractChannel(IntPtr src, IntPtr dst, int coi); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_insertChannel(IntPtr src, IntPtr dst, int coi); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_flip(IntPtr src, IntPtr dst, int flipCode); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_repeat1(IntPtr src, int ny, int nx, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_repeat2(IntPtr src, int ny, int nx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_hconcat1([MarshalAs(UnmanagedType.LPArray)] IntPtr[] src, uint nsrc, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_hconcat2(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_vconcat1([MarshalAs(UnmanagedType.LPArray)] IntPtr[] src, uint nsrc, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_vconcat2(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_bitwise_and(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_bitwise_or(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_bitwise_xor(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_bitwise_not(IntPtr src, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_absdiff(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_inRange_InputArray(IntPtr src, IntPtr lowerb, IntPtr upperb, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_inRange_Scalar(IntPtr src, Scalar lowerb, Scalar upperb, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_compare(IntPtr src1, IntPtr src2, IntPtr dst, int cmpop); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_min1(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_max1(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_min_MatMat(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_min_MatDouble(IntPtr src1, double src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_max_MatMat(IntPtr src1, IntPtr src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_max_MatDouble(IntPtr src1, double src2, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_sqrt(IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_pow_Mat(IntPtr src, double power, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_exp_Mat(IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_log_Mat(IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float core_cubeRoot(float val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float core_fastAtan2(float y, float x); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_polarToCart(IntPtr magnitude, IntPtr angle, IntPtr x, IntPtr y, int angleInDegrees); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_cartToPolar(IntPtr x, IntPtr y, IntPtr magnitude, IntPtr angle, int angleInDegrees); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_phase(IntPtr x, IntPtr y, IntPtr angle, int angleInDegrees); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_magnitude_Mat(IntPtr x, IntPtr y, IntPtr magnitude); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_checkRange(IntPtr a, int quiet, out Point pos, double minVal, double maxVal); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_patchNaNs(IntPtr a, double val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_gemm(IntPtr src1, IntPtr src2, double alpha, IntPtr src3, double gamma, IntPtr dst, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_mulTransposed(IntPtr src, IntPtr dst, int aTa, IntPtr delta, double scale, int dtype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_transpose(IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_transform(IntPtr src, IntPtr dst, IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform(IntPtr src, IntPtr dst, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform_Mat(IntPtr src, IntPtr dst, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform_Point2f(IntPtr src, int srcLength, IntPtr dst, int dstLength, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform_Point2d(IntPtr src, int srcLength, IntPtr dst, int dstLength, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform_Point3f(IntPtr src, int srcLength, IntPtr dst, int dstLength, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_perspectiveTransform_Point3d(IntPtr src, int srcLength, IntPtr dst, int dstLength, IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_completeSymm(IntPtr mtx, int lowerToUpper); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_setIdentity(IntPtr mtx, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_determinant(IntPtr mtx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Scalar core_trace(IntPtr mtx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_invert(IntPtr src, IntPtr dst, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_solve(IntPtr src1, IntPtr src2, IntPtr dst, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_solveLP(IntPtr func, IntPtr constr, IntPtr z); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_sort(IntPtr src, IntPtr dst, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_sortIdx(IntPtr src, IntPtr dst, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_solveCubic(IntPtr coeffs, IntPtr roots); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_solvePoly(IntPtr coeffs, IntPtr roots, int maxIters); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_eigen(IntPtr src, IntPtr eigenvalues, IntPtr eigenvectors); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_calcCovarMatrix_Mat([MarshalAs(UnmanagedType.LPArray)] IntPtr[] samples, + int nsamples, IntPtr covar, IntPtr mean, int flags, int ctype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_calcCovarMatrix_InputArray(IntPtr samples, IntPtr covar, + IntPtr mean, int flags, int ctype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCACompute(IntPtr data, IntPtr mean, IntPtr eigenvectors, int maxComponents); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCAComputeVar(IntPtr data, IntPtr mean, IntPtr eigenvectors, double retainedVariance); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCAProject(IntPtr data, IntPtr mean, IntPtr eigenvectors, IntPtr result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCABackProject(IntPtr data, IntPtr mean, IntPtr eigenvectors, IntPtr result); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVDecomp(IntPtr src, IntPtr w, IntPtr u, IntPtr vt, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVBackSubst(IntPtr w, IntPtr u, IntPtr vt, IntPtr rhs, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_Mahalanobis(IntPtr v1, IntPtr v2, IntPtr icovar); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_dft(IntPtr src, IntPtr dst, int flags, int nonzeroRows); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_idft(IntPtr src, IntPtr dst, int flags, int nonzeroRows); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_dct(IntPtr src, IntPtr dst, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_idct(IntPtr src, IntPtr dst, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_mulSpectrums(IntPtr a, IntPtr b, IntPtr c, int flags, int conjB); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_getOptimalDFTSize(int vecsize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_kmeans(IntPtr data, int k, IntPtr bestLabels, + TermCriteria criteria, int attempts, int flags, IntPtr centers); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_theRNG(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randu_InputArray(IntPtr dst, IntPtr low, IntPtr high); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randu_Scalar(IntPtr dst, Scalar low, Scalar high); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randn_InputArray(IntPtr dst, IntPtr mean, IntPtr stddev); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randn_Scalar(IntPtr dst, Scalar mean, Scalar stddev); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randShuffle(IntPtr dst, double iterFactor, ref ulong rng); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_randShuffle(IntPtr dst, double iterFactor, IntPtr rng); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Algorithm.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Algorithm.cs new file mode 100644 index 0000000..73dc626 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Algorithm.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Algorithm_write(IntPtr obj, IntPtr fs); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Algorithm_read(IntPtr obj, IntPtr fn); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Algorithm_empty(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Algorithm_save(IntPtr obj, string filename); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Algorithm_getDefaultName( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int bufLength); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Classes.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Classes.cs new file mode 100644 index 0000000..e86635f --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Classes.cs @@ -0,0 +1,128 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + #region PCA + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_new2(IntPtr data, IntPtr mean, int flags, + int maxComponents); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_new3(IntPtr data, IntPtr mean, int flags, + double retainedVariance); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCA_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCA_operatorThis(IntPtr obj, IntPtr data, IntPtr mean, + int flags, int maxComponents); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCA_computeVar(IntPtr obj, IntPtr data, IntPtr mean, + int flags, double retainedVariance); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_project1(IntPtr obj, IntPtr vec); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCA_project2(IntPtr obj, IntPtr vec, IntPtr result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_backProject1(IntPtr obj, IntPtr vec); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_PCA_backProject2(IntPtr obj, IntPtr vec, IntPtr result); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_eigenvectors(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_eigenvalues(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_PCA_mean(IntPtr obj); + #endregion + + #region RNG + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_RNG_fill(ref ulong state, IntPtr mat, int distType, IntPtr a, IntPtr b, int saturateRange); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_RNG_gaussian(ref ulong state, double sigma); + #endregion + + #region SVD + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SVD_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SVD_new2(IntPtr src, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_operatorThis(IntPtr obj, IntPtr src, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_backSubst(IntPtr obj, IntPtr rhs, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_static_compute1(IntPtr src, IntPtr w, IntPtr u, IntPtr vt, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_static_compute2(IntPtr src, IntPtr w, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_static_backSubst(IntPtr w, IntPtr u, IntPtr vt, IntPtr rhs, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SVD_static_solveZ(IntPtr src, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SVD_u(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SVD_w(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SVD_vt(IntPtr obj); + #endregion + + #region LDA + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_new1(int numComponents); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_new2(IntPtr src, IntPtr labels, int numComponents); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_save_String(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string filename); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_load_String(IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string filename); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_save_FileStorage(IntPtr obj, IntPtr fs); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_load_FileStorage(IntPtr obj, IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_LDA_compute(IntPtr obj, IntPtr src, IntPtr labels); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_project(IntPtr obj, IntPtr src); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_reconstruct(IntPtr obj, IntPtr src); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_eigenvectors(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_eigenvalues(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_subspaceProject(IntPtr w, IntPtr mean, IntPtr src); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_LDA_subspaceReconstruct(IntPtr w, IntPtr mean, IntPtr src); + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNode.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNode.cs new file mode 100644 index 0000000..741ccf0 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNode.cs @@ -0,0 +1,182 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_new2(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_delete(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_operatorThis_byString( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string nodeName); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_operatorThis_byInt(IntPtr obj, int i); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_type(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_empty(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isNone(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isSeq(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isMap(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isInt(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isReal(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isString(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_isNamed(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_name( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int bufLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_size(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNode_toInt(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float core_FileNode_toFloat(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_FileNode_toDouble(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_toString( + IntPtr obj, StringBuilder buf, int bufLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_toMat(IntPtr obj, IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_begin(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNode_end(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_readRaw( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string fmt, IntPtr vec, IntPtr len); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeComment(IntPtr obj, + [MarshalAs(UnmanagedType.LPStr)] string comment, int append); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_int(IntPtr node, out int value, int defaultValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_float(IntPtr node, out float value, float defaultValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_double(IntPtr node, out double value, double defaultValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_String( + IntPtr node, [MarshalAs(UnmanagedType.LPStr)] StringBuilder value, int valueCapacity, + [MarshalAs(UnmanagedType.LPStr)] string? defaultValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_Mat(IntPtr node, IntPtr mat, IntPtr defaultMat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_SparseMat(IntPtr node, IntPtr mat, IntPtr defaultMat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_vectorOfKeyPoint(IntPtr node, IntPtr keypoints); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNode_read_vectorOfDMatch(IntPtr node, IntPtr matches); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Range core_FileNode_read_Range(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern KeyPoint core_FileNode_read_KeyPoint(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern DMatch core_FileNode_read_DMatch(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point core_FileNode_read_Point2i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point2f core_FileNode_read_Point2f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point2d core_FileNode_read_Point2d(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point3i core_FileNode_read_Point3i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point3f core_FileNode_read_Point3f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point3d core_FileNode_read_Point3d(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size core_FileNode_read_Size2i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size2f core_FileNode_read_Size2f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size2d core_FileNode_read_Size2d(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect core_FileNode_read_Rect2i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect2f core_FileNode_read_Rect2f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect2d core_FileNode_read_Rect2d(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Scalar core_FileNode_read_Scalar(IntPtr node); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2i core_FileNode_read_Vec2i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3i core_FileNode_read_Vec3i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4i core_FileNode_read_Vec4i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6i core_FileNode_read_Vec6i(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2d core_FileNode_read_Vec2d(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3d core_FileNode_read_Vec3d(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4d core_FileNode_read_Vec4d(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6d core_FileNode_read_Vec6d(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2f core_FileNode_read_Vec2f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3f core_FileNode_read_Vec3f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4f core_FileNode_read_Vec4f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6f core_FileNode_read_Vec6f(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2b core_FileNode_read_Vec2b(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3b core_FileNode_read_Vec3b(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4b core_FileNode_read_Vec4b(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6b core_FileNode_read_Vec6b(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2s core_FileNode_read_Vec2s(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3s core_FileNode_read_Vec3s(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4s core_FileNode_read_Vec4s(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6s core_FileNode_read_Vec6s(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2w core_FileNode_read_Vec2w(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec3w core_FileNode_read_Vec3w(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec4w core_FileNode_read_Vec4w(IntPtr node); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec6w core_FileNode_read_Vec6w(IntPtr node); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNodeIterator.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNodeIterator.cs new file mode 100644 index 0000000..1d78219 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileNodeIterator.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_new1(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_new2(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileNodeIterator_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_operatorAsterisk(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNodeIterator_operatorIncrement(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNodeIterator_operatorPlusEqual(IntPtr obj, int ofs); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_readRaw( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string fmt, IntPtr vec, IntPtr maxCount); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_readRaw( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string fmt, byte[] vec, IntPtr maxCount); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNodeIterator_operatorEqual(IntPtr it1, IntPtr it2); + + //[DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + //public static extern int core_FileNodeIterator_operatorNotEqual(IntPtr it1, IntPtr it2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileNodeIterator_operatorMinus(IntPtr it1, IntPtr it2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileNodeIterator_operatorLessThan(IntPtr it1, IntPtr it2); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileStorage.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileStorage.cs new file mode 100644 index 0000000..932b92e --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_FileStorage.cs @@ -0,0 +1,246 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileStorage_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileStorage_new2( + [MarshalAs(UnmanagedType.LPStr)] string source, + int flags, [MarshalAs(UnmanagedType.LPStr)] string? encoding); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileStorage_open( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string filename, + int flags, [MarshalAs(UnmanagedType.LPStr)] string? encoding); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileStorage_isOpened(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_release(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_releaseAndGetString_stdString( + IntPtr obj, IntPtr outString); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileStorage_getFirstTopLevelNode(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileStorage_root(IntPtr obj, int streamIdx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_FileStorage_indexer( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string nodeName); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeRaw( + IntPtr obj, [MarshalAs(UnmanagedType.LPStr)] string fmt, IntPtr vec, IntPtr len); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_getDefaultObjectName( + [MarshalAs(UnmanagedType.LPStr)] string filename, + [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, int bufLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe sbyte* core_FileStorage_elname(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_startWriteStruct( + IntPtr obj, + [MarshalAs(UnmanagedType.LPStr)] string name, + int flags, + [MarshalAs(UnmanagedType.LPStr)] string typeName); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_endWriteStruct(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_FileStorage_state(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_int( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, int value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_float( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, float value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_double( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, double value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_String( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_Mat( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_SparseMat( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_vectorOfKeyPoint( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_write_vectorOfDMatch( + IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr value); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeScalar_int(IntPtr fs, int value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeScalar_float(IntPtr fs, float value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeScalar_double(IntPtr fs, double value); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_writeScalar_String(IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string value); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_String(IntPtr fs, [MarshalAs(UnmanagedType.LPStr)] string val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_int(IntPtr fs, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_float(IntPtr fs, float val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_double(IntPtr fs, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Mat(IntPtr fs, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_SparseMat(IntPtr fs, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Range(IntPtr fs, Range val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_KeyPoint(IntPtr fs, KeyPoint val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_DMatch(IntPtr fs, DMatch val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_vectorOfKeyPoint(IntPtr fs, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_vectorOfDMatch(IntPtr fs, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point2i(IntPtr fs, Point val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point2f(IntPtr fs, Point2f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point2d(IntPtr fs, Point2d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point3i(IntPtr fs, Point3i val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point3f(IntPtr fs, Point3f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Point3d(IntPtr fs, Point3d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Size2i(IntPtr fs, Size val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Size2f(IntPtr fs, Size2f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Size2d(IntPtr fs, Size2d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Rect2i(IntPtr fs, Rect val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Rect2f(IntPtr fs, Rect2f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Rect2d(IntPtr fs, Rect2d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Scalar(IntPtr fs, Scalar val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2i(IntPtr fs, Vec2i val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3i(IntPtr fs, Vec3i val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4i(IntPtr fs, Vec4i val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6i(IntPtr fs, Vec6i val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2d(IntPtr fs, Vec2d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3d(IntPtr fs, Vec3d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4d(IntPtr fs, Vec4d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6d(IntPtr fs, Vec6d val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2f(IntPtr fs, Vec2f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3f(IntPtr fs, Vec3f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4f(IntPtr fs, Vec4f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6f(IntPtr fs, Vec6f val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2b(IntPtr fs, Vec2b val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3b(IntPtr fs, Vec3b val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4b(IntPtr fs, Vec4b val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6b(IntPtr fs, Vec6b val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2s(IntPtr fs, Vec2s val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3s(IntPtr fs, Vec3s val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4s(IntPtr fs, Vec4s val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6s(IntPtr fs, Vec6s val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec2w(IntPtr fs, Vec2w val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec3w(IntPtr fs, Vec3w val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec4w(IntPtr fs, Vec4w val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_FileStorage_shift_Vec6w(IntPtr fs, Vec6w val); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_InputArray.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_InputArray.cs new file mode 100644 index 0000000..ae66fc8 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_InputArray.cs @@ -0,0 +1,101 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byMat(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byMatExpr(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byScalar(Scalar val, out IntPtr handle); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byDouble(IntPtr valPointer); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byGpuMat(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_new_byVectorOfMat(IntPtr vector); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_delete(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_delete_withScalar(IntPtr ia, IntPtr handle); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_getMat(IntPtr ia, int idx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_getMat_(IntPtr ia, int idx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_getUMat(IntPtr ia, int idx); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_getMatVector(IntPtr ia, IntPtr mv); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_getUMatVector(IntPtr ia, IntPtr umv); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_getGpuMatVector(IntPtr ia, IntPtr gpumv); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_getGpuMat(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_getFlags(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_getObj(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size core_InputArray_getSz(IntPtr ia); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_kind(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_dims(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_cols(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_rows(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size core_InputArray_size(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_sizend(IntPtr ia, int[] sz, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_sameSize(IntPtr self, IntPtr target); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_total(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_type(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_depth(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_channels(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isContinuous(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isSubmatrix(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_empty(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_copyTo1(IntPtr ia, IntPtr arr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_InputArray_copyTo2(IntPtr ia, IntPtr arr, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_offset(IntPtr ia, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_InputArray_step(IntPtr ia, int i); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isMat(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isUMat(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isMatVector(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isUMatVector(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isMatx(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isVector(IntPtr ia); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_InputArray_isGpuMatVector(IntPtr ia); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Mat.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Mat.cs new file mode 100644 index 0000000..3b07586 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_Mat.cs @@ -0,0 +1,623 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_sizeof(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new2(int rows, int cols, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new3(int rows, int cols, int type, Scalar scalar); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new4(IntPtr mat, Range rowRange, Range colRange); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new5(IntPtr mat, Range rowRange); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new6(IntPtr mat, [MarshalAs(UnmanagedType.LPArray)] Range[] rowRange); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new7(IntPtr mat, Rect roi); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new8(int rows, int cols, int type, IntPtr data, IntPtr step); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new9(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sizes, + int type, IntPtr data, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] steps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new9(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sizes, + int type, IntPtr data, IntPtr steps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new10(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sizes, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new11(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sizes, int type, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new12(IntPtr mat); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new_FromIplImage(IntPtr img, int copyData); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_new_FromCvMat(IntPtr mat, int copyData); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_release(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_delete(IntPtr mat); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_adjustROI(IntPtr nativeObj, int dtop, int dbottom, int dleft, int dright); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_assignTo1(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_assignTo2(IntPtr self, IntPtr m, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_channels(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_checkVector1(IntPtr self, int elemChannels); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_checkVector2(IntPtr self, int elemChannels, int depth); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_checkVector3(IntPtr self, int elemChannels, int depth, int requireContinuous); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_clone(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_col_toMat(IntPtr self, int x); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_col_toMatExpr(IntPtr self, int x); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_cols(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_colRange_toMat(IntPtr self, int startCol, int endCol); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_colRange_toMatExpr(IntPtr self, int startCol, int endCol); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_dims(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_convertTo(IntPtr self, IntPtr m, int rtype, double alpha, double beta); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_copyTo(IntPtr self, IntPtr m, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_create1(IntPtr self, int rows, int cols, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_create2(IntPtr self, int ndims, + [MarshalAs(UnmanagedType.LPArray)] int[] sizes, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_cross(IntPtr self, IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe byte* core_Mat_data(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_datastart(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_dataend(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_datalimit(IntPtr self); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_depth(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_diag1(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_diag2(IntPtr self, int d); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_diag3(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_Mat_dot(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_elemSize(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_elemSize1(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_empty(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_eye(int rows, int cols, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_inv1(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_inv2(IntPtr self, int method); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_isContinuous(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_isSubmatrix(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_locateROI(IntPtr self, out Size wholeSize, out Point ofs); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_mul1(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_mul2(IntPtr self, IntPtr m, double scale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ones1(int rows, int cols, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ones2(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sz, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_reshape1(IntPtr self, int cn); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_reshape2(IntPtr self, int cn, int rows); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_reshape3(IntPtr self, int cn, int newndims, [MarshalAs(UnmanagedType.LPArray)] int[] newsz); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_rows(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_row_toMat(IntPtr self, int y); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_row_toMatExpr(IntPtr self, int y); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_rowRange_toMat(IntPtr self, int startRow, int endRow); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_rowRange_toMatExpr(IntPtr self, int startRow, int endRow); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_setTo_Scalar(IntPtr self, Scalar value, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_setTo_InputArray(IntPtr self, IntPtr value, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size core_Mat_size(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_sizeAt(IntPtr self, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_step11(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_step12(IntPtr self, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern long core_Mat_step(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_stepAt(IntPtr self, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_subMat1(IntPtr self, int rowStart, int rowEnd, int colStart, int colEnd); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_subMat2(IntPtr self, int nRanges, Range[] ranges); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_t(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_Mat_total(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_Mat_type(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_zeros1(int rows, int cols, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_zeros2(int ndims, [MarshalAs(UnmanagedType.LPArray)] int[] sz, int type); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ptr1d(IntPtr self, int i0); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ptr2d(IntPtr self, int i0, int i1); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ptr3d(IntPtr self, int i0, int i1, int i2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_ptrnd(IntPtr self, [MarshalAs(UnmanagedType.LPArray)] int[] idx); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_assignment_FromMat(IntPtr self, IntPtr newMat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_assignment_FromMatExpr(IntPtr self, IntPtr newMatExpr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_assignment_FromScalar(IntPtr self, Scalar scalar); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_IplImage(IntPtr self, IntPtr outImage); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_IplImage_alignment(IntPtr self, out IntPtr outImage); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_CvMat(IntPtr self, IntPtr outMat); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorUnaryMinus(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAdd_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAdd_MatScalar(IntPtr a, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAdd_ScalarMat(Scalar s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorMinus_Mat(IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorSubtract_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorSubtract_MatScalar(IntPtr a, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorSubtract_ScalarMat(Scalar s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorMultiply_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorMultiply_MatDouble(IntPtr a, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorMultiply_DoubleMat(double s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorDivide_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorDivide_MatDouble(IntPtr a, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorDivide_DoubleMat(double s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAnd_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAnd_MatDouble(IntPtr a, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorAnd_DoubleMat(double s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorOr_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorOr_MatDouble(IntPtr a, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorOr_DoubleMat(double s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorXor_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorXor_MatDouble(IntPtr a, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorXor_DoubleMat(double s, IntPtr a); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorNot(IntPtr a); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLT_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLT_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLT_MatDouble(IntPtr a, double b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLE_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLE_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorLE_MatDouble(IntPtr a, double b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGT_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGT_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGT_MatDouble(IntPtr a, double b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGE_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGE_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorGE_MatDouble(IntPtr a, double b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorEQ_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorEQ_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorEQ_MatDouble(IntPtr a, double b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorNE_MatMat(IntPtr a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorNE_DoubleMat(double a, IntPtr b); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_Mat_operatorNE_MatDouble(IntPtr a, double b); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_abs_Mat(IntPtr e); + + #region nSet + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetB(IntPtr obj, int row, int col, + byte* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetS(IntPtr obj, int row, int col, + short* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetS(IntPtr obj, int row, int col, + ushort* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetI(IntPtr obj, int row, int col, + int* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetF(IntPtr obj, int row, int col, + float* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetD(IntPtr obj, int row, int col, + double* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetVec3b(IntPtr obj, int row, int col, + Vec3b* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetVec3d(IntPtr obj, int row, int col, + Vec3d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetVec4f(IntPtr obj, int row, int col, + Vec4f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetVec6f(IntPtr obj, int row, int col, + Vec6f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetVec4i(IntPtr obj, int row, int col, + Vec4i* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint(IntPtr obj, int row, int col, + Point* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint2f(IntPtr obj, int row, int col, + Point2f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint2d(IntPtr obj, int row, int col, + Point2d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint3i(IntPtr obj, int row, int col, + Point3i* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint3f(IntPtr obj, int row, int col, + Point3f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetPoint3d(IntPtr obj, int row, int col, + Point3d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nSetRect(IntPtr obj, int row, int col, + Rect* vals, int valsLength); + + #endregion + + #region nGet + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetB(IntPtr obj, int row, int col, + byte* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetS(IntPtr obj, int row, int col, + short* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetS(IntPtr obj, int row, int col, + ushort* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetI(IntPtr obj, int row, int col, + int* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetF(IntPtr obj, int row, int col, + float* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetD(IntPtr obj, int row, int col, + double* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetVec3b(IntPtr obj, int row, int col, + Vec3b* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetVec3d(IntPtr obj, int row, int col, + Vec3d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetVec4f(IntPtr obj, int row, int col, + Vec4f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetVec6f(IntPtr obj, int row, int col, + Vec6f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetVec4i(IntPtr obj, int row, int col, + Vec4i* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint(IntPtr obj, int row, int col, + Point* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint2f(IntPtr obj, int row, int col, + Point2f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint2d(IntPtr obj, int row, int col, + Point2d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint3i(IntPtr obj, int row, int col, + Point3i* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint3f(IntPtr obj, int row, int col, + Point3f* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetPoint3d(IntPtr obj, int row, int col, + Point3d* vals, int valsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern unsafe int core_Mat_nGetRect(IntPtr obj, int row, int col, + Rect* vals, int valsLength); + + #endregion + + #region push_back + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Mat(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_char(IntPtr self, sbyte v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_uchar(IntPtr self, byte v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_short(IntPtr self, short v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_ushort(IntPtr self, ushort v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_int(IntPtr self, int v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_float(IntPtr self, float v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_double(IntPtr self, double v); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2b(IntPtr self, Vec2b v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3b(IntPtr self, Vec3b v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4b(IntPtr self, Vec4b v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6b(IntPtr self, Vec6b v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2s(IntPtr self, Vec2s v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3s(IntPtr self, Vec3s v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4s(IntPtr self, Vec4s v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6s(IntPtr self, Vec6s v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2w(IntPtr self, Vec2w v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3w(IntPtr self, Vec3w v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4w(IntPtr self, Vec4w v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6w(IntPtr self, Vec6w v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2i(IntPtr self, Vec2i v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3i(IntPtr self, Vec3i v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4i(IntPtr self, Vec4i v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6i(IntPtr self, Vec6i v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2f(IntPtr self, Vec2f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3f(IntPtr self, Vec3f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4f(IntPtr self, Vec4f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6f(IntPtr self, Vec6f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec2d(IntPtr self, Vec2d v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec3d(IntPtr self, Vec3d v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec4d(IntPtr self, Vec4d v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Vec6d(IntPtr self, Vec6d v); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point(IntPtr self, Point v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point2f(IntPtr self, Point2f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point2d(IntPtr self, Point2d v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point3i(IntPtr self, Point3i v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point3f(IntPtr self, Point3f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Point3d(IntPtr self, Point3d v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Size(IntPtr self, Size v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Size2f(IntPtr self, Size2f v); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_push_back_Rect(IntPtr self, Rect v); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_reserve(IntPtr obj, IntPtr sz); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_resize1(IntPtr obj, IntPtr sz); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_resize2(IntPtr obj, IntPtr sz, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_pop_back(IntPtr obj, IntPtr nelems); + #endregion + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_uchar(IntPtr m, MatForeachFunctionByte proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec2b(IntPtr m, MatForeachFunctionVec2b proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec3b(IntPtr m, MatForeachFunctionVec3b proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec4b(IntPtr m, MatForeachFunctionVec4b proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec6b(IntPtr m, MatForeachFunctionVec6b proc); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_short(IntPtr m, MatForeachFunctionInt16 proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec2s(IntPtr m, MatForeachFunctionVec2s proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec3s(IntPtr m, MatForeachFunctionVec3s proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec4s(IntPtr m, MatForeachFunctionVec4s proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec6s(IntPtr m, MatForeachFunctionVec6s proc); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_int(IntPtr m, MatForeachFunctionInt32 proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec2i(IntPtr m, MatForeachFunctionVec2i proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec3i(IntPtr m, MatForeachFunctionVec3i proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec4i(IntPtr m, MatForeachFunctionVec4i proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec6i(IntPtr m, MatForeachFunctionVec6i proc); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_float(IntPtr m, MatForeachFunctionFloat proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec2f(IntPtr m, MatForeachFunctionVec2f proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec3f(IntPtr m, MatForeachFunctionVec3f proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec4f(IntPtr m, MatForeachFunctionVec4f proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec6f(IntPtr m, MatForeachFunctionVec6f proc); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_double(IntPtr m, MatForeachFunctionDouble proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec2d(IntPtr m, MatForeachFunctionVec2d proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec3d(IntPtr m, MatForeachFunctionVec3d proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec4d(IntPtr m, MatForeachFunctionVec4d proc); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_Mat_forEach_Vec6d(IntPtr m, MatForeachFunctionVec6d proc); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_MatExpr.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_MatExpr.cs new file mode 100644 index 0000000..71efcb7 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_MatExpr.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_new2(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_MatExpr_delete(IntPtr expr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_toMat(IntPtr expr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorUnaryMinus_MatExpr(IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorUnaryNot_MatExpr(IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorAdd_MatExprMat(IntPtr e, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorAdd_MatMatExpr(IntPtr m, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorAdd_MatExprScalar(IntPtr e, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorAdd_ScalarMatExpr(Scalar s, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorAdd_MatExprMatExpr(IntPtr e1, IntPtr e2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorSubtract_MatExprMat(IntPtr e, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorSubtract_MatMatExpr(IntPtr m, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorSubtract_MatExprScalar(IntPtr e, Scalar s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorSubtract_ScalarMatExpr(Scalar s, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorSubtract_MatExprMatExpr(IntPtr e1, IntPtr e2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorMultiply_MatExprMat(IntPtr e, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorMultiply_MatMatExpr(IntPtr m, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorMultiply_MatExprDouble(IntPtr e, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorMultiply_DoubleMatExpr(double s, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorMultiply_MatExprMatExpr(IntPtr e1, IntPtr e2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorDivide_MatExprMat(IntPtr e, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorDivide_MatMatExpr(IntPtr m, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorDivide_MatExprDouble(IntPtr e, double s); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorDivide_DoubleMatExpr(double s, IntPtr e); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_operatorDivide_MatExprMatExpr(IntPtr e1, IntPtr e2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_row(IntPtr self, int y); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_col(IntPtr self, int x); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_diag1(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_diag2(IntPtr self, int d); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_submat(IntPtr self, int rowStart, int rowEnd, int colStart, int colEnd); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_cross(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double core_MatExpr_dot(IntPtr self, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_t(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_inv1(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_inv2(IntPtr self, int method); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_mul_toMatExpr(IntPtr self, IntPtr e, double scale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_MatExpr_mul_toMat(IntPtr self, IntPtr m, double scale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size core_MatExpr_size(IntPtr self); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_MatExpr_type(IntPtr self); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_abs_MatExpr(IntPtr e); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_OutputArray.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_OutputArray.cs new file mode 100644 index 0000000..0e691e8 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_OutputArray.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_OutputArray_new_byMat(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_OutputArray_new_byGpuMat(IntPtr mat); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_OutputArray_new_byScalar(Scalar val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_OutputArray_new_byVectorOfMat(IntPtr vector); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_OutputArray_delete(IntPtr oa); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_OutputArray_getMat(IntPtr oa); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Scalar core_OutputArray_getScalar(IntPtr oa); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_OutputArray_getVectorOfMat(IntPtr oa, IntPtr vector); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_SparseMat.cs b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_SparseMat.cs new file mode 100644 index 0000000..a1c36c6 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/core/NativeMethods_core_SparseMat.cs @@ -0,0 +1,107 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ulong core_SparseMat_sizeof(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_new2(int dims, int[] sizes, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_new3(IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_operatorAssign_SparseMat(IntPtr obj, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_operatorAssign_Mat(IntPtr obj, IntPtr m); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_clone(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_copyTo_SparseMat(IntPtr obj, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_copyTo_Mat(IntPtr obj, IntPtr m); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_convertTo_SparseMat(IntPtr obj, IntPtr m, + int rtype, double alpha); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_convertTo_Mat(IntPtr obj, IntPtr m, int rtype, + double alpha, double beta); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_assignTo(IntPtr obj, IntPtr m, int type); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_create(IntPtr obj, int dims, int[] sizes, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_clear(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_addref(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void core_SparseMat_release(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_elemSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_elemSize1(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_type(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_depth(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_channels(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_size1(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_size2(IntPtr obj, int i); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int core_SparseMat_dims(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_nzcount(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_hash_1d(IntPtr obj, int i0); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_hash_2d(IntPtr obj, int i0, int i1); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_hash_3d(IntPtr obj, int i0, int i1, int i2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_hash_nd(IntPtr obj, int[] idx); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_1d(IntPtr obj, int i0, + int createMissing, ref ulong hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_1d(IntPtr obj, int i0, + int createMissing, IntPtr hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_2d(IntPtr obj, int i0, int i1, + int createMissing, ref ulong hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_2d(IntPtr obj, int i0, int i1, + int createMissing, IntPtr hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_3d(IntPtr obj, int i0, int i1, int i2, + int createMissing, ref ulong hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_3d(IntPtr obj, int i0, int i1, int i2, + int createMissing, IntPtr hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_nd(IntPtr obj, int[] idx, + int createMissing, ref ulong hashval); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr core_SparseMat_ptr_nd(IntPtr obj, int[] idx, + int createMissing, IntPtr hashval); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn.cs b/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn.cs new file mode 100644 index 0000000..64f616a --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromDarknet( + [MarshalAs(UnmanagedType.LPStr)] string cfgFile, [MarshalAs(UnmanagedType.LPStr)] string? darknetModel); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromCaffe( + [MarshalAs(UnmanagedType.LPStr)] string prototxt, [MarshalAs(UnmanagedType.LPStr)] string? caffeModel); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromTensorflow( + [MarshalAs(UnmanagedType.LPStr)] string model, [MarshalAs(UnmanagedType.LPStr)] string? config); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromTorch([MarshalAs(UnmanagedType.LPStr)] string model, int isBinary); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNet( + [MarshalAs(UnmanagedType.LPStr)] string model, [MarshalAs(UnmanagedType.LPStr)] string config, [MarshalAs(UnmanagedType.LPStr)] string framework); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readTorchBlob([MarshalAs(UnmanagedType.LPStr)] string filename, int isBinary); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromModelOptimizer([MarshalAs(UnmanagedType.LPStr)] string xml, [MarshalAs(UnmanagedType.LPStr)] string bin); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readNetFromONNX([MarshalAs(UnmanagedType.LPStr)] string onnxFile); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_readTensorFromONNX([MarshalAs(UnmanagedType.LPStr)] string path); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_blobFromImage( + IntPtr image, double scalefactor, Size size, Scalar mean, int swapRB, int crop); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_blobFromImages( + IntPtr[] images, int imagesLength, double scalefactor, Size size, Scalar mean, int swapRB, int crop); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_shrinkCaffeModel( + [MarshalAs(UnmanagedType.LPStr)] string src, [MarshalAs(UnmanagedType.LPStr)] string dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_writeTextGraph([MarshalAs(UnmanagedType.LPStr)] string model, [MarshalAs(UnmanagedType.LPStr)] string output); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_NMSBoxes_Rect( + IntPtr bboxes, IntPtr scores, + float score_threshold, float nms_threshold, + IntPtr indices, float eta, int top_k); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_NMSBoxes_Rect2d( + IntPtr bboxes, IntPtr scores, + float score_threshold, float nms_threshold, + IntPtr indices, float eta, int top_k); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_NMSBoxes_RotatedRect( + IntPtr bboxes, IntPtr scores, + float score_threshold, float nms_threshold, + IntPtr indices, float eta, int top_k); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_resetMyriadDevice(); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn_Net.cs b/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn_Net.cs new file mode 100644 index 0000000..ae006eb --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/dnn/NativeMethods_dnn_Net.cs @@ -0,0 +1,72 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + // ReSharper disable InconsistentNaming + + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr dnn_Net_new(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void dnn_Net_delete(IntPtr net); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int dnn_Net_empty(IntPtr net); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int dnn_Net_getLayerId(IntPtr net, [MarshalAs(UnmanagedType.LPStr)] string layer); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void dnn_Net_getLayerNames(IntPtr net, IntPtr outVec); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_connect1( + IntPtr net, [MarshalAs(UnmanagedType.LPStr)] string outPin, [MarshalAs(UnmanagedType.LPStr)] string inpPin); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void dnn_Net_connect2(IntPtr net, int outLayerId, int outNum, int inpLayerId, int inpNum); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_setInputsNames(IntPtr net, string[] inputBlobNames, int inputBlobNamesLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern IntPtr dnn_Net_forward1(IntPtr net, [MarshalAs(UnmanagedType.LPStr)] string? outputName); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_forward2( + IntPtr net, IntPtr[] outputBlobs, int outputBlobsLength, [MarshalAs(UnmanagedType.LPStr)] string? outputName); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_forward3( + IntPtr net, IntPtr[] outputBlobs, int outputBlobsLength, string[] outBlobNames, int outBlobNamesLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_setHalideScheduler(IntPtr net, [MarshalAs(UnmanagedType.LPStr)] string scheduler); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_setPreferableBackend(IntPtr net, int backendId); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_setPreferableTarget(IntPtr net, int targetId); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_setInput(IntPtr net, IntPtr blob, [MarshalAs(UnmanagedType.LPStr)] string name); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_getUnconnectedOutLayers(IntPtr net, IntPtr result); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_getUnconnectedOutLayersNames(IntPtr net, IntPtr result); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern void dnn_Net_enableFusion(IntPtr net, int fusion); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true)] + public static extern long dnn_Net_getPerfProfile(IntPtr net, IntPtr timings); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d.cs new file mode 100644 index 0000000..f632ac1 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d.cs @@ -0,0 +1,65 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + // DenseFeatureDetector + /* + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_DenseFeatureDetector_new( + float initFeatureScale, int featureScaleLevels, float featureScaleMul, + int initXyStep, int initImgBound, int varyXyStepWithScale, int varyImgBoundWithScale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DenseFeatureDetector_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_DenseFeatureDetector_info(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_DenseFeatureDetector_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_DenseFeatureDetector_delete(IntPtr ptr); + */ + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_drawKeypoints(IntPtr image, KeyPoint[] keypoints, int keypointsLength, + IntPtr outImage, Scalar color, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_drawMatches1(IntPtr img1, KeyPoint[] keypoints1, int keypoints1Length, + IntPtr img2, KeyPoint[] keypoints2, int keypoints2Length, + DMatch[] matches1to2, int matches1to2Length, IntPtr outImg, + Scalar matchColor, Scalar singlePointColor, + byte[]? matchesMask, int matchesMaskLength, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_drawMatches2(IntPtr img1, KeyPoint[] keypoints1, int keypoints1Length, + IntPtr img2, KeyPoint[] keypoints2, int keypoints2Length, + IntPtr[] matches1to2, int matches1to2Size1, int[] matches1to2Size2, + IntPtr outImg, Scalar matchColor, Scalar singlePointColor, + IntPtr[]? matchesMask, int matchesMaskSize1, int[]? matchesMaskSize2, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_evaluateFeatureDetector( + IntPtr img1, IntPtr img2, IntPtr H1to2, + IntPtr keypoints1, IntPtr keypoints2, + out float repeatability, out int correspCount); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_computeRecallPrecisionCurve( + IntPtr[] matches1to2, int matches1to2Size1, int[] matches1to2Size2, + IntPtr[] correctMatches1to2Mask, int correctMatches1to2MaskSize1, int[] correctMatches1to2MaskSize2, + IntPtr recallPrecisionCurve); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float features2d_getRecall( + Point2f[] recallPrecisionCurve, int recallPrecisionCurveSize, float l_precision); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_getNearestPoint( + Point2f[] recallPrecisionCurve, int recallPrecisionCurveSize, float l_precision); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AKAZE.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AKAZE.cs new file mode 100644 index 0000000..a29d606 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AKAZE.cs @@ -0,0 +1,58 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_AKAZE_create( + int descriptor_type, int descriptor_size, int descriptor_channels, + float threshold, int nOctaves, int nOctaveLayers, int diffusivity); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_AKAZE_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_AKAZE_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setDescriptorType(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getDescriptorType(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setDescriptorSize(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getDescriptorSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setDescriptorChannels(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getDescriptorChannels(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setThreshold(IntPtr obj, double val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_AKAZE_getThreshold(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setNOctaves(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getNOctaves(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setNOctaveLayers(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getNOctaveLayers(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AKAZE_setDiffusivity(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AKAZE_getDiffusivity(IntPtr obj); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AgastFeatureDetector.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AgastFeatureDetector.cs new file mode 100644 index 0000000..cae3cfe --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_AgastFeatureDetector.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AGAST(IntPtr image, IntPtr keypoints, + int threshold, int nonmaxSuppression, int type); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_AgastFeatureDetector_create( + int threshold, int nonmaxSuppression, int type); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_AgastFeatureDetector_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_AgastFeatureDetector_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AgastFeatureDetector_setThreshold(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AgastFeatureDetector_getThreshold(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AgastFeatureDetector_setNonmaxSuppression(IntPtr obj,int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AgastFeatureDetector_getNonmaxSuppression(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_AgastFeatureDetector_setType(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_AgastFeatureDetector_getType(IntPtr obj); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BOW.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BOW.cs new file mode 100644 index 0000000..120dcfd --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BOW.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + // BOWTrainer + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWTrainer_add(IntPtr obj, IntPtr descriptors); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWTrainer_getDescriptors(IntPtr obj, IntPtr descriptors); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_BOWTrainer_descriptorsCount(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWTrainer_clear(IntPtr obj); + + + // BOWKMeansTrainer + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWKMeansTrainer_new( + int clusterCount, TermCriteria termcrit, int attempts, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWKMeansTrainer_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWKMeansTrainer_cluster1(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWKMeansTrainer_cluster2(IntPtr obj, IntPtr descriptors); + + + // BOWImgDescriptorExtractor + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWImgDescriptorExtractor_new1_Ptr(IntPtr dextractor, IntPtr dmatcher); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWImgDescriptorExtractor_new2_Ptr(IntPtr dmatcher); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWImgDescriptorExtractor_new1_RawPtr(IntPtr dextractor, IntPtr dmatcher); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWImgDescriptorExtractor_new2_RawPtr(IntPtr dmatcher); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWImgDescriptorExtractor_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWImgDescriptorExtractor_setVocabulary(IntPtr obj, IntPtr vocabulary); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BOWImgDescriptorExtractor_getVocabulary(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWImgDescriptorExtractor_compute11( + IntPtr obj, IntPtr image, IntPtr keypoints, IntPtr imgDescriptor, + IntPtr pointIdxsOfClusters, IntPtr descriptors); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWImgDescriptorExtractor_compute12( + IntPtr obj, IntPtr keypointDescriptors, + IntPtr imgDescriptor, IntPtr pointIdxsOfClusters); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BOWImgDescriptorExtractor_compute2( + IntPtr obj, IntPtr image, IntPtr keypoints, IntPtr imgDescriptor); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_BOWImgDescriptorExtractor_descriptorSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_BOWImgDescriptorExtractor_descriptorType(IntPtr obj); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BRISK.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BRISK.cs new file mode 100644 index 0000000..e86c85c --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_BRISK.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + // BRISK + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BRISK_create1(int thresh, int octaves, float patternScale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BRISK_create2( + float[] radiusList, int radiusListLength, int[] numberList, int numberListLength, + float dMax, float dMin, + int[]? indexChange, int indexChangeLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_BRISK_delete(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_BRISK_get(IntPtr ptr); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorExtractor.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorExtractor.cs new file mode 100644 index 0000000..84d4367 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorExtractor.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // DescriptorExtractor + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorExtractor_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorExtractor_compute1( + IntPtr obj, IntPtr image, IntPtr keypoint, IntPtr descriptors); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorExtractor_compute2( + IntPtr obj, IntPtr[] images, int imagesSize, IntPtr keypoints, + IntPtr[] descriptors, int descriptorsSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_DescriptorExtractor_descriptorSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_DescriptorExtractor_descriptorType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_DescriptorExtractor_empty(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_DescriptorExtractor_create( + [MarshalAs(UnmanagedType.LPStr)] string descriptorExtractorType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_DescriptorExtractor_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_DescriptorExtractor_delete(IntPtr ptr); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorMatcher.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorMatcher.cs new file mode 100644 index 0000000..47ddbf8 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_DescriptorMatcher.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // DescriptorMatcher + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_add(IntPtr obj, IntPtr[] descriptors, + int descriptorLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_getTrainDescriptors(IntPtr obj, + IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_clear(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_DescriptorMatcher_empty(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_DescriptorMatcher_isMaskSupported(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_train(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_match1(IntPtr obj, + IntPtr queryDescriptors, IntPtr trainDescriptors, IntPtr matches, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_knnMatch1(IntPtr obj, + IntPtr queryDescriptors, IntPtr trainDescriptors, IntPtr matches, int k, + IntPtr mask, int compactResult); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_radiusMatch1(IntPtr obj, + IntPtr queryDescriptors,IntPtr trainDescriptors, IntPtr matches, float maxDistance, + IntPtr mask, int compactResult); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_match2( + IntPtr obj, IntPtr queryDescriptors, IntPtr matches, + IntPtr[] masks, int masksSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_knnMatch2( + IntPtr obj, IntPtr queryDescriptors, IntPtr matches, + int k, IntPtr[] masks, int masksSize, int compactResult); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_DescriptorMatcher_radiusMatch2( + IntPtr obj, IntPtr queryDescriptors, IntPtr matches, + float maxDistance, IntPtr[] masks, int masksSize, int compactResult); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern IntPtr features2d_DescriptorMatcher_create([MarshalAs(UnmanagedType.LPStr)] string descriptorMatcherType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_DescriptorMatcher_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_DescriptorMatcher_delete(IntPtr ptr); + + // BFMatcher + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_BFMatcher_new(int normType, int crossCheck); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_BFMatcher_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_BFMatcher_isMaskSupported(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_BFMatcher_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_BFMatcher_delete(IntPtr ptr); + + // FlannBasedMatcher + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_FlannBasedMatcher_new( + IntPtr indexParams, IntPtr searchParams); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FlannBasedMatcher_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FlannBasedMatcher_add( + IntPtr obj, IntPtr[] descriptors, int descriptorsSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FlannBasedMatcher_clear(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FlannBasedMatcher_train(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_FlannBasedMatcher_isMaskSupported(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_FlannBasedMatcher_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_FlannBasedMatcher_delete(IntPtr ptr); + + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_FastFeatureDetector.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_FastFeatureDetector.cs new file mode 100644 index 0000000..22e832e --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_FastFeatureDetector.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FAST1(IntPtr image, IntPtr keypoints, int threshold, int nonmaxSupression); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FAST2(IntPtr image, IntPtr keypoints, int threshold, int nonmaxSupression, int type); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_FastFeatureDetector_create(int threshold, int nonmaxSuppression); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_FastFeatureDetector_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_FastFeatureDetector_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FastFeatureDetector_setThreshold(IntPtr obj, int threshold); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_FastFeatureDetector_getThreshold(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FastFeatureDetector_setNonmaxSuppression(IntPtr obj, int f); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_FastFeatureDetector_getNonmaxSuppression(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_FastFeatureDetector_setType(IntPtr obj, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_FastFeatureDetector_getType(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_Feature2D.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_Feature2D.cs new file mode 100644 index 0000000..d75e411 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_Feature2D.cs @@ -0,0 +1,45 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_Feature2D_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_Feature2D_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_detect_Mat1(IntPtr detector, IntPtr image, IntPtr keypoints, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_detect_Mat2(IntPtr detector, IntPtr[] images, int imageLength, IntPtr keypoints, IntPtr[]? mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_detect_InputArray(IntPtr detector, IntPtr image, IntPtr keypoints, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_compute1(IntPtr obj, IntPtr image, IntPtr keypoints, IntPtr descriptors); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_compute2( + IntPtr detector, IntPtr[] images, int imageLength, + IntPtr keypoints, IntPtr[] descriptors, int descriptorsLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Feature2D_detectAndCompute( + IntPtr detector, IntPtr image, IntPtr mask, + IntPtr keypoints, IntPtr descriptors, int useProvidedKeypoints); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_Feature2D_descriptorSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_Feature2D_descriptorType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_Feature2D_defaultNorm(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_Feature2D_empty(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_GFTTDetector.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_GFTTDetector.cs new file mode 100644 index 0000000..7963afd --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_GFTTDetector.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_GFTTDetector_create(int maxCorners, double qualityLevel, + double minDistance, int blockSize, int useHarrisDetector, double k); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_GFTTDetector_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_GFTTDetector_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setMaxFeatures(IntPtr obj, int maxFeatures); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_GFTTDetector_getMaxFeatures(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setQualityLevel(IntPtr obj, double qlevel); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_GFTTDetector_getQualityLevel(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setMinDistance(IntPtr obj, double minDistance); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_GFTTDetector_getMinDistance(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setBlockSize(IntPtr obj, int blockSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_GFTTDetector_getBlockSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setHarrisDetector(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_GFTTDetector_getHarrisDetector(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_GFTTDetector_setK(IntPtr obj, double k); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_GFTTDetector_getK(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KAZE.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KAZE.cs new file mode 100644 index 0000000..3285a6e --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KAZE.cs @@ -0,0 +1,52 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_KAZE_create(bool extended, bool upright, float threshold, + int nOctaves, int nOctaveLayers, int diffusivity); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_KAZE_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_KAZE_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setDiffusivity(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_KAZE_getDiffusivity(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setExtended(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_KAZE_getExtended(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setNOctaveLayers(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_KAZE_getNOctaveLayers(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setNOctaves(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_KAZE_getNOctaves(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setThreshold(IntPtr obj, double val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_KAZE_getThreshold(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KAZE_setUpright(IntPtr obj, bool val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern bool features2d_KAZE_getUpright(IntPtr obj); + } +} diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KeyPointsFilter.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KeyPointsFilter.cs new file mode 100644 index 0000000..3904367 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_KeyPointsFilter.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KeyPointsFilter_runByImageBorder( + IntPtr keypoints, Size imageSize, int borderSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KeyPointsFilter_runByKeypointSize( + IntPtr keypoints, float minSize, float maxSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KeyPointsFilter_runByPixelsMask( + IntPtr keypoints, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KeyPointsFilter_removeDuplicated( + IntPtr keypoints); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_KeyPointsFilter_retainBest( + IntPtr keypoints, int npoints); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_MSER.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_MSER.cs new file mode 100644 index 0000000..4127203 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_MSER.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_MSER_create(int delta, int minArea, int maxArea, + double maxVariation, double minDiversity, int maxEvolution, + double areaThreshold, double minMargin, int edgeBlurSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_MSER_delete(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_detect(IntPtr obj, IntPtr image, out IntPtr msers, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_MSER_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_detectRegions( + IntPtr obj, IntPtr image, + IntPtr msers, + IntPtr bboxes); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_setDelta(IntPtr obj, int delta); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_MSER_getDelta(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_setMinArea(IntPtr obj, int minArea); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_MSER_getMinArea(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_setMaxArea(IntPtr obj, int maxArea); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_MSER_getMaxArea(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_MSER_setPass2Only(IntPtr obj, int f); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_MSER_getPass2Only(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_ORB.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_ORB.cs new file mode 100644 index 0000000..564ad96 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_ORB.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_ORB_create(int nFeatures, float scaleFactor, int nlevels, + int edgeThreshold, + int firstLevel, int wtaK, int scoreType, int patchSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_ORB_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_ORB_get(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setMaxFeatures(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getMaxFeatures(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setScaleFactor(IntPtr obj, double val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double features2d_ORB_getScaleFactor(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setNLevels(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getNLevels(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setEdgeThreshold(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getEdgeThreshold(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setFirstLevel(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getFirstLevel(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setWTA_K(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getWTA_K(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setScoreType(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getScoreType(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setPatchSize(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getPatchSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_ORB_setFastThreshold(IntPtr obj, int val); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int features2d_ORB_getFastThreshold(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_SimpleBlobDetector.cs b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_SimpleBlobDetector.cs new file mode 100644 index 0000000..be67cfd --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/features2d/NativeMethods_features2d_SimpleBlobDetector.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // ReSharper disable InconsistentNaming + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_SimpleBlobDetector_create( + ref SimpleBlobDetector.WParams parameters); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr features2d_Ptr_SimpleBlobDetector_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void features2d_Ptr_SimpleBlobDetector_delete(IntPtr ptr); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc.cs b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc.cs new file mode 100644 index 0000000..266f215 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc.cs @@ -0,0 +1,435 @@ +using System; +using System.Runtime.InteropServices; +// ReSharper disable IdentifierTypo + +#pragma warning disable 1591 +#pragma warning disable CA1401 // P/Invokes should not be visible + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getGaussianKernel( + int ksize, double sigma, int ktype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_getDerivKernels( + IntPtr kx, IntPtr ky,int dx, int dy, int ksize, int normalize, int ktype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi, int ktype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getStructuringElement(int shape, Size ksize, Point anchor); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_medianBlur(IntPtr src, IntPtr dst, int ksize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GaussianBlur(IntPtr src, IntPtr dst, Size ksize, double sigmaX, + double sigmaY, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_bilateralFilter(IntPtr src, IntPtr dst, int d, double sigmaColor, + double sigmaSpace, int borderType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_boxFilter(IntPtr src, IntPtr dst, int ddepth, Size ksize, Point anchor, + int normalize, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_blur(IntPtr src, IntPtr dst, Size ksize, Point anchor, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_filter2D(IntPtr src, IntPtr dst, int ddepth, IntPtr kernel, Point anchor, double delta, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_sepFilter2D(IntPtr src, IntPtr dst, int ddepth, IntPtr kernelX, IntPtr kernelY, Point anchor, double delta, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Sobel(IntPtr src, IntPtr dst, int ddepth, + int dx, int dy, int ksize, double scale, double delta, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Scharr(IntPtr src, IntPtr dst, int ddepth, + int dx, int dy, double scale, double delta, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Laplacian(IntPtr src, IntPtr dst, int ddepth, + int ksize, double scale, double delta, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Canny(IntPtr src, IntPtr edges, + double threshold1, double threshold2, int apertureSize, int l2Gradient); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_cornerEigenValsAndVecs(IntPtr src, IntPtr dst,int blockSize, int ksize, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_preCornerDetect(IntPtr src, IntPtr dst, int ksize, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_cornerSubPix(IntPtr image, IntPtr corners, + Size winSize, Size zeroZone, TermCriteria criteria); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_goodFeaturesToTrack(IntPtr src, IntPtr corners, + int maxCorners, double qualityLevel, double minDistance, IntPtr mask, int blockSize, int useHarrisDetector, double k); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_HoughLines(IntPtr src, IntPtr lines, + double rho, double theta, int threshold, double srn, double stn); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_HoughLinesP(IntPtr src, IntPtr lines, + double rho, double theta, int threshold, double minLineLength, double maxLineG); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_HoughCircles(IntPtr src, IntPtr circles, + int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_erode(IntPtr src, IntPtr dst, IntPtr kernel, Point anchor, int iterations, int borderType, Scalar borderValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_dilate(IntPtr src, IntPtr dst, IntPtr kernel, Point anchor, int iterations, int borderType, Scalar borderValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_morphologyEx(IntPtr src, IntPtr dst, int op, IntPtr kernel, Point anchor, int iterations, int borderType, Scalar borderValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_resize(IntPtr src, IntPtr dst, Size dsize, double fx, double fy, int interpolation); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_warpAffine(IntPtr src, IntPtr dst, IntPtr m, Size dsize, int flags, int borderMode, Scalar borderValue); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_warpPerspective_MisInputArray( + IntPtr src, IntPtr dst, IntPtr m, Size dsize, int flags, int borderMode, Scalar borderValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_warpPerspective_MisArray( + IntPtr src, IntPtr dst, [MarshalAs(UnmanagedType.LPArray)] float[,] m, int mRow, int mCol, + Size dsize, int flags, int borderMode, Scalar borderValue); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_remap(IntPtr src, IntPtr dst, IntPtr map1, IntPtr map2, int interpolation, int borderMode, Scalar borderValue); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convertMaps(IntPtr map1, IntPtr map2, IntPtr dstmap1, IntPtr dstmap2, int dstmap1Type, int nninterpolation); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getRotationMatrix2D(Point2f center, double angle, double scale); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_invertAffineTransform(IntPtr m, IntPtr im); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getPerspectiveTransform1(Point2f[] src, Point2f[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getPerspectiveTransform2(IntPtr src, IntPtr dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getAffineTransform1(Point2f[] src, Point2f[] dst); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_getAffineTransform2(IntPtr src, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_getRectSubPix(IntPtr image, Size patchSize, Point2f center, IntPtr patch, int patchType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_logPolar( + IntPtr src, IntPtr dst, Point2f center, double m, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_linearPolar( + IntPtr src, IntPtr dst, Point2f center, double maxRadius, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_integral1(IntPtr src, IntPtr sum, int sdepth); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_integral2(IntPtr src, IntPtr sum, IntPtr sqsum, int sdepth); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_integral3(IntPtr src, IntPtr sum, IntPtr sqsum, IntPtr tilted, int sdepth); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_accumulate(IntPtr src, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_accumulateSquare(IntPtr src, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_accumulateProduct(IntPtr src1, IntPtr src2, IntPtr dst, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_accumulateWeighted(IntPtr src, IntPtr dst, double alpha, IntPtr mask); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_PSNR(IntPtr src1, IntPtr src2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point2d imgproc_phaseCorrelate(IntPtr src1, IntPtr src2, IntPtr window); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point2d imgproc_phaseCorrelateRes(IntPtr src1, IntPtr src2, IntPtr window, out double response); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_createHanningWindow(IntPtr dst, Size winSize, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_threshold(IntPtr src, IntPtr dst, double thresh, double maxval, int type); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_adaptiveThreshold(IntPtr src, IntPtr dst, + double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double c); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_pyrDown(IntPtr src, IntPtr dst, Size dstsize, int borderType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_pyrUp(IntPtr src, IntPtr dst, Size dstsize, int borderType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_calcHist1(IntPtr[] images, int nimages, + int[] channels, IntPtr mask, IntPtr hist, int dims, int[] histSize, + IntPtr[] ranges, int uniform, int accumulate); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_calcBackProject(IntPtr[] images, int nimages, + int[] channels, IntPtr hist, IntPtr backProject, + IntPtr[] ranges, int uniform); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_compareHist1(IntPtr h1, IntPtr h2, int method); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_equalizeHist(IntPtr src, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float imgproc_EMD(IntPtr signature1, IntPtr signature2, + int distType, IntPtr cost, out float lowerBound, IntPtr flow); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_watershed(IntPtr image, IntPtr markers); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_pyrMeanShiftFiltering(IntPtr src, IntPtr dst, + double sp, double sr, int maxLevel, TermCriteria termcrit); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_grabCut(IntPtr img, IntPtr mask, Rect rect, + IntPtr bgdModel, IntPtr fgdModel, + int iterCount, int mode); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_distanceTransformWithLabels(IntPtr src, IntPtr dst, IntPtr labels, + int distanceType, int maskSize, int labelType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_distanceTransform(IntPtr src, IntPtr dst, + int distanceType, int maskSize); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_floodFill1(IntPtr image, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar loDiff, Scalar upDiff, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_floodFill2(IntPtr image, IntPtr mask, + Point seedPoint, Scalar newVal, out Rect rect, + Scalar loDiff, Scalar upDiff, int flags); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_cvtColor(IntPtr src, IntPtr dst, int code, int dstCn); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Moments.NativeStruct imgproc_moments(IntPtr arr, int binaryImage); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_matchTemplate( + IntPtr image, IntPtr templ, IntPtr result, int method, IntPtr mask); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_connectedComponents( + IntPtr image, IntPtr labels, int connectivity, int ltype); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_connectedComponentsWithStats( + IntPtr image, IntPtr labels, IntPtr stats, IntPtr centroids, int connectivity, int ltype); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_findContours1_vector(IntPtr image, out IntPtr contours, + out IntPtr hierarchy, int mode, int method, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_findContours1_OutputArray(IntPtr image, out IntPtr contours, + IntPtr hierarchy, int mode, int method, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_findContours2_vector(IntPtr image, out IntPtr contours, + int mode, int method, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_findContours2_OutputArray(IntPtr image, out IntPtr contours, + int mode, int method, Point offset); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_drawContours_vector(IntPtr image, + IntPtr[] contours, int contoursSize1, int[] contoursSize2, + int contourIdx, Scalar color, int thickness, int lineType, + Vec4i[] hierarchy, int hiearchyLength, int maxLevel, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_drawContours_vector(IntPtr image, + IntPtr[] contours, int contoursSize1, int[] contoursSize2, + int contourIdx, Scalar color, int thickness, int lineType, + IntPtr hierarchy, int hiearchyLength, int maxLevel, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_drawContours_InputArray(IntPtr image, + IntPtr[] contours, int contoursLength, + int contourIdx, Scalar color, int thickness, int lineType, + IntPtr hierarchy, int maxLevel, Point offset); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_approxPolyDP_InputArray(IntPtr curve, IntPtr approxCurve, + double epsilon, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_approxPolyDP_Point(Point[] curve, int curveLength, + out IntPtr approxCurve, double epsilon, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_approxPolyDP_Point2f(Point2f[] curve, int curveLength, + out IntPtr approxCurve, double epsilon, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_arcLength_InputArray(IntPtr curve, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_arcLength_Point(Point[] curve, int curveLength, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_arcLength_Point2f(Point2f[] curve, int curveLength, int closed); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect imgproc_boundingRect_InputArray(IntPtr curve); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect imgproc_boundingRect_Point(Point[] curve, int curveLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Rect imgproc_boundingRect_Point2f(Point2f[] curve, int curveLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_contourArea_InputArray(IntPtr contour, int oriented); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_contourArea_Point(Point[] contour, int contourLength, int oriented); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_contourArea_Point2f(Point2f[] contour, int contourLength, int oriented); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_minAreaRect_InputArray(IntPtr points); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_minAreaRect_Point(Point[] points, int pointsLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_minAreaRect_Point2f(Point2f[] points, int pointsLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_minEnclosingCircle_InputArray(IntPtr points, out Point2f center, out float radius); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_minEnclosingCircle_Point(Point[] points, int pointsLength, + out Point2f center, out float radius); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_minEnclosingCircle_Point2f(Point2f[] points, int pointsLength, + out Point2f center, out float radius); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_matchShapes_InputArray(IntPtr contour1, IntPtr contour2, + int method, double parameter); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_matchShapes_Point(Point[] contour1, int contour1Length, + Point[] contour2, int contour2Length, int method, double parameter); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexHull_InputArray(IntPtr points, IntPtr hull, + int clockwise, int returnPoints); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexHull_Point_ReturnsPoints(Point[] points, int pointsLength, + out IntPtr hull, int clockwise); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexHull_Point2f_ReturnsPoints(Point2f[] points, int pointsLength, + out IntPtr hull, int clockwise); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexHull_Point_ReturnsIndices(Point[] points, int pointsLength, + out IntPtr hull, int clockwise); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexHull_Point2f_ReturnsIndices(Point2f[] points, int pointsLength, + out IntPtr hull, int clockwise); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexityDefects_InputArray(IntPtr contour, IntPtr convexHull, + IntPtr convexityDefects); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexityDefects_Point(Point[] contour, int contourLength, int[] convexHull, + int convexHullLength, out IntPtr convexityDefects); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_convexityDefects_Point2f(Point2f[] contour, int contourLength, + int[] convexHull, int convexHullLength, out IntPtr convexityDefects); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_isContourConvex_InputArray(IntPtr contour); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_isContourConvex_Point(Point[] contour, int contourLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_isContourConvex_Point2f(Point2f[] contour, int contourLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float imgproc_intersectConvexConvex_InputArray(IntPtr p1, IntPtr p2, + IntPtr p12, int handleNested); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float imgproc_intersectConvexConvex_Point(Point[] p1, int p1Length, Point[] p2, + int p2Length,out IntPtr p12, int handleNested); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float imgproc_intersectConvexConvex_Point2f(Point2f[] p1, int p1Length, Point2f[] p2, + int p2Length,out IntPtr p12, int handleNested); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_fitEllipse_InputArray(IntPtr points); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_fitEllipse_Point(Point[] points, int pointsLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern RotatedRect imgproc_fitEllipse_Point2f(Point2f[] points, int pointsLength); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fitLine_InputArray(IntPtr points, IntPtr line, + int distType, double param, double reps, double aeps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fitLine_Point(Point[] points, int pointsLength, [In, Out] float[] line, int distType, + double param, double reps, double aeps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fitLine_Point2f(Point2f[] points, int pointsLength, [In, Out] float[] line, + int distType,double param, double reps, double aeps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fitLine_Point3i(Point3i[] points, int pointsLength, [In, Out] float[] line, + int distType,double param, double reps, double aeps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fitLine_Point3f(Point3f[] points, int pointsLength, [In, Out] float[] line, + int distType,double param, double reps, double aeps); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_pointPolygonTest_InputArray(IntPtr contour, Point2f pt, int measureDist); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_pointPolygonTest_Point(Point[] contour, int contourLength, Point2f pt, + int measureDist); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_pointPolygonTest_Point2f(Point2f[] contour, int contourLength, + Point2f pt, int measureDist); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_rotatedRectangleIntersection_OutputArray( + RotatedRect rect1, RotatedRect rect2, IntPtr intersectingRegion); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_rotatedRectangleIntersection_vector( + RotatedRect rect1, RotatedRect rect2, IntPtr intersectingRegion); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_applyColorMap(IntPtr src, IntPtr dst, int colormap); + + + #region Drawing + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_line( + IntPtr img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_arrowedLine( + IntPtr img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift, double tipLength); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_rectangle_InputOutputArray( + IntPtr img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_rectangle_Mat( + IntPtr img, Rect rect, Scalar color, int thickness, int lineType, int shift); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_circle(IntPtr img, Point center, int radius, Scalar color, int thickness, int lineType, int shift); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_ellipse1(IntPtr img, Point center, Size axes, + double angle, double startAngle, double endAngle, Scalar color, int thickness, int lineType, int shift); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_ellipse2(IntPtr img, RotatedRect box, Scalar color, int thickness, int lineType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fillConvexPoly_Mat( + IntPtr img, Point[] pts, int npts, Scalar color, int lineType, int shift); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fillConvexPoly_InputOutputArray( + IntPtr img, IntPtr points, Scalar color, int lineType, int shift); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fillPoly_Mat( + IntPtr img, IntPtr[] pts, int[] npts, int ncontours, + Scalar color, int lineType, int shift, Point offset); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_fillPoly_InputOutputArray( + IntPtr img, IntPtr pts, Scalar color, int lineType, int shift, Point offset); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_polylines_Mat( + IntPtr img, IntPtr[] pts, int[] npts, + int ncontours, int isClosed, Scalar color, int thickness, int lineType, int shift); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_polylines_InputOutputArray( + IntPtr img, IntPtr pts, int isClosed, Scalar color, int thickness, int lineType, int shift); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_clipLine1(Size imgSize, ref Point pt1, ref Point pt2); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_clipLine2(Rect imgRect, ref Point pt1, ref Point pt2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_ellipse2Poly( + Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, IntPtr pts); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern void core_putText(IntPtr img, [MarshalAs(UnmanagedType.LPStr)] string text, Point org, + int fontFace, double fontScale, Scalar color, + int thickness, int lineType, int bottomLeftOrigin); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true, ExactSpelling = true)] + public static extern Size core_getTextSize([MarshalAs(UnmanagedType.LPStr)] string text, int fontFace, + double fontScale, int thickness, out int baseLine); + + #endregion + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_CLAHE.cs b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_CLAHE.cs new file mode 100644 index 0000000..abf9309 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_CLAHE.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_createCLAHE(double clipLimit, Size tileGridSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Ptr_CLAHE_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_Ptr_CLAHE_get(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_CLAHE_apply(IntPtr obj, IntPtr src, IntPtr dst); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_CLAHE_setClipLimit(IntPtr obj, double clipLimit); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_CLAHE_getClipLimit(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_CLAHE_setTilesGridSize(IntPtr obj, Size tileGridSize); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Size imgproc_CLAHE_getTilesGridSize(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_CLAHE_collectGarbage(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_GeneralizedHough.cs b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_GeneralizedHough.cs new file mode 100644 index 0000000..ee877e8 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_GeneralizedHough.cs @@ -0,0 +1,185 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + // GeneralizedHough + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setTemplate1( + IntPtr obj, IntPtr templ, Point templCenter); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setTemplate2( + IntPtr obj, IntPtr edges, IntPtr dx, IntPtr dy, Point templCenter); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_detect1( + IntPtr obj, IntPtr image, IntPtr positions, IntPtr votes); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_detect2( + IntPtr obj, IntPtr edges, IntPtr dx, IntPtr dy, IntPtr positions, IntPtr votes); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setCannyLowThresh(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHough_getCannyLowThresh(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setCannyHighThresh(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHough_getCannyHighThresh(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setMinDist(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHough_getMinDist(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setDp(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHough_getDp(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHough_setMaxBufferSize(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHough_getMaxBufferSize(IntPtr obj); + + + + // GeneralizedHoughBallard + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_createGeneralizedHoughBallard(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_Ptr_GeneralizedHoughBallard_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Ptr_GeneralizedHoughBallard_delete(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughBallard_setLevels(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughBallard_getLevels(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughBallard_setVotesThreshold(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughBallard_getVotesThreshold(IntPtr obj); + + + + // GeneralizedHoughGuil + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_createGeneralizedHoughGuil(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_Ptr_GeneralizedHoughGuil_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Ptr_GeneralizedHoughGuil_delete(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setXi(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getXi(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setLevels(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughGuil_getLevels(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setAngleEpsilon(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getAngleEpsilon(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setMinAngle(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getMinAngle(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setMaxAngle(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getMaxAngle(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setAngleStep(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getAngleStep(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setAngleThresh(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughGuil_getAngleThresh(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setMinScale(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getMinScale(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setMaxScale(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getMaxScale(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setScaleStep(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double imgproc_GeneralizedHoughGuil_getScaleStep(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setScaleThresh(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughGuil_getScaleThresh(IntPtr obj); + + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_GeneralizedHoughGuil_setPosThresh(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_GeneralizedHoughGuil_getPosThresh(IntPtr obj); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_LineIterator.cs b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_LineIterator.cs new file mode 100644 index 0000000..b9dd5a3 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_LineIterator.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_LineIterator_new( + IntPtr img, Point pt1, Point pt2, int connectivity, int leftToRight); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_LineIterator_operatorEntity(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_operatorPP(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point imgproc_LineIterator_pos(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_LineIterator_ptr_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_ptr_set(IntPtr obj, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_LineIterator_ptr0_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_step_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_step_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_elemSize_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_elemSize_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_err_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_err_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_count_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_count_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_minusDelta_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_minusDelta_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_plusDelta_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_plusDelta_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_minusStep_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_minusStep_set(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_LineIterator_plusStep_get(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_LineIterator_plusStep_set(IntPtr obj, int val); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_Subdiv2D.cs b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_Subdiv2D.cs new file mode 100644 index 0000000..7f25c3d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/imgproc/NativeMethods_imgproc_Subdiv2D.cs @@ -0,0 +1,52 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_Subdiv2D_new1(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr imgproc_Subdiv2D_new2(Rect rect); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_initDelaunay(IntPtr obj, Rect rect); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_insert1(IntPtr obj, Point2f pt); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_insert2(IntPtr obj, [MarshalAs(UnmanagedType.LPArray)] Point2f[] ptArray, int length); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_locate(IntPtr obj, Point2f pt, out int edge, out int vertex); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_findNearest(IntPtr obj, Point2f pt, out Point2f nearestPt); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_getEdgeList(IntPtr obj, out IntPtr edgeList); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_getTriangleList(IntPtr obj, out IntPtr triangleList); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_getVoronoiFacetList(IntPtr obj, [MarshalAs(UnmanagedType.LPArray)] int[] idx, int idxCount, + out IntPtr facetList, out IntPtr facetCenters); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void imgproc_Subdiv2D_getVoronoiFacetList(IntPtr obj, IntPtr idx, int idxCount, + out IntPtr facetList, out IntPtr facetCenters); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Point2f imgproc_Subdiv2D_getVertex(IntPtr obj, int vertex, out int firstEdge); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_getEdge(IntPtr obj, int edge, int nextEdgeType); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_nextEdge(IntPtr obj, int edge); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_rotateEdge(IntPtr obj, int edge, int rotate); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_symEdge(IntPtr obj, int edge); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_edgeOrg(IntPtr obj, int edge, out Point2f orgpt); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int imgproc_Subdiv2D_edgeDst(IntPtr obj, int edge, out Point2f dstpt); + + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_ANN_MLP.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_ANN_MLP.cs new file mode 100644 index 0000000..285c5c5 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_ANN_MLP.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setTrainMethod(IntPtr obj, int method, double param1, double param2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_ANN_MLP_getTrainMethod(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setActivationFunction(IntPtr obj, int type, double param1, double param2); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setLayerSizes(IntPtr obj, IntPtr layerSizes); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_ANN_MLP_getLayerSizes(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern TermCriteria ml_ANN_MLP_getTermCriteria(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setTermCriteria(IntPtr obj, TermCriteria val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getBackpropWeightScale(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setBackpropWeightScale(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getBackpropMomentumScale(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setBackpropMomentumScale(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getRpropDW0(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setRpropDW0(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getRpropDWPlus(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setRpropDWPlus(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getRpropDWMinus(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setRpropDWMinus(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getRpropDWMin(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setRpropDWMin(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_ANN_MLP_getRpropDWMax(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_ANN_MLP_setRpropDWMax(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_ANN_MLP_getWeights(IntPtr obj, int layerIdx); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_ANN_MLP_create(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_ANN_MLP_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_ANN_MLP_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_ANN_MLP_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_ANN_MLP_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_Boost.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_Boost.cs new file mode 100644 index 0000000..17f7d3d --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_Boost.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_Boost_getBoostType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Boost_setBoostType(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_Boost_getWeakCount(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Boost_setWeakCount(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_Boost_getWeightTrimRate(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Boost_setWeightTrimRate(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Boost_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_Boost_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_Boost_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Boost_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Boost_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_DTrees.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_DTrees.cs new file mode 100644 index 0000000..8a55e9a --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_DTrees.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getMaxCategories(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setMaxCategories(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getMaxDepth(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setMaxDepth(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getMinSampleCount(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setMinSampleCount(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getCVFolds(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setCVFolds(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getUseSurrogates(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setUseSurrogates(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getUse1SERule(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setUse1SERule(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_DTrees_getTruncatePrunedTree(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setTruncatePrunedTree(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_DTrees_getRegressionAccuracy(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setRegressionAccuracy(IntPtr obj, float val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_DTrees_getPriors(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_setPriors(IntPtr obj, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_getRoots(IntPtr obj, IntPtr result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_getNodes(IntPtr obj, IntPtr result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_getSplits(IntPtr obj, IntPtr result); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_DTrees_getSubsets(IntPtr obj, IntPtr result); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_DTrees_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_DTrees_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_DTrees_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_DTrees_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_DTrees_loadFromString(string strModel); + + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_EM.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_EM.cs new file mode 100644 index 0000000..7cae916 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_EM.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_EM_getClustersNumber(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_EM_setClustersNumber(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_EM_getCovarianceMatrixType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_EM_setCovarianceMatrixType(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern TermCriteria ml_EM_getTermCriteria(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_EM_setTermCriteria(IntPtr obj, TermCriteria val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_EM_getWeights(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_EM_getMeans(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_EM_getCovs(IntPtr obj, IntPtr covs); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern Vec2d ml_EM_predict2(IntPtr model, IntPtr sample, IntPtr probs); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_EM_trainEM( + IntPtr obj, IntPtr samples, IntPtr logLikelihoods, IntPtr labels, IntPtr probs); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_EM_trainE( + IntPtr model, IntPtr samples, IntPtr means0, IntPtr covs0, IntPtr weights0, + IntPtr logLikelihoods, IntPtr labels, IntPtr probs); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_EM_trainM( + IntPtr model, IntPtr samples, IntPtr probs0, IntPtr logLikelihoods, + IntPtr labels, IntPtr probs); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_EM_create(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_EM_get(IntPtr ptr); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_EM_delete(IntPtr ptr); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_EM_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_EM_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_KNearest.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_KNearest.cs new file mode 100644 index 0000000..b0fcf79 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_KNearest.cs @@ -0,0 +1,49 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_KNearest_getDefaultK(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_KNearest_setDefaultK(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_KNearest_getIsClassifier(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_KNearest_setIsClassifier(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_KNearest_getEmax(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_KNearest_setEmax(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_KNearest_getAlgorithmType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_KNearest_setAlgorithmType(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_KNearest_findNearest(IntPtr obj, IntPtr samples, int k, + IntPtr results, IntPtr neighborResponses, IntPtr dist); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_KNearest_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_KNearest_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_KNearest_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_KNearest_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_KNearest_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_LogisticRegression.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_LogisticRegression.cs new file mode 100644 index 0000000..ef61c54 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_LogisticRegression.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_LogisticRegression_getLearningRate(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setLearningRate(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_LogisticRegression_getIterations(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setIterations(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_LogisticRegression_getRegularization(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setRegularization(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_LogisticRegression_getTrainMethod(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setTrainMethod(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_LogisticRegression_getMiniBatchSize(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setMiniBatchSize(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern TermCriteria ml_LogisticRegression_getTermCriteria(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_LogisticRegression_setTermCriteria(IntPtr obj, TermCriteria val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_LogisticRegression_predict( + IntPtr obj, IntPtr samples, IntPtr results, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_LogisticRegression_get_learnt_thetas(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_LogisticRegression_create(); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_LogisticRegression_delete(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_LogisticRegression_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_LogisticRegression_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_LogisticRegression_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_NormalBayesClassifier.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_NormalBayesClassifier.cs new file mode 100644 index 0000000..e9c2ed2 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_NormalBayesClassifier.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_NormalBayesClassifier_predictProb( + IntPtr obj, IntPtr inputs, + IntPtr samples, IntPtr outputProbs, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_NormalBayesClassifier_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_NormalBayesClassifier_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_NormalBayesClassifier_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_NormalBayesClassifier_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_NormalBayesClassifier_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_RTrees.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_RTrees.cs new file mode 100644 index 0000000..7f0db15 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_RTrees.cs @@ -0,0 +1,43 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_RTrees_getCalculateVarImportance(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_RTrees_setCalculateVarImportance(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_RTrees_getActiveVarCount(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_RTrees_setActiveVarCount(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern TermCriteria ml_RTrees_getTermCriteria(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_RTrees_setTermCriteria(IntPtr obj, TermCriteria val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_RTrees_getVarImportance(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_RTrees_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_RTrees_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_RTrees_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_RTrees_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_RTrees_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_SVM.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_SVM.cs new file mode 100644 index 0000000..447c72f --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_SVM.cs @@ -0,0 +1,88 @@ +using System; +using System.Runtime.InteropServices; +using OpenCvSharp.ML; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_SVM_getType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setType(IntPtr obj, int val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getGamma(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setGamma(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getCoef0(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setCoef0(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getDegree(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setDegree(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getC(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setC(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getP(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setP(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getNu(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setNu(IntPtr obj, double val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_SVM_getClassWeights(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setClassWeights(IntPtr obj, IntPtr val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern TermCriteria ml_SVM_getTermCriteria(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setTermCriteria(IntPtr obj, TermCriteria val); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_SVM_getKernelType(IntPtr obj); + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_SVM_setKernel(IntPtr obj, int kernelType); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_SVM_getSupportVectors(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern double ml_SVM_getDecisionFunction( + IntPtr obj, int i, IntPtr alpha, IntPtr svidx); + + // static + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern ParamGrid ml_SVM_getDefaultGrid(int paramId); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_SVM_create(); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_Ptr_SVM_delete(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_Ptr_SVM_get(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_SVM_load(string filePath); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern IntPtr ml_SVM_loadFromString(string strModel); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_StatModel.cs b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_StatModel.cs new file mode 100644 index 0000000..74834c6 --- /dev/null +++ b/OpenVinoOpenCvSharp/PInvoke/ml/NativeMethods_ml_StatModel.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp +{ + static partial class NativeMethods + { + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_StatModel_clear(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_getVarCount(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_empty(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_isTrained(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_isClassifier(IntPtr obj); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_train1( + IntPtr obj, IntPtr trainData, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern int ml_StatModel_train2( + IntPtr obj, IntPtr samples, int layout, IntPtr responses); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_StatModel_calcError( + IntPtr obj, IntPtr data, int test, IntPtr resp); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern float ml_StatModel_predict( + IntPtr obj, IntPtr samples, IntPtr results, int flags); + + [DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] + public static extern void ml_StatModel_save(IntPtr obj, string filename); + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Util/ArrayAddress.cs b/OpenVinoOpenCvSharp/Util/ArrayAddress.cs new file mode 100644 index 0000000..9504642 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/ArrayAddress.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 +// ReSharper disable InconsistentNaming + +namespace OpenCvSharp.Util +{ + /// + /// + /// + /// + public class ArrayAddress1 : DisposableObject + where T : unmanaged + { + protected Array array; + protected GCHandle gch; + + /// + /// + /// + /// + public ArrayAddress1(T[] array) + { + this.array = array ?? throw new ArgumentNullException(); + gch = GCHandle.Alloc(array, GCHandleType.Pinned); + } + + /// + /// + /// + /// + public ArrayAddress1(IEnumerable enumerable) + : this(EnumerableEx.ToArray(enumerable)) + { + } + + /// + /// + /// + /// + public ArrayAddress1(T[,] array) + { + this.array = array ?? throw new ArgumentNullException(); + gch = GCHandle.Alloc(array, GCHandleType.Pinned); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + if (gch.IsAllocated) + { + gch.Free(); + } + base.DisposeUnmanaged(); + } + + /// + /// + /// + public IntPtr Pointer => gch.AddrOfPinnedObject(); + + /// + /// + /// + /// + /// + public static implicit operator IntPtr(ArrayAddress1 self) + { + return self.Pointer; + } + + /// + /// + /// + public int Length => array.Length; + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Util/ArrayAddress2.cs b/OpenVinoOpenCvSharp/Util/ArrayAddress2.cs new file mode 100644 index 0000000..7b250a7 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/ArrayAddress2.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace OpenCvSharp.Util +{ + /// + /// Class to get address of specified jagged array + /// + /// + public class ArrayAddress2 : DisposableObject + where T : unmanaged + { + private readonly T[][] array; + private readonly GCHandle[] gch; + private readonly IntPtr[] ptr; + + /// + /// + /// + /// + public ArrayAddress2(T[][] array) + { + this.array = array ?? throw new ArgumentNullException(nameof(array)); + + // T[][]をIntPtr[]に変換する + ptr = new IntPtr[array.Length]; + gch = new GCHandle[array.Length]; + for (var i = 0; i < array.Length; i++) + { + var elem = array[i]; + if (elem == null/* || elem.Length == 0*/) + throw new ArgumentException($"array[{i}] is not valid array object."); + + // メモリ確保 + gch[i] = GCHandle.Alloc(elem, GCHandleType.Pinned); + ptr[i] = gch[i].AddrOfPinnedObject(); + } + } + + /// + /// + /// + /// + public ArrayAddress2(IEnumerable> enumerable) + : this(EnumerableEx.SelectToArray(enumerable, EnumerableEx.ToArray)) + { + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + foreach (var h in gch) + { + if (h.IsAllocated) + { + h.Free(); + } + } + base.DisposeUnmanaged(); + } + +#if LANG_JP +/// +/// ポインタを得る +/// +/// +#else + /// + /// + /// +#endif + public IntPtr[] Pointer + { + get { return ptr; } + } + +#if LANG_JP +/// +/// ポインタへの暗黙のキャスト +/// +/// +/// +#else + /// + /// + /// + /// + /// +#endif + public static implicit operator IntPtr[](ArrayAddress2 self) + { + return self.Pointer; + } + + /// + /// + /// + public int Dim1Length => array.Length; + + /// + /// + /// + public int[] Dim2Lengths + { + get + { + var lengths = new int[array.Length]; + for (var i = 0; i < array.Length; i++) + { + lengths[i] = array[i].Length; + } + return lengths; + } + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Util/DynamicInvoker.cs b/OpenVinoOpenCvSharp/Util/DynamicInvoker.cs new file mode 100644 index 0000000..6faf6e0 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/DynamicInvoker.cs @@ -0,0 +1,135 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace OpenCvSharp.Util +{ +#if !uap10 +#if LANG_JP + /// + /// 動的にアンマネージのアセンブリにある関数を呼び出すためのクラス + /// + /// 実行させたい関数の定義に合わせたデリゲート +#else + /// + /// + /// + /// +#endif + public class DynamicInvoker : DisposableObject + { +#if LANG_JP + /// + /// 読み込むライブラリの名前 + /// +#else + /// + /// Name of library to be loaded + /// +#endif + public string DllName { get; } + +#if LANG_JP + /// + /// 呼び出す関数の名前 + /// +#else + /// + /// Name of function to be called + /// +#endif + public string FunctionName { get; } + +#if LANG_JP + /// + /// LoadLibraryで得られたポインタ + /// +#else + /// + /// Pointer which retrieved by LoadLibrary + /// +#endif + public IntPtr PtrLib { get; } + +#if LANG_JP + /// + /// GetProcAddressで得られたポインタ + /// +#else + /// + /// Pointer which retrieved by GetProcAddress + /// +#endif + public IntPtr PtrProc { get; } + +#if LANG_JP + /// + /// 呼び出す関数ポインタをデリゲートに変換したものを取得する + /// +#else + /// + /// Delegate which is converted from function pointer + /// +#endif + public T Call { get; } + +#if LANG_JP + /// + /// 初期化 + /// + /// ライブラリの名前 + /// 関数の名前 +#else + /// + /// Constructor + /// + /// Name of library + /// Name of function +#endif + public DynamicInvoker(string dllName, string functionName) + { + if (Platform.OS == OS.Unix) + { + throw new PlatformNotSupportedException("This method is for only Windows"); + } + +#if NET20 || NET40 + if (!typeof(T).IsSubclassOf(typeof(Delegate))) +#else + if (!typeof(T).GetTypeInfo().IsSubclassOf(typeof(Delegate))) +#endif + throw new OpenCvSharpException("The type argument must be Delegate."); + if (string.IsNullOrEmpty(dllName)) + throw new ArgumentNullException(nameof(dllName)); + if (string.IsNullOrEmpty(functionName)) + throw new ArgumentNullException(nameof(functionName)); + + PtrLib = Win32Api.LoadLibrary(dllName); + if (PtrLib == IntPtr.Zero) + throw new OpenCvSharpException("Failed to load \"{0}\".", dllName); + PtrProc = Win32Api.GetProcAddress(PtrLib, functionName); + if (PtrProc == IntPtr.Zero) + throw new OpenCvSharpException("Failed to get address of function \"{0}\".", functionName); + + DllName = dllName; + FunctionName = functionName; + IsDisposed = false; + +#if NET20 || NET40 + Call = (T)(object)Marshal.GetDelegateForFunctionPointer(PtrProc, typeof(T)); +#else + Call = Marshal.GetDelegateForFunctionPointer(PtrProc); +#endif + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + Win32Api.FreeLibrary(PtrLib); + base.DisposeUnmanaged(); + } + } +#endif +} diff --git a/OpenVinoOpenCvSharp/Util/EnumerableEx.cs b/OpenVinoOpenCvSharp/Util/EnumerableEx.cs new file mode 100644 index 0000000..e7df49b --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/EnumerableEx.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections; +using System.Collections.Generic; +#if !NET20 +using System.Linq; +#endif + +namespace OpenCvSharp.Util +{ +#if NET20 + internal delegate TResult Func(T1 t1); +#endif + + /// + /// IEnumerable<T> extension methods for .NET Framework 2.0 + /// + internal static class EnumerableEx + { + /// + /// Enumerable.Select + /// + /// + /// + /// + /// + /// + public static IEnumerable Select( + IEnumerable enumerable, Func selector) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + if (selector == null) + throw new ArgumentNullException(nameof(selector)); + foreach (var elem in enumerable) + { + yield return selector(elem); + } +#else + return enumerable.Select(selector); +#endif + } + + /// + /// Enumerable.Select -> ToArray + /// + /// + /// + /// + /// + /// + public static TResult[] SelectToArray( + IEnumerable enumerable, Func selector) + { +#if NET20 + return ToArray(Select(enumerable, selector)); +#else + return enumerable.Select(selector).ToArray(); +#endif + } + + /// + /// Enumerable.Select -> ToArray + /// + /// + /// + /// + /// + /// + public static TResult[] SelectToArray( + IEnumerable enumerable, Func selector) + { +#if NET20 + var result = new List(); + foreach (TSource source in enumerable) + { + result.Add(selector(source)); + } + return result.ToArray(); +#else + return enumerable.Cast().Select(selector).ToArray(); +#endif + } + + /// + /// Enumerable.Select -> ToArray + /// + /// + /// + public static IntPtr[] SelectPtrs(IEnumerable enumerable) + { + return SelectToArray(enumerable, obj => + { + if (obj == null) + throw new ArgumentException("enumerable contains null"); + obj.ThrowIfDisposed(); + return obj.CvPtr; + }); + } + + /// + /// Enumerable.Select -> ToArray + /// + /// + /// + public static IntPtr[] SelectPtrs(IEnumerable enumerable) + { + return SelectToArray(enumerable, obj => + { + if (obj == null) + throw new ArgumentException("enumerable contains null"); + obj.ThrowIfDisposed(); + return obj.CvPtr; + }); + } + + /// + /// Enumerable.Where + /// + /// + /// + /// + /// + public static IEnumerable Where( + IEnumerable enumerable, Func predicate) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + if (predicate == null) + throw new ArgumentNullException(nameof(predicate)); + foreach (var elem in enumerable) + { + if (predicate(elem)) + yield return elem; + } +#else + return enumerable.Where(predicate); +#endif + } + + /// + /// Enumerable.Where -> ToArray + /// + /// + /// + /// + /// + public static TSource[] WhereToArray( + IEnumerable enumerable, Func predicate) + { +#if NET20 + return ToArray(Where(enumerable, predicate)); +#else + return enumerable.Where(predicate).ToArray(); +#endif + } + + /// + /// Enumerable.ToArray + /// + /// + /// + /// + public static TSource[] ToArray(IEnumerable enumerable) + { + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); +#if NET20 + if (enumerable is TSource[] arr) + return arr; + return new List(enumerable).ToArray(); +#else + return enumerable.ToArray(); +#endif + } + + /// + /// Enumerable.Any + /// + /// + /// + /// + /// + public static bool Any( + IEnumerable enumerable, Func predicate) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + foreach (var elem in enumerable) + { + if (predicate(elem)) + return true; + } + return false; +#else + return enumerable.Any(predicate); +#endif + } + + /// + /// Enumerable.Any + /// + /// + /// + /// + public static bool AnyNull(IEnumerable enumerable) + where TSource : class + { + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + +#if NET20 + foreach (var elem in enumerable) + { + if (elem == null) + return true; + } + return false; +#else + return enumerable.Any(e => e == null); +#endif + } + + /// + /// Enumerable.All + /// + /// + /// + /// + /// + public static bool All( + IEnumerable enumerable, Func predicate) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + foreach (var elem in enumerable) + { + if (!predicate(elem)) + return false; + } + return true; +#else + return enumerable.All(predicate); +#endif + } + + /// + /// Enumerable.Count + /// + /// + /// + /// + /// + public static int Count( + IEnumerable enumerable, Func predicate) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + var count = 0; + foreach (var elem in enumerable) + { + if (predicate(elem)) + count++; + } + return count; +#else + return enumerable.Count(predicate); +#endif + } + + /// + /// Enumerable.Count + /// + /// + /// + /// + public static int Count(IEnumerable enumerable) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + + if (enumerable is TSource[] array) + return array.Length; + if (enumerable is ICollection collection) + return collection.Count; + + var count = 0; + foreach (var elem in enumerable) + { + count++; + } + return count; +#else + return enumerable.Count(); +#endif + } + + /// + /// + /// + /// + /// + /// + public static bool IsEmpty(IEnumerable enumerable) + { +#if NET20 + if (enumerable == null) + throw new ArgumentNullException(nameof(enumerable)); + + foreach (var elem in enumerable) + { + return false; + } + return true; +#else + return !enumerable.Any(); +#endif + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/MarshalHelper.cs b/OpenVinoOpenCvSharp/Util/MarshalHelper.cs new file mode 100644 index 0000000..fd9ebc1 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/MarshalHelper.cs @@ -0,0 +1,41 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp.Util +{ + /// + /// + /// + public static class MarshalHelper + { + public static int SizeOf() + { +#if NET20 || NET40 + if (typeof(T).IsValueType) + { + return Marshal.SizeOf(typeof(T)); + } + return IntPtr.Size; +#else + if (typeof(T).GetTypeInfo().IsValueType) + { + return Marshal.SizeOf(); + } + return IntPtr.Size; +#endif + } + + public static T PtrToStructure(IntPtr p) + where T : struct + { +#if NET20 || NET40 + return (T)Marshal.PtrToStructure(p, typeof(T)); +#else + return Marshal.PtrToStructure(p); +#endif + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/MemoryHelper.cs b/OpenVinoOpenCvSharp/Util/MemoryHelper.cs new file mode 100644 index 0000000..8852d2f --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/MemoryHelper.cs @@ -0,0 +1,150 @@ +using System; + +#pragma warning disable 1591 + +namespace OpenCvSharp.Util +{ + /// + /// + /// + public static class MemoryHelper + { + #region CopyMemory +#if LANG_JP + /// + /// 指定されたメモリブロックの内容を、他の場所へコピーします。 + /// + /// + /// + /// + /// + /// Yanesdk.NET (http://yanesdkdotnet.sourceforge.jp/) の Screen2DGl.cs から借用させて頂きました。 + /// +#else + /// + /// + /// + /// + /// + /// +#endif + public static unsafe void CopyMemory(void* outDest, void* inSrc, uint inNumOfBytes) + { +#if NET20 || NET40 + // 転送先をuint幅にalignする + const uint align = sizeof(uint) - 1; + var offset = (uint)outDest & align; + // ↑ポインタは32bitとは限らないので本来このキャストはuintではダメだが、 + // 今は下位2bitだけあればいいのでこれでOK。 + if (offset != 0) + offset = align - offset; + offset = Math.Min(offset, inNumOfBytes); + + // 先頭の余り部分をbyteでちまちまコピー + var srcBytes = (byte*)inSrc; + var dstBytes = (byte*)outDest; + for (uint i = 0; i < offset; i++) + dstBytes[i] = srcBytes[i]; + + // uintで一気に転送 + var dst = (uint*)((byte*)outDest + offset); + var src = (uint*)((byte*)inSrc + offset); + var numOfUInt = (inNumOfBytes - offset) / sizeof(uint); + for (uint i = 0; i < numOfUInt; i++) + dst[i] = src[i]; + + // 末尾の余り部分をbyteでちまちまコピー + for (var i = offset + numOfUInt * sizeof(uint); i < inNumOfBytes; i++) + dstBytes[i] = srcBytes[i]; +#else + Buffer.MemoryCopy(inSrc, outDest, inNumOfBytes, inNumOfBytes); +#endif + } + public static unsafe void CopyMemory(void* outDest, void* inSrc, int inNumOfBytes) + { +#if NET20 || NET40 + CopyMemory(outDest, inSrc, (uint)inNumOfBytes); +#else + Buffer.MemoryCopy(inSrc, outDest, inNumOfBytes, inNumOfBytes); +#endif + } + public static unsafe void CopyMemory(IntPtr outDest, IntPtr inSrc, uint inNumOfBytes) + { +#if NET20 || NET40 + CopyMemory(outDest.ToPointer(), inSrc.ToPointer(), inNumOfBytes); +#else + Buffer.MemoryCopy(inSrc.ToPointer(), outDest.ToPointer(), inNumOfBytes, inNumOfBytes); +#endif + } + public static unsafe void CopyMemory(IntPtr outDest, IntPtr inSrc, int inNumOfBytes) + { +#if NET20 || NET40 + CopyMemory(outDest.ToPointer(), inSrc.ToPointer(), (uint)inNumOfBytes); +#else + Buffer.MemoryCopy(inSrc.ToPointer(), outDest.ToPointer(), inNumOfBytes, inNumOfBytes); +#endif + } + //[DllImport("kernel32")] + //public static unsafe extern void CopyMemory(void* outDest, void* inSrc, [MarshalAs(UnmanagedType.U4)] int inNumOfBytes); + //[DllImport("kernel32")] + //public static extern void CopyMemory(IntPtr outDest, IntPtr inSrc, [MarshalAs(UnmanagedType.U4)] int inNumOfBytes); + #endregion + + #region ZeroMemory +#if LANG_JP + /// + /// 指定されたメモリブロックの内容を、他の場所へコピーします。 + /// + /// + /// + /// + /// Yanesdk.NET (http://yanesdkdotnet.sourceforge.jp/) の Screen2DGl.cs から借用させて頂きました。 + /// +#else + /// + /// + /// + /// + /// +#endif + public static unsafe void ZeroMemory(void* outDest, uint inNumOfBytes) + { + // 転送先をuint幅にalignする + const uint align = sizeof(uint) - 1; + var offset = (uint)outDest & align; + // ↑ポインタは32bitとは限らないので本来このキャストはuintではダメだが、 + // 今は下位2bitだけあればいいのでこれでOK。 + if (offset != 0) + offset = align - offset; + offset = Math.Min(offset, inNumOfBytes); + + // 先頭の余り部分をbyteでちまちまコピー + var dstBytes = (byte*)outDest; + for (uint i = 0; i < offset; i++) + dstBytes[i] = 0; + + // uintで一気に転送 + var dst = (uint*)((byte*)outDest + offset); + var numOfUInt = (inNumOfBytes - offset) / sizeof(uint); + for (uint i = 0; i < numOfUInt; i++) + dst[i] = 0; + + // 末尾の余り部分をbyteでちまちまコピー + for (var i = offset + numOfUInt * sizeof(uint); i < inNumOfBytes; i++) + dstBytes[i] = 0; + } + public static unsafe void ZeroMemory(void* outDest, int inNumOfBytes) + { + ZeroMemory(outDest, (uint)inNumOfBytes); + } + public static unsafe void ZeroMemory(IntPtr outDest, uint inNumOfBytes) + { + ZeroMemory(outDest.ToPointer(), inNumOfBytes); + } + public static unsafe void ZeroMemory(IntPtr outDest, int inNumOfBytes) + { + ZeroMemory(outDest.ToPointer(), (uint)inNumOfBytes); + } +#endregion + } +} diff --git a/OpenVinoOpenCvSharp/Util/PInvokeHelper.cs b/OpenVinoOpenCvSharp/Util/PInvokeHelper.cs new file mode 100644 index 0000000..4c2f7d5 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/PInvokeHelper.cs @@ -0,0 +1,78 @@ +using System; + +namespace OpenCvSharp.Util +{ + /// + /// + /// + public static class PInvokeHelper + { +#if LANG_JP + /// + /// PInvokeが正常に行えるかチェックする + /// +#else + /// + /// Checks whether PInvoke functions can be called + /// +#endif + public static void TryPInvoke() + { + try + { + NativeMethods.core_Mat_sizeof(); + } + catch (DllNotFoundException e) + { + DllImportError(e); + } + catch (BadImageFormatException e) + { + DllImportError(e); + } + } + + /// + /// DllImportの際にDllNotFoundExceptionかBadImageFormatExceptionが発生した際に呼び出されるメソッド。 + /// エラーメッセージを表示して解決策をユーザに示す。 + /// + /// + public static void DllImportError(Exception ex) + { + throw CreateException(ex); + } + + /// + /// + /// + /// + public static OpenCvSharpException CreateException(Exception ex) + { + /*StringBuilder message = new StringBuilder(); + if (System.Globalization.CultureInfo.CurrentCulture.Name.Contains("ja")) + { + message.AppendFormat("{0}\n", ex.Message); + message.Append("*** P/Invokeが原因で例外が発生しました。***\n") + .Append("以下の項目を確認して下さい。\n") + .Append("(1) OpenCVのDLLが実行ファイルと同じ場所に置かれていますか? またはパスが正しく通っていますか?\n") + .Append("(2) Visual C++ Redistributable Packageをインストールしましたか?\n") + .Append("(3) OpenCVのDLLやOpenCvSharpの対象プラットフォーム(x86またはx64)と、プロジェクトのプラットフォーム設定が合っていますか?\n") + .Append("\n") + .Append(ex.ToString()); + } + else + { + message.AppendFormat("{0}\n", ex.Message); + message.Append("*** An exception has occurred because of P/Invoke. ***\n") + .Append("Please check the following:\n") + .Append("(1) OpenCV's DLL files exist in the same directory as the executable file.\n") + .Append("(2) Visual C++ Redistributable Package has been installed.\n") + .Append("(3) The target platform(x86/x64) of OpenCV's DLL files and OpenCvSharp is the same as your project's.\n") + .Append("\n") + .Append(ex.ToString()); + } + return new OpenCvSharpException(message.ToString(), ex);*/ + return new OpenCvSharpException(ex.Message, ex); + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/Platform.cs b/OpenVinoOpenCvSharp/Util/Platform.cs new file mode 100644 index 0000000..7b07dc9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/Platform.cs @@ -0,0 +1,51 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp.Util +{ + // ReSharper disable once InconsistentNaming + internal enum OS + { + Windows, + Unix + } + internal enum Runtime + { + DotNet, + Mono + } + + /// + /// Provides information for the platform which the user is using + /// + internal static class Platform + { + /// + /// OS type + /// + // ReSharper disable once InconsistentNaming + public static readonly OS OS; + /// + /// Runtime type + /// + public static readonly Runtime Runtime; + + static Platform() + { +#if DOTNET_FRAMEWORK + var p = (int)Environment.OSVersion.Platform; + OS = ((p == 4) || (p == 6) || (p == 128)) ? OS.Unix : OS.Windows; +#elif uap10 + OS = OS.Windows; +#else + OS = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || + RuntimeInformation.IsOSPlatform(OSPlatform.OSX) + ? OS.Unix + : OS.Windows; +#endif + Runtime = (Type.GetType("Mono.Runtime") == null) ? Runtime.Mono : Runtime.DotNet; + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/PlatformUtil.cs b/OpenVinoOpenCvSharp/Util/PlatformUtil.cs new file mode 100644 index 0000000..97ce5d2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/PlatformUtil.cs @@ -0,0 +1,19 @@ +using System; + +namespace OpenCvSharp +{ + internal static class PlatformUtil + { + public static long AlignSize(long sz, int n) + { + return (sz + n - 1) & -n; + } + + public static long TruncateForX86(long value) + { + if (IntPtr.Size == 4) + return (int)value; + return value; + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/ScopedGCHandle.cs b/OpenVinoOpenCvSharp/Util/ScopedGCHandle.cs new file mode 100644 index 0000000..c31e7b7 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/ScopedGCHandle.cs @@ -0,0 +1,337 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp.Util +{ +#if LANG_JP + /// + /// IDisposableを実装したGCHandle + /// +#else + /// + /// Original GCHandle that implement IDisposable + /// +#endif + // ReSharper disable once InconsistentNaming + public class ScopedGCHandle : IDisposable + { + private GCHandle handle; + private bool disposed; + + #region Init and Disposal + +#if LANG_JP + /// + /// 指定したオブジェクトに System.Runtime.InteropServices.GCHandleType.Normal ハンドルを割り当てます + /// + /// GCの対象からはずすオブジェクト +#else + /// + /// + /// + /// +#endif + public ScopedGCHandle(object value) + { + if (value != null) + { + handle = GCHandle.Alloc(value); + } + disposed = false; + } + +#if LANG_JP + /// + /// 指定したオブジェクトに指定した型のハンドルを割り当てます + /// + /// GCの対象からはずすオブジェクト + /// 作成する System.Runtime.InteropServices.GCHandle の型を示す、System.Runtime.InteropServices.GCHandleType 値の 1 つ +#else + /// + /// + /// + /// + /// +#endif + public ScopedGCHandle(object value, GCHandleType type) + { + if (value != null) + { + handle = GCHandle.Alloc(value, type); + } + disposed = false; + } + +#if LANG_JP + /// + /// GCHandleから初期化 + /// + /// +#else + /// + /// + /// + /// +#endif + private ScopedGCHandle(GCHandle handle) + { + this.handle = handle; + disposed = false; + } + +#if LANG_JP + /// + /// 指定したオブジェクトに System.Runtime.InteropServices.GCHandleType.Normal ハンドルを割り当てます + /// + /// System.Runtime.InteropServices.GCHandle を使用するオブジェクト + /// オブジェクトをガベージ コレクションから保護する新しい System.Runtime.InteropServices.GCHandle。 + /// System.Runtime.InteropServices.GCHandle は、不要になったときに System.Runtime.InteropServices.GCHandle.Free() で解放する必要があります。 + /// 非プリミティブ (blittable でない) メンバを持つインスタンスは固定できません +#else + /// + /// + /// + /// + /// +#endif + public static ScopedGCHandle Alloc(object value) + { + return new ScopedGCHandle(value); + } + +#if LANG_JP + /// + /// 指定したオブジェクトに指定した型のハンドルを割り当てます + /// + /// System.Runtime.InteropServices.GCHandle を使用するオブジェクト + /// 作成する System.Runtime.InteropServices.GCHandle の型を示す、System.Runtime.InteropServices.GCHandleType 値の 1 つ + /// オブジェクトをガベージ コレクションから保護する新しい System.Runtime.InteropServices.GCHandle。 + /// System.Runtime.InteropServices.GCHandle は、不要になったときに System.Runtime.InteropServices.GCHandle.Free() で解放する必要があります。 + /// 非プリミティブ (blittable でない) メンバを持つインスタンスは固定できません +#else + /// + /// + /// + /// + /// + /// +#endif + public static ScopedGCHandle Alloc(object value, GCHandleType type) + { + return new ScopedGCHandle(value, type); + } + +#if LANG_JP + /// + /// GCHandle.Freeによりリソースの解放を行う + /// +#else + /// + /// + /// +#endif + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// + /// + /// + protected virtual void Dispose(bool disposing) + { + if (!disposed) + { + if (disposing) + { + } + // Release managed resources. + if (handle.IsAllocated) + { + handle.Free(); + } + disposed = true; + } + } + + /// + /// Destructor + /// + ~ScopedGCHandle() + { + Dispose(false); + } + #endregion + + #region Static methods +#if LANG_JP + /// + /// マネージ オブジェクトを識別するハンドルから作成された新しい System.Runtime.InteropServices.GCHandle オブジェクトを返します + /// + /// System.Runtime.InteropServices.GCHandle オブジェクトの作成元のマネージ オブジェクトを識別する System.IntPtr ハンドル + /// value パラメータの値が System.IntPtr.Zero です + /// 値パラメータに対応する新しい System.Runtime.InteropServices.GCHandle オブジェクト +#else + /// + /// + /// + /// + /// +#endif + public static ScopedGCHandle FromIntPtr(IntPtr value) + { + return new ScopedGCHandle(GCHandle.FromIntPtr(value)); + } + +#if LANG_JP + /// + /// System.Runtime.InteropServices.GCHandle オブジェクトの内部整数表現を返します + /// + /// 内部整数表現の取得元の System.Runtime.InteropServices.GCHandle オブジェクト + /// System.Runtime.InteropServices.GCHandle オブジェクトを表す System.IntPtr オブジェクト +#else + /// + /// + /// + /// + /// +#endif + public static IntPtr ToIntPtr(ScopedGCHandle value) + { + return GCHandle.ToIntPtr(value.Handle); + } + #endregion + + #region Properties +#if LANG_JP + /// + /// 内部で保持するGCHandle + /// +#else + /// + /// + /// +#endif + public GCHandle Handle + { + get { return handle; } + } + +#if LANG_JP + /// + /// ハンドルが割り当てられているかどうかを示す値を取得します + /// +#else + /// + /// + /// +#endif + public bool IsAllocated + { + get { return handle.IsAllocated; } + } + +#if LANG_JP + /// + /// ハンドルが表すオブジェクトを取得または設定します + /// +#else + /// + /// + /// +#endif + public object? Target + { + get { return handle.Target; } + set { handle.Target = value; } + } + + #endregion + + #region Methods + +#if LANG_JP + /// + /// System.Runtime.InteropServices.GCHandleType.Pinned ハンドル内のオブジェクトのアドレスを取得します + /// + /// System.IntPtr としての Pinned オブジェクトのアドレス +#else + /// + /// + /// + /// +#endif + public IntPtr AddrOfPinnedObject() + { + return handle.AddrOfPinnedObject(); + } + +#if LANG_JP + /// + /// 指定した System.Runtime.InteropServices.GCHandle オブジェクトが、現在の System.Runtime.InteropServices.GCHandle オブジェクトと等しいかどうかを判断します + /// + /// 現在の System.Runtime.InteropServices.GCHandle オブジェクトと比較する System.Runtime.InteropServices.GCHandle オブジェクト + /// +#else + /// + /// + /// + /// + /// +#endif + public override bool Equals(object? obj) + { + return handle.Equals(obj); + } + +#if LANG_JP + /// + /// System.Runtime.InteropServices.GCHandle を解放します + /// +#else + /// + /// + /// +#endif + public void Free() + { + handle.Free(); + } + +#if LANG_JP + /// + /// 現在の System.Runtime.InteropServices.GCHandle オブジェクトの識別子を返します + /// + /// 現在の System.Runtime.InteropServices.GCHandle オブジェクトの識別子 +#else + /// + /// + /// + /// +#endif + public override int GetHashCode() + { + return handle.GetHashCode(); + } + +#if LANG_JP + /// + /// 文字列形式を返す + /// + /// +#else + /// + /// + /// + /// +#endif + public override string? ToString() + { + return handle.ToString(); + } + + #endregion + } +} diff --git a/OpenVinoOpenCvSharp/Util/StringArrayAddress.cs b/OpenVinoOpenCvSharp/Util/StringArrayAddress.cs new file mode 100644 index 0000000..6de8696 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/StringArrayAddress.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace OpenCvSharp.Util +{ + /// + /// + /// Class to get address of string array + /// + public class StringArrayAddress : ArrayAddress2 + { + /// + /// + /// + /// + public StringArrayAddress(IEnumerable stringEnumerable) + : base(ToJaggedByteArray(stringEnumerable)) + { + } + + private static byte[][] ToJaggedByteArray(IEnumerable stringEnumerable) + { + if (stringEnumerable == null) + throw new ArgumentNullException(nameof(stringEnumerable)); + + var byteList = new List(); + foreach (var s in stringEnumerable) + { + byteList.Add(Encoding.ASCII.GetBytes(s)); + } + return byteList.ToArray(); + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Util/StringHelper.cs b/OpenVinoOpenCvSharp/Util/StringHelper.cs new file mode 100644 index 0000000..9b1e2db --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/StringHelper.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp.Util +{ + internal static class StringHelper + { + public static unsafe string? PtrToStringAnsi(sbyte* p) + { +#if DOTNET_FRAMEWORK + return new string(p); +#else + // memo: https://github.com/dotnet/standard/blob/master/netstandard/ref/mscorlib.cs#L2970 + return Marshal.PtrToStringAnsi(new IntPtr(p)); +#endif + } + + public static string? PtrToStringAnsi(IntPtr p) + { +#if DOTNET_FRAMEWORK + unsafe + { + return new string((sbyte*)p); + } +#else + // memo: https://github.com/dotnet/standard/blob/master/netstandard/ref/mscorlib.cs#L2970 + return Marshal.PtrToStringAnsi(p); +#endif + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/StructurePointer.cs b/OpenVinoOpenCvSharp/Util/StructurePointer.cs new file mode 100644 index 0000000..59c8753 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/StructurePointer.cs @@ -0,0 +1,122 @@ +using System; +using System.Runtime.InteropServices; + +namespace OpenCvSharp.Util +{ +#if LANG_JP + /// + /// 構造体とポインタの変換やメモリの解放を自動的にやってくれるクラス (ジェネリック版) + /// + /// +#else + /// + /// Class that converts structure into pointer and cleans up resources automatically (generic version) + /// + /// +#endif + public class StructurePointer + where T : struct + { + +#if LANG_JP + /// + /// 実体ポインタ + /// +#else + /// + /// Pointer + /// +#endif + + public IntPtr Ptr { get; protected set; } +#if LANG_JP + /// + /// 初期化の際に渡された構造体オブジェクト + /// +#else + /// + /// Structure + /// +#endif + public T SrcObj { get; protected set; } +#if LANG_JP + /// + /// 確保したメモリのバイトサイズ + /// +#else + /// + /// Size of allocated memory + /// +#endif + public int Size { get; protected set; } + + +#if LANG_JP + /// + /// 指定した構造体オブジェクトをポインタに変換して初期化 + /// + /// +#else + /// + /// + /// + /// +#endif + public StructurePointer(T obj) + { + SrcObj = obj; + Size = MarshalHelper.SizeOf(); + Ptr = Marshal.AllocHGlobal(Size); + Marshal.StructureToPtr(obj, Ptr, false); + } +#if LANG_JP + /// + /// T型のバイトサイズのポインタを生成して初期化 + /// +#else + /// + /// + /// +#endif + public StructurePointer() + { + SrcObj = default; + Size = MarshalHelper.SizeOf(); + Ptr = Marshal.AllocHGlobal(Size); + } + +#if LANG_JP + /// + /// IntPtrへの暗黙の変換 + /// + /// + /// +#else + /// + /// + /// + /// + /// +#endif + public static implicit operator IntPtr(StructurePointer self) + { + return self.Ptr; + } + +#if LANG_JP + /// + /// ポインタから構造体に変換して返す + /// + /// +#else + /// + /// + /// + /// +#endif + public T ToStructure() + { + return MarshalHelper.PtrToStructure(Ptr); + } + } +} \ No newline at end of file diff --git a/OpenVinoOpenCvSharp/Util/TimeMeasurer.cs b/OpenVinoOpenCvSharp/Util/TimeMeasurer.cs new file mode 100644 index 0000000..b06d412 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/TimeMeasurer.cs @@ -0,0 +1,29 @@ +using System; +using System.Diagnostics; + +namespace OpenCvSharp.Util +{ + /// + /// Substitute of System.Action + /// + public delegate void Action(); + + /// + /// + /// + public static class TimeMeasurer + { + /// + /// + /// + /// + /// + public static TimeSpan Measure(Action action) + { + var watch = Stopwatch.StartNew(); + action(); + watch.Stop(); + return watch.Elapsed; + } + } +} diff --git a/OpenVinoOpenCvSharp/Util/TypeHelper.cs b/OpenVinoOpenCvSharp/Util/TypeHelper.cs new file mode 100644 index 0000000..f6dfc52 --- /dev/null +++ b/OpenVinoOpenCvSharp/Util/TypeHelper.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.InteropServices; + +#pragma warning disable 1591 + +namespace OpenCvSharp.Util +{ + /// + /// + /// + public static class TypeHelper + { +#if LANG_JP +/// +/// ポインタから構造体にキャストを試みる +/// +/// +/// +/// +#else + /// + /// + /// + /// + /// + /// +#endif + public static T ToObject(IntPtr ptr) where T : struct + { + var t = typeof(T); + // IntPtrはそのまま返す + if (t == typeof(IntPtr)) + { + return (T) (object) ptr; + } + +#if NET20 || NET40 + return (T)Marshal.PtrToStructure(ptr, typeof(T)); +#else + return Marshal.PtrToStructure(ptr); +#endif + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/IStdVector.cs b/OpenVinoOpenCvSharp/Vector/IStdVector.cs new file mode 100644 index 0000000..e7b8f75 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/IStdVector.cs @@ -0,0 +1,26 @@ +using System; + +namespace OpenCvSharp +{ + /// + /// Represents std::vector + /// + public interface IStdVector : IDisposable + { + /// + /// vector.size() + /// + int Size { get; } + + /// + /// &vector[0] + /// + IntPtr ElemPtr { get; } + + /// + /// Convert std::vector<T> to managed array T[] + /// + /// + T[] ToArray(); + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfByte.cs b/OpenVinoOpenCvSharp/Vector/VectorOfByte.cs new file mode 100644 index 0000000..5c77e2b --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfByte.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfByte : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfByte() + { + ptr = NativeMethods.vector_uchar_new1(); + } + + /// + /// + /// + /// + public VectorOfByte(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_uchar_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfByte(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_uchar_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_uchar_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_uchar_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_uchar_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public byte[] ToArray() + { + var size = Size; + if (size == 0) + { + return new byte[0]; + } + var dst = new byte[size]; + Marshal.Copy(ElemPtr, dst, 0, dst.Length); + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfDMatch.cs b/OpenVinoOpenCvSharp/Vector/VectorOfDMatch.cs new file mode 100644 index 0000000..b0359ec --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfDMatch.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfDMatch : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfDMatch() + { + ptr = NativeMethods.vector_DMatch_new1(); + } + + /// + /// + /// + /// + public VectorOfDMatch(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfDMatch(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_DMatch_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfDMatch(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_DMatch_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_DMatch_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_DMatch_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_DMatch_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public DMatch[] ToArray() + { + var size = Size; + if (size == 0) + { + return new DMatch[0]; + } + var dst = new DMatch[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf()*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfDTreesNode.cs b/OpenVinoOpenCvSharp/Vector/VectorOfDTreesNode.cs new file mode 100644 index 0000000..a97ed6e --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfDTreesNode.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; +using OpenCvSharp.ML; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfDTreesNode : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfDTreesNode() + { + ptr = NativeMethods.vector_DTrees_Node_new1(); + } + + /// + /// + /// + /// + public VectorOfDTreesNode(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfDTreesNode(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_DTrees_Node_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfDTreesNode(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_DTrees_Node_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_DTrees_Node_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_DTrees_Node_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_DTrees_Node_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public DTrees.Node[] ToArray() + { + var size = Size; + if (size == 0) + { + return new DTrees.Node[0]; + } + var dst = new DTrees.Node[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf() * dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfDTreesSplit.cs b/OpenVinoOpenCvSharp/Vector/VectorOfDTreesSplit.cs new file mode 100644 index 0000000..d295cc2 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfDTreesSplit.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; +using OpenCvSharp.ML; + +namespace OpenCvSharp +{ + /// + /// + /// + internal class VectorOfDTreesSplit : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfDTreesSplit() + { + ptr = NativeMethods.vector_DTrees_Split_new1(); + } + + /// + /// + /// + /// + public VectorOfDTreesSplit(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfDTreesSplit(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_DTrees_Split_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfDTreesSplit(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_DTrees_Split_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_DTrees_Split_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_DTrees_Split_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_DTrees_Split_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public DTrees.Split[] ToArray() + { + var size = Size; + if (size == 0) + { + return new DTrees.Split[0]; + } + var dst = new DTrees.Split[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf() * dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfDouble.cs b/OpenVinoOpenCvSharp/Vector/VectorOfDouble.cs new file mode 100644 index 0000000..21c304d --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfDouble.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfDouble : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfDouble() + { + ptr = NativeMethods.vector_double_new1(); + } + + /// + /// + /// + /// + public VectorOfDouble(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_double_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfDouble(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_double_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_double_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_double_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_double_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public double[] ToArray() + { + var size = Size; + if (size == 0) + { + return new double[0]; + } + var dst = new double[size]; + Marshal.Copy(ElemPtr, dst, 0, dst.Length); + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfFloat.cs b/OpenVinoOpenCvSharp/Vector/VectorOfFloat.cs new file mode 100644 index 0000000..f81b300 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfFloat.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfFloat : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfFloat() + { + ptr = NativeMethods.vector_float_new1(); + } + + /// + /// + /// + /// + public VectorOfFloat(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_float_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfFloat(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_float_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_float_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_float_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_float_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public float[] ToArray() + { + var size = Size; + if (size == 0) + { + return new float[0]; + } + var dst = new float[size]; + Marshal.Copy(ElemPtr, dst, 0, dst.Length); + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfInt32.cs b/OpenVinoOpenCvSharp/Vector/VectorOfInt32.cs new file mode 100644 index 0000000..9368117 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfInt32.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfInt32 : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfInt32() + { + ptr = NativeMethods.vector_int32_new1(); + } + + /// + /// + /// + /// + public VectorOfInt32(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_int32_new2(new IntPtr(size)); + } + + /// + /// + /// + public VectorOfInt32(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfInt32(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_int32_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_int32_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_int32_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_int32_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public int[] ToArray() + { + var size = Size; + if (size == 0) + { + return new int[0]; + } + var dst = new int[size]; + Marshal.Copy(ElemPtr, dst, 0, dst.Length); + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfKeyPoint.cs b/OpenVinoOpenCvSharp/Vector/VectorOfKeyPoint.cs new file mode 100644 index 0000000..507ca45 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfKeyPoint.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfKeyPoint : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfKeyPoint() + { + ptr = NativeMethods.vector_KeyPoint_new1(); + } + + /// + /// + /// + /// + public VectorOfKeyPoint(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfKeyPoint(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_KeyPoint_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfKeyPoint(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_KeyPoint_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_KeyPoint_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_KeyPoint_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_KeyPoint_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public KeyPoint[] ToArray() + { + var size = Size; + if (size == 0) + { + return new KeyPoint[0]; + } + var dst = new KeyPoint[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, MarshalHelper.SizeOf() * dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfMat.cs b/OpenVinoOpenCvSharp/Vector/VectorOfMat.cs new file mode 100644 index 0000000..390883c --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfMat.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfMat : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfMat() + { + ptr = NativeMethods.vector_Mat_new1(); + } + + /// + /// + /// + /// + public VectorOfMat(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Mat_new2((uint)size); + } + + /// + /// + /// + /// + public VectorOfMat(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfMat(IEnumerable mats) + { + if (mats == null) + throw new ArgumentNullException(nameof(mats)); + + var matsArray = EnumerableEx.ToArray(mats); + var matPointers = EnumerableEx.SelectPtrs(matsArray); + + ptr = NativeMethods.vector_Mat_new3( + matPointers, + (uint) matPointers.Length); + + GC.KeepAlive(matPointers); + GC.KeepAlive(mats); // todo: rsb - should probably generate Mat[] and then get CvPtrs + foreach (var m in matsArray) + { + GC.KeepAlive(m); + } + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Mat_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Mat_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Mat_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Mat[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// + public T[] ToArray() + where T : Mat, new() + { + var size = Size; + if (size == 0) + return new T[0]; + + var dst = new T[size]; + var dstPtr = new IntPtr[size]; + for (var i = 0; i < size; i++) + { + var m = new T(); + dst[i] = m; + dstPtr[i] = m.CvPtr; + } + NativeMethods.vector_Mat_assignToArray(ptr, dstPtr); + GC.KeepAlive(this); + + return dst; + } + + /// + /// 各要素の参照カウントを1追加する + /// + public void AddRef() + { + NativeMethods.vector_Mat_addref(ptr); + GC.KeepAlive(this); + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfPoint.cs b/OpenVinoOpenCvSharp/Vector/VectorOfPoint.cs new file mode 100644 index 0000000..b790c44 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfPoint.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfPoint : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfPoint() + { + ptr = NativeMethods.vector_Point2i_new1(); + } + + /// + /// + /// + /// + public VectorOfPoint(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Point2i_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfPoint(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfPoint(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Point2i_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Point2i_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Point2i_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Point2i_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Point[] ToArray() + { + var size = Size; + if (size == 0) + { + return new Point[0]; + } + var dst = new Point[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, Point.SizeOf*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfPoint2f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfPoint2f.cs new file mode 100644 index 0000000..968d40c --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfPoint2f.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfPoint2f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfPoint2f() + { + ptr = NativeMethods.vector_Point2f_new1(); + } + + /// + /// + /// + /// + public VectorOfPoint2f(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfPoint2f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Point2f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfPoint2f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Point2f_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Point2f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Point2f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Point2f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Point2f[] ToArray() + { + var size = Size; + if (size == 0) + { + return new Point2f[0]; + } + var dst = new Point2f[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, Point2f.SizeOf*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfPoint3f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfPoint3f.cs new file mode 100644 index 0000000..8ddfe6d --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfPoint3f.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfPoint3f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfPoint3f() + { + ptr = NativeMethods.vector_Point3f_new1(); + } + + /// + /// + /// + /// + public VectorOfPoint3f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Point3f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfPoint3f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Point3f_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Point3f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Point3f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Point3f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Point3f[] ToArray() + { + var size = Size; + if (size == 0) + { + return new Point3f[0]; + } + var dst = new Point3f[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, Point3f.SizeOf*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfRect.cs b/OpenVinoOpenCvSharp/Vector/VectorOfRect.cs new file mode 100644 index 0000000..146e32f --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfRect.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfRect : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfRect() + { + ptr = NativeMethods.vector_Rect_new1(); + } + + /// + /// + /// + /// + public VectorOfRect(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Rect_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfRect(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Rect_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Rect_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Rect_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Rect_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Rect[] ToArray() + { + var size = Size; + if (size == 0) + { + return new Rect[0]; + } + var dst = new Rect[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, Rect.SizeOf*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfRect2d.cs b/OpenVinoOpenCvSharp/Vector/VectorOfRect2d.cs new file mode 100644 index 0000000..549a82a --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfRect2d.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfRect2d : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfRect2d() + { + ptr = NativeMethods.vector_Rect2d_new1(); + } + + /// + /// + /// + /// + public VectorOfRect2d(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Rect2d_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfRect2d(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Rect2d_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Rect2d_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Rect2d_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Rect2d_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Rect2d[] ToArray() + { + var size = Size; + if (size == 0) + { + return new Rect2d[0]; + } + var dst = new Rect2d[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, Rect.SizeOf*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfRotatedRect.cs b/OpenVinoOpenCvSharp/Vector/VectorOfRotatedRect.cs new file mode 100644 index 0000000..4c2aa65 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfRotatedRect.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +// ReSharper disable UnusedMember.Global + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfRotatedRect : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfRotatedRect() + { + ptr = NativeMethods.vector_RotatedRect_new1(); + } + + /// + /// + /// + /// + public VectorOfRotatedRect(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_RotatedRect_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfRotatedRect(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_RotatedRect_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_RotatedRect_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_RotatedRect_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_RotatedRect_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public RotatedRect[] ToArray() + { + var size = Size; + if (size == 0) + return new RotatedRect[0]; + + var dst = new RotatedRect[size]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, RotatedRect.SizeOf * dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfSByte.cs b/OpenVinoOpenCvSharp/Vector/VectorOfSByte.cs new file mode 100644 index 0000000..577a1f0 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfSByte.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfSByte : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfSByte() + { + ptr = NativeMethods.vector_char_new1(); + } + + /// + /// + /// + /// + public VectorOfSByte(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_char_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfSByte(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_char_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_char_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_char_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_char_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public sbyte[] ToArray() + { + var size = Size; + if (size == 0) + { + return new sbyte[0]; + } + var dst = new byte[size]; + Marshal.Copy(ElemPtr, dst, 0, dst.Length); + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return EnumerableEx.SelectToArray(dst, b => (sbyte)b); + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfString.cs b/OpenVinoOpenCvSharp/Vector/VectorOfString.cs new file mode 100644 index 0000000..4a835f3 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfString.cs @@ -0,0 +1,97 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfString : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfString() + { + ptr = NativeMethods.vector_string_new1(); + } + + /// + /// + /// + /// + public VectorOfString(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfString(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_string_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_string_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_string_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_string_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public string?[] ToArray() + { + var size = Size; + if (size == 0) + return new string?[0]; + + var ret = new string?[size]; + for (var i = 0; i < size; i++) + { + unsafe + { + var p = NativeMethods.vector_string_elemAt(ptr, i); + ret[i] = StringHelper.PtrToStringAnsi(p); + } + } + GC.KeepAlive(this); + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec2f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec2f.cs new file mode 100644 index 0000000..c76982a --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec2f.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfVec2f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec2f() + { + ptr = NativeMethods.vector_Vec2f_new1(); + } + + /// + /// + /// + /// + public VectorOfVec2f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec2f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec2f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec2f_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec2f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec2f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec2f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec2f[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has two float members (ex. CvLineSegmentPolar, CvPoint2D32f, PointF) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (float)*2) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + else + { + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec3f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec3f.cs new file mode 100644 index 0000000..3996a5b --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec3f.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfVec3f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec3f() + { + ptr = NativeMethods.vector_Vec3f_new1(); + } + + /// + /// + /// + /// + public VectorOfVec3f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec3f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec3f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec3f_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec3f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec3f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec3f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec3f[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has two float members (ex. CvLineSegmentPolar, CvPoint2D32f, PointF) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (float)*3) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec4f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec4f.cs new file mode 100644 index 0000000..47af838 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec4f.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfVec4f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec4f() + { + ptr = NativeMethods.vector_Vec4f_new1(); + } + + /// + /// + /// + /// + public VectorOfVec4f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec4f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec4f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec4f_new3(array, new IntPtr(array.Length)); + } + + /// + /// + /// + /// + public VectorOfVec4f(IntPtr p) + { + ptr = p; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec4f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec4f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec4f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec4f[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has four int members (ex. CvLineSegmentPoint, CvRect) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (float)*4) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec4i.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec4i.cs new file mode 100644 index 0000000..39e2d38 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec4i.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfVec4i : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec4i() + { + ptr = NativeMethods.vector_Vec4i_new1(); + } + + /// + /// + /// + /// + public VectorOfVec4i(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec4i_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec4i(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfVec4i(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec4i_new3(array, new IntPtr(array.Length)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec4i_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec4i_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec4i_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec4i[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has four int members (ex. CvLineSegmentPoint, CvRect) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (int)*4) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec6d.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec6d.cs new file mode 100644 index 0000000..1cf0d5d --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec6d.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVec6d : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec6d() + { + ptr = NativeMethods.vector_Vec6d_new1(); + } + + /// + /// + /// + /// + public VectorOfVec6d(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec6d_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec6d(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec6d_new3(array, new IntPtr(array.Length)); + } + + /// + /// + /// + /// + public VectorOfVec6d(IntPtr p) + { + ptr = p; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec6d_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec6d_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec6d_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec6d[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has four int members (ex. CvLineSegmentPoint, CvRect) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (double)*6) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVec6f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVec6f.cs new file mode 100644 index 0000000..dab2054 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVec6f.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + internal class VectorOfVec6f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVec6f() + { + ptr = NativeMethods.vector_Vec6f_new1(); + } + + /// + /// + /// + /// + public VectorOfVec6f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_Vec6f_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVec6f(IEnumerable data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + var array = EnumerableEx.ToArray(data); + ptr = NativeMethods.vector_Vec6f_new3(array, new IntPtr(array.Length)); + } + + /// + /// + /// + /// + public VectorOfVec6f(IntPtr p) + { + ptr = p; + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_Vec6f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size + { + get + { + var res = NativeMethods.vector_Vec6f_getSize(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_Vec6f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Vec6f[] ToArray() + { + return ToArray(); + } + + /// + /// Converts std::vector to managed array + /// + /// structure that has four int members (ex. CvLineSegmentPoint, CvRect) + /// + public T[] ToArray() where T : unmanaged + { + var typeSize = MarshalHelper.SizeOf(); + if (typeSize != sizeof (float)*6) + { + throw new OpenCvSharpException(); + } + + var arySize = Size; + if (arySize == 0) + { + return new T[0]; + } + var dst = new T[arySize]; + using (var dstPtr = new ArrayAddress1(dst)) + { + MemoryHelper.CopyMemory(dstPtr, ElemPtr, typeSize*dst.Length); + } + GC.KeepAlive(this); // ElemPtr is IntPtr to memory held by this object, so + // make sure we are not disposed until finished with copy. + return dst; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorDMatch.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorDMatch.cs new file mode 100644 index 0000000..45bc876 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorDMatch.cs @@ -0,0 +1,114 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorDMatch : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorDMatch() + { + ptr = NativeMethods.vector_vector_DMatch_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorDMatch(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_DMatch_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_DMatch_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_DMatch_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_DMatch_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_DMatch_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public DMatch[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new DMatch[0][]; + var size2 = Size2; + + var ret = new DMatch[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new DMatch[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_DMatch_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorDouble.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorDouble.cs new file mode 100644 index 0000000..72bee18 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorDouble.cs @@ -0,0 +1,114 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorDouble : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorDouble() + { + ptr = NativeMethods.vector_vector_double_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorDouble(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_double_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_double_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_double_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_double_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_double_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public double[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new double[0][]; + var size2 = Size2; + + var ret = new double[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new double[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_double_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorFloat.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorFloat.cs new file mode 100644 index 0000000..0667a87 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorFloat.cs @@ -0,0 +1,114 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorFloat : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorFloat() + { + ptr = NativeMethods.vector_vector_float_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorFloat(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_float_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_float_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_float_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_float_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_float_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public float[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new float[0][]; + var size2 = Size2; + + var ret = new float[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new float[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_float_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorInt.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorInt.cs new file mode 100644 index 0000000..d5fcf4e --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorInt.cs @@ -0,0 +1,114 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorInt : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorInt() + { + ptr = NativeMethods.vector_vector_int_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorInt(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_int_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_int_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_int_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_int_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_int_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public int[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new int[0][]; + var size2 = Size2; + + var ret = new int[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new int[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_int_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorKeyPoint.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorKeyPoint.cs new file mode 100644 index 0000000..2d57836 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorKeyPoint.cs @@ -0,0 +1,130 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorKeyPoint : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorKeyPoint() + { + ptr = NativeMethods.vector_vector_KeyPoint_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorKeyPoint(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_KeyPoint_new2(new IntPtr(size)); + } + + /// + /// + /// + /// + public VectorOfVectorKeyPoint(KeyPoint[][] values) + { + if (values == null) + throw new ArgumentNullException(nameof(values)); + + using (var aa = new ArrayAddress2(values)) + { + ptr = NativeMethods.vector_vector_KeyPoint_new3( + aa.Pointer, aa.Dim1Length, aa.Dim2Lengths); + } + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_KeyPoint_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_KeyPoint_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_KeyPoint_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_KeyPoint_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public KeyPoint[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new KeyPoint[0][]; + var size2 = Size2; + + var ret = new KeyPoint[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new KeyPoint[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_KeyPoint_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint.cs new file mode 100644 index 0000000..c04d3a9 --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint.cs @@ -0,0 +1,123 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + public class VectorOfVectorPoint : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorPoint() + { + ptr = NativeMethods.vector_vector_Point_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorPoint(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfVectorPoint(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_Point_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_Point_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_Point_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector.size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_Point_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_Point_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Point[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new Point[0][]; + var size2 = Size2; + + var ret = new Point[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new Point[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_Point_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint2f.cs b/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint2f.cs new file mode 100644 index 0000000..9a506fa --- /dev/null +++ b/OpenVinoOpenCvSharp/Vector/VectorOfVectorPoint2f.cs @@ -0,0 +1,124 @@ +using System; +using OpenCvSharp.Util; + +namespace OpenCvSharp +{ + /// + /// + /// + // ReSharper disable once InconsistentNaming + public class VectorOfVectorPoint2f : DisposableCvObject, IStdVector + { + /// + /// + /// + public VectorOfVectorPoint2f() + { + ptr = NativeMethods.vector_vector_Point2f_new1(); + } + + /// + /// + /// + /// + public VectorOfVectorPoint2f(IntPtr ptr) + { + this.ptr = ptr; + } + + /// + /// + /// + /// + public VectorOfVectorPoint2f(int size) + { + if (size < 0) + throw new ArgumentOutOfRangeException(nameof(size)); + ptr = NativeMethods.vector_vector_Point2f_new2(new IntPtr(size)); + } + + /// + /// Releases unmanaged resources + /// + protected override void DisposeUnmanaged() + { + NativeMethods.vector_vector_Point2f_delete(ptr); + base.DisposeUnmanaged(); + } + + /// + /// vector.size() + /// + public int Size1 + { + get + { + var res = NativeMethods.vector_vector_Point2f_getSize1(ptr).ToInt32(); + GC.KeepAlive(this); + return res; + } + } + + /// + /// + /// + public int Size => Size1; + + /// + /// vector[i].size() + /// + public long[] Size2 + { + get + { + var size1 = Size1; + var size2Org = new IntPtr[size1]; + NativeMethods.vector_vector_Point2f_getSize2(ptr, size2Org); + GC.KeepAlive(this); + var size2 = new long[size1]; + for (var i = 0; i < size1; i++) + { + size2[i] = size2Org[i].ToInt64(); + } + return size2; + } + } + + /// + /// &vector[0] + /// + public IntPtr ElemPtr + { + get + { + var res = NativeMethods.vector_vector_Point2f_getPointer(ptr); + GC.KeepAlive(this); + return res; + } + } + + /// + /// Converts std::vector to managed array + /// + /// + public Point2f[][] ToArray() + { + var size1 = Size1; + if (size1 == 0) + return new Point2f[0][]; + var size2 = Size2; + + var ret = new Point2f[size1][]; + for (var i = 0; i < size1; i++) + { + ret[i] = new Point2f[size2[i]]; + } + using (var retPtr = new ArrayAddress2(ret)) + { + NativeMethods.vector_vector_Point2f_copy(ptr, retPtr); + GC.KeepAlive(this); + } + return ret; + } + } +} diff --git a/OpenVinoOpenCvSharpExtern/CMakeLists.txt b/OpenVinoOpenCvSharpExtern/CMakeLists.txt new file mode 100644 index 0000000..4a8ef72 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(OpenCV REQUIRED) +message(STATUS "OpenCV library status:") +message(STATUS " version: ${OpenCV_VERSION}") +message(STATUS " libraries: ${OpenCV_LIBS}") +message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}") + +file(GLOB OPENVINOOPENCVSHARP_FILES *.cpp) + +find_package(OpenCV REQUIRED) + +add_library(OpenVinoOpenCvSharpExtern SHARED ${OPENVINOOPENCVSHARP_FILES}) +target_link_libraries(OpenVinoOpenCvSharpExtern ${OpenCV_LIBS}) + +install(TARGETS OpenVinoOpenCvSharpExtern + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib/static +) diff --git a/OpenVinoOpenCvSharpExtern/core.cpp b/OpenVinoOpenCvSharpExtern/core.cpp new file mode 100644 index 0000000..1d6a023 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core.cpp @@ -0,0 +1,14 @@ +// ReSharper disable CppUnusedIncludeDirective +#include "core.h" +#include "core_Algorithm.h" +#include "core_FileStorage.h" +#include "core_FileNode.h" +#include "core_InputArray.h" +#include "core_Mat.h" +#include "core_MatExpr.h" +#include "core_OutputArray.h" +#include "core_PCA.h" +#include "core_RNG.h" +#include "core_SparseMat.h" +#include "core_SVD.h" +#include "core_LDA.h" \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core.h b/OpenVinoOpenCvSharpExtern/core.h new file mode 100644 index 0000000..7d00d97 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core.h @@ -0,0 +1,700 @@ +#ifndef _CPP_CORE_H_ +#define _CPP_CORE_H_ + +#include "include_opencv.h" + +#pragma region Miscellaneous + +CVAPI(void) core_setNumThreads(int nthreads) +{ + cv::setNumThreads(nthreads); +} +CVAPI(int) core_getNumThreads() +{ + return cv::getNumThreads(); +} +CVAPI(int) core_getThreadNum() +{ + return cv::getThreadNum(); +} + +CVAPI(void) core_getBuildInformation(char *buf, int maxLength) +{ + const cv::String &str = cv::getBuildInformation(); + copyString(str, buf, maxLength); +} +CVAPI(int) core_getBuildInformation_length() +{ + const cv::String &str = cv::getBuildInformation(); + return static_cast(str.length()); +} + +CVAPI(void) core_getVersionString(char *buf, int bufLength) +{ + const std::string &str = cv::getVersionString(); + copyString(str, buf, bufLength); +} + +CVAPI(int) core_getVersionMajor() +{ + return cv::getVersionMajor(); +} + +CVAPI(int) core_getVersionMinor() +{ + return cv::getVersionMinor(); +} + +CVAPI(int) core_getVersionRevision() +{ + return cv::getVersionRevision(); +} + +CVAPI(int64) core_getTickCount() +{ + return cv::getTickCount(); +} +CVAPI(double) core_getTickFrequency() +{ + return cv::getTickFrequency(); +} +CVAPI(int64) core_getCPUTickCount() +{ + return cv::getCPUTickCount(); +} + +CVAPI(int) core_checkHardwareSupport(int feature) +{ + return cv::checkHardwareSupport(feature) ? 1 : 0; +} + +CVAPI(void) core_getHardwareFeatureName(int feature, char *buf, int bufLength) +{ + const cv::String &str = cv::getHardwareFeatureName(feature); + copyString(str, buf, bufLength); +} + +CVAPI(void) core_getCPUFeaturesLine(char *buf, int bufLength) +{ + const cv::String &str = cv::getCPUFeaturesLine(); + copyString(str, buf, bufLength); +} + +CVAPI(int) core_getNumberOfCPUs() +{ + return cv::getNumberOfCPUs(); +} + +CVAPI(void*) core_fastMalloc(size_t bufSize) +{ + return cv::fastMalloc(bufSize); +} +CVAPI(void) core_fastFree(void *ptr) +{ + return cv::fastFree(ptr); +} + +CVAPI(void) core_setUseOptimized(int onoff) +{ + cv::setUseOptimized(onoff != 0); +} +CVAPI(int) core_useOptimized() +{ + return cv::useOptimized() ? 1 : 0; +} + +CVAPI(void) core_glob(const char *pattern, std::vector *result, int recursive) +{ + cv::glob(pattern, *result, recursive != 0); +} + +CVAPI(int) core_setBreakOnError(int flag) +{ + return cv::setBreakOnError(flag != 0) ? 1 : 0; +} + +CVAPI(cv::ErrorCallback) redirectError(cv::ErrorCallback errCallback, void* userdata, void** prevUserdata) +{ + return cv::redirectError(errCallback, userdata, prevUserdata); +} + +CVAPI(char*) core_format(cv::_InputArray *mtx, int fmt) +{ + auto formatted = cv::format(*mtx, static_cast(fmt)); + + std::stringstream s; + s << formatted; + std::string str = s.str(); + + const char *src = str.c_str(); + char *dst = new char[str.length() + 1]; + std::memcpy(dst, src, str.length() + 1); + return dst; +} +CVAPI(void) core_char_delete(char *buf) +{ + delete[] buf; +} + +#pragma endregion + +#pragma region Array Operations + +CVAPI(void) core_add(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, cv::_InputArray *mask, int dtype) +{ + cv::add(*src1, *src2, *dst, entity(mask), dtype); +} + +CVAPI(void) core_subtract_InputArray2(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, cv::_InputArray *mask, int dtype) +{ + cv::subtract(*src1, *src2, *dst, entity(mask), dtype); +} +CVAPI(void) core_subtract_InputArrayScalar(cv::_InputArray *src1, MyCvScalar src2, cv::_OutputArray *dst, cv::_InputArray *mask, int dtype) +{ + cv::Scalar src2_ = cpp(src2); + cv::subtract(*src1, src2_, *dst, entity(mask), dtype); +} +CVAPI(void) core_subtract_ScalarInputArray(MyCvScalar src1, cv::_InputArray *src2, cv::_OutputArray *dst, cv::_InputArray *mask, int dtype) +{ + cv::Scalar src1_ = cpp(src1); + cv::subtract(src1_, *src2, *dst, entity(mask), dtype); +} + +CVAPI(void) core_multiply(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, double scale, int dtype) +{ + cv::multiply(*src1, *src2, *dst, scale, dtype); +} +CVAPI(void) core_divide1(double scale, cv::_InputArray *src2, cv::_OutputArray *dst, int dtype) +{ + cv::divide(scale, *src2, *dst, dtype); +} +CVAPI(void) core_divide2(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, double scale, int dtype) +{ + cv::divide(*src1, *src2, *dst, scale, dtype); +} + +CVAPI(void) core_scaleAdd(cv::_InputArray *src1, double alpha, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::scaleAdd(*src1, alpha, *src2, *dst); +} +CVAPI(void) core_addWeighted(cv::_InputArray *src1, double alpha, cv::_InputArray *src2, + double beta, double gamma, cv::_OutputArray *dst, int dtype) +{ + cv::addWeighted(*src1, alpha, *src2, beta, gamma, *dst, dtype); +} + +#pragma endregion + +CVAPI(int) core_borderInterpolate(int p, int len, int borderType) +{ + return cv::borderInterpolate(p, len, borderType); +} + +CVAPI(void) core_copyMakeBorder(cv::_InputArray *src, cv::_OutputArray *dst, + int top, int bottom, int left, int right, int borderType, MyCvScalar value) +{ + cv::copyMakeBorder(*src, *dst, top, bottom, left, right, borderType, cpp(value)); +} + +CVAPI(void) core_convertScaleAbs(cv::_InputArray *src, cv::_OutputArray *dst, double alpha, double beta) +{ + cv::convertScaleAbs(*src, *dst, alpha, beta); +} + +CVAPI(void) core_LUT(cv::_InputArray *src, cv::_InputArray *lut, cv::_OutputArray *dst) +{ + cv::LUT(*src, *lut, *dst); +} +CVAPI(MyCvScalar) core_sum(cv::_InputArray *src) +{ + return c(cv::sum(*src)); +} +CVAPI(int) core_countNonZero(cv::_InputArray *src) +{ + return cv::countNonZero(*src); +} +CVAPI(void) core_findNonZero(cv::_InputArray *src, cv::_OutputArray *idx) +{ + cv::findNonZero(*src, *idx); +} + +CVAPI(MyCvScalar) core_mean(cv::_InputArray *src, cv::_InputArray *mask) +{ + return c(cv::mean(*src, entity(mask))); +} + +CVAPI(void) core_meanStdDev_OutputArray( + cv::_InputArray *src, cv::_OutputArray *mean, cv::_OutputArray *stddev, cv::_InputArray *mask) +{ + cv::meanStdDev(*src, *mean, *stddev, entity(mask)); +} +CVAPI(void) core_meanStdDev_Scalar( + cv::_InputArray *src, MyCvScalar *mean, MyCvScalar *stddev, cv::_InputArray *mask) +{ + cv::Scalar mean0, stddev0; + cv::meanStdDev(*src, mean0, stddev0, entity(mask)); + *mean = c(mean0); + *stddev = c(stddev0); +} + +CVAPI(double) core_norm1(cv::_InputArray *src1, int normType, cv::_InputArray *mask) +{ + return cv::norm(*src1, normType, entity(mask)); +} +CVAPI(double) core_norm2(cv::_InputArray *src1, cv::_InputArray *src2, + int normType, cv::_InputArray *mask) +{ + return cv::norm(*src1, *src2, normType, entity(mask)); +} + +CVAPI(void) core_batchDistance(cv::_InputArray *src1, cv::_InputArray *src2, + cv::_OutputArray *dist, int dtype, cv::_OutputArray *nidx, + int normType, int K, cv::_InputArray *mask, + int update, int crosscheck) +{ + cv::batchDistance(*src1, *src2, *dist, dtype, *nidx, normType, K, entity(mask), update, crosscheck != 0); +} + +CVAPI(void) core_normalize(cv::_InputArray *src, cv::_InputOutputArray *dst, double alpha, double beta, + int normType, int dtype, cv::_InputArray *mask) +{ + cv::InputArray maskVal = entity(mask); + cv::normalize(*src, *dst, alpha, beta, normType, dtype, maskVal); +} + +CVAPI(void) core_minMaxLoc1(cv::_InputArray *src, double *minVal, double *maxVal) +{ + cv::minMaxLoc(*src, minVal, maxVal); +} +CVAPI(void) core_minMaxLoc2(cv::_InputArray *src, double *minVal, double *maxVal, + CvPoint *minLoc, CvPoint *maxLoc, cv::_InputArray *mask) +{ + cv::InputArray maskVal = entity(mask); + cv::Point minLoc0, maxLoc0; + cv::minMaxLoc(*src, minVal, maxVal, &minLoc0, &maxLoc0, maskVal); + *minLoc = minLoc0; + *maxLoc = maxLoc0; +} +CVAPI(void) core_minMaxIdx1(cv::_InputArray *src, double *minVal, double *maxVal) +{ + cv::minMaxIdx(*src, minVal, maxVal); +} +CVAPI(void) core_minMaxIdx2(cv::_InputArray *src, double *minVal, double *maxVal, + int *minIdx, int *maxIdx, cv::_InputArray *mask) +{ + cv::InputArray maskVal = entity(mask); + cv::minMaxIdx(*src, minVal, maxVal, minIdx, maxIdx, maskVal); +} + +CVAPI(void) core_reduce(cv::_InputArray *src, cv::_OutputArray *dst, int dim, int rtype, int dtype) +{ + cv::reduce(*src, *dst, dim, rtype, dtype); +} +CVAPI(void) core_merge(cv::Mat **mv, uint32 count, cv::Mat *dst) +{ + std::vector vec((size_t)count); + for (uint32 i = 0; i < count; i++) + vec[i] = *mv[i]; + + cv::merge(vec, *dst); +} +CVAPI(void) core_split(cv::Mat *src, std::vector **mv) +{ + *mv = new std::vector(); + cv::split(*src, **mv); +} +CVAPI(void) core_mixChannels(cv::Mat **src, uint32 nsrcs, cv::Mat **dst, uint32 ndsts, int *fromTo, uint32 npairs) +{ + std::vector srcVec((size_t)nsrcs); + std::vector dstVec((size_t)ndsts); + for (uint32 i = 0; i < nsrcs; i++) + srcVec[i] = *(src[i]); + for (uint32 i = 0; i < ndsts; i++) + dstVec[i] = *(dst[i]); + + cv::mixChannels(srcVec, dstVec, fromTo, npairs); +} + +CVAPI(void) core_extractChannel(cv::_InputArray *src, cv::_OutputArray *dst, int coi) +{ + cv::extractChannel(*src, *dst, coi); +} +CVAPI(void) core_insertChannel(cv::_InputArray *src, cv::_InputOutputArray *dst, int coi) +{ + cv::insertChannel(*src, *dst, coi); +} +CVAPI(void) core_flip(cv::_InputArray *src, cv::_OutputArray *dst, int flipCode) +{ + cv::flip(*src, *dst, flipCode); +} +CVAPI(void) core_repeat1(cv::_InputArray *src, int ny, int nx, cv::_OutputArray *dst) +{ + cv::repeat(*src, ny, nx, *dst); +} +CVAPI(cv::Mat*) core_repeat2(cv::Mat *src, int ny, int nx) +{ + cv::Mat ret = cv::repeat(*src, ny, nx); + return new cv::Mat(ret); +} +CVAPI(void) core_hconcat1(cv::Mat **src, uint32 nsrc, cv::_OutputArray *dst) +{ + std::vector srcVec((size_t)nsrc); + for (uint32 i = 0; i < nsrc; i++) + srcVec[i] = *(src[i]); + cv::hconcat(&srcVec[0], nsrc, *dst); +} +CVAPI(void) core_hconcat2(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::hconcat(*src1, *src2, *dst); +} +CVAPI(void) core_vconcat1(cv::Mat **src, uint32 nsrc, cv::_OutputArray *dst) +{ + std::vector srcVec((size_t)nsrc); + for (uint32 i = 0; i < nsrc; i++) + srcVec[i] = *(src[i]); + cv::vconcat(&srcVec[0], nsrc, *dst); +} +CVAPI(void) core_vconcat2(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::vconcat(*src1, *src2, *dst); +} + +CVAPI(void) core_bitwise_and(cv::_InputArray *src1, cv::_InputArray *src2, + cv::_OutputArray *dst, cv::_InputArray *mask) +{ + cv::bitwise_and(*src1, *src2, *dst, entity(mask)); +} +CVAPI(void) core_bitwise_or(cv::_InputArray *src1, cv::_InputArray *src2, + cv::_OutputArray *dst, cv::_InputArray *mask) +{ + cv::bitwise_or(*src1, *src2, *dst, entity(mask)); +} +CVAPI(void) core_bitwise_xor(cv::_InputArray *src1, cv::_InputArray *src2, + cv::_OutputArray *dst, cv::_InputArray *mask) +{ + cv::bitwise_xor(*src1, *src2, *dst, entity(mask)); +} +CVAPI(void) core_bitwise_not(cv::_InputArray *src, cv::_OutputArray *dst, + cv::_InputArray *mask) +{ + cv::bitwise_not(*src, *dst, entity(mask)); +} + +CVAPI(void) core_absdiff(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::absdiff(*src1, *src2, *dst); +} + +CVAPI(void) core_inRange_InputArray(cv::_InputArray *src, cv::_InputArray *lowerb, cv::_InputArray *upperb, cv::_OutputArray *dst) +{ + cv::inRange(*src, *lowerb, *upperb, *dst); +} +CVAPI(void) core_inRange_Scalar(cv::_InputArray *src, CvScalar lowerb, CvScalar upperb, cv::_OutputArray *dst) +{ + cv::inRange(*src, cv::Scalar(lowerb), cv::Scalar(upperb), *dst); +} + +CVAPI(void) core_compare(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, int cmpop) +{ + cv::compare(*src1, *src2, *dst, cmpop); +} +CVAPI(void) core_min1(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::min(*src1, *src2, *dst); +} +CVAPI(void) core_max1(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst) +{ + cv::max(*src1, *src2, *dst); +} +CVAPI(void) core_min_MatMat(cv::Mat *src1, cv::Mat *src2, cv::Mat *dst) +{ + cv::min(*src1, *src2, *dst); +} +CVAPI(void) core_min_MatDouble(cv::Mat *src1, double src2, cv::Mat *dst) +{ + cv::min(*src1, src2, *dst); +} +CVAPI(void) core_max_MatMat(cv::Mat *src1, const cv::Mat *src2, cv::Mat *dst) +{ + cv::max(*src1, *src2, *dst); +} +CVAPI(void) core_max_MatDouble(cv::Mat *src1, double src2, cv::Mat *dst) +{ + cv::max(*src1, src2, *dst); +} +CVAPI(void) core_sqrt(cv::_InputArray *src, cv::_OutputArray *dst) +{ + cv::sqrt(*src, *dst); +} +CVAPI(void) core_pow_Mat(cv::_InputArray *src, double power, cv::_OutputArray *dst) +{ + cv::pow(*src, power, *dst); +} +CVAPI(void) core_exp_Mat(cv::_InputArray *src, cv::_OutputArray *dst) +{ + cv::exp(*src, *dst); +} +CVAPI(void) core_log_Mat(cv::_InputArray *src, cv::_OutputArray *dst) +{ + cv::log(*src, *dst); +} +CVAPI(float) core_cubeRoot(float val) +{ + return cv::cubeRoot(val); +} +CVAPI(float) core_fastAtan2(float y, float x) +{ + return cv::fastAtan2(y, x); +} + +CVAPI(void) core_polarToCart(cv::_InputArray *magnitude, cv::_InputArray *angle, + cv::_OutputArray *x, cv::_OutputArray *y, int angleInDegrees) +{ + cv::polarToCart(*magnitude, *angle, *x, *y, angleInDegrees != 0); +} +CVAPI(void) core_cartToPolar(cv::_InputArray *x, cv::_InputArray *y, + cv::_OutputArray *magnitude, cv::_OutputArray *angle, int angleInDegrees) +{ + cv::cartToPolar(*x, *y, *magnitude, *angle, angleInDegrees != 0); +} +CVAPI(void) core_phase(cv::_InputArray *x, cv::_InputArray *y, cv::_OutputArray *angle, int angleInDegrees) +{ + cv::phase(*x, *y, *angle, angleInDegrees != 0); +} +CVAPI(void) core_magnitude_Mat(cv::_InputArray *x, cv::_InputArray *y, cv::_OutputArray *magnitude) +{ + cv::magnitude(*x, *y, *magnitude); +} +CVAPI(int) core_checkRange(cv::_InputArray *a, int quiet, CvPoint *pos, double minVal, double maxVal) +{ + cv::Point pos0; + int ret = cv::checkRange(*a, quiet != 0, &pos0, minVal, maxVal); + *pos = pos0; + return ret; +} +CVAPI(void) core_patchNaNs(cv::_InputOutputArray *a, double val) +{ + cv::patchNaNs(*a, val); +} +CVAPI(void) core_gemm(cv::_InputArray *src1, cv::_InputArray *src2, double alpha, + cv::_InputArray *src3, double gamma, cv::_OutputArray *dst, int flags) +{ + cv::gemm(*src1, *src2, alpha, *src3, gamma, *dst, flags); +} +CVAPI(void) core_mulTransposed(cv::_InputArray *src, cv::_OutputArray *dst, int aTa, + cv::_InputArray *delta, double scale, int dtype) +{ + cv::mulTransposed(*src, *dst, aTa != 0, entity(delta), scale, dtype); +} +CVAPI(void) core_transpose(cv::_InputArray *src, cv::_OutputArray *dst) +{ + cv::transpose(*src, *dst); +} +CVAPI(void) core_transform(cv::_InputArray *src, cv::_OutputArray *dst, cv::_InputArray *m) +{ + cv::transform(*src, *dst, *m); +} + +CVAPI(void) core_perspectiveTransform(cv::_InputArray *src, cv::_OutputArray *dst, cv::_InputArray *m) +{ + cv::perspectiveTransform(*src, *dst, *m); +} +CVAPI(void) core_perspectiveTransform_Mat(cv::Mat *src, cv::Mat *dst, cv::Mat *m) +{ + cv::perspectiveTransform(*src, *dst, *m); +} +CVAPI(void) core_perspectiveTransform_Point2f(cv::Point2f *src, int srcLength, cv::Point2f *dst, int dstLength, cv::_InputArray *m) +{ + std::vector srcVector(src, src + srcLength); + std::vector dstVector(dst, dst + dstLength); + cv::perspectiveTransform(srcVector, dstVector, *m); +} +CVAPI(void) core_perspectiveTransform_Point2d(cv::Point2d *src, int srcLength, cv::Point2d *dst, int dstLength, cv::_InputArray *m) +{ + std::vector srcVector(src, src + srcLength); + std::vector dstVector(dst, dst + dstLength); + cv::perspectiveTransform(srcVector, dstVector, *m); +} +CVAPI(void) core_perspectiveTransform_Point3f(cv::Point3f *src, int srcLength, cv::Point3f *dst, int dstLength, cv::_InputArray *m) +{ + std::vector srcVector(src, src + srcLength); + std::vector dstVector(dst, dst + dstLength); + cv::perspectiveTransform(srcVector, dstVector, *m); +} +CVAPI(void) core_perspectiveTransform_Point3d(cv::Point3d *src, int srcLength, cv::Point3d *dst, int dstLength, cv::_InputArray *m) +{ + std::vector srcVector(src, src + srcLength); + std::vector dstVector(dst, dst + dstLength); + cv::perspectiveTransform(srcVector, dstVector, *m); +} + +CVAPI(void) core_completeSymm(cv::_InputOutputArray *mtx, int lowerToUpper) +{ + cv::completeSymm(*mtx, lowerToUpper != 0); +} +CVAPI(void) core_setIdentity(cv::_InputOutputArray *mtx, MyCvScalar s) +{ + cv::setIdentity(*mtx, cpp(s)); +} +CVAPI(double) core_determinant(cv::_InputArray *mtx) +{ + return cv::determinant(*mtx); +} +CVAPI(MyCvScalar) core_trace(cv::_InputArray *mtx) +{ + return c(cv::trace(*mtx)); +} +CVAPI(double) core_invert(cv::_InputArray *src, cv::_OutputArray *dst, int flags) +{ + return cv::invert(*src, *dst, flags); +} + + +CVAPI(int) core_solve(cv::_InputArray *src1, cv::_InputArray *src2, cv::_OutputArray *dst, int flags) +{ + return cv::solve(*src1, *src2, *dst, flags); +} + +CVAPI(int) core_solveLP(cv::Mat *Func, cv::Mat *Constr, cv::Mat *z) +{ + return cv::solveLP(*Func, *Constr, *z); +} + +CVAPI(void) core_sort(cv::_InputArray *src, cv::_OutputArray *dst, int flags) +{ + cv::sort(*src, *dst, flags); +} +CVAPI(void) core_sortIdx(cv::_InputArray *src, cv::_OutputArray *dst, int flags) +{ + cv::sortIdx(*src, *dst, flags); +} +CVAPI(int) core_solveCubic(cv::_InputArray *coeffs, cv::_OutputArray *roots) +{ + return cv::solveCubic(*coeffs, *roots); +} +CVAPI(double) core_solvePoly(cv::_InputArray *coeffs, cv::_OutputArray *roots, int maxIters) +{ + return cv::solvePoly(*coeffs, *roots, maxIters); +} + +CVAPI(int) core_eigen(cv::_InputArray *src, cv::_OutputArray *eigenvalues, cv::_OutputArray *eigenvectors) +{ + return cv::eigen(*src, *eigenvalues, *eigenvectors) ? 1 : 0; +} + +CVAPI(void) core_calcCovarMatrix_Mat(cv::Mat **samples, int nsamples, cv::Mat *covar, + cv::Mat *mean, int flags, int ctype) +{ + std::vector samplesVec(nsamples); + for (int i = 0; i < nsamples; i++) + samplesVec[i] = *samples[i]; + + cv::calcCovarMatrix(&samplesVec[0], nsamples, *covar, *mean, flags, ctype); +} +CVAPI(void) core_calcCovarMatrix_InputArray(cv::_InputArray *samples, cv::_OutputArray *covar, + cv::_InputOutputArray *mean, int flags, int ctype) +{ + cv::calcCovarMatrix(*samples, *covar, *mean, flags, ctype); +} + + +CVAPI(void) core_PCACompute(cv::_InputArray *data, cv::_InputOutputArray *mean, + cv::_OutputArray *eigenvectors, int maxComponents) +{ + cv::PCACompute(*data, *mean, *eigenvectors, maxComponents); +} +CVAPI(void) core_PCAComputeVar(cv::_InputArray *data, cv::_InputOutputArray *mean, + cv::_OutputArray *eigenvectors, double retainedVariance) +{ + cv::PCACompute(*data, *mean, *eigenvectors, retainedVariance); +} +CVAPI(void) core_PCAProject(cv::_InputArray *data, cv::_InputArray *mean, + cv::_InputArray *eigenvectors, cv::_OutputArray *result) +{ + cv::PCAProject(*data, *mean, *eigenvectors, *result); +} +CVAPI(void) core_PCABackProject(cv::_InputArray *data, cv::_InputArray *mean, + cv::_InputArray *eigenvectors, cv::_OutputArray *result) +{ + cv::PCABackProject(*data, *mean, *eigenvectors, *result); +} + +CVAPI(void) core_SVDecomp(cv::_InputArray *src, cv::_OutputArray *w, + cv::_OutputArray *u, cv::_OutputArray *vt, int flags) +{ + cv::SVDecomp(*src, *w, *u, *vt, flags); +} + +CVAPI(void) core_SVBackSubst(cv::_InputArray *w, cv::_InputArray *u, cv::_InputArray *vt, + cv::_InputArray *rhs, cv::_OutputArray *dst) +{ + cv::SVBackSubst(*w, *u, *vt, *rhs, *dst); +} + +CVAPI(double) core_Mahalanobis(cv::_InputArray *v1, cv::_InputArray *v2, cv::_InputArray *icovar) +{ + return cv::Mahalanobis(*v1, *v2, *icovar); +} +CVAPI(void) core_dft(cv::_InputArray *src, cv::_OutputArray *dst, int flags, int nonzeroRows) +{ + cv::dft(*src, *dst, flags, nonzeroRows); +} +CVAPI(void) core_idft(cv::_InputArray *src, cv::_OutputArray *dst, int flags, int nonzeroRows) +{ + cv::idft(*src, *dst, flags, nonzeroRows); +} +CVAPI(void) core_dct(cv::_InputArray *src, cv::_OutputArray *dst, int flags) +{ + cv::dct(*src, *dst, flags); +} +CVAPI(void) core_idct(cv::_InputArray *src, cv::_OutputArray *dst, int flags) +{ + cv::idct(*src, *dst, flags); +} +CVAPI(void) core_mulSpectrums(cv::_InputArray *a, cv::_InputArray *b, cv::_OutputArray *c, int flags, int conjB) +{ + cv::mulSpectrums(*a, *b, *c, flags, conjB != 0); +} +CVAPI(int) core_getOptimalDFTSize(int vecsize) +{ + return cv::getOptimalDFTSize(vecsize); +} + +CVAPI(double) core_kmeans(cv::_InputArray *data, int k, cv::_InputOutputArray *bestLabels, + MyCvTermCriteria criteria, int attempts, int flags, cv::_OutputArray *centers) +{ + return cv::kmeans(*data, k, *bestLabels, cpp(criteria), attempts, flags, entity(centers)); +} + +CVAPI(uint64) core_theRNG() +{ + cv::RNG &rng = cv::theRNG(); + return rng.state; +} + +CVAPI(void) core_randu_InputArray(cv::_InputOutputArray *dst, cv::_InputArray *low, cv::_InputArray *high) +{ + cv::randu(*dst, *low, *high); +} +CVAPI(void) core_randu_Scalar(cv::_InputOutputArray *dst, MyCvScalar low, MyCvScalar high) +{ + cv::randu(*dst, cpp(low), cpp(high)); +} + +CVAPI(void) core_randn_InputArray(cv::_InputOutputArray *dst, cv::_InputArray *mean, cv::_InputArray *stddev) +{ + cv::randn(*dst, *mean, *stddev); +} +CVAPI(void) core_randn_Scalar(cv::_InputOutputArray *dst, MyCvScalar mean, MyCvScalar stddev) +{ + cv::randn(*dst, cpp(mean), cpp(stddev)); +} + +CVAPI(void) core_randShuffle(cv::_InputOutputArray *dst, double iterFactor, uint64 *rng) +{ + cv::RNG rng0; + cv::randShuffle(*dst, iterFactor, &rng0); + *rng = rng0.state; +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_Algorithm.h b/OpenVinoOpenCvSharpExtern/core_Algorithm.h new file mode 100644 index 0000000..d6d0103 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_Algorithm.h @@ -0,0 +1,32 @@ +#ifndef _CPP_CORE_ALGORITHM_H_ +#define _CPP_CORE_ALGORITHM_H_ + +#include "include_opencv.h" + +CVAPI(void) core_Algorithm_write(cv::Algorithm *obj, cv::FileStorage *fs) +{ + obj->write(*fs); +} + +CVAPI(void) core_Algorithm_read(cv::Algorithm *obj, cv::FileNode *fn) +{ + obj->read(*fn); +} + +CVAPI(int) core_Algorithm_empty(cv::Algorithm *obj) +{ + return obj->empty() ? 1 : 0; +} + +CVAPI(void) core_Algorithm_save(cv::Algorithm *obj, const char *filename) +{ + obj->save(filename); +} + +CVAPI(void) core_Algorithm_getDefaultName(cv::Algorithm *obj, char *buf, int bufLength) +{ + cv::String str = obj->getDefaultName(); + copyString(str, buf, bufLength); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_FileNode.h b/OpenVinoOpenCvSharpExtern/core_FileNode.h new file mode 100644 index 0000000..6d11fe3 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_FileNode.h @@ -0,0 +1,290 @@ +#ifndef _CPP_CORE_FILENODE_H_ +#define _CPP_CORE_FILENODE_H_ + +#include "include_opencv.h" + +CVAPI(cv::FileNode*) core_FileNode_new1() +{ + return new cv::FileNode(); +} +CVAPI(cv::FileNode*) core_FileNode_new3(cv::FileNode *node) +{ + return new cv::FileNode(*node); +} + +CVAPI(void) core_FileNode_delete(cv::FileNode *node) +{ + delete node; +} + +CVAPI(cv::FileNode*) core_FileNode_operatorThis_byString(cv::FileNode *obj, const char *nodeName) +{ + cv::FileNode ret = (*obj)[nodeName]; + return new cv::FileNode(ret); +} +CVAPI(cv::FileNode*) core_FileNode_operatorThis_byInt(cv::FileNode *obj, int i) +{ + cv::FileNode ret = (*obj)[i]; + return new cv::FileNode(ret); +} +CVAPI(int) core_FileNode_type(cv::FileNode *obj) +{ + return obj->type(); +} + +CVAPI(int) core_FileNode_empty(cv::FileNode *obj) +{ + return obj->empty() ? 1 : 0; +} +CVAPI(int) core_FileNode_isNone(cv::FileNode *obj) +{ + return obj->isNone() ? 1 : 0; +} +CVAPI(int) core_FileNode_isSeq(cv::FileNode *obj) +{ + return obj->isSeq() ? 1 : 0; +} +CVAPI(int) core_FileNode_isMap(cv::FileNode *obj) +{ + return obj->isMap() ? 1 : 0; +} +CVAPI(int) core_FileNode_isInt(cv::FileNode *obj) +{ + return obj->isInt() ? 1 : 0; +} +CVAPI(int) core_FileNode_isReal(cv::FileNode *obj) +{ + return obj->isReal() ? 1 : 0; +} +CVAPI(int) core_FileNode_isString(cv::FileNode *obj) +{ + return obj->isString() ? 1 : 0; +} +CVAPI(int) core_FileNode_isNamed(cv::FileNode *obj) +{ + return obj->isNamed() ? 1 : 0; +} + +CVAPI(void) core_FileNode_name(cv::FileNode *obj, char *buf, int bufLength) +{ + std::string str = obj->name(); + copyString(str, buf, bufLength); +} +CVAPI(size_t) core_FileNode_size(cv::FileNode *obj) +{ + return obj->size(); +} + +CVAPI(int) core_FileNode_toInt(cv::FileNode *obj) +{ + return (int)(*obj); +} +CVAPI(float) core_FileNode_toFloat(cv::FileNode *obj) +{ + return (float)(*obj); +} +CVAPI(double) core_FileNode_toDouble(cv::FileNode *obj) +{ + return (double)(*obj); +} +CVAPI(void) core_FileNode_toString(cv::FileNode *obj, char *buf, int bufLength) +{ + std::string str = (std::string)(*obj); + copyString(str, buf, bufLength); +} +CVAPI(void) core_FileNode_toMat(cv::FileNode *obj, cv::Mat *m) +{ + (*obj) >> (*m); +} + +CVAPI(cv::FileNodeIterator*) core_FileNode_begin(cv::FileNode *obj) +{ + return new cv::FileNodeIterator(obj->begin()); +} +CVAPI(cv::FileNodeIterator*) core_FileNode_end(cv::FileNode *obj) +{ + return new cv::FileNodeIterator(obj->end()); +} + +CVAPI(void) core_FileNode_readRaw(cv::FileNode *obj, const char *fmt, uchar* vec, size_t len) +{ + obj->readRaw(fmt, vec, len); +} + +CVAPI(void) core_FileNode_read_int(cv::FileNode *node, int *value, int default_value) +{ + int temp; + cv::read(*node, temp, default_value); + *value = temp; +} +CVAPI(void) core_FileNode_read_float(cv::FileNode *node, float *value, float default_value) +{ + float temp; + cv::read(*node, temp, default_value); + *value = temp; +} +CVAPI(void) core_FileNode_read_double(cv::FileNode *node, double *value, double default_value) +{ + double temp; + cv::read(*node, temp, default_value); + *value = temp; +} +CVAPI(void) core_FileNode_read_String(cv::FileNode *node, char *value, int valueCapacity, const char *default_value) +{ + cv::String str; + cv::read(*node, str, (default_value == NULL) ? cv::String() : cv::String(default_value)); + copyString(str, value, valueCapacity); +} +CVAPI(void) core_FileNode_read_Mat(cv::FileNode *node, cv::Mat *mat, cv::Mat *default_mat) +{ + cv::read(*node, *mat, entity(default_mat)); +} +CVAPI(void) core_FileNode_read_SparseMat(cv::FileNode *node, cv::SparseMat *mat, cv::SparseMat *default_mat) +{ + cv::read(*node, *mat, entity(default_mat)); +} +CVAPI(void) core_FileNode_read_vectorOfKeyPoint(cv::FileNode *node, std::vector *keypoints) +{ + cv::read(*node, *keypoints); +} +CVAPI(void) core_FileNode_read_vectorOfDMatch(cv::FileNode *node, std::vector *matches) +{ + cv::read(*node, *matches); +} + + + +CVAPI(MyCvSlice) core_FileNode_read_Range(cv::FileNode *node) +{ + cv::Range ret; + (*node) >> ret; + return c(ret); +} +CVAPI(MyKeyPoint) core_FileNode_read_KeyPoint(cv::FileNode *node) +{ + cv::KeyPoint ret; + (*node) >> ret; + return c(ret); +} +CVAPI(MyDMatch) core_FileNode_read_DMatch(cv::FileNode *node) +{ + cv::DMatch ret; + (*node) >> ret; + return c(ret); +} +CVAPI(MyCvPoint) core_FileNode_read_Point2i(cv::FileNode *node) +{ + cv::Point2i ret; + (*node) >> ret; + return MyCvPoint{ ret.x, ret.y }; +} +CVAPI(MyCvPoint2D32f) core_FileNode_read_Point2f(cv::FileNode *node) +{ + cv::Point2f ret; + (*node) >> ret; + return MyCvPoint2D32f{ ret.x, ret.y }; +} +CVAPI(MyCvPoint2D64f) core_FileNode_read_Point2d(cv::FileNode *node) +{ + cv::Point2d ret; + (*node) >> ret; + return MyCvPoint2D64f{ ret.x, ret.y }; +} +CVAPI(MyCvPoint3D32i) core_FileNode_read_Point3i(cv::FileNode *node) +{ + cv::Point3i ret; + (*node) >> ret; + return MyCvPoint3D32i{ ret.x, ret.y, ret.z }; +} +CVAPI(MyCvPoint3D32f) core_FileNode_read_Point3f(cv::FileNode *node) +{ + cv::Point3f ret; + (*node) >> ret; + return MyCvPoint3D32f{ ret.x, ret.y, ret.z }; +} +CVAPI(MyCvPoint3D64f) core_FileNode_read_Point3d(cv::FileNode *node) +{ + cv::Point3d ret; + (*node) >> ret; + return MyCvPoint3D64f{ ret.x, ret.y, ret.z }; +} +CVAPI(MyCvSize) core_FileNode_read_Size2i(cv::FileNode *node) +{ + cv::Size2i ret; + (*node) >> ret; + return MyCvSize{ ret.width, ret.height }; +} +CVAPI(MyCvSize2D32f) core_FileNode_read_Size2f(cv::FileNode *node) +{ + cv::Size2f ret; + (*node) >> ret; + return MyCvSize2D32f{ ret.width, ret.height }; +} +CVAPI(MyCvSize2D64f) core_FileNode_read_Size2d(cv::FileNode *node) +{ + cv::Size2d ret; + (*node) >> ret; + return MyCvSize2D64f{ ret.width, ret.height }; +} +CVAPI(MyCvRect) core_FileNode_read_Rect2i(cv::FileNode *node) +{ + cv::Rect2i ret; + (*node) >> ret; + return MyCvRect{ ret.x, ret.y, ret.width, ret.height }; +} +CVAPI(MyCvRect2D32f) core_FileNode_read_Rect2f(cv::FileNode *node) +{ + cv::Rect2f ret; + (*node) >> ret; + return MyCvRect2D32f{ ret.x, ret.y, ret.width, ret.height }; +} +CVAPI(MyCvRect2D64f) core_FileNode_read_Rect2d(cv::FileNode *node) +{ + cv::Rect2d ret; + (*node) >> ret; + return MyCvRect2D64f{ ret.x, ret.y, ret.width, ret.height }; +} +CVAPI(MyCvScalar) core_FileNode_read_Scalar(cv::FileNode *node) +{ + cv::Scalar s; + (*node) >> s; + MyCvScalar ret; + ret.val[0] = s.val[0]; + ret.val[1] = s.val[1]; + ret.val[2] = s.val[2]; + ret.val[3] = s.val[3]; + return ret; +} + +CVAPI(CvVec2i) core_FileNode_read_Vec2i(cv::FileNode *node) { cv::Vec2i v; (*node) >> v; CvVec2i ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3i) core_FileNode_read_Vec3i(cv::FileNode *node) { cv::Vec3i v; (*node) >> v; CvVec3i ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4i) core_FileNode_read_Vec4i(cv::FileNode *node) { cv::Vec4i v; (*node) >> v; CvVec4i ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6i) core_FileNode_read_Vec6i(cv::FileNode *node) { cv::Vec6i v; (*node) >> v; CvVec6i ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec2d) core_FileNode_read_Vec2d(cv::FileNode *node) { cv::Vec2d v; (*node) >> v; CvVec2d ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3d) core_FileNode_read_Vec3d(cv::FileNode *node) { cv::Vec3d v; (*node) >> v; CvVec3d ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4d) core_FileNode_read_Vec4d(cv::FileNode *node) { cv::Vec4d v; (*node) >> v; CvVec4d ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6d) core_FileNode_read_Vec6d(cv::FileNode *node) { cv::Vec6d v; (*node) >> v; CvVec6d ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec2f) core_FileNode_read_Vec2f(cv::FileNode *node) { cv::Vec2f v; (*node) >> v; CvVec2f ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3f) core_FileNode_read_Vec3f(cv::FileNode *node) { cv::Vec3f v; (*node) >> v; CvVec3f ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4f) core_FileNode_read_Vec4f(cv::FileNode *node) { cv::Vec4f v; (*node) >> v; CvVec4f ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6f) core_FileNode_read_Vec6f(cv::FileNode *node) { cv::Vec6f v; (*node) >> v; CvVec6f ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec2b) core_FileNode_read_Vec2b(cv::FileNode *node) { cv::Vec2b v; (*node) >> v; CvVec2b ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3b) core_FileNode_read_Vec3b(cv::FileNode *node) { cv::Vec3b v; (*node) >> v; CvVec3b ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4b) core_FileNode_read_Vec4b(cv::FileNode *node) { cv::Vec4b v; (*node) >> v; CvVec4b ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6b) core_FileNode_read_Vec6b(cv::FileNode *node) { cv::Vec6b v; (*node) >> v; CvVec6b ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec2s) core_FileNode_read_Vec2s(cv::FileNode *node) { cv::Vec2s v; (*node) >> v; CvVec2s ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3s) core_FileNode_read_Vec3s(cv::FileNode *node) { cv::Vec3s v; (*node) >> v; CvVec3s ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4s) core_FileNode_read_Vec4s(cv::FileNode *node) { cv::Vec4s v; (*node) >> v; CvVec4s ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6s) core_FileNode_read_Vec6s(cv::FileNode *node) { cv::Vec6s v; (*node) >> v; CvVec6s ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec2w) core_FileNode_read_Vec2w(cv::FileNode *node) { cv::Vec2w v; (*node) >> v; CvVec2w ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec3w) core_FileNode_read_Vec3w(cv::FileNode *node) { cv::Vec3w v; (*node) >> v; CvVec3w ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec4w) core_FileNode_read_Vec4w(cv::FileNode *node) { cv::Vec4w v; (*node) >> v; CvVec4w ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } +CVAPI(CvVec6w) core_FileNode_read_Vec6w(cv::FileNode *node) { cv::Vec6w v; (*node) >> v; CvVec6w ret; std::copy(std::begin(v.val), std::end(v.val), std::begin(ret.val)); return ret; } + +/* +CVAPI(CvVec2f) core_FileNode_read_Vec2f(cv::FileNode *node); +CVAPI(CvVec3f) core_FileNode_read_Vec3f(cv::FileNode *node); +CVAPI(CvVec4f) core_FileNode_read_Vec4f(cv::FileNode *node); +CVAPI(CvVec6f) core_FileNode_read_Vec6f(cv::FileNode *node); +//*/ +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_FileStorage.h b/OpenVinoOpenCvSharpExtern/core_FileStorage.h new file mode 100644 index 0000000..89d19bc --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_FileStorage.h @@ -0,0 +1,410 @@ +#ifndef _CPP_CORE_FILESTORAGE_H_ +#define _CPP_CORE_FILESTORAGE_H_ + +#include "include_opencv.h" + +#pragma region FileStorage + +CVAPI(cv::FileStorage*) core_FileStorage_new1() +{ + return new cv::FileStorage(); +} +CVAPI(cv::FileStorage*) core_FileStorage_new2(const char *source, int flags, const char *encoding) +{ + std::string encodingStr; + if (encoding != NULL) + encodingStr = std::string(encoding); + return new cv::FileStorage(source, flags, encodingStr); +} + +CVAPI(void) core_FileStorage_delete(cv::FileStorage *obj) +{ + delete obj; +} + +CVAPI(int) core_FileStorage_open(cv::FileStorage *obj, + const char *filename, int flags, const char *encoding) +{ + std::string encodingStr; + if (encoding != NULL) + encodingStr = std::string(encoding); + return obj->open(filename, flags, encodingStr) ? 1 : 0; +} +CVAPI(int) core_FileStorage_isOpened(cv::FileStorage *obj) +{ + return obj->isOpened() ? 1 : 0; +} +CVAPI(void) core_FileStorage_release(cv::FileStorage *obj) +{ + return obj->release(); +} + +CVAPI(void) core_FileStorage_releaseAndGetString_stdString(cv::FileStorage* obj, + std::string * outString) +{ + *outString = obj->releaseAndGetString(); +} + +CVAPI(cv::FileNode*) core_FileStorage_getFirstTopLevelNode(cv::FileStorage *obj) +{ + cv::FileNode node = obj->getFirstTopLevelNode(); + return new cv::FileNode(node); +} +CVAPI(cv::FileNode*) core_FileStorage_root(cv::FileStorage *obj, int streamIdx) +{ + cv::FileNode node = obj->root(streamIdx); + return new cv::FileNode(node); +} +CVAPI(cv::FileNode*) core_FileStorage_indexer(cv::FileStorage *obj, const char *nodeName) +{ + cv::FileNode node = (*obj)[nodeName]; + return new cv::FileNode(node); +} + +CVAPI(void) core_FileStorage_writeRaw(cv::FileStorage *obj, const char *fmt, const uchar *vec, size_t len) +{ + obj->writeRaw(fmt, vec, len); +} + +CVAPI(void) core_FileStorage_writeComment(cv::FileStorage *obj, const char *comment, int append) +{ + obj->writeComment(comment, append != 0); +} + +CVAPI(void) core_FileStorage_getDefaultObjectName(const char *filename, char *buf, int bufLength) +{ + std::string ret = cv::FileStorage::getDefaultObjectName(filename); + copyString(ret, buf, bufLength); +} + +CVAPI(const char*) core_FileStorage_elname(cv::FileStorage *obj) +{ + return obj->elname.c_str(); +} + +CVAPI(void) core_FileStorage_startWriteStruct( + cv::FileStorage *obj, const char* name, int flags, const char *typeName) +{ + obj->startWriteStruct(name, flags, typeName); +} +CVAPI(void) core_FileStorage_endWriteStruct( cv::FileStorage *obj) +{ + obj->endWriteStruct(); +} + +CVAPI(int) core_FileStorage_state(cv::FileStorage *obj) +{ + return obj->state; +} + +CVAPI(void) core_FileStorage_write_int(cv::FileStorage *fs, const char *name, int value) +{ + cv::write(*fs, cv::String(name), value); +} +CVAPI(void) core_FileStorage_write_float(cv::FileStorage *fs, const char *name, float value) +{ + cv::write(*fs, cv::String(name), value); +} +CVAPI(void) core_FileStorage_write_double(cv::FileStorage *fs, const char *name, double value) +{ + cv::write(*fs, cv::String(name), value); +} +CVAPI(void) core_FileStorage_write_String(cv::FileStorage *fs, const char *name, const char *value) +{ + cv::write(*fs, cv::String(name), value); +} +CVAPI(void) core_FileStorage_write_Mat(cv::FileStorage *fs, const char *name, const cv::Mat *value) +{ + cv::write(*fs, cv::String(name), *value); +} +CVAPI(void) core_FileStorage_write_SparseMat(cv::FileStorage *fs, const char *name, const cv::SparseMat *value) +{ + cv::write(*fs, cv::String(name), *value); +} +CVAPI(void) core_FileStorage_write_vectorOfKeyPoint(cv::FileStorage *fs, const char *name, const std::vector *value) +{ + cv::write(*fs, cv::String(name), *value); +} +CVAPI(void) core_FileStorage_write_vectorOfDMatch(cv::FileStorage *fs, const char *name, const std::vector *value) +{ + cv::write(*fs, cv::String(name), *value); +} + +CVAPI(void) core_FileStorage_writeScalar_int(cv::FileStorage *fs, int value) +{ + cv::writeScalar(*fs, value); +} +CVAPI(void) core_FileStorage_writeScalar_float(cv::FileStorage *fs, float value) +{ + cv::writeScalar(*fs, value); +} +CVAPI(void) core_FileStorage_writeScalar_double(cv::FileStorage *fs, double value) +{ + cv::writeScalar(*fs, value); +} +CVAPI(void) core_FileStorage_writeScalar_String(cv::FileStorage *fs, const char *value) +{ + cv::writeScalar(*fs, cv::String(value)); +} + +CVAPI(void) core_FileStorage_shift_String(cv::FileStorage *fs, const char *val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_int(cv::FileStorage *fs, int val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_float(cv::FileStorage *fs, float val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_double(cv::FileStorage *fs, double val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_Mat(cv::FileStorage *fs, cv::Mat *val) +{ + (*fs) << *val; +} +CVAPI(void) core_FileStorage_shift_SparseMat(cv::FileStorage *fs, cv::SparseMat *val) +{ + (*fs) << *val; +} +CVAPI(void) core_FileStorage_shift_Range(cv::FileStorage *fs, MyCvSlice val) +{ + (*fs) << cpp(val); +} +CVAPI(void) core_FileStorage_shift_KeyPoint(cv::FileStorage *fs, cv::KeyPoint val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_DMatch(cv::FileStorage *fs, cv::DMatch val) +{ + (*fs) << val; +} +CVAPI(void) core_FileStorage_shift_vectorOfKeyPoint(cv::FileStorage *fs, std::vector *val) +{ + (*fs) << *val; +} +CVAPI(void) core_FileStorage_shift_vectorOfDMatch(cv::FileStorage *fs, std::vector *val) +{ + (*fs) << *val; +} +CVAPI(void) core_FileStorage_shift_Point2i(cv::FileStorage *fs, MyCvPoint val) +{ + (*fs) << cv::Point2i(val.x, val.y); +} +CVAPI(void) core_FileStorage_shift_Point2f(cv::FileStorage *fs, MyCvPoint2D32f val) +{ + (*fs) << cv::Point2f(val.x, val.y); +} +CVAPI(void) core_FileStorage_shift_Point2d(cv::FileStorage *fs, MyCvPoint2D64f val) +{ + (*fs) << cv::Point2d(val.x, val.y); +} +CVAPI(void) core_FileStorage_shift_Point3i(cv::FileStorage *fs, MyCvPoint3D32i val) +{ + (*fs) << cv::Point3i(val.x, val.y, val.z); +} +CVAPI(void) core_FileStorage_shift_Point3f(cv::FileStorage *fs, MyCvPoint3D32f val) +{ + (*fs) << cv::Point3f(val.x, val.y, val.z); +} +CVAPI(void) core_FileStorage_shift_Point3d(cv::FileStorage *fs, MyCvPoint3D64f val) +{ + (*fs) << cv::Point3d(val.x, val.y, val.z); +} +CVAPI(void) core_FileStorage_shift_Size2i(cv::FileStorage *fs, MyCvSize val) +{ + (*fs) << cv::Size2i(val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Size2f(cv::FileStorage *fs, MyCvSize2D32f val) +{ + (*fs) << cv::Size2f(val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Size2d(cv::FileStorage *fs, MyCvSize2D64f val) +{ + (*fs) << cv::Size2d(val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Rect2i(cv::FileStorage *fs, MyCvRect val) +{ + (*fs) << cv::Rect2i(val.x, val.y, val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Rect2f(cv::FileStorage *fs, MyCvRect2D32f val) +{ + (*fs) << cv::Rect2f(val.x, val.y, val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Rect2d(cv::FileStorage *fs, MyCvRect2D64f val) +{ + (*fs) << cv::Rect2d(val.x, val.y, val.width, val.height); +} +CVAPI(void) core_FileStorage_shift_Scalar(cv::FileStorage *fs, MyCvScalar val) +{ + (*fs) << cpp(val); +} + +CVAPI(void) core_FileStorage_shift_Vec2i(cv::FileStorage *fs, CvVec2i v) +{ + (*fs) << cv::Vec2i(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3i(cv::FileStorage *fs, CvVec3i v) +{ + (*fs) << cv::Vec3i(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4i(cv::FileStorage *fs, CvVec4i v) +{ + (*fs) << cv::Vec4i(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6i(cv::FileStorage *fs, CvVec6i v) +{ + (*fs) << cv::Vec6i(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} +CVAPI(void) core_FileStorage_shift_Vec2d(cv::FileStorage *fs, CvVec2d v) +{ + (*fs) << cv::Vec2d(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3d(cv::FileStorage *fs, CvVec3d v) +{ + (*fs) << cv::Vec3d(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4d(cv::FileStorage *fs, CvVec4d v) +{ + (*fs) << cv::Vec4d(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6d(cv::FileStorage *fs, CvVec6d v) +{ + (*fs) << cv::Vec6d(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} +CVAPI(void) core_FileStorage_shift_Vec2f(cv::FileStorage *fs, CvVec2f v) +{ + (*fs) << cv::Vec2f(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3f(cv::FileStorage *fs, CvVec3f v) +{ + (*fs) << cv::Vec3f(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4f(cv::FileStorage *fs, CvVec4f v) +{ + (*fs) << cv::Vec4f(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6f(cv::FileStorage *fs, CvVec6f v) +{ + (*fs) << cv::Vec6f(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} +CVAPI(void) core_FileStorage_shift_Vec2b(cv::FileStorage *fs, CvVec2b v) +{ + (*fs) << cv::Vec2b(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3b(cv::FileStorage *fs, CvVec3b v) +{ + (*fs) << cv::Vec3b(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4b(cv::FileStorage *fs, CvVec4b v) +{ + (*fs) << cv::Vec4b(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6b(cv::FileStorage *fs, CvVec6b v) +{ + (*fs) << cv::Vec6b(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} +CVAPI(void) core_FileStorage_shift_Vec2s(cv::FileStorage *fs, CvVec2s v) +{ + (*fs) << cv::Vec2s(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3s(cv::FileStorage *fs, CvVec3s v) +{ + (*fs) << cv::Vec3s(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4s(cv::FileStorage *fs, CvVec4s v) +{ + (*fs) << cv::Vec4s(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6s(cv::FileStorage *fs, CvVec6s v) +{ + (*fs) << cv::Vec6s(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} +CVAPI(void) core_FileStorage_shift_Vec2w(cv::FileStorage *fs, CvVec2w v) +{ + (*fs) << cv::Vec2w(v.val[0], v.val[1]); +} +CVAPI(void) core_FileStorage_shift_Vec3w(cv::FileStorage *fs, CvVec3w v) +{ + (*fs) << cv::Vec3w(v.val[0], v.val[1], v.val[2]); +} +CVAPI(void) core_FileStorage_shift_Vec4w(cv::FileStorage *fs, CvVec4w v) +{ + (*fs) << cv::Vec4w(v.val[0], v.val[1], v.val[2], v.val[3]); +} +CVAPI(void) core_FileStorage_shift_Vec6w(cv::FileStorage *fs, CvVec6w v) +{ + (*fs) << cv::Vec6w(v.val[0], v.val[1], v.val[2], v.val[3], v.val[4], v.val[5]); +} + +#pragma endregion + +#pragma region FileNodeIterator + +CVAPI(cv::FileNodeIterator*) core_FileNodeIterator_new1() +{ + return new cv::FileNodeIterator; +} +CVAPI(cv::FileNodeIterator*) core_FileNodeIterator_new2(cv::FileNodeIterator *obj) +{ + return new cv::FileNodeIterator(*obj); +} + +CVAPI(void) core_FileNodeIterator_delete(cv::FileNodeIterator *obj) +{ + delete obj; +} + +CVAPI(cv::FileNode*) core_FileNodeIterator_operatorAsterisk(cv::FileNodeIterator *obj) +{ + return new cv::FileNode(*(*obj)); +} + +CVAPI(int) core_FileNodeIterator_operatorIncrement(cv::FileNodeIterator *obj) +{ + const size_t prev_remaining = obj->remaining(); + ++(*obj); + return (prev_remaining == obj->remaining()) ? 0 : 1; +} + +CVAPI(int) core_FileNodeIterator_operatorPlusEqual(cv::FileNodeIterator *obj, int ofs) +{ + const size_t prev_remaining = obj->remaining(); + (*obj) += ofs; + return (prev_remaining == obj->remaining()) ? 0 : 1; +} + +CVAPI(cv::FileNodeIterator*) core_FileNodeIterator_readRaw( + cv::FileNodeIterator *obj, const char *fmt, uchar* vec, size_t maxCount) +{ + return &(obj->readRaw(fmt, vec, maxCount)); +} + +CVAPI(int) core_FileNodeIterator_operatorEqual(cv::FileNodeIterator *it1, cv::FileNodeIterator *it2) +{ + return ((*it1) == (*it2)) ? 1 : 0; +} + +/* +CVAPI(int) core_FileNodeIterator_operatorNotEqual(cv::FileNodeIterator *it1, cv::FileNodeIterator *it2) +{ + return ((*it1) != (*it2)) ? 1 : 0; +}*/ + +CVAPI(ptrdiff_t) core_FileNodeIterator_operatorMinus(cv::FileNodeIterator *it1, cv::FileNodeIterator *it2) +{ + return (*it1) - (*it2); +} + +CVAPI(int) core_FileNodeIterator_operatorLessThan(cv::FileNodeIterator *it1, cv::FileNodeIterator *it2) +{ + return (*it1) < (*it2); +} + +#pragma endregion + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_InputArray.h b/OpenVinoOpenCvSharpExtern/core_InputArray.h new file mode 100644 index 0000000..f42263f --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_InputArray.h @@ -0,0 +1,196 @@ +#ifndef _CPP_CORE_INPUTARRAY_H_ +#define _CPP_CORE_INPUTARRAY_H_ + +#include "include_opencv.h" + +// ReSharper disable CppNonInlineFunctionDefinitionInHeaderFile + +CVAPI(cv::_InputArray*) core_InputArray_new_byMat(cv::Mat *mat) +{ + return new cv::_InputArray(*mat); +} + +CVAPI(cv::_InputArray*) core_InputArray_new_byMatExpr(cv::MatExpr *expr) +{ + return new cv::_InputArray(*expr); +} + +CVAPI(cv::_InputArray*) core_InputArray_new_byScalar(MyCvScalar s, cv::Scalar **handle) +{ + *handle = new cv::Scalar(s.val[0], s.val[1], s.val[2], s.val[3]); + return new cv::_InputArray(**handle); +} + +CVAPI(cv::_InputArray*) core_InputArray_new_byDouble(double *handle) +{ + return new cv::_InputArray(*handle); +} + +CVAPI(cv::_InputArray*) core_InputArray_new_byGpuMat(cv::cuda::GpuMat *gm) +{ + return new cv::_InputArray(*gm); +} + +CVAPI(cv::_InputArray*) core_InputArray_new_byVectorOfMat(std::vector *vector) +{ + return new cv::_InputArray(*vector); +} + +CVAPI(void) core_InputArray_delete(cv::_InputArray *ia) +{ + delete ia; +} +CVAPI(void) core_InputArray_delete_withScalar(cv::_InputArray *ia, cv::Scalar *handle) +{ + delete ia; + delete handle; +} + +CVAPI(cv::Mat*) core_InputArray_getMat(cv::_InputArray *ia, int idx) +{ + return new cv::Mat(ia->getMat(idx)); +} +CVAPI(cv::Mat*) core_InputArray_getMat_(cv::_InputArray *ia, int idx) +{ + return new cv::Mat(ia->getMat_(idx)); +} +CVAPI(cv::UMat*) core_InputArray_getUMat(cv::_InputArray *ia, int idx) +{ + return new cv::UMat(ia->getUMat(idx)); +} +CVAPI(void) core_InputArray_getMatVector(cv::_InputArray *ia, std::vector *mv) +{ + ia->getMatVector(*mv); +} +CVAPI(void) core_InputArray_getUMatVector(cv::_InputArray *ia, std::vector *umv) +{ + ia->getUMatVector(*umv); +} +CVAPI(void) core_InputArray_getGpuMatVector(cv::_InputArray *ia, std::vector *gpumv) +{ + ia->getGpuMatVector(*gpumv); +} +CVAPI(cv::cuda::GpuMat*) core_InputArray_getGpuMat(cv::_InputArray *ia) +{ + return new cv::cuda::GpuMat(ia->getGpuMat()); +} +//CVAPI(cv::ogl::Buffer*) core_InputArray_getOGlBuffer(cv::_InputArray *ia) +//{ +// return new cv::ogl::Buffer(ia->getOGlBuffer()); +//} + +CVAPI(int) core_InputArray_getFlags(cv::_InputArray *ia) +{ + return ia->getFlags(); +} +CVAPI(void*) core_InputArray_getObj(cv::_InputArray *ia) +{ + return ia->getObj(); +} +CVAPI(MyCvSize) core_InputArray_getSz(cv::_InputArray *ia) +{ + return c(ia->getSz()); +} + +CVAPI(int) core_InputArray_kind(cv::_InputArray *ia) +{ + return ia->kind(); +} +CVAPI(int) core_InputArray_dims(cv::_InputArray *ia, int i) +{ + return ia->dims(i); +} +CVAPI(int) core_InputArray_cols(cv::_InputArray *ia, int i) +{ + return ia->cols(); +} +CVAPI(int) core_InputArray_rows(cv::_InputArray *ia, int i) +{ + return ia->rows(); +} +CVAPI(MyCvSize) core_InputArray_size(cv::_InputArray *ia, int i) +{ + return c(ia->size(i)); +} +CVAPI(int) core_InputArray_sizend(cv::_InputArray *ia, int* sz, int i) +{ + return ia->sizend(sz, i); +} +CVAPI(int) core_InputArray_sameSize(cv::_InputArray *self, cv::_InputArray * target) +{ + return self->sameSize(*target) ? 1 : 0; +} +CVAPI(size_t) core_InputArray_total(cv::_InputArray *ia, int i) +{ + return ia->total(i); +} +CVAPI(int) core_InputArray_type(cv::_InputArray *ia, int i) +{ + return ia->type(i); +} +CVAPI(int) core_InputArray_depth(cv::_InputArray *ia, int i) +{ + return ia->depth(i); +} +CVAPI(int) core_InputArray_channels(cv::_InputArray *ia, int i) +{ + return ia->channels(i); +} +CVAPI(int) core_InputArray_isContinuous(cv::_InputArray *ia, int i) +{ + return ia->isContinuous(i) ? 1 : 0; +} +CVAPI(int) core_InputArray_isSubmatrix(cv::_InputArray *ia, int i) +{ + return ia->isSubmatrix(i) ? 1 : 0; +} +CVAPI(int) core_InputArray_empty(cv::_InputArray *ia) +{ + return ia->empty() ? 1 : 0; +} +CVAPI(void) core_InputArray_copyTo1(cv::_InputArray *ia, cv::_OutputArray *arr) +{ + ia->copyTo(*arr); +} +CVAPI(void) core_InputArray_copyTo2(cv::_InputArray *ia, cv::_OutputArray *arr, cv::_InputArray *mask) +{ + ia->copyTo(*arr, *mask); +} +CVAPI(size_t) core_InputArray_offset(cv::_InputArray *ia, int i) +{ + return ia->offset(i); +} +CVAPI(size_t) core_InputArray_step(cv::_InputArray *ia, int i) +{ + return ia->step(i); +} +CVAPI(int) core_InputArray_isMat(cv::_InputArray *ia) +{ + return ia->isMat() ? 1 : 0; +} +CVAPI(int) core_InputArray_isUMat(cv::_InputArray *ia) +{ + return ia->isUMat() ? 1 : 0; +} +CVAPI(int) core_InputArray_isMatVector(cv::_InputArray *ia) +{ + return ia->isMatVector() ? 1 : 0; +} +CVAPI(int) core_InputArray_isUMatVector(cv::_InputArray *ia) +{ + return ia->isUMatVector() ? 1 : 0; +} +CVAPI(int) core_InputArray_isMatx(cv::_InputArray *ia) +{ + return ia->isMatx() ? 1 : 0; +} +CVAPI(int) core_InputArray_isVector(cv::_InputArray *ia) +{ + return ia->isVector() ? 1 : 0; +} +CVAPI(int) core_InputArray_isGpuMatVector(cv::_InputArray *ia) +{ + return ia->isGpuMatVector() ? 1 : 0; +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_LDA.h b/OpenVinoOpenCvSharpExtern/core_LDA.h new file mode 100644 index 0000000..3e5ad35 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_LDA.h @@ -0,0 +1,81 @@ +#ifndef _CPP_CORE_LDA_H_ +#define _CPP_CORE_LDA_H_ + +#include "include_opencv.h" + +CVAPI(cv::LDA*) core_LDA_new1(int num_components) +{ + return new cv::LDA(num_components); +} + +CVAPI(cv::LDA*) core_LDA_new2(cv::_InputArray *src, cv::_InputArray *labels, int num_components) +{ + return new cv::LDA(*src, *labels, num_components); +} + +CVAPI(void) core_LDA_delete(cv::LDA *obj) +{ + delete obj; +} + +CVAPI(void) core_LDA_save_String(cv::LDA *obj, const char *filename) +{ + obj->save(filename); +} + +CVAPI(void) core_LDA_load_String(cv::LDA *obj, const char *filename) +{ + obj->load(filename); +} + +CVAPI(void) core_LDA_save_FileStorage(cv::LDA *obj, cv::FileStorage *fs) +{ + obj->save(*fs); +} + +CVAPI(void) core_LDA_load_FileStorage(cv::LDA *obj, cv::FileStorage *node) +{ + obj->load(*node); +} + +CVAPI(void) core_LDA_compute(cv::LDA *obj, cv::_InputArray *src, cv::_InputArray *labels) +{ + obj->compute(*src, *labels); +} + +CVAPI(cv::Mat*) core_LDA_project(cv::LDA *obj, cv::_InputArray *src) +{ + const cv::Mat mat = obj->project(*src); + return new cv::Mat(mat); +} + +CVAPI(cv::Mat*) core_LDA_reconstruct(cv::LDA *obj, cv::_InputArray *src) +{ + const cv::Mat mat = obj->reconstruct(*src); + return new cv::Mat(mat); +} + +CVAPI(cv::Mat*) core_LDA_eigenvectors(cv::LDA *obj) +{ + const cv::Mat mat = obj->eigenvectors(); + return new cv::Mat(mat); +} + +CVAPI(cv::Mat*) core_LDA_eigenvalues(cv::LDA *obj) +{ + const cv::Mat mat = obj->eigenvalues(); + return new cv::Mat(mat); +} + +CVAPI(cv::Mat*) core_LDA_subspaceProject(cv::_InputArray *W, cv::_InputArray *mean, cv::_InputArray *src) +{ + const cv::Mat mat = cv::LDA::subspaceProject(*W, *mean, *src); + return new cv::Mat(mat); +} +CVAPI(cv::Mat*) core_LDA_subspaceReconstruct(cv::_InputArray *W, cv::_InputArray *mean, cv::_InputArray *src) +{ + const cv::Mat mat = cv::LDA::subspaceReconstruct(*W, *mean, *src); + return new cv::Mat(mat); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_Mat.h b/OpenVinoOpenCvSharpExtern/core_Mat.h new file mode 100644 index 0000000..1c301fb --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_Mat.h @@ -0,0 +1,1371 @@ +#ifndef _CPP_CORE_MAT_H_ +#define _CPP_CORE_MAT_H_ + +#include "include_opencv.h" + + +#pragma region Init & Release +CVAPI(uint64) core_Mat_sizeof() +{ + return sizeof(cv::Mat); +} + +CVAPI(cv::Mat*) core_Mat_new1() +{ + return new cv::Mat(); +} +CVAPI(cv::Mat*) core_Mat_new2(int rows, int cols, int type) +{ + return new cv::Mat(rows, cols, type); +} +CVAPI(cv::Mat*) core_Mat_new3(int rows, int cols, int type, MyCvScalar scalar) +{ + return new cv::Mat(rows, cols, type, cpp(scalar)); +} +CVAPI(cv::Mat*) core_Mat_new4(cv::Mat *mat, cv::Range rowRange, cv::Range colRange) +{ + return new cv::Mat(*mat, rowRange, colRange); +} +CVAPI(cv::Mat*) core_Mat_new5(cv::Mat *mat, cv::Range rowRange) +{ + return new cv::Mat(*mat, rowRange); +} +CVAPI(cv::Mat*) core_Mat_new6(cv::Mat *mat, cv::Range *ranges) +{ + return new cv::Mat(*mat, ranges); +} +CVAPI(cv::Mat*) core_Mat_new7(cv::Mat *mat, MyCvRect roi) +{ + return new cv::Mat(*mat, cpp(roi)); +} +CVAPI(cv::Mat*) core_Mat_new8(int rows, int cols, int type, void* data, size_t step) +{ + return new cv::Mat(rows, cols, type, data, step); +} +CVAPI(cv::Mat*) core_Mat_new9(int ndims, const int* sizes, int type, void* data, const size_t* steps) +{ + return new cv::Mat(ndims, sizes, type, data, steps); +} + +CVAPI(cv::Mat*) core_Mat_new10(int ndims, int* sizes, int type) +{ + return new cv::Mat(ndims, sizes, type); +} +CVAPI(cv::Mat*) core_Mat_new11(int ndims, int* sizes, int type, MyCvScalar s) +{ + return new cv::Mat(ndims, sizes, type, cpp(s)); +} +CVAPI(cv::Mat*) core_Mat_new12(cv::Mat *mat) +{ + return new cv::Mat(*mat); +} + +CVAPI(cv::Mat*) core_Mat_new_FromIplImage(IplImage *img, int copyData) +{ + cv::Size size(img->height, img->width); + cv::Mat m(size, CV_MAKETYPE(img->depth, img->nChannels), img->imageData, img->widthStep); + if (copyData) + return new cv::Mat(m.clone()); + else + return new cv::Mat(m); +} + +CVAPI(cv::Mat*) core_Mat_new_FromCvMat(CvMat *mat, int copyData) +{ + cv::Size size(mat->rows, mat->cols); + cv::Mat m(size, mat->type, (mat->data).ptr); + if (copyData) + return new cv::Mat(m.clone()); + else + return new cv::Mat(m); +} + + +CVAPI(void) core_Mat_release(cv::Mat *self) +{ + self->release(); +} +CVAPI(void) core_Mat_delete(cv::Mat *self) +{ + delete self; +} + +#pragma endregion + +#pragma region Functions +CVAPI(cv::Mat*) core_Mat_adjustROI(cv::Mat *self, int dtop, int dbottom, int dleft, int dright) +{ + cv::Mat ret = self->adjustROI(dtop, dbottom, dleft, dright); + return new cv::Mat(ret); +} + +CVAPI(void) core_Mat_assignTo1(cv::Mat *self, cv::Mat *m) +{ + self->assignTo(*m); +} +CVAPI(void) core_Mat_assignTo2(cv::Mat *self, cv::Mat *m, int type) +{ + self->assignTo(*m, type); +} + +CVAPI(int) core_Mat_channels(cv::Mat *self) +{ + return self->channels(); +} + +CVAPI(int) core_Mat_checkVector1(cv::Mat *self, int elemChannels) +{ + return self->checkVector(elemChannels); +} +CVAPI(int) core_Mat_checkVector2(cv::Mat *self, int elemChannels, int depth) +{ + return self->checkVector(elemChannels, depth); +} +CVAPI(int) core_Mat_checkVector3(cv::Mat *self, int elemChannels, int depth, int requireContinuous) +{ + return self->checkVector(elemChannels, depth, requireContinuous != 0); +} + +CVAPI(cv::Mat*) core_Mat_clone(cv::Mat *self) +{ + cv::Mat ret = self->clone(); + return new cv::Mat(ret); +} + +CVAPI(cv::Mat*) core_Mat_col_toMat(cv::Mat *self, int x) +{ + cv::Mat ret = self->col(x); + return new cv::Mat(ret); +} +CVAPI(cv::MatExpr*) core_Mat_col_toMatExpr(cv::Mat *self, int x) +{ + cv::Mat ret = self->col(x); + return new cv::MatExpr(ret); +} + +CVAPI(int) core_Mat_cols(cv::Mat *self) +{ + return self->cols; +} + +CVAPI(cv::Mat*) core_Mat_colRange_toMat(cv::Mat *self, int startCol, int endCol) +{ + cv::Mat ret = self->colRange(startCol, endCol); + return new cv::Mat(ret); +} +CVAPI(cv::MatExpr*) core_Mat_colRange_toMatExpr(cv::Mat *self, int startCol, int endCol) +{ + cv::Mat ret = self->colRange(startCol, endCol); + return new cv::MatExpr(ret); +} + +CVAPI(int) core_Mat_dims(cv::Mat *self) +{ + return self->dims; +} + +CVAPI(void) core_Mat_convertTo(cv::Mat *self, cv::Mat *m, int rtype, double alpha, double beta) +{ + self->convertTo(*m, rtype, alpha, beta); +} + +CVAPI(void) core_Mat_copyTo(cv::Mat *self, cv::Mat *m, cv::Mat *mask) +{ + const cv::Mat &maskMat = (mask == NULL) ? cv::Mat() : *mask; + self->copyTo(*m, maskMat); +} + + +CVAPI(void) core_Mat_create1(cv::Mat *self, int rows, int cols, int type) +{ + self->create(rows, cols, type); +} +CVAPI(void) core_Mat_create2(cv::Mat *self, int ndims, const int *sizes, int type) +{ + self->create(ndims, sizes, type); +} + +CVAPI(cv::Mat*) core_Mat_cross(cv::Mat *self, cv::Mat *m) +{ + cv::Mat ret = self->cross(*m); + return new cv::Mat(ret); +} + +CVAPI(uchar*) core_Mat_data(cv::Mat *self) +{ + return self->data; +} +CVAPI(const uchar*) core_Mat_datastart(cv::Mat *self) +{ + return self->datastart; +} +CVAPI(const uchar*) core_Mat_dataend(cv::Mat *self) +{ + return self->dataend; +} +CVAPI(const uchar*) core_Mat_datalimit(cv::Mat *self) +{ + return self->datalimit; +} + + +CVAPI(int) core_Mat_depth(cv::Mat *self) +{ + return self->depth(); +} + + +CVAPI(cv::Mat*) core_Mat_diag1(cv::Mat *self) +{ + cv::Mat ret = self->diag(); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_diag2(cv::Mat *self, int d) +{ + cv::Mat ret = self->diag(d); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_diag3(cv::Mat *self) +{ + cv::Mat ret = cv::Mat::diag(*self); + return new cv::Mat(ret); +} + +CVAPI(double) core_Mat_dot(cv::Mat *self, cv::Mat *m) +{ + return self->dot(*m); +} + +CVAPI(uint64) core_Mat_elemSize(cv::Mat *self) +{ + return self->elemSize(); +} + +CVAPI(uint64) core_Mat_elemSize1(cv::Mat *self) +{ + return self->elemSize1(); +} + +CVAPI(int) core_Mat_empty(cv::Mat *self) +{ + return self->empty() ? 1 : 0; +} + +CVAPI(cv::MatExpr*) core_Mat_eye(int rows, int cols, int type) +{ + cv::MatExpr eye = cv::Mat::eye(rows, cols, type); + cv::MatExpr *ret = new cv::MatExpr(eye); + return ret; +} + +CVAPI(cv::Mat*) core_Mat_inv1(cv::Mat *self) +{ + cv::Mat ret = self->inv(); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_inv2(cv::Mat *self, int method) +{ + cv::Mat ret = self->inv(method); + return new cv::Mat(ret); +} + +CVAPI(int) core_Mat_isContinuous(cv::Mat *self) +{ + return self->isContinuous() ? 1 : 0; +} + +CVAPI(int) core_Mat_isSubmatrix(cv::Mat *self) +{ + return self->isSubmatrix() ? 1 : 0; +} + +CVAPI(void) core_Mat_locateROI(cv::Mat *self, MyCvSize *wholeSize, MyCvPoint *ofs) +{ + cv::Size wholeSize2; + cv::Point ofs2; + self->locateROI(wholeSize2, ofs2); + *wholeSize = c(cv::Size(wholeSize2.width, wholeSize2.height)); + *ofs = c(cv::Point(ofs2.x, ofs2.y)); +} + + +CVAPI(cv::MatExpr*) core_Mat_mul1(cv::Mat *self, cv::Mat *m) +{ + cv::MatExpr ret = self->mul(*m); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_Mat_mul2(cv::Mat *self, cv::Mat *m, double scale) +{ + cv::MatExpr ret = self->mul(*m, scale); + return new cv::MatExpr(ret); +} + +CVAPI(cv::MatExpr*) core_Mat_ones1(int rows, int cols, int type) +{ + cv::MatExpr ret = cv::Mat::ones(rows, cols, type); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_Mat_ones2(int ndims, const int *sz, int type) +{ + //cv::MatExpr ret = cv::Mat::ones(ndims, sz, type); + //return new cv::MatExpr(ret); + return NULL; +} + +CVAPI(cv::Mat*) core_Mat_reshape1(cv::Mat *self, int cn) +{ + cv::Mat ret = self->reshape(cn); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_reshape2(cv::Mat *self, int cn, int rows) +{ + cv::Mat ret = self->reshape(cn, rows); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_reshape3(cv::Mat *self, int cn, int newndims, const int* newsz) +{ + cv::Mat ret = self->reshape(cn, newndims, newsz); + return new cv::Mat(ret); +} + +CVAPI(cv::Mat*) core_Mat_row_toMat(cv::Mat *self, int y) +{ + cv::Mat ret = self->row(y); + return new cv::Mat(ret); +} +CVAPI(cv::MatExpr*) core_Mat_row_toMatExpr(cv::Mat *self, int y) +{ + cv::Mat ret = self->row(y); + return new cv::MatExpr(ret); +} + +CVAPI(cv::Mat*) core_Mat_rowRange_toMat(cv::Mat *self, int startRow, int endRow) +{ + cv::Mat ret = self->rowRange(startRow, endRow); + return new cv::Mat(ret); +} +CVAPI(cv::MatExpr*) core_Mat_rowRange_toMatExpr(cv::Mat *self, int startRow, int endRow) +{ + cv::Mat ret = self->rowRange(startRow, endRow); + return new cv::MatExpr(ret); +} + +CVAPI(int) core_Mat_rows(cv::Mat *self) +{ + return self->rows; +} + +CVAPI(void) core_Mat_setTo_Scalar(cv::Mat *self, MyCvScalar value, cv::Mat *mask) +{ + // crash + // core_Mat_setTo_Scalar(cv::Mat *self, MyCvScalar value, cv::InputArray *mask) + + if (mask == NULL) + self->setTo(cpp(value)); + else + self->setTo(cpp(value), entity(mask)); +} +CVAPI(void) core_Mat_setTo_InputArray(cv::Mat *self, cv::_InputArray *value, cv::Mat *mask) +{ + self->setTo(*value, entity(mask)); +} + +CVAPI(MyCvSize) core_Mat_size(cv::Mat *self) +{ + return c(self->size()); +} +CVAPI(int) core_Mat_sizeAt(cv::Mat *self, int i) +{ + int size = self->size[i]; + return size; +} + +CVAPI(uint64) core_Mat_step11(cv::Mat *self) +{ + return self->step1(); +} +CVAPI(uint64) core_Mat_step12(cv::Mat *self, int i) +{ + return self->step1(i); +} + +CVAPI(uint64) core_Mat_step(cv::Mat *self) +{ + return self->step; +} +CVAPI(uint64) core_Mat_stepAt(cv::Mat *self, int i) +{ + return self->step[i]; +} + +CVAPI(cv::Mat*) core_Mat_subMat1(cv::Mat *self, int rowStart, int rowEnd, int colStart, int colEnd) +{ + cv::Range rowRange(rowStart, rowEnd); + cv::Range colRange(colStart, colEnd); + cv::Mat ret = (*self)(rowRange, colRange); + return new cv::Mat(ret); +} +CVAPI(cv::Mat*) core_Mat_subMat2(cv::Mat *self, int nRanges, MyCvSlice *ranges) +{ + std::vector rangesVec(nRanges); + for (int i = 0; i < nRanges; i++) + { + rangesVec[i] = (cpp(ranges[i])); + } + cv::Mat ret = (*self)(&rangesVec[0]); + return new cv::Mat(ret); +} + +CVAPI(cv::Mat*) core_Mat_t(cv::Mat *self) +{ + cv::Mat expr = self->t(); + return new cv::Mat(expr); +} + +CVAPI(uint64) core_Mat_total(cv::Mat *self) +{ + return self->total(); +} + +CVAPI(int) core_Mat_type(cv::Mat *self) +{ + return self->type(); +} + +CVAPI(cv::MatExpr*) core_Mat_zeros1(int rows, int cols, int type) +{ + cv::MatExpr expr = cv::Mat::zeros(rows, cols, type); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_zeros2(int ndims, const int *sz, int type) // Not defined in .lib +{ + //cv::MatExpr expr = cv::Mat::zeros(ndims, sz, type); + //return new cv::MatExpr(expr); + return NULL; +} + +CVAPI(uchar*) core_Mat_ptr1d(cv::Mat *self, int i0) +{ + return self->ptr(i0); +} +CVAPI(uchar*) core_Mat_ptr2d(cv::Mat *self, int i0, int i1) +{ + return self->ptr(i0, i1); +} +CVAPI(uchar*) core_Mat_ptr3d(cv::Mat *self, int i0, int i1, int i2) +{ + return self->ptr(i0, i1, i2); +} +CVAPI(uchar*) core_Mat_ptrnd(cv::Mat *self, int *idx) +{ + return self->ptr(idx); +} + +CVAPI(void) core_Mat_reserve(cv::Mat *obj, size_t sz) +{ + obj->reserve(sz); +} +CVAPI(void) core_Mat_resize1(cv::Mat *obj, size_t sz) +{ + obj->resize(sz); +} +CVAPI(void) core_Mat_resize2(cv::Mat *obj, size_t sz, MyCvScalar s) +{ + obj->resize(sz, cpp(s)); +} +CVAPI(void) core_Mat_pop_back(cv::Mat *obj, size_t nelems) +{ + obj->pop_back(nelems); +} + +#pragma endregion + +#pragma region Operators + +CVAPI(void) core_Mat_assignment_FromMat(cv::Mat *self, cv::Mat *newMat) +{ + *self = *newMat; +} +CVAPI(void) core_Mat_assignment_FromMatExpr(cv::Mat *self, cv::MatExpr *newMatExpr) +{ + *self = *newMatExpr; +} +CVAPI(void) core_Mat_assignment_FromScalar(cv::Mat *self, MyCvScalar scalar) +{ + *self = cpp(scalar); +} + +CVAPI(void) core_Mat_IplImage(cv::Mat *self, IplImage *outImage) +{ + *outImage = IplImage(); + IplImage inImage = (IplImage)(*self); + memcpy(outImage, &inImage, sizeof(IplImage)); +} +CVAPI(void) core_Mat_IplImage_alignment(cv::Mat *self, IplImage **outImage) +{ + // キャストの結果を参考に使う. + // メモリ管理の問題から、直接は使わない. + IplImage dummy = (IplImage)(*self); + // alignmentをそろえる + IplImage *img = cvCreateImage(cvSize(dummy.width, dummy.height), dummy.depth, dummy.nChannels); + int height = img->height; + size_t sstep = self->step; + size_t dstep = img->widthStep; + for (int i = 0; i < height; ++i) + { + char *dp = img->imageData + (dstep * i); + char *sp = (char*)(self->data) + (sstep * i); + memcpy(dp, sp, sstep); + } + *outImage = img; +} + +CVAPI(void) core_Mat_CvMat(cv::Mat *self, CvMat *outMat) +{ + *outMat = CvMat(); + CvMat inMat = (CvMat)(*self); + memcpy(outMat, &inMat, sizeof(CvMat)); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorUnaryMinus(cv::Mat *mat) +{ + cv::MatExpr expr = -(*mat); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorAdd_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) + (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorAdd_MatScalar(cv::Mat *a, MyCvScalar s) +{ + cv::MatExpr expr = (*a) + cpp(s); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorAdd_ScalarMat(MyCvScalar s, cv::Mat *a) +{ + cv::MatExpr expr = cpp(s) + (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorMinus_Mat(cv::Mat *a) +{ + cv::MatExpr expr = -(*a); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorSubtract_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) - (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorSubtract_MatScalar(cv::Mat *a, MyCvScalar s) +{ + cv::MatExpr expr = (*a) - cpp(s); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorSubtract_ScalarMat(MyCvScalar s, cv::Mat *a) +{ + cv::MatExpr expr = cpp(s) - (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorMultiply_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) * (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorMultiply_MatDouble(cv::Mat *a, double s) +{ + cv::MatExpr expr = (*a) * s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorMultiply_DoubleMat(double s, cv::Mat *a) +{ + cv::MatExpr expr = s * (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorDivide_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) / (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorDivide_MatDouble(cv::Mat *a, double s) +{ + cv::MatExpr expr = (*a) / s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorDivide_DoubleMat(double s, cv::Mat *a) +{ + cv::MatExpr expr = s / (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorAnd_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) & (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorAnd_MatDouble(cv::Mat *a, double s) +{ + cv::MatExpr expr = (*a) & s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorAnd_DoubleMat(double s, cv::Mat *a) +{ + cv::MatExpr expr = s & (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorOr_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) | (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorOr_MatDouble(cv::Mat *a, double s) +{ + cv::MatExpr expr = (*a) | s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorOr_DoubleMat(double s, cv::Mat *a) +{ + cv::MatExpr expr = s | (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorXor_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) ^ (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorXor_MatDouble(cv::Mat *a, double s) +{ + cv::MatExpr expr = (*a) ^ s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorXor_DoubleMat(double s, cv::Mat *a) +{ + cv::MatExpr expr = s ^ (*a); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_Mat_operatorNot(cv::Mat *a) +{ + cv::MatExpr expr = ~(*a); + return new cv::MatExpr(expr); +} + + +// Comparison Operators + +// < +CVAPI(cv::MatExpr*) core_Mat_operatorLT_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) < (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorLT_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a < (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorLT_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) < b; + return new cv::MatExpr(expr); +} +// <= +CVAPI(cv::MatExpr*) core_Mat_operatorLE_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) <= (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorLE_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a <= (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorLE_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) <= b; + return new cv::MatExpr(expr); +} +// > +CVAPI(cv::MatExpr*) core_Mat_operatorGT_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) > (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorGT_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a > (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorGT_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) > b; + return new cv::MatExpr(expr); +} +// >= +CVAPI(cv::MatExpr*) core_Mat_operatorGE_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) >= (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorGE_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a >= (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorGE_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) >= b; + return new cv::MatExpr(expr); +} +// == +CVAPI(cv::MatExpr*) core_Mat_operatorEQ_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) == (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorEQ_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a == (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorEQ_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) == b; + return new cv::MatExpr(expr); +} +// != +CVAPI(cv::MatExpr*) core_Mat_operatorNE_MatMat(cv::Mat *a, cv::Mat *b) +{ + cv::MatExpr expr = (*a) != (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorNE_DoubleMat(double a, cv::Mat *b) +{ + cv::MatExpr expr = a != (*b); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_Mat_operatorNE_MatDouble(cv::Mat *a, double b) +{ + cv::MatExpr expr = (*a) != b; + return new cv::MatExpr(expr); +} + +#pragma endregion + +CVAPI(cv::MatExpr*) core_abs_Mat(cv::Mat *m) +{ + cv::MatExpr ret = cv::abs(*m); + return new cv::MatExpr(ret); +} + +#pragma region nSet/nGet + +template +static int internal_Mat_set(cv::Mat *m, int row, int col, char *buff, int count) +{ + if (!m) return 0; + if (!buff) return 0; + + count *= sizeof(T); + int rest = ((m->rows - row) * m->cols - col) * (int)m->elemSize(); + if (count>rest) + count = rest; + int res = count; + + if (m->isContinuous()) + { + memcpy(m->ptr(row, col), buff, count); + } + else + { + // row by row + int num = (m->cols - col) * (int)m->elemSize(); // 1st partial row + if (countptr(row++, col); + while (count>0) + { + memcpy(data, buff, num); + count -= num; + buff += num; + num = m->cols * (int)m->elemSize(); + if (countptr(row++, 0); + } + } + return res; +} + +template +static int internal_Mat_get(cv::Mat *m, int row, int col, char *buff, int count) +{ + if (!m) return 0; + if (!buff) return 0; + + int bytesToCopy = count * sizeof(T); + int bytesRestInMat = ((m->rows - row) * m->cols - col) * (int)m->elemSize(); + if (bytesToCopy > bytesRestInMat) + bytesToCopy = bytesRestInMat; + int res = bytesToCopy; + + if (m->isContinuous()) + { + memcpy(buff, m->ptr(row, col), bytesToCopy); + } + else + { + // row by row + int bytesInRow = (m->cols - col) * (int)m->elemSize(); // 1st partial row + while (bytesToCopy > 0) + { + int len = std::min(bytesToCopy, bytesInRow); + memcpy(buff, m->ptr(row, col), len); + bytesToCopy -= len; + buff += len; + row++; + col = 0; + bytesInRow = m->cols * (int)m->elemSize(); + } + } + return res; +} + +// unlike other nPut()-s this one (with double[]) should convert input values to correct type +template +static void internal_set_item(cv::Mat *mat, int r, int c, double *src, int &count) +{ + T *dst = (T*)mat->ptr(r, c); + for (int ch = 0; ch < mat->channels() && count > 0; count--, ch++, src++, dst++) + *dst = cv::saturate_cast(*src); +} + + +CVAPI(int) core_Mat_nSetB(cv::Mat *obj, int row, int col, uchar *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetS(cv::Mat *obj, int row, int col, short *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetI(cv::Mat *obj, int row, int col, int *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetF(cv::Mat *obj, int row, int col, float *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetD(cv::Mat *obj, int row, int col, double *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); + /* + int rest = ((obj->rows - row) * obj->cols - col) * obj->channels(); + int count = valsLength; + if (count > rest) + count = rest; + int res = count; + double* src = vals; + int r, c; + for (c = col; ccols && count > 0; c++) + { + switch (obj->depth()) + { + case CV_8U: internal_set_item(obj, row, c, src, count); break; + case CV_8S: internal_set_item(obj, row, c, src, count); break; + case CV_16U: internal_set_item(obj, row, c, src, count); break; + case CV_16S: internal_set_item(obj, row, c, src, count); break; + case CV_32S: internal_set_item(obj, row, c, src, count); break; + case CV_32F: internal_set_item(obj, row, c, src, count); break; + case CV_64F: internal_set_item(obj, row, c, src, count); break; + } + } + for (r = row + 1; r < obj->rows && count > 0; r++) + { + for (c = 0; c < obj->cols && count > 0; c++) + { + switch (obj->depth()) + { + case CV_8U: internal_set_item(obj, r, c, src, count); break; + case CV_8S: internal_set_item(obj, r, c, src, count); break; + case CV_16U: internal_set_item(obj, r, c, src, count); break; + case CV_16S: internal_set_item(obj, r, c, src, count); break; + case CV_32S: internal_set_item(obj, r, c, src, count); break; + case CV_32F: internal_set_item(obj, r, c, src, count); break; + case CV_64F: internal_set_item(obj, r, c, src, count); break; + } + } + } + return res;*/ +} +CVAPI(int) core_Mat_nSetVec3b(cv::Mat *obj, int row, int col, cv::Vec3b *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetVec3d(cv::Mat *obj, int row, int col, cv::Vec3d *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetVec4f(cv::Mat *obj, int row, int col, cv::Vec4f *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetVec6f(cv::Mat *obj, int row, int col, cv::Vec6f *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetVec4i(cv::Mat *obj, int row, int col, cv::Vec4i *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint(cv::Mat *obj, int row, int col, cv::Point *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint2f(cv::Mat *obj, int row, int col, cv::Point2f *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint2d(cv::Mat *obj, int row, int col, cv::Point2d *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint3i(cv::Mat *obj, int row, int col, cv::Point3i *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint3f(cv::Mat *obj, int row, int col, cv::Point3f *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetPoint3d(cv::Mat *obj, int row, int col, cv::Point3d *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nSetRect(cv::Mat *obj, int row, int col, cv::Rect *vals, int valsLength) +{ + return internal_Mat_set(obj, row, col, (char*)vals, valsLength); +} + +CVAPI(int) core_Mat_nGetB(cv::Mat *obj, int row, int col, uchar *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetS(cv::Mat *obj, int row, int col, short *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetI(cv::Mat *obj, int row, int col, int *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetF(cv::Mat *obj, int row, int col, float *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetD(cv::Mat *obj, int row, int col, double *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetVec3b(cv::Mat *obj, int row, int col, cv::Vec3b *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetVec3d(cv::Mat *obj, int row, int col, cv::Vec3d *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetVec4f(cv::Mat *obj, int row, int col, cv::Vec4f *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetVec6f(cv::Mat *obj, int row, int col, cv::Vec6f *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetVec4i(cv::Mat *obj, int row, int col, cv::Vec4i *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint(cv::Mat *obj, int row, int col, cv::Point *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint2f(cv::Mat *obj, int row, int col, cv::Point2f *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint2d(cv::Mat *obj, int row, int col, cv::Point2d *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint3i(cv::Mat *obj, int row, int col, cv::Point3i *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint3f(cv::Mat *obj, int row, int col, cv::Point3f *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetPoint3d(cv::Mat *obj, int row, int col, cv::Point3d *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} +CVAPI(int) core_Mat_nGetRect(cv::Mat *obj, int row, int col, cv::Rect *vals, int valsLength) +{ + return internal_Mat_get(obj, row, col, (char*)vals, valsLength); +} + +#pragma endregion + +#pragma region push_back + +CVAPI(void) core_Mat_push_back_Mat(cv::Mat *self, cv::Mat *m) +{ + self->push_back(*m); +} +CVAPI(void) core_Mat_push_back_char(cv::Mat *self, char v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_uchar(cv::Mat *self, uchar v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_short(cv::Mat *self, short v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_ushort(cv::Mat *self, ushort v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_int(cv::Mat *self, int v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_float(cv::Mat *self, float v) +{ + self->push_back(v); +} +CVAPI(void) core_Mat_push_back_double(cv::Mat *self, double v) +{ + self->push_back(v); +} + +CVAPI(void) core_Mat_push_back_Vec2b(cv::Mat *self, CvVec2b v) +{ + self->push_back(cv::Vec2b(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3b(cv::Mat *self, CvVec3b v) +{ + self->push_back(cv::Vec3b(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4b(cv::Mat *self, CvVec4b v) +{ + self->push_back(cv::Vec4b(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6b(cv::Mat *self, CvVec6b v) +{ + self->push_back(cv::Vec6b(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec2s(cv::Mat *self, CvVec2s v) +{ + self->push_back(cv::Vec2s(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3s(cv::Mat *self, CvVec3s v) +{ + self->push_back(cv::Vec3s(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4s(cv::Mat *self, CvVec4s v) +{ + self->push_back(cv::Vec4s(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6s(cv::Mat *self, CvVec6s v) +{ + self->push_back(cv::Vec6s(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec2w(cv::Mat *self, CvVec2w v) +{ + self->push_back(cv::Vec2w(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3w(cv::Mat *self, CvVec3w v) +{ + self->push_back(cv::Vec3w(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4w(cv::Mat *self, CvVec4w v) +{ + self->push_back(cv::Vec4w(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6w(cv::Mat *self, CvVec6w v) +{ + self->push_back(cv::Vec6w(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec2i(cv::Mat *self, CvVec2i v) +{ + self->push_back(cv::Vec2i(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3i(cv::Mat *self, CvVec3i v) +{ + self->push_back(cv::Vec3i(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4i(cv::Mat *self, CvVec4i v) +{ + self->push_back(cv::Vec4i(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6i(cv::Mat *self, CvVec6i v) +{ + self->push_back(cv::Vec6i(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec2f(cv::Mat *self, CvVec2f v) +{ + self->push_back(cv::Vec2f(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3f(cv::Mat *self, CvVec3f v) +{ + self->push_back(cv::Vec3f(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4f(cv::Mat *self, CvVec4f v) +{ + self->push_back(cv::Vec4f(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6f(cv::Mat *self, CvVec6f v) +{ + self->push_back(cv::Vec6f(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec2d(cv::Mat *self, CvVec2d v) +{ + self->push_back(cv::Vec2d(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec3d(cv::Mat *self, CvVec3d v) +{ + self->push_back(cv::Vec3d(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec4d(cv::Mat *self, CvVec4d v) +{ + self->push_back(cv::Vec4d(v.val)); +} +CVAPI(void) core_Mat_push_back_Vec6d(cv::Mat *self, CvVec6d v) +{ + self->push_back(cv::Vec6d(v.val)); +} + +CVAPI(void) core_Mat_push_back_Point(cv::Mat *self, CvPoint v) +{ + self->push_back((cv::Point)v); +} +CVAPI(void) core_Mat_push_back_Point2f(cv::Mat *self, CvPoint2D32f v) +{ + self->push_back((cv::Point2f)v); +} +CVAPI(void) core_Mat_push_back_Point2d(cv::Mat *self, CvPoint2D64f v) +{ + self->push_back(cv::Point2d(v.x, v.y)); +} +CVAPI(void) core_Mat_push_back_Point3i(cv::Mat *self, CvPoint3D v) +{ + self->push_back(cv::Point3i(v.x, v.y, v.z)); +} +CVAPI(void) core_Mat_push_back_Point3f(cv::Mat *self, CvPoint3D32f v) +{ + self->push_back((cv::Point3f)v); +} +CVAPI(void) core_Mat_push_back_Point3d(cv::Mat *self, CvPoint3D64f v) +{ + self->push_back(cv::Point3d(v.x, v.y, v.z)); +} +CVAPI(void) core_Mat_push_back_Size(cv::Mat *self, CvSize v) +{ + self->push_back((cv::Size)v); +} +CVAPI(void) core_Mat_push_back_Size2f(cv::Mat *self, CvSize2D32f v) +{ + self->push_back((cv::Size2f)v); +} +CVAPI(void) core_Mat_push_back_Rect(cv::Mat *self, CvRect v) +{ + self->push_back((cv::Rect)v); +} + +#pragma endregion + +#pragma region forEach +typedef void *(Mat_foreach_uchar)(uchar *value, const int *position); +typedef void *(Mat_foreach_Vec2b)(cv::Vec2b *value, const int *position); +typedef void *(Mat_foreach_Vec3b)(cv::Vec3b *value, const int *position); +typedef void *(Mat_foreach_Vec4b)(cv::Vec4b *value, const int *position); +typedef void *(Mat_foreach_Vec6b)(cv::Vec6b *value, const int *position); +typedef void *(Mat_foreach_short)(short *value, const int *position); +typedef void *(Mat_foreach_Vec2s)(cv::Vec2s *value, const int *position); +typedef void *(Mat_foreach_Vec3s)(cv::Vec3s *value, const int *position); +typedef void *(Mat_foreach_Vec4s)(cv::Vec4s *value, const int *position); +typedef void *(Mat_foreach_Vec6s)(cv::Vec6s *value, const int *position); +typedef void *(Mat_foreach_int)(int *value, const int *position); +typedef void *(Mat_foreach_Vec2i)(cv::Vec2i *value, const int *position); +typedef void *(Mat_foreach_Vec3i)(cv::Vec3i *value, const int *position); +typedef void *(Mat_foreach_Vec4i)(cv::Vec4i *value, const int *position); +typedef void *(Mat_foreach_Vec6i)(cv::Vec6i *value, const int *position); +typedef void *(Mat_foreach_float)(float *value, const int *position); +typedef void *(Mat_foreach_Vec2f)(cv::Vec2f *value, const int *position); +typedef void *(Mat_foreach_Vec3f)(cv::Vec3f *value, const int *position); +typedef void *(Mat_foreach_Vec4f)(cv::Vec4f *value, const int *position); +typedef void *(Mat_foreach_Vec6f)(cv::Vec6f *value, const int *position); +typedef void *(Mat_foreach_double)(double *value, const int *position); +typedef void *(Mat_foreach_Vec2d)(cv::Vec2d *value, const int *position); +typedef void *(Mat_foreach_Vec3d)(cv::Vec3d *value, const int *position); +typedef void *(Mat_foreach_Vec4d)(cv::Vec4d *value, const int *position); +typedef void *(Mat_foreach_Vec6d)(cv::Vec6d *value, const int *position); + +template +struct Functor +{ + TFunction *proc; + Functor(TFunction *_proc) + { + proc = _proc; + } + void operator()(TElem &value, const int *position) const + { + proc(&value, position); + } +}; + +CVAPI(void) core_Mat_forEach_uchar(cv::Mat *m, Mat_foreach_uchar proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec2b(cv::Mat *m, Mat_foreach_Vec2b proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec3b(cv::Mat *m, Mat_foreach_Vec3b proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec4b(cv::Mat *m, Mat_foreach_Vec4b proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec6b(cv::Mat *m, Mat_foreach_Vec6b proc) +{ + Functor functor(proc); + m->forEach(functor); +} + +CVAPI(void) core_Mat_forEach_short(cv::Mat *m, Mat_foreach_short proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec2s(cv::Mat *m, Mat_foreach_Vec2s proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec3s(cv::Mat *m, Mat_foreach_Vec3s proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec4s(cv::Mat *m, Mat_foreach_Vec4s proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec6s(cv::Mat *m, Mat_foreach_Vec6s proc) +{ + Functor functor(proc); + m->forEach(functor); +} + +CVAPI(void) core_Mat_forEach_int(cv::Mat *m, Mat_foreach_int proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec2i(cv::Mat *m, Mat_foreach_Vec2i proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec3i(cv::Mat *m, Mat_foreach_Vec3i proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec4i(cv::Mat *m, Mat_foreach_Vec4i proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec6i(cv::Mat *m, Mat_foreach_Vec6i proc) +{ + Functor functor(proc); + m->forEach(functor); +} + +CVAPI(void) core_Mat_forEach_float(cv::Mat *m, Mat_foreach_float proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec2f(cv::Mat *m, Mat_foreach_Vec2f proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec3f(cv::Mat *m, Mat_foreach_Vec3f proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec4f(cv::Mat *m, Mat_foreach_Vec4f proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec6f(cv::Mat *m, Mat_foreach_Vec6f proc) +{ + Functor functor(proc); + m->forEach(functor); +} + + +CVAPI(void) core_Mat_forEach_double(cv::Mat *m, Mat_foreach_double proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec2d(cv::Mat *m, Mat_foreach_Vec2d proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec3d(cv::Mat *m, Mat_foreach_Vec3d proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec4d(cv::Mat *m, Mat_foreach_Vec4d proc) +{ + Functor functor(proc); + m->forEach(functor); +} +CVAPI(void) core_Mat_forEach_Vec6d(cv::Mat *m, Mat_foreach_Vec6d proc) +{ + Functor functor(proc); + m->forEach(functor); +} +#pragma endregion + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_MatExpr.h b/OpenVinoOpenCvSharpExtern/core_MatExpr.h new file mode 100644 index 0000000..9adc841 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_MatExpr.h @@ -0,0 +1,220 @@ +#ifndef _CPP_CORE_MATEXPR_H_ +#define _CPP_CORE_MATEXPR_H_ + +#include "include_opencv.h" + +CVAPI(cv::MatExpr*) core_MatExpr_new1() +{ + return new cv::MatExpr(); +} +CVAPI(cv::MatExpr*) core_MatExpr_new2(cv::Mat *mat) +{ + return new cv::MatExpr(*mat); +} +CVAPI(void) core_MatExpr_delete(cv::MatExpr *self) +{ + delete self; +} + +CVAPI(cv::Mat*) core_MatExpr_toMat(cv::MatExpr *self) +{ + cv::Mat ret = (*self); + return new cv::Mat(ret); +} + +#pragma region Functions +CVAPI(cv::MatExpr*) core_MatExpr_row(cv::MatExpr *self, int y) +{ + cv::MatExpr ret = self->row(y); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_col(cv::MatExpr *self, int x) +{ + cv::MatExpr ret = self->col(x); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_diag1(cv::MatExpr *self) +{ + cv::MatExpr ret = self->diag(); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_diag2(cv::MatExpr *self, int d) +{ + cv::MatExpr ret = self->diag(d); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_submat(cv::MatExpr *self, int rowStart, int rowEnd, int colStart, int colEnd) +{ + cv::Range rowRange(rowStart, rowEnd); + cv::Range colRange(colStart, colEnd); + cv::MatExpr ret = (*self)(rowRange, colRange); + return new cv::MatExpr(ret); +} +CVAPI(cv::Mat*) core_MatExpr_cross(cv::MatExpr *self, cv::Mat *m) +{ + cv::Mat ret = self->cross(*m); + return new cv::Mat(ret); +} +CVAPI(double) core_MatExpr_dot(cv::MatExpr *self, cv::Mat *m) +{ + return self->dot(*m); +} +CVAPI(cv::MatExpr*) core_MatExpr_t(cv::MatExpr *self) +{ + cv::MatExpr ret = self->t(); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_inv1(cv::MatExpr *self) +{ + cv::MatExpr ret = self->inv(); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_inv2(cv::MatExpr *self, int method) +{ + cv::MatExpr ret = self->inv(method); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_mul_toMatExpr(cv::MatExpr *self, cv::MatExpr *e, double scale) +{ + cv::MatExpr ret = self->mul(*e, scale); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_MatExpr_mul_toMat(cv::MatExpr *self, cv::Mat *m, double scale) +{ + cv::MatExpr ret = self->mul(*m, scale); + return new cv::MatExpr(ret); +} +CVAPI(MyCvSize) core_MatExpr_size(cv::MatExpr *self) +{ + return c(self->size()); +} +CVAPI(int) core_MatExpr_type(cv::MatExpr *self) +{ + return self->type(); +} +#pragma endregion + +#pragma region Operators +CVAPI(cv::MatExpr*) core_operatorUnaryMinus_MatExpr(cv::MatExpr *e) +{ + cv::MatExpr expr = -(*e); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorUnaryNot_MatExpr(cv::MatExpr *e) +{ + cv::MatExpr expr = ~(*e); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_operatorAdd_MatExprMat(cv::MatExpr *e, cv:: Mat *m) +{ + cv::MatExpr expr = (*e) + (*m); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorAdd_MatMatExpr(cv::Mat *m, cv::MatExpr *e) +{ + cv::MatExpr expr = (*m) + (*e); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorAdd_MatExprScalar(cv::MatExpr *e, CvScalar s) +{ + cv::MatExpr expr = (*e) + s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorAdd_ScalarMatExpr(CvScalar s, cv::MatExpr *e) +{ + cv::MatExpr expr = s + (*e); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorAdd_MatExprMatExpr(cv::MatExpr *e1, cv::MatExpr *e2) +{ + cv::MatExpr expr = (*e1) + (*e2); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_operatorSubtract_MatExprMat(cv::MatExpr *e, cv::Mat *m) +{ + cv::MatExpr expr = (*e) - (*m); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorSubtract_MatMatExpr(cv::Mat *m, cv::MatExpr *e) +{ + cv::MatExpr expr = (*m) - (*e); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorSubtract_MatExprScalar(cv::MatExpr *e, CvScalar s) +{ + cv::MatExpr expr = (*e) - s; + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorSubtract_ScalarMatExpr(CvScalar s, cv::MatExpr *e) +{ + cv::MatExpr expr = s - (*e); + return new cv::MatExpr(expr); +} +CVAPI(cv::MatExpr*) core_operatorSubtract_MatExprMatExpr(cv::MatExpr *e1, cv::MatExpr *e2) +{ + cv::MatExpr expr = (*e1) - (*e2); + return new cv::MatExpr(expr); +} + +CVAPI(cv::MatExpr*) core_operatorMultiply_MatExprMat(cv::MatExpr *e, cv::Mat *m) +{ + cv::MatExpr ret = (*e) * (*m); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorMultiply_MatMatExpr(cv::Mat *m, cv::MatExpr *e) +{ + cv::MatExpr ret = (*m) * (*e); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorMultiply_MatExprDouble(cv::MatExpr *e, double s) +{ + cv::MatExpr ret = (*e) * s; + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorMultiply_DoubleMatExpr(double s, cv::MatExpr *e) +{ + cv::MatExpr ret = s * (*e); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorMultiply_MatExprMatExpr(cv::MatExpr *e1, cv::MatExpr *e2) +{ + cv::MatExpr ret = (*e1) * (*e2); + return new cv::MatExpr(ret); +} + +CVAPI(cv::MatExpr*) core_operatorDivide_MatExprMat(cv::MatExpr *e, cv::Mat *m) +{ + cv::MatExpr ret = (*e) / (*m); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorDivide_MatMatExpr(cv::Mat *m, cv::MatExpr *e) +{ + cv::MatExpr ret = (*m) / (*e); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorDivide_MatExprDouble(cv::MatExpr *e, double s) +{ + cv::MatExpr ret = (*e) / s; + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorDivide_DoubleMatExpr(double s, cv::MatExpr *e) +{ + cv::MatExpr ret = s / (*e); + return new cv::MatExpr(ret); +} +CVAPI(cv::MatExpr*) core_operatorDivide_MatExprMatExpr(cv::MatExpr *e1, cv::MatExpr *e2) +{ + cv::MatExpr ret = (*e1) / (*e2); + return new cv::MatExpr(ret); +} +#pragma endregion + +CVAPI(cv::MatExpr*) core_abs_MatExpr(cv::MatExpr *e) +{ + cv::MatExpr ret = cv::abs(*e); + return new cv::MatExpr(ret); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_OutputArray.h b/OpenVinoOpenCvSharpExtern/core_OutputArray.h new file mode 100644 index 0000000..dafe618 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_OutputArray.h @@ -0,0 +1,61 @@ +#ifndef _CPP_CORE_OUTPUTARRAY_H_ +#define _CPP_CORE_OUTPUTARRAY_H_ + +#include "include_opencv.h" + +CVAPI(cv::_OutputArray*) core_OutputArray_new_byMat(cv::Mat *mat) +{ + cv::_OutputArray ia(*mat); + return new cv::_OutputArray(ia); +} + +CVAPI(cv::_OutputArray*) core_OutputArray_new_byGpuMat(cv::cuda::GpuMat *gm) +{ + cv::_OutputArray ia(*gm); + return new cv::_OutputArray(ia); +} + +CVAPI(cv::_OutputArray*) core_OutputArray_new_byScalar(MyCvScalar scalar) +{ + cv::Scalar scalarVal(cpp(scalar)); + cv::_OutputArray ia(scalarVal); + return new cv::_OutputArray(ia); +} + +CVAPI(cv::_OutputArray*) core_OutputArray_new_byVectorOfMat(std::vector *vector) +{ + cv::_OutputArray ia(*vector); + return new cv::_OutputArray(ia); +} + +CVAPI(void) core_OutputArray_delete(cv::_OutputArray *oa) +{ + delete oa; +} + +CVAPI(cv::Mat*) core_OutputArray_getMat(cv::_OutputArray *oa) +{ + cv::Mat &mat = oa->getMatRef(); + return new cv::Mat(mat); +} + +CVAPI(MyCvScalar) core_OutputArray_getScalar(cv::_OutputArray *oa) +{ + cv::Mat &mat = oa->getMatRef(); + cv::Scalar scalar = mat.at(0); + return c(scalar); +} + +CVAPI(void) core_OutputArray_getVectorOfMat(cv::_OutputArray *oa, std::vector *vector) +{ + 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]); + } +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_PCA.h b/OpenVinoOpenCvSharpExtern/core_PCA.h new file mode 100644 index 0000000..c933660 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_PCA.h @@ -0,0 +1,71 @@ +#ifndef _CPP_CORE_PCA_H_ +#define _CPP_CORE_PCA_H_ + +#include "include_opencv.h" + +CVAPI(cv::PCA*) core_PCA_new1() +{ + return new cv::PCA; +} +CVAPI(cv::PCA*) core_PCA_new2(cv::_InputArray *data, cv::_InputArray *mean, int flags, int maxComponents) +{ + return new cv::PCA(*data, *mean, flags, maxComponents); +} +CVAPI(cv::PCA*) core_PCA_new3(cv::_InputArray *data, cv::_InputArray *mean, int flags, double retainedVariance) +{ + return new cv::PCA(*data, *mean, flags, retainedVariance); +} +CVAPI(void) core_PCA_delete(cv::PCA *obj) +{ + delete obj; +} + +//! operator that performs PCA. The previously stored data, if any, is released +CVAPI(void) core_PCA_operatorThis(cv::PCA *obj, cv::_InputArray *data, cv::_InputArray *mean, int flags, int maxComponents) +{ + (*obj)(*data, *mean, flags, maxComponents); +} +CVAPI(void) core_PCA_computeVar(cv::PCA *obj, cv::_InputArray *data, cv::_InputArray *mean, int flags, double retainedVariance) +{ + (*obj)(*data, *mean, flags, retainedVariance); +} +//! projects vector from the original space to the principal components subspace +CVAPI(cv::Mat*) core_PCA_project1(cv::PCA *obj, cv::_InputArray *vec) +{ + cv::Mat ret = obj->project(*vec); + return new cv::Mat(ret); +} +//! projects vector from the original space to the principal components subspace +CVAPI(void) core_PCA_project2(cv::PCA *obj, cv::_InputArray *vec, cv::_OutputArray *result) +{ + obj->project(*vec, *result); +} +//! reconstructs the original vector from the projection +CVAPI(cv::Mat*) core_PCA_backProject1(cv::PCA *obj, cv::_InputArray *vec) +{ + cv::Mat ret = obj->backProject(*vec); + return new cv::Mat(ret); +} +//! reconstructs the original vector from the projection +CVAPI(void) core_PCA_backProject2(cv::PCA *obj, cv::_InputArray *vec, cv::_OutputArray *result) +{ + obj->backProject(*vec, *result); +} + +//!< eigenvectors of the covariation matrix +CVAPI(cv::Mat*) core_PCA_eigenvectors(cv::PCA *obj) +{ + return new cv::Mat(obj->eigenvectors); +} +//!< eigenvalues of the covariation matrix +CVAPI(cv::Mat*) core_PCA_eigenvalues(cv::PCA *obj) +{ + return new cv::Mat(obj->eigenvalues); +} +//!< mean value subtracted before the projection and added after the back projection +CVAPI(cv::Mat*) core_PCA_mean(cv::PCA *obj) +{ + return new cv::Mat(obj->mean); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_RNG.h b/OpenVinoOpenCvSharpExtern/core_RNG.h new file mode 100644 index 0000000..e0a0784 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_RNG.h @@ -0,0 +1,21 @@ +#ifndef _CPP_CORE_RNG_H_ +#define _CPP_CORE_RNG_H_ + +#include "include_opencv.h" + +CVAPI(void) core_RNG_fill(uint64 *state, cv::_InputOutputArray *mat, int distType, cv::_InputArray *a, cv::_InputArray *b, int saturateRange) +{ + cv::RNG rng(*state); + rng.fill(*mat, distType, *a, *b, saturateRange != 0); + *state = rng.state; +} +//! returns Gaussian random variate with mean zero. +CVAPI(double) core_RNG_gaussian(uint64 *state, double sigma) +{ + cv::RNG rng(*state); + double result = rng.gaussian(sigma); + *state = rng.state; + return result; +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_SVD.h b/OpenVinoOpenCvSharpExtern/core_SVD.h new file mode 100644 index 0000000..3787871 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_SVD.h @@ -0,0 +1,65 @@ +#ifndef _CPP_CORE_SVD_H_ +#define _CPP_CORE_SVD_H_ + +#include "include_opencv.h" + +CVAPI(cv::SVD*) core_SVD_new1() +{ + return new cv::SVD; +} +CVAPI(cv::SVD*) core_SVD_new2(cv::_InputArray *src, int flags) +{ + return new cv::SVD(*src, flags); +} +CVAPI(void) core_SVD_delete(cv::SVD *obj) +{ + delete obj; +} + +CVAPI(void) core_SVD_operatorThis(cv::SVD *obj, cv::_InputArray *src, int flags) +{ + (*obj)(*src, flags); +} +//! performs back substitution, so that dst is the solution or pseudo-solution of m*dst = rhs, where m is the decomposed matrix +CVAPI(void) core_SVD_backSubst(cv::SVD *obj, cv::_InputArray *rhs, cv::_OutputArray *dst) +{ + obj->backSubst(*rhs, *dst); +} + +//! decomposes matrix and stores the results to user-provided matrices +CVAPI(void) core_SVD_static_compute1(cv::_InputArray *src, cv::_OutputArray *w, + cv::_OutputArray *u, cv::_OutputArray *vt, int flags) +{ + cv::SVD::compute(*src, *w, *u, *vt, flags); +} +//! computes singular values of a matrix +CVAPI(void) core_SVD_static_compute2(cv::_InputArray *src, cv::_OutputArray *w, int flags) +{ + cv::SVD::compute(*src, *w, flags); +} +//! performs back substitution +CVAPI(void) core_SVD_static_backSubst(cv::_InputArray *w, cv::_InputArray *u, + cv::_InputArray *vt, cv::_InputArray *rhs, cv::_OutputArray *dst) +{ + cv::SVD::backSubst(*w, *u, *vt, *rhs, *dst); +} +//! finds dst = arg min_{|dst|=1} |m*dst| +CVAPI(void) core_SVD_static_solveZ(cv::_InputArray *src, cv::_OutputArray *dst) +{ + cv::SVD::solveZ(*src, *dst); +} + +CVAPI(cv::Mat*) core_SVD_u(cv::SVD *obj) +{ + return new cv::Mat(obj->u); +} +CVAPI(cv::Mat*) core_SVD_w(cv::SVD *obj) +{ + return new cv::Mat(obj->w); +} +CVAPI(cv::Mat*) core_SVD_vt(cv::SVD *obj) +{ + return new cv::Mat(obj->vt); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/core_SparseMat.h b/OpenVinoOpenCvSharpExtern/core_SparseMat.h new file mode 100644 index 0000000..44e3e58 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/core_SparseMat.h @@ -0,0 +1,167 @@ +#ifndef _CPP_CORE_SPARSEMAT_H_ +#define _CPP_CORE_SPARSEMAT_H_ + +#include "include_opencv.h" + +CVAPI(uint64) core_SparseMat_sizeof() +{ + return sizeof(cv::SparseMat); +} + +CVAPI(cv::SparseMat*) core_SparseMat_new1() +{ + return new cv::SparseMat(); +} +CVAPI(cv::SparseMat*) core_SparseMat_new2(int dims, const int *sizes, int type) +{ + return new cv::SparseMat(dims, sizes, type); +} +CVAPI(cv::SparseMat*) core_SparseMat_new3(cv::Mat *m) +{ + return new cv::SparseMat(*m); +} + +CVAPI(void) core_SparseMat_delete(cv::SparseMat *obj) +{ + delete obj; +} + + +CVAPI(void) core_SparseMat_operatorAssign_SparseMat(cv::SparseMat *obj, cv::SparseMat *m) +{ + *obj = *m; +} +CVAPI(void) core_SparseMat_operatorAssign_Mat(cv::SparseMat *obj, cv::Mat *m) +{ + *obj = *m; +} + +CVAPI(cv::SparseMat*) core_SparseMat_clone(cv::SparseMat *obj) +{ + cv::SparseMat sm = obj->clone(); + return new cv::SparseMat(sm); +} +CVAPI(void) core_SparseMat_copyTo_SparseMat(cv::SparseMat *obj, cv::SparseMat *m) +{ + obj->copyTo(*m); +} +CVAPI(void) core_SparseMat_copyTo_Mat(cv::SparseMat *obj, cv::Mat *m) +{ + obj->copyTo(*m); +} +CVAPI(void) core_SparseMat_convertTo_SparseMat(cv::SparseMat *obj, cv::SparseMat *m, int rtype, double alpha) +{ + obj->convertTo(*m, rtype, alpha); +} +CVAPI(void) core_SparseMat_convertTo_Mat(cv::SparseMat *obj, cv::Mat *m, int rtype, double alpha = 1, double beta = 0) +{ + obj->convertTo(*m, rtype, alpha, beta); +} +CVAPI(void) core_SparseMat_assignTo(cv::SparseMat *obj, cv::SparseMat *m, int type = -1) +{ + obj->assignTo(*m, type); +} + +CVAPI(void) core_SparseMat_create(cv::SparseMat *obj, int dims, const int* sizes, int type) +{ + obj->create(dims, sizes, type); +} +CVAPI(void) core_SparseMat_clear(cv::SparseMat *obj) +{ + obj->clear(); +} +CVAPI(void) core_SparseMat_addref(cv::SparseMat *obj) +{ + obj->addref(); +} +CVAPI(void) core_SparseMat_release(cv::SparseMat *obj) +{ + obj->release(); +} + +CVAPI(int) core_SparseMat_elemSize(cv::SparseMat *obj) +{ + return static_cast(obj->elemSize()); +} +CVAPI(int) core_SparseMat_elemSize1(cv::SparseMat *obj) +{ + return static_cast(obj->elemSize1()); +} + +CVAPI(int) core_SparseMat_type(cv::SparseMat *obj) +{ + return obj->type(); +} +CVAPI(int) core_SparseMat_depth(cv::SparseMat *obj) +{ + return obj->depth(); +} +CVAPI(int) core_SparseMat_channels(cv::SparseMat *obj) +{ + return obj->channels(); +} + +CVAPI(const int*) core_SparseMat_size1(cv::SparseMat *obj) +{ + return obj->size(); +} +CVAPI(int) core_SparseMat_size2(cv::SparseMat *obj, int i) +{ + return obj->size(i); +} +CVAPI(int) core_SparseMat_dims(cv::SparseMat *obj) +{ + return obj->dims(); +} +CVAPI(size_t) core_SparseMat_nzcount(cv::SparseMat *obj) +{ + return obj->nzcount(); +} + +CVAPI(size_t) core_SparseMat_hash_1d(cv::SparseMat *obj, int i0) +{ + return obj->hash(i0); +} +CVAPI(size_t) core_SparseMat_hash_2d(cv::SparseMat *obj, int i0, int i1) +{ + return obj->hash(i0, i1); +} +CVAPI(size_t) core_SparseMat_hash_3d(cv::SparseMat *obj, int i0, int i1, int i2) +{ + return obj->hash(i0, i1, i2); +} +CVAPI(size_t) core_SparseMat_hash_nd(cv::SparseMat *obj, const int* idx) +{ + return obj->hash(idx); +} + +CVAPI(uchar*) core_SparseMat_ptr_1d(cv::SparseMat *obj, int i0, int createMissing, uint64* hashval) +{ + if (hashval == NULL) + return obj->ptr(i0, createMissing != 0); + size_t hashval0 = static_cast(*hashval); + return obj->ptr(i0, createMissing != 0, &hashval0); +} +CVAPI(uchar*) core_SparseMat_ptr_2d(cv::SparseMat *obj, int i0, int i1, int createMissing, uint64* hashval) +{ + if (hashval == NULL) + return obj->ptr(i0, i1, createMissing != 0); + size_t hashval0 = static_cast(*hashval); + return obj->ptr(i0, i1, createMissing != 0, &hashval0); +} +CVAPI(uchar*) core_SparseMat_ptr_3d(cv::SparseMat *obj, int i0, int i1, int i2, int createMissing, uint64* hashval) +{ + if (hashval == NULL) + return obj->ptr(i0, i1, i2, createMissing != 0); + size_t hashval0 = static_cast(*hashval); + return obj->ptr(i0, i1, i2, createMissing != 0, &hashval0); +} +CVAPI(uchar*) core_SparseMat_ptr_nd(cv::SparseMat *obj, const int* idx, int createMissing, uint64* hashval) +{ + if (hashval == NULL) + return obj->ptr(idx, createMissing != 0); + size_t hashval0 = static_cast(*hashval); + return obj->ptr(idx, createMissing != 0, &hashval0); +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/dnn.cpp b/OpenVinoOpenCvSharpExtern/dnn.cpp new file mode 100644 index 0000000..3997efb --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/dnn.cpp @@ -0,0 +1,3 @@ +// ReSharper disable CppUnusedIncludeDirective +#include "dnn.h" +#include "dnn_Net.h" \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/dnn.h b/OpenVinoOpenCvSharpExtern/dnn.h new file mode 100644 index 0000000..58c7539 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/dnn.h @@ -0,0 +1,120 @@ +#ifndef _CPP_DNN_H_ +#define _CPP_DNN_H_ + +#ifndef _WINRT_DLL +#include "include_opencv.h" + +CVAPI(cv::dnn::Net*) dnn_readNetFromDarknet(const char *cfgFile, const char *darknetModel) +{ + const auto darknetModelStr = (darknetModel == nullptr) ? cv::String() : cv::String(darknetModel); + const auto net = cv::dnn::readNetFromDarknet(cfgFile, darknetModelStr); + return new cv::dnn::Net(net); +} + +CVAPI(cv::dnn::Net*) dnn_readNetFromCaffe(const char *prototxt, const char *caffeModel) +{ + const auto caffeModelStr = (caffeModel == nullptr) ? cv::String() : cv::String(caffeModel); + const auto net = cv::dnn::readNetFromCaffe(prototxt, caffeModelStr); + return new cv::dnn::Net(net); +} + +CVAPI(cv::dnn::Net*) dnn_readNetFromTensorflow(const char *model, const char *config) +{ + const auto configStr = (config == nullptr) ? cv::String() : cv::String(config); + const auto net = cv::dnn::readNetFromTensorflow(model, configStr); + return new cv::dnn::Net(net); +} + +CVAPI(cv::dnn::Net*) dnn_readNetFromTorch(const char *model, const int isBinary) +{ + const auto net = cv::dnn::readNetFromTorch(model, isBinary != 0); + return new cv::dnn::Net(net); +} + +CVAPI(cv::dnn::Net*) dnn_readNet(const char *model, const char *config, const char *framework) +{ + const auto configStr = (config == nullptr) ? "" : cv::String(config); + const auto frameworkStr = (framework == nullptr) ? "" : cv::String(framework); + const auto net = cv::dnn::readNet(model, configStr, frameworkStr); + return new cv::dnn::Net(net); +} + +CVAPI(cv::Mat*) dnn_readTorchBlob(const char *filename, const int isBinary) +{ + const auto blob = cv::dnn::readTorchBlob(filename, isBinary != 0); + return new cv::Mat(blob); +} + +CVAPI(cv::dnn::Net*) dnn_readNetFromModelOptimizer(const char *xml, const char *bin) +{ + const auto net = cv::dnn::readNetFromModelOptimizer(xml, bin); + return new cv::dnn::Net(net); +} + +CVAPI(cv::dnn::Net*) dnn_readNetFromONNX(const char *onnxFile) +{ + const auto net = cv::dnn::readNetFromONNX(onnxFile); + return new cv::dnn::Net(net); +} + +CVAPI(cv::Mat*) dnn_readTensorFromONNX(const char *path) +{ + const auto mat = cv::dnn::readTensorFromONNX(path); + return new cv::Mat(mat); +} + +CVAPI(cv::Mat*) dnn_blobFromImage( + cv::Mat *image, const double scalefactor, const MyCvSize size, const MyCvScalar mean, const int swapRB, const int crop) +{ + const auto blob = cv::dnn::blobFromImage(*image, scalefactor, cpp(size), cpp(mean), swapRB != 0, crop != 0); + return new cv::Mat(blob); +} + +CVAPI(cv::Mat*) dnn_blobFromImages( + const cv::Mat **images, const int imagesLength, const double scalefactor, const MyCvSize size, const MyCvScalar mean, const int swapRB, const int crop) +{ + std::vector imagesVec; + toVec(images, imagesLength, imagesVec); + + const auto blob = cv::dnn::blobFromImages(imagesVec, scalefactor, cpp(size), cpp(mean), swapRB != 0, crop != 0); + return new cv::Mat(blob); +} + +CVAPI(void) dnn_shrinkCaffeModel(const char *src, const char *dst) +{ + cv::dnn::shrinkCaffeModel(src, dst); +} + +CVAPI(void) dnn_writeTextGraph(const char *model, const char *output) +{ + cv::dnn::writeTextGraph(model, output); +} + +CVAPI(void) dnn_NMSBoxes_Rect(std::vector *bboxes, std::vector *scores, + const float score_threshold, const float nms_threshold, + std::vector *indices, const float eta, const int top_k) +{ + cv::dnn::NMSBoxes(*bboxes, *scores, score_threshold, nms_threshold, *indices, eta, top_k); +} + +CVAPI(void) dnn_NMSBoxes_Rect2d(std::vector *bboxes, std::vector *scores, + const float score_threshold, const float nms_threshold, + std::vector *indices, const float eta, const int top_k) +{ + cv::dnn::NMSBoxes(*bboxes, *scores, score_threshold, nms_threshold, *indices, eta, top_k); +} + +CVAPI(void) dnn_NMSBoxes_RotatedRect(std::vector *bboxes, std::vector *scores, + const float score_threshold, const float nms_threshold, + std::vector *indices, const float eta, const int top_k) +{ + cv::dnn::NMSBoxes(*bboxes, *scores, score_threshold, nms_threshold, *indices, eta, top_k); +} + +CVAPI(void) dnn_resetMyriadDevice() +{ + cv::dnn::resetMyriadDevice(); +} +#endif // !#ifndef _WINRT_DLL + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/dnn_Net.h b/OpenVinoOpenCvSharpExtern/dnn_Net.h new file mode 100644 index 0000000..3cf1b8a --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/dnn_Net.h @@ -0,0 +1,149 @@ +#ifndef _CPP_DNN_NET_H_ +#define _CPP_DNN_NET_H_ + +#ifndef _WINRT_DLL +#include "include_opencv.h" + +CVAPI(cv::dnn::Net*) dnn_Net_new() +{ + return new cv::dnn::Net; +} + +CVAPI(void) dnn_Net_delete(cv::dnn::Net* net) +{ + delete net; +} + +CVAPI(int) dnn_Net_empty(cv::dnn::Net* net) +{ + return net->empty() ? 1 : 0; +} + +CVAPI(int) dnn_Net_getLayerId(cv::dnn::Net* net, const char *layer) +{ + return net->getLayerId(layer); +} + +CVAPI(void) dnn_Net_getLayerNames(cv::dnn::Net* net, std::vector *outVec) +{ + const auto result = net->getLayerNames(); + outVec->assign(result.begin(), result.end()); +} + +CVAPI(void) dnn_Net_connect1(cv::dnn::Net* net, const char *outPin, const char *inpPin) +{ + net->connect(outPin, inpPin); +} + +CVAPI(void) dnn_Net_connect2(cv::dnn::Net* net, int outLayerId, int outNum, int inpLayerId, int inpNum) +{ + net->connect(outLayerId, outNum, inpLayerId, inpNum); +} + +CVAPI(void) dnn_Net_setInputsNames(cv::dnn::Net* net, const char **inputBlobNames, int inputBlobNamesLength) +{ + std::vector inputBlobNamesVec(inputBlobNamesLength); + for (int i = 0; i < inputBlobNamesLength; i++) + { + inputBlobNamesVec[i] = inputBlobNames[i]; + } + net->setInputsNames(inputBlobNamesVec); +} + +CVAPI(cv::Mat*) dnn_Net_forward1(cv::dnn::Net* net, const char *outputName) +{ + const cv::String outputNameStr = (outputName == nullptr) ? cv::String() : cv::String(outputName); + const auto ret = net->forward(outputNameStr); + return new cv::Mat(ret); +} + +CVAPI(void) dnn_Net_forward2( + cv::dnn::Net* net, cv::Mat **outputBlobs, int outputBlobsLength, const char *outputName) +{ + const auto outputNameStr = (outputName == nullptr) ? cv::String() : cv::String(outputName); + std::vector outputBlobsVec; + toVec(outputBlobs, outputBlobsLength, outputBlobsVec); + + net->forward(outputBlobsVec, outputNameStr); + + for (int i = 0; i < outputBlobsLength; i++) + { + *outputBlobs[i] = outputBlobsVec[i]; + } +} + +CVAPI(void) dnn_Net_forward3( + cv::dnn::Net* net, cv::Mat **outputBlobs, int outputBlobsLength, const char **outBlobNames, int outBlobNamesLength) +{ + std::vector outputBlobsVec; + toVec(outputBlobs, outputBlobsLength, outputBlobsVec); + + std::vector outBlobNamesVec(outBlobNamesLength); + for (int i = 0; i < outBlobNamesLength; i++) + { + outBlobNamesVec[i] = outBlobNames[i]; + } + + net->forward(outputBlobsVec, outBlobNamesVec); + + for (int i = 0; i < outputBlobsLength; i++) + { + *outputBlobs[i] = outputBlobsVec[i]; + } +} + +CVAPI(void) dnn_Net_setHalideScheduler(cv::dnn::Net* net, const char *scheduler) +{ + net->setHalideScheduler(scheduler); +} + +CVAPI(void) dnn_Net_setPreferableBackend(cv::dnn::Net* net, int backendId) +{ + net->setPreferableBackend(backendId); +} + +CVAPI(void) dnn_Net_setPreferableTarget(cv::dnn::Net* net, int targetId) +{ + net->setPreferableTarget(targetId); +} + +CVAPI(void) dnn_Net_setInput(cv::dnn::Net* net, const cv::Mat *blob, const char *name) +{ + const cv::String nameStr = (name == nullptr) ? "" : cv::String(name); + net->setInput(*blob, name); +} + +CVAPI(void) dnn_Net_getUnconnectedOutLayers(cv::dnn::Net* net, std::vector *result) +{ + std::vector v = net->getUnconnectedOutLayers(); + result->clear(); + result->resize(v.size()); + for (size_t i = 0; i < v.size(); i++) + { + result->at(i) = v[i]; + } +} + +CVAPI(void) dnn_Net_getUnconnectedOutLayersNames(cv::dnn::Net* net, std::vector *result) +{ + std::vector v = net->getUnconnectedOutLayersNames(); + result->clear(); + result->resize(v.size()); + for (size_t i = 0; i < v.size(); i++) + { + result->at(i) = v[i]; + } +} + +CVAPI(void) dnn_Net_enableFusion(cv::dnn::Net* net, int fusion) +{ + net->enableFusion(fusion != 0); +} + +CVAPI(int64) dnn_Net_getPerfProfile(cv::dnn::Net* net, std::vector *timings) +{ + return net->getPerfProfile(*timings); +} +#endif // !#ifndef _WINRT_DLL + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/include_opencv.h b/OpenVinoOpenCvSharpExtern/include_opencv.h new file mode 100644 index 0000000..75ba7d4 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/include_opencv.h @@ -0,0 +1,39 @@ +#ifndef _INCLUDE_OPENCV_H_ +#define _INCLUDE_OPENCV_H_ + +//#define ENABLED_CONTRIB +//#undef ENABLED_CONTRIB + +#ifdef _MSC_VER +#define NOMINMAX +#define _CRT_SECURE_NO_WARNINGS +#pragma warning(push) +#pragma warning(disable: 4251) +#pragma warning(disable: 4996) +#endif + + +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _MSC_VER +#pragma warning(pop) +#endif +// Additional types +#include "my_types.h" + +// Additional functions +#include "my_functions.h" + +#endif diff --git a/OpenVinoOpenCvSharpExtern/my_functions.h b/OpenVinoOpenCvSharpExtern/my_functions.h new file mode 100644 index 0000000..fd82e82 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/my_functions.h @@ -0,0 +1,168 @@ +// Additional functions + +#ifndef _MY_FUNCTIONS_H_ +#define _MY_FUNCTIONS_H_ + +#ifdef _WIN32 +#pragma warning(disable: 4996) +#endif + + +#include +#include "my_types.h" + +#ifdef _WIN32 +#include + +// MP! Added: To provide WinRT version of MessageBox handling. +#ifdef _WINRT_DLL +void StringConvert(const std::string from, std::wstring& to); +void StringConvert(const std::wstring from, std::string& to); +#endif + +static int p(const char *msg, const char caption[] = "MessageBox") +{ +#ifdef _WINRT_DLL + std::wstring wmsg; + std::wstring wcaption; + StringConvert(msg, wmsg); + StringConvert(caption, wcaption); + + Windows::UI::Popups::MessageDialog(ref new Platform::String(wmsg.c_str()), ref new Platform::String(wcaption.c_str())).ShowAsync(); + return MB_OK; +#else + return MessageBoxA(NULL, msg, caption, MB_OK); +#endif +} + +template +static int p(T obj, const std::string &caption = "MessageBox") +{ + std::stringstream ss; + ss << obj; + return p(ss.str().c_str(), caption.c_str()); +} +#endif + + +#if defined WIN32 || defined _WIN32 +# define CV_CDECL __cdecl +# define CV_STDCALL __stdcall +#else +# define CV_CDECL +# define CV_STDCALL +#endif + +#ifndef CVAPI +# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL +#endif + + + +static cv::_InputArray entity(cv::_InputArray *obj) +{ + return (obj != NULL) ? *obj : static_cast(cv::noArray()); +} +static cv::_OutputArray entity(cv::_OutputArray *obj) +{ + return (obj != NULL) ? *obj : static_cast(cv::noArray()); +} +static cv::_InputOutputArray entity(cv::_InputOutputArray *obj) +{ + return (obj != NULL) ? *obj : cv::noArray(); +} +static cv::Mat entity(cv::Mat *obj) +{ + return (obj != NULL) ? *obj : cv::Mat(); +} +static cv::SparseMat entity(cv::SparseMat *obj) +{ + return (obj != NULL) ? *obj : cv::SparseMat(); +} +static cv::cuda::GpuMat entity(cv::cuda::GpuMat *obj) +{ + return (obj != NULL) ? *obj : cv::cuda::GpuMat(); +} +static cv::cuda::Stream entity(cv::cuda::Stream *obj) +{ + return (obj != NULL) ? *obj : cv::cuda::Stream::Null(); +} + +template +static cv::Ptr *clone(const cv::Ptr &ptr) +{ + return new cv::Ptr(ptr); +} + +static void copyString(const char *src, char *dst, int dstLength) +{ + size_t length = (size_t)std::max(0, dstLength - 1); + if (strlen(src) == 0) + std::strncpy(dst, "", length); + else + std::strncpy(dst, src, length); +} +static void copyString(const std::string &src, char *dst, int dstLength) +{ + size_t length = (size_t)std::max(0, dstLength - 1); + if (src.empty()) + std::strncpy(dst, "", length); + else + std::strncpy(dst, src.c_str(), length); +} + +template +static void dump(T *obj, const std::string &outFile) +{ + int size = sizeof(T); + std::vector bytes(size); + std::memcpy(&bytes[0], reinterpret_cast(obj), size); + + FILE *fp = fopen(outFile.c_str(), "w"); + for (std::vector::iterator it = bytes.begin(); it != bytes.end(); ++it) + { + std::fprintf(fp, "%x,", static_cast(*it)); + } + fclose(fp); +} + +static void toVec( + const cv::Mat **inPtr, const int size, std::vector &outVec) +{ + outVec.resize(size); + for (int i = 0; i < size; i++) + { + outVec[i] = *inPtr[i]; + } +} + +static void toVec( + cv::Mat **inPtr, const int size, std::vector &outVec) +{ + outVec.resize(size); + for (int i = 0; i < size; i++) + { + outVec[i] = *inPtr[i]; + } +} + +template +static void toVec( + const TIn **inPtr, const int size1, const int *size2, std::vector > &outVec) +{ + outVec.resize(size1); + for (int i = 0; i < size1; i++) + { + int size = size2[i]; + const TIn *p = inPtr[i]; + std::vector v(p, p + size); + /*std::vector v(size); + for (int j = 0; j < size; j++) + { + v[j] = inPtr[i][j]; + }*/ + outVec[i] = v; + } +} + +#endif \ No newline at end of file diff --git a/OpenVinoOpenCvSharpExtern/my_types.h b/OpenVinoOpenCvSharpExtern/my_types.h new file mode 100644 index 0000000..9749dc8 --- /dev/null +++ b/OpenVinoOpenCvSharpExtern/my_types.h @@ -0,0 +1,444 @@ +// Additional types + +#ifndef _MY_TYPES_H_ +#define _MY_TYPES_H_ + +typedef unsigned char uchar; +typedef unsigned short uint16; +typedef unsigned short ushort; +typedef unsigned int uint32; + +namespace cv +{ + typedef cv::Vec Vec6b; + typedef cv::Vec Vec6s; + typedef cv::Vec Vec6w; +} + +extern "C" +{ + #pragma region OpenCV1.0-compatible Types + + struct MyCvPoint + { + int x; + int y; + }; + struct MyCvPoint2D32f + { + float x; + float y; + }; + struct MyCvPoint2D64f + { + double x; + double y; + }; + + struct MyCvPoint3D32i + { + int x; + int y; + int z; + }; + struct MyCvPoint3D32f + { + float x; + float y; + float z; + }; + struct MyCvPoint3D64f + { + double x; + double y; + double z; + }; + + struct MyCvSize + { + int width; + int height; + }; + struct MyCvSize2D32f + { + float width; + float height; + }; + struct MyCvSize2D64f + { + double width; + double height; + }; + + struct MyCvRect + { + int x; + int y; + int width; + int height; + }; + struct MyCvRect2D32f + { + float x; + float y; + float width; + float height; + }; + struct MyCvRect2D64f + { + double x; + double y; + double width; + double height; + }; + + struct MyCvScalar + { + double val[4]; + }; + + struct MyCvSlice + { + int start_index, end_index; + }; + + struct MyCvMoments + { + double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; /* spatial moments */ + double mu20, mu11, mu02, mu30, mu21, mu12, mu03; /* central moments */ + double inv_sqrt_m00; /* m00 != 0 ? 1/sqrt(m00) : 0 */ + }; + + struct MyCvTermCriteria + { + int type; + int max_iter; + double epsilon; + }; + + struct MyCvBox2D + { + MyCvPoint2D32f center; + MyCvSize2D32f size; + float angle; + }; + + struct MyKeyPoint + { + MyCvPoint2D32f pt; + float size; + float angle; + float response; + int octave; + int class_id; + }; + + struct MyDMatch + { + int queryIdx; + int trainIdx; + int imgIdx; + float distance; + }; + + #pragma endregion + + struct CvPoint3D + { + int x; + int y; + int z; + }; + + struct aruco_DetectorParameters + { + int adaptiveThreshWinSizeMin; + int adaptiveThreshWinSizeMax; + int adaptiveThreshWinSizeStep; + double adaptiveThreshConstant; + double minMarkerPerimeterRate; + double maxMarkerPerimeterRate; + double polygonalApproxAccuracyRate; + double minCornerDistanceRate; + int minDistanceToBorder; + double minMarkerDistanceRate; + int doCornerRefinement; // bool + int cornerRefinementWinSize; + int cornerRefinementMaxIterations; + double cornerRefinementMinAccuracy; + int markerBorderBits; + int perspectiveRemovePixelPerCell; + double perspectiveRemoveIgnoredMarginPerCell; + double maxErroneousBitsInBorderRate; + double minOtsuStdDev; + double errorCorrectionRate; + }; + + typedef struct CvVec2b { uchar val[2]; } CvVec2b; + typedef struct CvVec3b { uchar val[3]; } CvVec3b; + typedef struct CvVec4b { uchar val[4]; } CvVec4b; + typedef struct CvVec6b { uchar val[6]; } CvVec6b; + typedef struct CvVec2s { short val[2]; } CvVec2s; + typedef struct CvVec3s { short val[3]; } CvVec3s; + typedef struct CvVec4s { short val[4]; } CvVec4s; + typedef struct CvVec6s { short val[6]; } CvVec6s; + typedef struct CvVec2w { ushort val[2]; } CvVec2w; + typedef struct CvVec3w { ushort val[3]; } CvVec3w; + typedef struct CvVec4w { ushort val[4]; } CvVec4w; + typedef struct CvVec6w { ushort val[6]; } CvVec6w; + typedef struct CvVec2i { int val[2]; } CvVec2i; + typedef struct CvVec3i { int val[3]; } CvVec3i; + typedef struct CvVec4i { int val[4]; } CvVec4i; + typedef struct CvVec6i { int val[6]; } CvVec6i; + typedef struct CvVec2f { float val[2]; } CvVec2f; + typedef struct CvVec3f { float val[3]; } CvVec3f; + typedef struct CvVec4f { float val[4]; } CvVec4f; + typedef struct CvVec6f { float val[6]; } CvVec6f; + typedef struct CvVec2d { double val[2]; } CvVec2d; + typedef struct CvVec3d { double val[3]; } CvVec3d; + typedef struct CvVec4d { double val[4]; } CvVec4d; + typedef struct CvVec6d { double val[6]; } CvVec6d; +} + + +static MyCvPoint c(const cv::Point p) +{ + const MyCvPoint ret = { p.x, p.y }; + return ret; +} +static cv::Point cpp(const MyCvPoint p) +{ + return cv::Point(p.x, p.y); +} + +static MyCvPoint2D32f c(const cv::Point2f p) +{ + const MyCvPoint2D32f ret = { p.x, p.y }; + return ret; +} +static cv::Point2f cpp(const MyCvPoint2D32f p) +{ + return cv::Point2f(p.x, p.y); +} + +static MyCvPoint3D64f c(const cv::Point3d p) +{ + const MyCvPoint3D64f ret = { p.x, p.y, p.z }; + return ret; +} +static cv::Point3d cpp(const MyCvPoint3D64f p) +{ + return cv::Point3d(p.x, p.y, p.z); +} + +static MyCvSize c(const cv::Size s) +{ + const MyCvSize ret = { s.width, s.height }; + return ret; +} +static cv::Size cpp(const MyCvSize s) +{ + return cv::Size(s.width, s.height); +} + +static MyCvSize2D32f c(const cv::Size2f s) +{ + const MyCvSize2D32f ret = { s.width, s.height }; + return ret; +} +static cv::Size2f cpp(const MyCvSize2D32f s) +{ + return cv::Size2f(s.width, s.height); +} + +static MyCvRect c(const cv::Rect r) +{ + const MyCvRect ret = { r.x, r.y, r.width, r.height }; + return ret; +} +static cv::Rect cpp(const MyCvRect r) +{ + return cv::Rect(r.x, r.y, r.width, r.height); +} + +static MyCvRect2D64f c(const cv::Rect2d r) +{ + const MyCvRect2D64f ret = { r.x, r.y, r.width, r.height }; + return ret; +} +static cv::Rect2d cpp(const MyCvRect2D64f r) +{ + return cv::Rect2d(r.x, r.y, r.width, r.height); +} + +static MyCvScalar c(const cv::Scalar s) +{ + MyCvScalar ret; + ret.val[0] = s[0]; + ret.val[1] = s[1]; + ret.val[2] = s[2]; + ret.val[3] = s[3]; + return ret; +} +static cv::Scalar cpp(const MyCvScalar s) +{ + return cv::Scalar(s.val[0], s.val[1], s.val[2], s.val[3]); +} + +static CvVec4i c(const cv::Vec4i v) +{ + CvVec4i vv; + vv.val[0] = v.val[0]; + vv.val[1] = v.val[1]; + vv.val[2] = v.val[2]; + vv.val[3] = v.val[3]; + return vv; +} +static cv::Vec4i cpp(const CvVec4i v) +{ + return cv::Vec4i(v.val[0], v.val[1], v.val[2], v.val[3]); +} + +static MyCvSlice c(const cv::Range s) +{ + MyCvSlice ret; + ret.start_index = s.start; + ret.end_index = s.end; + return ret; +} +static cv::Range cpp(const MyCvSlice s) +{ + return cv::Range(s.start_index, s.end_index); +} + +static MyCvMoments c(const cv::Moments m) +{ + MyCvMoments ret; + ret.m00 = m.m00; ret.m10 = m.m10; ret.m01 = m.m01; + ret.m20 = m.m20; ret.m11 = m.m11; ret.m02 = m.m02; + ret.m30 = m.m30; ret.m21 = m.m21; ret.m12 = m.m12; ret.m03 = m.m03; + ret.mu20 = m.mu20; ret.mu11 = m.mu11; ret.mu02 = m.mu02; + ret.mu30 = m.mu30; ret.mu21 = m.mu21; ret.mu12 = m.mu12; ret.mu03 = m.mu03; + const double am00 = std::abs(m.m00); + ret.inv_sqrt_m00 = am00 > DBL_EPSILON ? 1. / std::sqrt(am00) : 0; + + return ret; +} +static cv::Moments cpp(const MyCvMoments m) +{ + return cv::Moments(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03); +} + +static MyCvTermCriteria c(const cv::TermCriteria tc) +{ + MyCvTermCriteria ret; + ret.type = tc.type; + ret.max_iter = tc.maxCount; + ret.epsilon = tc.epsilon; + return ret; +} +static cv::TermCriteria cpp(const MyCvTermCriteria tc) +{ + return cv::TermCriteria(tc.type, tc.max_iter, tc.epsilon); +} + +static MyCvBox2D c(const cv::RotatedRect r) +{ + MyCvBox2D ret; + ret.center = c(r.center); + ret.size = c(r.size); + ret.angle = r.angle; + return ret; +} +static cv::RotatedRect cpp(const MyCvBox2D b) +{ + return cv::RotatedRect(cpp(b.center), cpp(b.size), b.angle); +} + +static cv::KeyPoint cpp(const MyKeyPoint k) +{ + return cv::KeyPoint(cpp(k.pt), k.size, k.angle, k.response, k.octave, k.class_id); +} +static MyKeyPoint c(const cv::KeyPoint k) +{ + MyKeyPoint ret; + ret.pt = c(k.pt); + ret.size = k.size; + ret.angle = k.angle; + ret.response = k.response; + ret.octave = k.octave; + ret.class_id = k.class_id; + return ret; +} + +static cv::DMatch cpp(const MyDMatch d) +{ + return cv::DMatch(d.queryIdx, d.trainIdx, d.imgIdx, d.distance); +} +static MyDMatch c(const cv::DMatch d) +{ + MyDMatch ret; + ret.queryIdx = d.queryIdx; + ret.trainIdx = d.trainIdx; + ret.imgIdx = d.imgIdx; + ret.distance = d.distance; + return ret; +} + +#ifdef HAVE_OPENCV2_CONTRIB + +static cv::aruco::DetectorParameters cpp(const aruco_DetectorParameters p) +{ + cv::aruco::DetectorParameters pp; + pp.adaptiveThreshWinSizeMin = p.adaptiveThreshWinSizeMin; + pp.adaptiveThreshWinSizeMax = p.adaptiveThreshWinSizeMax; + pp.adaptiveThreshWinSizeStep = p.adaptiveThreshWinSizeStep; + pp.adaptiveThreshConstant = p.adaptiveThreshConstant; + pp.minMarkerPerimeterRate = p.minMarkerPerimeterRate; + pp.maxMarkerPerimeterRate = p.maxMarkerPerimeterRate; + pp.polygonalApproxAccuracyRate = p.polygonalApproxAccuracyRate; + pp.minCornerDistanceRate = p.minCornerDistanceRate; + pp.minDistanceToBorder = p.minDistanceToBorder; + pp.minMarkerDistanceRate = p.minMarkerDistanceRate; + //pp.doCornerRefinement = p.doCornerRefinement != 0; + pp.cornerRefinementWinSize = p.cornerRefinementWinSize; + pp.cornerRefinementMaxIterations = p.cornerRefinementMaxIterations; + pp.cornerRefinementMinAccuracy = p.cornerRefinementMinAccuracy; + pp.markerBorderBits = p.markerBorderBits; + pp.perspectiveRemovePixelPerCell = p.perspectiveRemovePixelPerCell; + pp.perspectiveRemoveIgnoredMarginPerCell = p.perspectiveRemoveIgnoredMarginPerCell;; + pp.maxErroneousBitsInBorderRate = p.maxErroneousBitsInBorderRate; + pp.minOtsuStdDev = p.minOtsuStdDev; + pp.errorCorrectionRate = p.errorCorrectionRate; + return pp; +} +static aruco_DetectorParameters c(const cv::aruco::DetectorParameters &p) +{ + aruco_DetectorParameters pp; + pp.adaptiveThreshWinSizeMin = p.adaptiveThreshWinSizeMin; + pp.adaptiveThreshWinSizeMax = p.adaptiveThreshWinSizeMax; + pp.adaptiveThreshWinSizeStep = p.adaptiveThreshWinSizeStep; + pp.adaptiveThreshConstant = p.adaptiveThreshConstant; + pp.minMarkerPerimeterRate = p.minMarkerPerimeterRate; + pp.maxMarkerPerimeterRate = p.maxMarkerPerimeterRate; + pp.polygonalApproxAccuracyRate = p.polygonalApproxAccuracyRate; + pp.minCornerDistanceRate = p.minCornerDistanceRate; + pp.minDistanceToBorder = p.minDistanceToBorder; + pp.minMarkerDistanceRate = p.minMarkerDistanceRate; + //pp.doCornerRefinement = p.doCornerRefinement ? 1 : 0; + pp.cornerRefinementWinSize = p.cornerRefinementWinSize; + pp.cornerRefinementMaxIterations = p.cornerRefinementMaxIterations; + pp.cornerRefinementMinAccuracy = p.cornerRefinementMinAccuracy; + pp.markerBorderBits = p.markerBorderBits; + pp.perspectiveRemovePixelPerCell = p.perspectiveRemovePixelPerCell; + pp.perspectiveRemoveIgnoredMarginPerCell = p.perspectiveRemoveIgnoredMarginPerCell;; + pp.maxErroneousBitsInBorderRate = p.maxErroneousBitsInBorderRate; + pp.minOtsuStdDev = p.minOtsuStdDev; + pp.errorCorrectionRate = p.errorCorrectionRate; + return pp; +} + +#endif + + +#endif \ No newline at end of file diff --git a/PeopleDetectionOpenCV/AssemblyLoadConfiguration.cs b/PeopleDetectionOpenCV/AssemblyLoadConfiguration.cs new file mode 100644 index 0000000..f914fc9 --- /dev/null +++ b/PeopleDetectionOpenCV/AssemblyLoadConfiguration.cs @@ -0,0 +1,119 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace PeopleDetectionOpenCV +{ + public class AssemblyLoadConfiguration + { + public static void For() => new AssemblyLoadConfiguration(typeof(T).Assembly).Configure(); + + public Assembly Assembly { get; } + + public AssemblyLoadConfiguration(Assembly assembly) + { + Assembly = assembly; + } + + public void Configure() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + ConfigureForWindows(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + ConfigureForOSX(); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + ConfigureForLinux(); + } + else + { + throw new NotSupportedException($"Unsupported operating system {RuntimeInformation.OSDescription}"); + } + } + + private void ConfigureForWindows() + { + return; + } + + private void ConfigureForOSX() + { + return; + } + + private void ConfigureForLinux() + { + var osRelease = new FileInfo("/etc/os-release"); + if (osRelease.Exists) + { + var map = File.ReadAllLines(osRelease.FullName) + .Select(line => line.Split('=', StringSplitOptions.RemoveEmptyEntries)) + .Where(split => split.Length == 2) + .ToDictionary(split => split[0], split => split[1].Replace("\"", ""), StringComparer.OrdinalIgnoreCase); + + if (map.TryGetValue("ID", out var id) && map.TryGetValue("VERSION_ID", out var versionId)) + { + var architecture = RuntimeInformation.ProcessArchitecture; + var architectureName = architecture switch + { + Architecture.Arm => "arm32", + Architecture.Arm64 => "arm64", + Architecture.X64 => "x64", + Architecture.X86 => "x86", + _ => throw new NotSupportedException($"Unknown architecture: {architecture}"), + }; + + NativeLibrary.SetDllImportResolver(Assembly, (libraryName, assembly, searchPath) => + { + Console.WriteLine($"Looking for library {libraryName} for {assembly.FullName} in ${id} ${versionId}"); + if (MapLibraryName(assembly.Location, $"runtimes/{id}/{versionId}/{architectureName}/native/lib{libraryName}.so", out var mappedName) + || MapLibraryName(assembly.Location, $"runtimes/{id}/{architectureName}/native/lib{libraryName}.so", out mappedName)) + { + return NativeLibrary.Load(mappedName, assembly, searchPath); + } + else + { + return NativeLibrary.Load(libraryName, assembly, searchPath); + } + }); + return; + } + else + { + throw new NotSupportedException($"Failed to find ID or VERSION_ID from {osRelease.FullName}"); + } + } + else + { + throw new NotSupportedException($"Failed to find {osRelease.FullName}"); + } + } + + private static bool MapLibraryName(string assemblyLocation, string relative, [NotNullWhen(true)] out string? mappedName) + { + var candidate = Path.Combine( + Path.GetDirectoryName(assemblyLocation)!, + relative); + + Console.WriteLine($"Looking for {candidate}"); + + if (File.Exists(candidate)) + { + mappedName = candidate; + return true; + } + else + { + mappedName = default; + return false; + } + } + } +} diff --git a/PeopleDetectionOpenCV/CaffeDnnFaceDetector.cs b/PeopleDetectionOpenCV/CaffeDnnFaceDetector.cs new file mode 100644 index 0000000..26f7a5d --- /dev/null +++ b/PeopleDetectionOpenCV/CaffeDnnFaceDetector.cs @@ -0,0 +1,50 @@ +using OpenCvSharp; +using OpenCvSharp.Dnn; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using Shared; + +namespace PeopleDetectionOpenCV +{ + public class CaffeDnnFaceDetector : IDetector + { + public Net Net { get; } + + public CaffeDnnFaceDetector(string modelFile) + { + var modelDirectory = Path.GetDirectoryName(modelFile)!; + var configFile = Path.Combine(modelDirectory, "deploy.prototxt"); + + Net = CvDnn.ReadNetFromCaffe(configFile, modelFile); + Net.SetPreferableBackend(Net.Backend.INFERENCE_ENGINE); + Net.SetPreferableTarget(Net.Target.OPENCL_FP16); + } + + public Rectangle[] Detect(Mat mat, byte[] buffer) + { + var frameWidth = mat.Width; + var frameHeight = mat.Height; + using var blob = CvDnn.BlobFromImage(mat, 1.0, new OpenCvSharp.Size(300, 300), new OpenCvSharp.Scalar(104, 117, 123), false, false); + Net.SetInput(blob); + using var detections = Net.Forward(); + using var detectionMat = new Mat(detections.Size(2), detections.Size(3), MatType.CV_32F, detections.Ptr(0)); + var rectangles = new List(); + for (var i = 0; i < detectionMat.Rows; i++) + { + var confidence = detectionMat.At(i, 2); + if (confidence > 0.7) + { + var left = (int)(detectionMat.At(i, 3) * frameWidth); + var top = (int)(detectionMat.At(i, 4) * frameHeight); + var right = (int)(detectionMat.At(i, 5) * frameWidth); + var bottom = (int)(detectionMat.At(i, 6) * frameHeight); + + rectangles.Add(new Rectangle(left, top, right - left, bottom - top)); + } + } + + return rectangles.ToArray(); + } + } +} diff --git a/PeopleDetectionOpenCV/Detector.cs b/PeopleDetectionOpenCV/Detector.cs new file mode 100644 index 0000000..be428fc --- /dev/null +++ b/PeopleDetectionOpenCV/Detector.cs @@ -0,0 +1,32 @@ +#if USE_DLIB +using DlibDotNet; +using OpenCvSharp; +using System; + +namespace PeopleDetectionOpenCV +{ + public class Detector : IDisposable + { + public FrontalFaceDetector FaceDetector { get; } + + public Detector() + { + FaceDetector = Dlib.GetFrontalFaceDetector(); + } + + public Rectangle[] Detect(Mat mat, byte[] buffer) + { + var height = (uint)mat.Height; + var width = (uint)mat.Width; + using var cimg = Dlib.LoadImageData(buffer, height, width, width * 3); + var faces = FaceDetector.Operator(cimg); + return faces; + } + + public void Dispose() + { + FaceDetector.Dispose(); + } + } +} +#endif diff --git a/PeopleDetectionOpenCV/Dockerfile b/PeopleDetectionOpenCV/Dockerfile new file mode 100644 index 0000000..152bc9c --- /dev/null +++ b/PeopleDetectionOpenCV/Dockerfile @@ -0,0 +1,31 @@ +FROM mcr.microsoft.com/dotnet/core/runtime:3.1.0 AS base +RUN apt update && \ + apt install -y \ + ffmpeg \ + libgdiplus \ + libgtk2.0-0 \ + libtbb2 + +WORKDIR /app + +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/core/sdk:3.1.100-buster AS build +WORKDIR /src +COPY ["Directory.Build.props", "nuget.config", "./"] +COPY ["PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj", "PeopleDetectionOpenCV/"] +COPY ["Shared/Shared.csproj", "Shared/"] +RUN dotnet restore --configfile nuget.config "PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj" + +COPY ["GlobalSuppressions.cs", "./"] +COPY ["PeopleDetectionOpenCV/", "PeopleDetectionOpenCV/"] +COPY ["Shared/", "Shared/"] + +WORKDIR "/src/PeopleDetectionOpenCV/" +RUN dotnet build --no-restore -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish --no-restore -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "PeopleDetectionOpenCV.dll"] diff --git a/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj b/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj new file mode 100644 index 0000000..5fa6903 --- /dev/null +++ b/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj @@ -0,0 +1,24 @@ + + + + Exe + netcoreapp3.1 + true + x64 + $([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows))) + $([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux))) + $([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX))) + 3 + enable + + + + + + + + + + + + diff --git a/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj.user b/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj.user new file mode 100644 index 0000000..b498b80 --- /dev/null +++ b/PeopleDetectionOpenCV/PeopleDetectionOpenCV.csproj.user @@ -0,0 +1,9 @@ + + + + ProjectDebugger + + + PeopleDetectionOpenCVTF + + \ No newline at end of file diff --git a/PeopleDetectionOpenCV/Program.cs b/PeopleDetectionOpenCV/Program.cs new file mode 100644 index 0000000..e029c6d --- /dev/null +++ b/PeopleDetectionOpenCV/Program.cs @@ -0,0 +1,127 @@ +using OpenCvSharp; +// using OpenCvSharp.Extensions; +using Shared; +using System; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace PeopleDetectionOpenCV +{ + internal static class Program + { + public static async Task Main(string[] args) + { + WindowsLibraryLoader.Instance.AdditionalPaths.Add(@"C:\Users\nick\Source\Repos\OpenVinoOpenCvSharp\install\bin"); + + if (args.Length != 4) + { + Console.WriteLine("Usage: PersonDetection "); + return -1; + } + + try + { + FFmpegHelper.Register(); + //AssemblyLoadConfiguration.For(); + + var buildInfo = OpenCvSharp.Cv2.GetBuildInformation(); + Console.WriteLine($"Build info: {buildInfo}"); + + var inputFormat = args[0]; + var inputCamera = args[1]; + var model = args[2]; + var output = args[3]; + + var outputFolder = new DirectoryInfo(output); + if (!outputFolder.Exists) + { + outputFolder.Create(); + } + + var dataTransfer = new DataTransfer(); + var detector = model.EndsWith(".pb", StringComparison.OrdinalIgnoreCase) ? (IDetector)(new TensorFlowDnnFaceDetector(model)) : (IDetector)(new CaffeDnnFaceDetector(model)); + ProcessStream(inputFormat, inputCamera, dataTransfer); + + var counter = 0; + while (true) + { + using var data = await dataTransfer.GetNext(default); + HandleFrame(data.Value.Mat, data.Value.Buffer, ref counter, detector, outputFolder); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error {ex.Message}"); + Console.WriteLine(ex); + return -2; + } + } + + private static void ProcessStream(string inputFormat, string inputCamera, DataTransfer dataTransfer) + { + var thread = new Thread(() => + { + try + { + using var decoder = new Decoder(inputFormat, inputCamera, dataTransfer); + Console.WriteLine($"Codec name: {decoder.CodecName}"); + + var info = decoder.GetContextInfo(); + foreach (var (key, value) in info) + { + Console.WriteLine($"{key} = '{value}'"); + } + decoder.Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Error in thread: {ex.Message}"); + } + }); + + thread.Start(); + } + + private static void HandleFrame(Mat mat, byte[] buffer, ref int counter, IDetector detector, DirectoryInfo outputFolder) + { + var sw = Stopwatch.StartNew(); + + var faces = detector.Detect(mat, buffer); + var predictTime = sw.Elapsed; + if (faces.Length > 0) + { + using var bitmap = mat.ToBitmap(); + + AugmentOutputImage(faces, bitmap); + var outputFileName = Path.Combine(outputFolder.FullName, $"image-{counter:D03}.png"); + bitmap.Save(outputFileName, ImageFormat.Png); + counter = (counter + 1) % 20; + Console.WriteLine($"Processed {counter} in {predictTime} total {sw.Elapsed}"); + } + else + { + Console.WriteLine($"Skipped in {predictTime} total {sw.Elapsed}"); + } + } + + private static void AugmentOutputImage(Rectangle[] output, Bitmap bitmap) + { + Console.WriteLine($"Got {output.Length} detections"); + + using var graphics = Graphics.FromImage(bitmap); + graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; + using var pen = new Pen(Color.Red, 4); + + for (var i = 0; i < output.Length; i++) + { + var rectangle = output[i]; + var rect = new Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height); + graphics.DrawRectangle(pen, rect); + } + } + } +} diff --git a/PeopleDetectionOpenCV/Properties/launchSettings.json b/PeopleDetectionOpenCV/Properties/launchSettings.json new file mode 100644 index 0000000..6ecd922 --- /dev/null +++ b/PeopleDetectionOpenCV/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "PeopleDetectionOpenCV": { + "commandName": "Project", + "commandLineArgs": "dshow \"video=Razer Kiyo\" \"c:\\users\\nick\\downloads\\models\\res10_300x300_ssd_iter_140000_fp16.caffemodel\" \"c:\\temp\\pddumps\"" + }, + "PeopleDetectionOpenCVTF": { + "commandName": "Project", + "commandLineArgs": "dshow \"video=Razer Kiyo\" \"c:\\users\\nick\\downloads\\models\\opencv_face_detector_uint8.pb\" \"c:\\temp\\pddumps\"" + } + } +} \ No newline at end of file diff --git a/PeopleDetectionOpenCV/TensorFlowDnnFaceDetector.cs b/PeopleDetectionOpenCV/TensorFlowDnnFaceDetector.cs new file mode 100644 index 0000000..0b6089c --- /dev/null +++ b/PeopleDetectionOpenCV/TensorFlowDnnFaceDetector.cs @@ -0,0 +1,50 @@ +using OpenCvSharp; +using OpenCvSharp.Dnn; +using Shared; +using System.Collections.Generic; +using System.Drawing; +using System.IO; + +namespace PeopleDetectionOpenCV +{ + public class TensorFlowDnnFaceDetector : IDetector + { + public Net Net { get; } + + public TensorFlowDnnFaceDetector(string modelFile) + { + var modelDirectory = Path.GetDirectoryName(modelFile)!; + var configFile = Path.Combine(modelDirectory, "opencv_face_detector.pbtxt"); + + Net = CvDnn.ReadNetFromTensorflow(modelFile, configFile); + // Net.SetPreferableTarget(Net.Target.OPENCL_FP16); + Net.SetPreferableBackend(Net.Backend.OPENCV); + } + + public Rectangle[] Detect(Mat mat, byte[] buffer) + { + var frameWidth = mat.Width; + var frameHeight = mat.Height; + using var blob = CvDnn.BlobFromImage(mat, 1.0, new OpenCvSharp.Size(300, 300), new OpenCvSharp.Scalar(104, 117, 123), false, false); + Net.SetInput(blob); + using var detections = Net.Forward(); + using var detectionMat = new Mat(detections.Size(2), detections.Size(3), MatType.CV_32F, detections.Ptr(0)); + var rectangles = new List(); + for (var i = 0; i < detectionMat.Rows; i++) + { + var confidence = detectionMat.At(i, 2); + if (confidence > 0.7) + { + var left = (int)(detectionMat.At(i, 3) * frameWidth); + var top = (int)(detectionMat.At(i, 4) * frameHeight); + var right = (int)(detectionMat.At(i, 5) * frameWidth); + var bottom = (int)(detectionMat.At(i, 6) * frameHeight); + + rectangles.Add(new Rectangle(left, top, right - left, bottom - top)); + } + } + + return rectangles.ToArray(); + } + } +} diff --git a/PeopleDetectionOpenCV/build.ps1 b/PeopleDetectionOpenCV/build.ps1 new file mode 100644 index 0000000..c70b815 --- /dev/null +++ b/PeopleDetectionOpenCV/build.ps1 @@ -0,0 +1,4 @@ +$BUILD_VERSION="0.0.23" + +docker buildx build --platform linux/arm/v7,linux/amd64 -t nrandell/pdopencv:${BUILD_VERSION} --push -f Dockerfile .. + diff --git a/PeopleDetectionOpenCV/run.bat b/PeopleDetectionOpenCV/run.bat new file mode 100644 index 0000000..1a0b150 --- /dev/null +++ b/PeopleDetectionOpenCV/run.bat @@ -0,0 +1,4 @@ +@echo off +set PATH=C:\Program Files (x86)\IntelSWTools\openvino\deployment_tools\inference_engine\bin\intel64\Release;C:\Program Files (x86)\IntelSWTools\openvino\opencv\bin;%PATH% +dotnet run --no-build dshow "video=Razer Kiyo" "c:\users\nick\downloads\models\opencv_face_Detector_uint8.pb" "c:\temp\pddumps" + diff --git a/PeopleDetectionOpenCV/run.sh b/PeopleDetectionOpenCV/run.sh new file mode 100644 index 0000000..62af2ca --- /dev/null +++ b/PeopleDetectionOpenCV/run.sh @@ -0,0 +1,6 @@ +#! /bin/bash +ARGS="$@" + +. /opt/intel/openvino/bin/setupvars.sh + +exec dotnet PeopleDetectionOpenCV.dll $ARGS diff --git a/Shared/Converter.cs b/Shared/Converter.cs new file mode 100644 index 0000000..0c47135 --- /dev/null +++ b/Shared/Converter.cs @@ -0,0 +1,55 @@ +using FFmpeg.AutoGen; +using OpenCvSharp; +using System; +using System.Drawing; +using System.Runtime.InteropServices; + +namespace Shared +{ + public unsafe class Converter : IDisposable + { + public System.Drawing.Size Size { get; } + private readonly int _convertedBufferSize; + private readonly IntPtr _convertedFrameBuffer; + private readonly byte_ptrArray4 _dstData; + private readonly int_array4 _dstLineSize; + private readonly SwsContext* _convertContext; + private readonly byte[] _buffer; + private readonly GCHandle _bufferHandle; + + public Converter(System.Drawing.Size size, AVPixelFormat sourcePixelFormat) + { + Size = size; + const AVPixelFormat targetPixelFormat = AVPixelFormat.AV_PIX_FMT_BGR24; + var context = ffmpeg.sws_getContext(size.Width, size.Height, sourcePixelFormat, size.Width, size.Height, targetPixelFormat, ffmpeg.SWS_FAST_BILINEAR, null, null, null); + _convertedBufferSize = ffmpeg.av_image_get_buffer_size(targetPixelFormat, size.Width, size.Height, 1); + + _buffer = new byte[_convertedBufferSize]; + _bufferHandle = GCHandle.Alloc(_buffer); + + _convertedFrameBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0); + _dstData = new byte_ptrArray4(); + _dstLineSize = new int_array4(); + _convertContext = context; + + ffmpeg.av_image_fill_arrays(ref _dstData, ref _dstLineSize, (byte*)_convertedFrameBuffer, targetPixelFormat, size.Width, size.Height, 1); + } + + public void Dispose() + { + _bufferHandle.Free(); + ffmpeg.sws_freeContext(_convertContext); + } + +#pragma warning disable IDE0060 // Remove unused parameter + internal static void DummyFreeData(IntPtr _, IntPtr __, IntPtr ___) { } +#pragma warning restore IDE0060 // Remove unused parameter + + public MatAndBuffer Convert(AVFrame* frame) + { + ffmpeg.sws_scale(_convertContext, frame->data, frame->linesize, 0, frame->height, _dstData, _dstLineSize); + var mat = new Mat(Size.Height, Size.Width, MatType.CV_8UC3, _convertedFrameBuffer); + return new MatAndBuffer(mat, _buffer); + } + } +} diff --git a/Shared/DataTransfer.cs b/Shared/DataTransfer.cs new file mode 100644 index 0000000..d0a6372 --- /dev/null +++ b/Shared/DataTransfer.cs @@ -0,0 +1,65 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Shared +{ + public class DataTransfer : IDisposable + { + private readonly SemaphoreSlim _lock = new SemaphoreSlim(1); + private DataOwner? _currentValue; + + public class DataOwner : IDisposable + { + public T Value { get; } + private readonly DataTransfer _parent; + + internal DataOwner(T value, DataTransfer parent) + { + Value = value; + _parent = parent; + } + + public void Dispose() + { + _parent._currentValue = null; + } + } + + public void Dispose() + { + _currentValue?.Dispose(); + _lock.Dispose(); + } + + public bool CanWrite => _currentValue == null; + + public bool TryWrite(T value) + { + if (_currentValue == null) + { + _currentValue = new DataOwner(value, this); + _lock.Release(); + return true; + } + else + { + return false; + } + } + + public async Task GetNext(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + await _lock.WaitAsync(stoppingToken); + var value = _currentValue; + if (value != null) + { + return value; + } + } + throw new OperationCanceledException(stoppingToken); + } + } +} diff --git a/Shared/Decoder.cs b/Shared/Decoder.cs new file mode 100644 index 0000000..8de3358 --- /dev/null +++ b/Shared/Decoder.cs @@ -0,0 +1,322 @@ +using FFmpeg.AutoGen; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; + +namespace Shared +{ + public unsafe class Decoder : IDisposable + { + private AVFormatContext* _inputContext; + private AVCodecContext* _decoderContext; + private AVBufferRef* _hwDeviceContext; + public readonly int StreamIndex; + public readonly string CodecName; + public readonly System.Drawing.Size FrameSize; + public readonly AVPixelFormat PixelFormat; + private readonly AVPixelFormat _hwPixelFormat; + private readonly Converter _converter; + private readonly DataTransfer _dataTransfer; + + public Decoder(string format, string camera, DataTransfer dataTransfer, bool enableHardware = false) + { + _dataTransfer = dataTransfer; + var inputFormat = ffmpeg.av_find_input_format(format); + if (inputFormat == null) + { + throw new ApplicationException($"Failed to find input format '{format}'"); + } + + var inputContext = ffmpeg.avformat_alloc_context(); + try + { + AVDictionary* options = null; + ffmpeg.av_dict_set(&options, "video_size", "640x480", ffmpeg.AV_DICT_APPEND); + ffmpeg.avformat_open_input(&inputContext, camera, inputFormat, &options).ThrowExceptionIfError(); + ffmpeg.av_dict_free(&options); + options = null; + + try + { + ffmpeg.avformat_find_stream_info(inputContext, null).ThrowExceptionIfError(); + AVCodec* decoder; + var videoStream = ffmpeg.av_find_best_stream(inputContext, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0); + if (videoStream < 0) + { + throw new ApplicationException("No video stream found"); + } + + AVBufferRef* hwDeviceContext = null; + var (hwPixelFormat, pixelFormat) = enableHardware ? SortoutHardware(decoder, out hwDeviceContext) : (AVPixelFormat.AV_PIX_FMT_NONE, AVPixelFormat.AV_PIX_FMT_NONE); + + var decoderContext = ffmpeg.avcodec_alloc_context3(decoder); + var video = inputContext->streams[videoStream]; + video->discard = AVDiscard.AVDISCARD_NONKEY; + ffmpeg.avcodec_parameters_to_context(decoderContext, video->codecpar).ThrowExceptionIfError(); + + if (hwPixelFormat != AVPixelFormat.AV_PIX_FMT_NONE) + { + AVCodecContext_get_format getFormat = (_, formats) => + { + //AVPixelFormat* pixelFormat; + for (var pixelFormat = formats; *pixelFormat != AVPixelFormat.AV_PIX_FMT_NONE; pixelFormat++) + { + if (*pixelFormat == hwPixelFormat) + { + return *pixelFormat; + } + } + throw new ApplicationException("Failed to get hardware pixel format"); + }; + + decoderContext->get_format = getFormat; + } + + ffmpeg.av_opt_set_int(decoderContext, "refcounted_frames", 1, 0); + + if (hwPixelFormat != AVPixelFormat.AV_PIX_FMT_NONE) + { + decoderContext->hw_device_ctx = ffmpeg.av_buffer_ref(hwDeviceContext); + } + else + { + pixelFormat = ConvertFormat(video->codec->pix_fmt); + } + + ffmpeg.avcodec_open2(decoderContext, decoder, null).ThrowExceptionIfError(); + + // Now all opened + _inputContext = inputContext; + _decoderContext = decoderContext; + CodecName = ffmpeg.avcodec_get_name(decoder->id); + FrameSize = new System.Drawing.Size(video->codec->width, video->codec->height); + PixelFormat = pixelFormat; + StreamIndex = videoStream; + _hwPixelFormat = hwPixelFormat; + + _converter = new Converter(FrameSize, pixelFormat); + + Console.WriteLine($"Opened stream {StreamIndex} of {CodecName} as {FrameSize.Width} x {FrameSize.Height} @ {PixelFormat}"); + } + catch (Exception) + { + ffmpeg.avformat_close_input(&inputContext); + throw; + } + } + catch (Exception) + { + ffmpeg.avformat_free_context(inputContext); + throw; + } + } + + private static AVPixelFormat ConvertFormat(AVPixelFormat format) => format switch + { + AVPixelFormat.AV_PIX_FMT_YUVJ411P => AVPixelFormat.AV_PIX_FMT_YUV411P, + AVPixelFormat.AV_PIX_FMT_YUVJ420P => AVPixelFormat.AV_PIX_FMT_YUV420P, + AVPixelFormat.AV_PIX_FMT_YUVJ422P => AVPixelFormat.AV_PIX_FMT_YUV422P, + AVPixelFormat.AV_PIX_FMT_YUVJ444P => AVPixelFormat.AV_PIX_FMT_YUV444P, + AVPixelFormat.AV_PIX_FMT_YUVJ440P => AVPixelFormat.AV_PIX_FMT_YUV440P, + _ => format, + }; + + private static (AVPixelFormat hwPixelFormat, AVPixelFormat pixelFormat) SortoutHardware(AVCodec* decoder, out AVBufferRef* hwDeviceContext) + { + var pixelFormat = AVPixelFormat.AV_PIX_FMT_NONE; + var hwPixelFormat = AVPixelFormat.AV_PIX_FMT_NONE; + var hwDeviceType = AVHWDeviceType.AV_HWDEVICE_TYPE_NONE; + AVBufferRef* localHwDeviceContext = hwDeviceContext = null; + + for (var i = 0; ; i++) + { + var hwConfig = ffmpeg.avcodec_get_hw_config(decoder, i); + if (hwConfig == null) + { + Console.WriteLine("No hardware decoder"); + break; + } + Console.WriteLine($"hwConfig: {hwConfig->methods} {hwConfig->pix_fmt} {hwConfig->device_type}"); + } + + for (var i = 0; ; i++) + { + var hwConfig = ffmpeg.avcodec_get_hw_config(decoder, i); + if (hwConfig == null) + { + Console.WriteLine("No hardware decoder"); + break; + } + + Console.WriteLine($"hwConfig: {hwConfig->methods} {hwConfig->pix_fmt} {hwConfig->device_type}"); + if ((hwConfig->methods & 0x02 /*FFmpeg.AutoGen. AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX*/) != 0) + { + ffmpeg.av_hwdevice_ctx_create(&localHwDeviceContext, hwConfig->device_type, null, null, 0).ThrowExceptionIfError(); + + var constraints = ffmpeg.av_hwdevice_get_hwframe_constraints(localHwDeviceContext, null); + AVPixelFormat found = AVPixelFormat.AV_PIX_FMT_NONE; + if (constraints != null) + { + AVPixelFormat first = AVPixelFormat.AV_PIX_FMT_NONE; + for (var p = constraints->valid_sw_formats; *p != AVPixelFormat.AV_PIX_FMT_NONE; p++) + { + Console.WriteLine($"Try pixel format {*p}"); + if (ffmpeg.sws_isSupportedInput(*p) != 0) + { + Console.WriteLine($"Valid pixel format {*p}"); + if (*p == AVPixelFormat.AV_PIX_FMT_NV12) + { + found = *p; + first = *p; + break; + } + else if (first == AVPixelFormat.AV_PIX_FMT_NONE) + { + first = *p; + } + } + } + ffmpeg.av_hwframe_constraints_free(&constraints); + if (found == AVPixelFormat.AV_PIX_FMT_NONE) + { + found = first; + } + } + if (found != AVPixelFormat.AV_PIX_FMT_NONE) + { + pixelFormat = found; + hwPixelFormat = hwConfig->pix_fmt; + hwDeviceType = hwConfig->device_type; + hwDeviceContext = localHwDeviceContext; + break; + } + else + { + ffmpeg.av_buffer_unref(&localHwDeviceContext); + } + } + } + + return (hwPixelFormat, pixelFormat); + } + + public void Run() + { + var _packet = ffmpeg.av_packet_alloc(); + var _frameA = ffmpeg.av_frame_alloc(); + var _frameB = ffmpeg.av_frame_alloc(); + var _swFrame = ffmpeg.av_frame_alloc(); + while (true) + { + int error; + do + { + ffmpeg.av_packet_unref(_packet); + error = ffmpeg.av_read_frame(_inputContext, _packet); + if (error == ffmpeg.AVERROR_EOF) + { + throw new EndOfStreamException("Finished stream"); + } + error.ThrowExceptionIfError(); + } while (_packet->stream_index != StreamIndex); + + ffmpeg.avcodec_send_packet(_decoderContext, _packet); + + var useA = true; + while (true) + { + var frame = useA ? _frameA : _frameB; + ffmpeg.av_frame_unref(frame); + error = ffmpeg.avcodec_receive_frame(_decoderContext, frame); + if (error == ffmpeg.AVERROR(ffmpeg.EAGAIN)) + { + break; + } + else if (error == ffmpeg.AVERROR_EOF) + { + throw new EndOfStreamException("No more frames"); + } + error.ThrowExceptionIfError(); + + if (_dataTransfer.CanWrite) + { + AVFrame* tmpFrame; + var isHw = frame->format == (int)_hwPixelFormat; + if (isHw) + { + ffmpeg.av_frame_unref(_swFrame); + _swFrame->format = (int)PixelFormat; + ffmpeg.av_hwframe_transfer_data(_swFrame, frame, 0).ThrowExceptionIfError(); + ffmpeg.av_frame_copy_props(_swFrame, frame); + tmpFrame = _swFrame; + } + else + { + tmpFrame = frame; + } + + var array = _converter.Convert(tmpFrame); + if (_dataTransfer.TryWrite(array)) + { + useA = !useA; + } + } + } + } + } + + public void Dispose() + { + if (_inputContext != null) + { + //ffmpeg.av_frame_unref(_frameA); + //ffmpeg.av_free(_frameA); + //_frameA = null; + + //ffmpeg.av_frame_unref(_frameB); + //ffmpeg.av_free(_frameB); + //_frameB = null; + + //ffmpeg.av_frame_unref(_swFrame); + //ffmpeg.av_free(_swFrame); + //_swFrame = null; + + //ffmpeg.av_packet_unref(_packet); + //ffmpeg.av_free(_packet); + //_packet = null; + + var hwDeviceContext = _hwDeviceContext; + ffmpeg.av_buffer_unref(&hwDeviceContext); + _hwDeviceContext = null; + + ffmpeg.avcodec_close(_decoderContext); + _decoderContext = null; + + var inputContext = _inputContext; + ffmpeg.avformat_close_input(&inputContext); + _inputContext = null; + + _converter.Dispose(); + } + } + + public IReadOnlyDictionary GetContextInfo() + { + AVDictionaryEntry* tag = null; + var result = new Dictionary(); + while ((tag = ffmpeg.av_dict_get(_inputContext->metadata, "", tag, ffmpeg.AV_DICT_IGNORE_SUFFIX)) != null) + { + var key = Marshal.PtrToStringAnsi((IntPtr)tag->key); + var value = Marshal.PtrToStringAnsi((IntPtr)tag->value); + + if ((key != null) && (value != null)) + { + result.Add(key, value); + } + } + + return result; + } + } +} diff --git a/Shared/Extensions.cs b/Shared/Extensions.cs new file mode 100644 index 0000000..3586dbe --- /dev/null +++ b/Shared/Extensions.cs @@ -0,0 +1,159 @@ +using OpenCvSharp; +using OpenCvSharp.Util; +using System; +using System.Drawing; +using System.Drawing.Imaging; + +namespace Shared +{ + public static class Extensions + { + public static Bitmap ToBitmap(this Mat src) + { + if (src == null) + { + throw new ArgumentNullException(nameof(src)); + } + + var pf = (src.Channels()) switch + { + 1 => PixelFormat.Format8bppIndexed, + 3 => PixelFormat.Format24bppRgb, + 4 => PixelFormat.Format32bppArgb, + _ => throw new ArgumentException("Number of channels must be 1, 3 or 4.", nameof(src)), + }; + return ToBitmap(src, pf); + } + + public static Bitmap ToBitmap(this Mat src, PixelFormat pf) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + src.ThrowIfDisposed(); + + Bitmap bitmap = new Bitmap(src.Width, src.Height, pf); + ToBitmap(src, bitmap); + return bitmap; + } + + public static unsafe void ToBitmap(this Mat src, Bitmap dst) + { + if (src == null) + throw new ArgumentNullException(nameof(src)); + if (dst == null) + throw new ArgumentNullException(nameof(dst)); + if (src.IsDisposed) + throw new ArgumentException("The image is disposed.", nameof(src)); + if (src.Depth() != MatType.CV_8U) + throw new ArgumentException("Depth of the image must be CV_8U"); + //if (src.IsSubmatrix()) + // throw new ArgumentException("Submatrix is not supported"); + if (src.Width != dst.Width || src.Height != dst.Height) + throw new ArgumentException(""); + + PixelFormat pf = dst.PixelFormat; + + // 1プレーン用の場合、グレースケールのパレット情報を生成する + if (pf == PixelFormat.Format8bppIndexed) + { + ColorPalette plt = dst.Palette; + for (int x = 0; x < 256; x++) + { + plt.Entries[x] = Color.FromArgb(x, x, x); + } + dst.Palette = plt; + } + + int w = src.Width; + int h = src.Height; + Rectangle rect = new Rectangle(0, 0, w, h); + BitmapData? bd = null; + + bool submat = src.IsSubmatrix(); + bool continuous = src.IsContinuous(); + + try + { + bd = dst.LockBits(rect, ImageLockMode.WriteOnly, pf); + + IntPtr srcData = src.Data; + byte* pSrc = (byte*)(srcData.ToPointer()); + byte* pDst = (byte*)(bd.Scan0.ToPointer()); + int ch = src.Channels(); + int sstep = (int)src.Step(); + int dstep = ((src.Width * ch) + 3) / 4 * 4; // 4の倍数に揃える + int stride = bd.Stride; + + switch (pf) + { + case PixelFormat.Format1bppIndexed: + { + if (submat) + throw new NotImplementedException("submatrix not supported"); + + // BitmapDataは4byte幅だが、IplImageは1byte幅 + // 手作業で移し替える + //int offset = stride - (w / 8); + int x = 0; + int y; + int bytePos; + byte mask; + byte b = 0; + int i; + for (y = 0; y < h; y++) + { + for (bytePos = 0; bytePos < stride; bytePos++) + { + if (x < w) + { + for (i = 0; i < 8; i++) + { + mask = (byte)(0x80 >> i); + if (x < w && pSrc[sstep * y + x] == 0) + b &= (byte)(mask ^ 0xff); + else + b |= mask; + + x++; + } + pDst[bytePos] = b; + } + } + x = 0; + pDst += stride; + } + break; + } + + case PixelFormat.Format8bppIndexed: + case PixelFormat.Format24bppRgb: + case PixelFormat.Format32bppArgb: + if (sstep == dstep && !submat && continuous) + { + uint imageSize = (uint)(src.DataEnd.ToInt64() - src.Data.ToInt64()); + MemoryHelper.CopyMemory(pDst, pSrc, imageSize); + } + else + { + for (int y = 0; y < h; y++) + { + long offsetSrc = (y * sstep); + long offsetDst = (y * dstep); + // 一列ごとにコピー + MemoryHelper.CopyMemory(pDst + offsetDst, pSrc + offsetSrc, w * ch); + } + } + break; + + default: + throw new NotImplementedException(); + } + } + finally + { + dst.UnlockBits(bd); + } + } + + } +} \ No newline at end of file diff --git a/Shared/FFmpegHelper.cs b/Shared/FFmpegHelper.cs new file mode 100644 index 0000000..08b4b33 --- /dev/null +++ b/Shared/FFmpegHelper.cs @@ -0,0 +1,41 @@ +using FFmpeg.AutoGen; +using System; +using System.Runtime.InteropServices; + +namespace Shared +{ + public static class FFmpegHelper + { + public static unsafe string? AvStrerror(int error) + { + const int bufferSize = 1024; + Span buffer = stackalloc byte[bufferSize]; + fixed (byte* bp = buffer) + { + ffmpeg.av_strerror(error, bp, (ulong)bufferSize); + return Marshal.PtrToStringAnsi((IntPtr)bp); + } + } + + public static int ThrowExceptionIfError(this int error) + { + if (error < 0) throw new ApplicationException(AvStrerror(error)); + return error; + } + + public static void Register() + { + switch (Environment.OSVersion.Platform) + { + case PlatformID.Win32NT: + ffmpeg.RootPath = @"c:\utils\ffmpeg\bin"; + break; + + default: + break; + } + + ffmpeg.avdevice_register_all(); + } + } +} diff --git a/Shared/IDetector.cs b/Shared/IDetector.cs new file mode 100644 index 0000000..b9c4d3b --- /dev/null +++ b/Shared/IDetector.cs @@ -0,0 +1,10 @@ +using OpenCvSharp; +using System.Drawing; + +namespace Shared +{ + public interface IDetector + { + Rectangle[] Detect(Mat mat, byte[] buffer); + } +} diff --git a/Shared/MatAndBuffer.cs b/Shared/MatAndBuffer.cs new file mode 100644 index 0000000..fc8b4e9 --- /dev/null +++ b/Shared/MatAndBuffer.cs @@ -0,0 +1,16 @@ +using OpenCvSharp; + +namespace Shared +{ + public class MatAndBuffer + { + public Mat Mat { get; } + public byte[] Buffer { get; } + + public MatAndBuffer(Mat mat, byte[] buffer) + { + Mat = mat; + Buffer = buffer; + } + } +} diff --git a/Shared/Shared.csproj b/Shared/Shared.csproj new file mode 100644 index 0000000..336cc58 --- /dev/null +++ b/Shared/Shared.csproj @@ -0,0 +1,18 @@ + + + + netstandard2.1 + true + enable + + + + + + + + + + + + diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..d355e9e --- /dev/null +++ b/build.bat @@ -0,0 +1,14 @@ +call "C:\Program Files (x86)\IntelSWTools\openvino\bin\setupvars.bat" + +PATH="C:\Program Files\CMake\bin\";%PATH% + +rmdir /s/q build +mkdir build +cd build + +cmake ^ + -D CMAKE_INSTALL_PREFIX=..\install ^ + -D CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS=TRUE ^ + .. + +cmake --build . --target install --config Release \ No newline at end of file