Example #1
0
        /// <summary>
        /// Computes a dense optical flow using the Gunnar Farneback's algorithm.
        /// </summary>
        /// <param name="prev">first 8-bit single-channel input image.</param>
        /// <param name="next">second input image of the same size and the same type as prev.</param>
        /// <param name="flow">computed flow image that has the same size as prev and type CV_32FC2.</param>
        /// <param name="pyrScale">parameter, specifying the image scale (&lt;1) to build pyramids for each image;
        /// pyrScale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous one.</param>
        /// <param name="levels">number of pyramid layers including the initial image;
        /// levels=1 means that no extra layers are created and only the original images are used.</param>
        /// <param name="winsize">averaging window size; larger values increase the algorithm robustness to
        /// image noise and give more chances for fast motion detection, but yield more blurred motion field.</param>
        /// <param name="iterations">number of iterations the algorithm does at each pyramid level.</param>
        /// <param name="polyN">size of the pixel neighborhood used to find polynomial expansion in each pixel;
        /// larger values mean that the image will be approximated with smoother surfaces,
        /// yielding more robust algorithm and more blurred motion field, typically poly_n =5 or 7.</param>
        /// <param name="polySigma">standard deviation of the Gaussian that is used to smooth derivatives used as
        /// a basis for the polynomial expansion; for polyN=5, you can set polySigma=1.1,
        /// for polyN=7, a good value would be polySigma=1.5.</param>
        /// <param name="flags">operation flags that can be a combination of OPTFLOW_USE_INITIAL_FLOW and/or OPTFLOW_FARNEBACK_GAUSSIAN</param>
        public static void CalcOpticalFlowFarneback(InputArray prev, InputArray next,
                                                    InputOutputArray flow, double pyrScale, int levels, int winsize,
                                                    int iterations, int polyN, double polySigma, OpticalFlowFlags flags)
        {
            if (prev == null)
            {
                throw new ArgumentNullException("prev");
            }
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (flow == null)
            {
                throw new ArgumentNullException("flow");
            }
            prev.ThrowIfDisposed();
            next.ThrowIfDisposed();
            flow.ThrowIfNotReady();

            NativeMethods.video_calcOpticalFlowFarneback(prev.CvPtr, next.CvPtr,
                                                         flow.CvPtr, pyrScale, levels, winsize, iterations, polyN, polySigma,
                                                         (int)flags);

            flow.Fix();
        }
Example #2
0
        /// <summary>
        /// computes sparse optical flow using multi-scale Lucas-Kanade algorithm
        /// </summary>
        /// <param name="prevImg"></param>
        /// <param name="nextImg"></param>
        /// <param name="prevPts"></param>
        /// <param name="nextPts"></param>
        /// <param name="status"></param>
        /// <param name="err"></param>
        /// <param name="winSize"></param>
        /// <param name="maxLevel"></param>
        /// <param name="criteria"></param>
        /// <param name="flags"></param>
        /// <param name="minEigThreshold"></param>
        public static void CalcOpticalFlowPyrLK(
            InputArray prevImg, InputArray nextImg,
            InputArray prevPts, InputOutputArray nextPts,
            OutputArray status, OutputArray err,
            Size?winSize           = null,
            int maxLevel           = 3,
            TermCriteria?criteria  = null,
            OpticalFlowFlags flags = OpticalFlowFlags.None,
            double minEigThreshold = 1e-4)
        {
            if (prevImg == null)
            {
                throw new ArgumentNullException("prevImg");
            }
            if (nextImg == null)
            {
                throw new ArgumentNullException("nextImg");
            }
            if (prevPts == null)
            {
                throw new ArgumentNullException("prevPts");
            }
            if (nextPts == null)
            {
                throw new ArgumentNullException("nextPts");
            }
            if (status == null)
            {
                throw new ArgumentNullException("status");
            }
            if (err == null)
            {
                throw new ArgumentNullException("err");
            }
            prevImg.ThrowIfDisposed();
            nextImg.ThrowIfDisposed();
            prevPts.ThrowIfDisposed();
            nextPts.ThrowIfNotReady();
            status.ThrowIfNotReady();
            err.ThrowIfNotReady();

            Size         winSize0  = winSize.GetValueOrDefault(new Size(21, 21));
            TermCriteria criteria0 = criteria.GetValueOrDefault(
                TermCriteria.Both(30, 0.01));

            NativeMethods.video_calcOpticalFlowPyrLK_InputArray(
                prevImg.CvPtr, nextImg.CvPtr, prevPts.CvPtr, nextPts.CvPtr,
                status.CvPtr, err.CvPtr, winSize0, maxLevel,
                criteria0, (int)flags, minEigThreshold);

            nextPts.Fix();
            status.Fix();
            err.Fix();
        }
Example #3
0
 /// <summary>
 /// Updates motion history image using the current silhouette
 /// </summary>
 /// <param name="silhouette">Silhouette mask that has non-zero pixels where the motion occurs.</param>
 /// <param name="mhi">Motion history image that is updated by the function (single-channel, 32-bit floating-point).</param>
 /// <param name="timestamp">Current time in milliseconds or other units.</param>
 /// <param name="duration">Maximal duration of the motion track in the same units as timestamp .</param>
 public static void UpdateMotionHistory(
     InputArray silhouette, InputOutputArray mhi,
     double timestamp, double duration)
 {
     if (silhouette == null)
         throw new ArgumentNullException("silhouette");
     if (mhi == null)
         throw new ArgumentNullException("mhi");
     silhouette.ThrowIfDisposed();
     mhi.ThrowIfNotReady();
     NativeMethods.video_updateMotionHistory(
         silhouette.CvPtr, mhi.CvPtr, timestamp, duration);
     mhi.Fix();
 }
Example #4
0
 /// <summary>
 /// Updates motion history image using the current silhouette
 /// </summary>
 /// <param name="silhouette">Silhouette mask that has non-zero pixels where the motion occurs.</param>
 /// <param name="mhi">Motion history image that is updated by the function (single-channel, 32-bit floating-point).</param>
 /// <param name="timestamp">Current time in milliseconds or other units.</param>
 /// <param name="duration">Maximal duration of the motion track in the same units as timestamp .</param>
 public static void UpdateMotionHistory(
     InputArray silhouette, InputOutputArray mhi,
     double timestamp, double duration)
 {
     if (silhouette == null)
     {
         throw new ArgumentNullException("silhouette");
     }
     if (mhi == null)
     {
         throw new ArgumentNullException("mhi");
     }
     silhouette.ThrowIfDisposed();
     mhi.ThrowIfNotReady();
     NativeMethods.video_updateMotionHistory(
         silhouette.CvPtr, mhi.CvPtr, timestamp, duration);
     mhi.Fix();
 }
Example #5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="mat"></param>
 /// <param name="distType"></param>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <param name="saturateRange"></param>
 public void Fill(InputOutputArray mat, DistributionType distType, InputArray a, InputArray b, bool saturateRange = false)
 {
     if (mat == null)
     {
         throw new ArgumentNullException("mat");
     }
     if (a == null)
     {
         throw new ArgumentNullException("a");
     }
     if (b == null)
     {
         throw new ArgumentNullException("b");
     }
     mat.ThrowIfNotReady();
     a.ThrowIfDisposed();
     b.ThrowIfDisposed();
     NativeMethods.core_RNG_fill(State, mat.CvPtr, (int)distType, a.CvPtr, b.CvPtr, saturateRange ? 1 : 0);
     mat.Fix();
 }
Example #6
0
 /// <summary>
 /// 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.
 /// </summary>
 /// <param name="mask">(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.</param>
 /// <param name="seedPoint">Starting point.</param>
 /// <param name="newVal">New value of the repainted domain pixels.</param>
 /// <returns></returns>
 public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal)
 {
     return Cv2.FloodFill(this, mask, seedPoint, newVal);
 }
Example #7
0
 /// <summary>
 /// Performs a marker-based image segmentation using the watershed algorithm.
 /// Input matrix is 8-bit 3-channel image.
 /// </summary>
 /// <param name="markers">Input/output 32-bit single-channel image (map) of markers. 
 /// It should have the same size as image.</param>
 public void Watershed(InputOutputArray markers)
 {
     Cv2.Watershed(this, markers);
 }
Example #8
0
        /// <summary>
        /// filters off speckles (small regions of incorrectly computed disparity)
        /// </summary>
        /// <param name="img">The input 16-bit signed disparity image</param>
        /// <param name="newVal">The disparity value used to paint-off the speckles</param>
        /// <param name="maxSpeckleSize">The maximum speckle size to consider it a speckle. Larger blobs are not affected by the algorithm</param>
        /// <param name="maxDiff">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.</param>
        /// <param name="buf">The optional temporary buffer to avoid memory allocation within the function.</param>
        public static void FilterSpeckles(InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff,
            InputOutputArray buf = null)
        {
            if (img == null)
                throw new ArgumentNullException("img");
            img.ThrowIfNotReady();

            NativeMethods.calib3d_filterSpeckles(img.CvPtr, newVal, maxSpeckleSize, maxDiff, ToPtr(buf));
            img.Fix();
        }
Example #9
0
        /// <summary>
        /// finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern.
        /// </summary>
        /// <param name="objectPoints">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.</param>
        /// <param name="imagePoints">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.</param>
        /// <param name="imageSize">Size of the image used only to initialize the intrinsic camera matrix.</param>
        /// <param name="cameraMatrix">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.</param>
        /// <param name="distCoeffs">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.</param>
        /// <param name="rvecs">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)</param>
        /// <param name="tvecs">Output vector of translation vectors estimated for each pattern view.</param>
        /// <param name="flags">Different flags that may be zero or a combination of the CalibrationFlag values</param>
        /// <param name="criteria">Termination criteria for the iterative optimization algorithm.</param>
        /// <returns></returns>
        public static double CalibrateCamera(
            IEnumerable<Mat> objectPoints,
            IEnumerable<Mat> imagePoints,
            Size imageSize,
            InputOutputArray cameraMatrix,
            InputOutputArray distCoeffs,
            out Mat[] rvecs, 
            out Mat[] tvecs,
            CalibrationFlag flags = CalibrationFlag.Zero, 
            TermCriteria? criteria = null)
        {
            if (objectPoints == null)
                throw new ArgumentNullException("objectPoints");
            if (objectPoints == null)
                throw new ArgumentNullException("objectPoints");
            if (cameraMatrix == null)
                throw new ArgumentNullException("cameraMatrix");
            if (distCoeffs == null)
                throw new ArgumentNullException("distCoeffs");
            cameraMatrix.ThrowIfNotReady();
            distCoeffs.ThrowIfNotReady();

            TermCriteria criteria0 = criteria.GetValueOrDefault(
                new TermCriteria(CriteriaType.Iteration | CriteriaType.Epsilon, 30, Double.Epsilon));

            IntPtr[] objectPointsPtrs = EnumerableEx.SelectPtrs(objectPoints);
            IntPtr[] 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);
                rvecs = rvecsVec.ToArray();
                tvecs = tvecsVec.ToArray();
            }

            cameraMatrix.Fix();
            distCoeffs.Fix();
            return ret;
        }
Example #10
0
        /// <summary>
        /// Renders the detected chessboard corners.
        /// </summary>
        /// <param name="image">Destination image. It must be an 8-bit color image.</param>
        /// <param name="patternSize">Number of inner corners per a chessboard row and column (patternSize = cv::Size(points_per_row,points_per_column)).</param>
        /// <param name="corners">Array of detected corners, the output of findChessboardCorners.</param>
        /// <param name="patternWasFound">Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here.</param>
        public static void DrawChessboardCorners(InputOutputArray image, Size patternSize,
            InputArray corners, bool patternWasFound)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (corners == null)
                throw new ArgumentNullException("corners");
            image.ThrowIfNotReady();
            corners.ThrowIfDisposed();

            NativeMethods.calib3d_drawChessboardCorners_InputArray(
                image.CvPtr, patternSize, corners.CvPtr, patternWasFound ? 1 : 0);
            image.Fix();
        }
        /// <summary>
        /// 輪郭線,または内側が塗りつぶされた輪郭を描きます.
        /// </summary>
        /// <param name="image">出力画像</param>
        /// <param name="contours"> 入力される全輪郭.各輪郭は,点のベクトルとして格納されています.</param>
        /// <param name="contourIdx">描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます.</param>
        /// <param name="color">輪郭の色.</param>
        /// <param name="thickness">輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます.</param>
        /// <param name="lineType">線の連結性</param>
        /// <param name="hierarchy">階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります.</param>
        /// <param name="maxLevel">描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます.
        /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と,
        /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, 
        /// hierarchy が有効な場合のみ考慮されます.</param>
        /// <param name="offset">輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます.</param>
#else
        /// <summary>
        /// draws contours in the image
        /// </summary>
        /// <param name="image">Destination image.</param>
        /// <param name="contours">All the input contours. Each contour is stored as a point vector.</param>
        /// <param name="contourIdx">Parameter indicating a contour to draw. If it is negative, all the contours are drawn.</param>
        /// <param name="color">Color of the contours.</param>
        /// <param name="thickness">Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), 
        /// the contour interiors are drawn.</param>
        /// <param name="lineType">Line connectivity. </param>
        /// <param name="hierarchy">Optional information about hierarchy. It is only needed if you want to draw only some of the contours</param>
        /// <param name="maxLevel">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.</param>
        /// <param name="offset">Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy)</param>
#endif
        public static void DrawContours(
            InputOutputArray image,
            IEnumerable<Mat> contours,
            int contourIdx,
            Scalar color,
            int thickness = 1,
            LineType lineType = LineType.Link8,
            Mat hierarchy = null,
            int maxLevel = Int32.MaxValue,
            Point? offset = null)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (contours == null)
                throw new ArgumentNullException("contours");
            image.ThrowIfNotReady();

            CvPoint offset0 = offset.GetValueOrDefault(new Point());
            IntPtr[] contoursPtr = EnumerableEx.SelectPtrs(contours);
            NativeMethods.imgproc_drawContours_InputArray(image.CvPtr, contoursPtr, contoursPtr.Length,
                        contourIdx, color, thickness, (int)lineType, ToPtr(hierarchy), maxLevel, offset0);
            image.Fix();
        }
        /// <summary>
        /// 2値画像中の輪郭を検出します.
        /// </summary>
        /// <param name="image">入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます.
        /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます.</param>
        /// <param name="mode">輪郭抽出モード</param>
        /// <param name="method">輪郭の近似手法</param>
        /// <param name="offset">オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます.</param>
        /// <return>検出された輪郭.各輪郭は,点のベクトルとして格納されます.</return>
#else
        /// <summary>
        /// Finds contours in a binary image.
        /// </summary>
        /// <param name="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.</param> 
        /// <param name="mode">Contour retrieval mode</param>
        /// <param name="method">Contour approximation method</param>
        /// <param name="offset"> 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.</param>
        /// <returns>Detected contours. Each contour is stored as a vector of points.</returns>
#endif
        public static MatOfPoint[] FindContoursAsMat(InputOutputArray image, 
            ContourRetrieval mode, ContourChain method, Point? offset = null)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            image.ThrowIfNotReady();

            CvPoint offset0 = offset.GetValueOrDefault(new Point());
            IntPtr contoursPtr;
            NativeMethods.imgproc_findContours2_OutputArray(image.CvPtr, out contoursPtr, (int)mode, (int)method, offset0);
            image.Fix();

            using (var contoursVec = new VectorOfMat(contoursPtr))
            {
                return contoursVec.ToArray<MatOfPoint>();
            }
        }
Example #13
0
        /// <summary>
        /// Computes a dense optical flow using the Gunnar Farneback's algorithm.
        /// </summary>
        /// <param name="prev">first 8-bit single-channel input image.</param>
        /// <param name="next">second input image of the same size and the same type as prev.</param>
        /// <param name="flow">computed flow image that has the same size as prev and type CV_32FC2.</param>
        /// <param name="pyrScale">parameter, specifying the image scale (&lt;1) to build pyramids for each image; 
        /// pyrScale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous one.</param>
        /// <param name="levels">number of pyramid layers including the initial image; 
        /// levels=1 means that no extra layers are created and only the original images are used.</param>
        /// <param name="winsize">averaging window size; larger values increase the algorithm robustness to 
        /// image noise and give more chances for fast motion detection, but yield more blurred motion field.</param>
        /// <param name="iterations">number of iterations the algorithm does at each pyramid level.</param>
        /// <param name="polyN">size of the pixel neighborhood used to find polynomial expansion in each pixel; 
        /// larger values mean that the image will be approximated with smoother surfaces, 
        /// yielding more robust algorithm and more blurred motion field, typically poly_n =5 or 7.</param>
        /// <param name="polySigma">standard deviation of the Gaussian that is used to smooth derivatives used as 
        /// a basis for the polynomial expansion; for polyN=5, you can set polySigma=1.1, 
        /// for polyN=7, a good value would be polySigma=1.5.</param>
        /// <param name="flags">operation flags that can be a combination of OPTFLOW_USE_INITIAL_FLOW and/or OPTFLOW_FARNEBACK_GAUSSIAN</param>
        public static void CalcOpticalFlowFarneback(InputArray prev, InputArray next,
            InputOutputArray flow, double pyrScale, int levels, int winsize,
            int iterations, int polyN, double polySigma, OpticalFlowFlags flags)
        {
            if (prev == null)
                throw new ArgumentNullException("prev");
            if (next == null)
                throw new ArgumentNullException("next");
            if (flow == null)
                throw new ArgumentNullException("flow");
            prev.ThrowIfDisposed();
            next.ThrowIfDisposed();
            flow.ThrowIfNotReady();

            NativeMethods.video_calcOpticalFlowFarneback(prev.CvPtr, next.CvPtr, 
                flow.CvPtr, pyrScale, levels, winsize, iterations, polyN, polySigma, 
                (int)flags);

            flow.Fix();
        }
Example #14
0
        /// <summary>
        /// computes sparse optical flow using multi-scale Lucas-Kanade algorithm
        /// </summary>
        /// <param name="prevImg"></param>
        /// <param name="nextImg"></param>
        /// <param name="prevPts"></param>
        /// <param name="nextPts"></param>
        /// <param name="status"></param>
        /// <param name="err"></param>
        /// <param name="winSize"></param>
        /// <param name="maxLevel"></param>
        /// <param name="criteria"></param>
        /// <param name="flags"></param>
        /// <param name="minEigThreshold"></param>
        public static void CalcOpticalFlowPyrLK(
            InputArray prevImg, InputArray nextImg,
            InputArray prevPts, InputOutputArray nextPts,
            OutputArray status, OutputArray err,
            Size? winSize = null,
            int maxLevel = 3,
            TermCriteria? criteria = null,
            OpticalFlowFlags flags = OpticalFlowFlags.None,
            double minEigThreshold = 1e-4)
        {
            if (prevImg == null)
                throw new ArgumentNullException("prevImg");
            if (nextImg == null)
                throw new ArgumentNullException("nextImg");
            if (prevPts == null)
                throw new ArgumentNullException("prevPts");
            if (nextPts == null)
                throw new ArgumentNullException("nextPts");
            if (status == null)
                throw new ArgumentNullException("status");
            if (err == null)
                throw new ArgumentNullException("err");
            prevImg.ThrowIfDisposed();
            nextImg.ThrowIfDisposed();
            prevPts.ThrowIfDisposed();
            nextPts.ThrowIfNotReady();
            status.ThrowIfNotReady();
            err.ThrowIfNotReady();

            Size winSize0 = winSize.GetValueOrDefault(new Size(21, 21));
            TermCriteria criteria0 = criteria.GetValueOrDefault(
                TermCriteria.Both(30, 0.01));

            NativeMethods.video_calcOpticalFlowPyrLK_InputArray(
                prevImg.CvPtr, nextImg.CvPtr, prevPts.CvPtr, nextPts.CvPtr,
                status.CvPtr, err.CvPtr, winSize0,maxLevel,
                criteria0, (int)flags, minEigThreshold);

            nextPts.Fix();
            status.Fix();
            err.Fix();
        }
Example #15
0
 /// <summary>
 /// inserts a single channel to dst (coi is 0-based index)
 /// </summary>
 /// <param name="src"></param>
 /// <param name="dst"></param>
 /// <param name="coi"></param>
 public static void InsertChannel(InputArray src, InputOutputArray dst, int coi)
 {
     if (src == null)
         throw new ArgumentNullException("src");
     if (dst == null)
         throw new ArgumentNullException("dst");
     src.ThrowIfDisposed();
     dst.ThrowIfNotReady();
     NativeMethods.core_insertChannel(src.CvPtr, dst.CvPtr, coi);
     dst.Fix();
 }
Example #16
0
    /// <summary>
    /// 輪郭線,または内側が塗りつぶされた輪郭を描きます.
    /// </summary>
    /// <param name="image">出力画像</param>
    /// <param name="contours"> 入力される全輪郭.各輪郭は,点のベクトルとして格納されています.</param>
    /// <param name="contourIdx">描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます.</param>
    /// <param name="color">輪郭の色.</param>
    /// <param name="thickness">輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます.</param>
    /// <param name="lineType">線の連結性</param>
    /// <param name="hierarchy">階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります.</param>
    /// <param name="maxLevel">描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます.
    /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と,
    /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, 
    /// hierarchy が有効な場合のみ考慮されます.</param>
    /// <param name="offset">輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます.</param>
#else
        /// <summary>
        /// Draws contours in the image
        /// </summary>
        /// <param name="image">Destination image.</param>
        /// <param name="contours">All the input contours. Each contour is stored as a point vector.</param>
        /// <param name="contourIdx">Parameter indicating a contour to draw. If it is negative, all the contours are drawn.</param>
        /// <param name="color">Color of the contours.</param>
        /// <param name="thickness">Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), 
        /// the contour interiors are drawn.</param>
        /// <param name="lineType">Line connectivity. </param>
        /// <param name="hierarchy">Optional information about hierarchy. It is only needed if you want to draw only some of the contours</param>
        /// <param name="maxLevel">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.</param>
        /// <param name="offset">Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy)</param>
#endif
        public void DrawContours(
            InputOutputArray image,
            IEnumerable<Mat> contours,
            int contourIdx,
            Scalar color,
            int thickness = 1,
            LineType lineType = LineType.Link8,
            Mat hierarchy = null,
            int maxLevel = Int32.MaxValue,
            Point? offset = null)
        {
            Cv2.DrawContours(image, contours, contourIdx, color, 
                thickness, lineType, hierarchy, maxLevel, offset);
        }
Example #17
0
 /// <summary>
 /// shuffles the input array elements
 /// </summary>
 /// <param name="dst"></param>
 /// <param name="iterFactor"></param>
 public static void RandShuffle(InputOutputArray dst, double iterFactor = 1.0)
 {
     if (dst == null)
         throw new ArgumentNullException("dst");
     dst.ThrowIfNotReady();
     NativeMethods.core_randShuffle_(dst.CvPtr, iterFactor);
     dst.Fix();
 }
 /// <summary>
 /// Adds the per-element product of two input images to the accumulator.
 /// </summary>
 /// <param name="src1">First input image, 1- or 3-channel, 8-bit or 32-bit floating point.</param>
 /// <param name="src2">Second input image of the same type and the same size as src1</param>
 /// <param name="dst">Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point.</param>
 /// <param name="mask">Optional operation mask.</param>
 public static void AccumulateProduct(InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask)
 {
     if (src1 == null)
         throw new ArgumentNullException("src1");
     if (src2 == null)
         throw new ArgumentNullException("src2");
     if (dst == null)
         throw new ArgumentNullException("dst");
     src1.ThrowIfDisposed();
     src2.ThrowIfDisposed();
     dst.ThrowIfNotReady();
     NativeMethods.imgproc_accumulateProduct(src1.CvPtr, src2.CvPtr, dst.CvPtr, ToPtr(mask));
     dst.Fix();
 }
        /// <summary>
        /// 輪郭線,または内側が塗りつぶされた輪郭を描きます.
        /// </summary>
        /// <param name="image">出力画像</param>
        /// <param name="contours"> 入力される全輪郭.各輪郭は,点のベクトルとして格納されています.</param>
        /// <param name="contourIdx">描かれる輪郭を示します.これが負値の場合,すべての輪郭が描画されます.</param>
        /// <param name="color">輪郭の色.</param>
        /// <param name="thickness">輪郭線の太さ.これが負値の場合(例えば thickness=CV_FILLED ),輪郭の内側が塗りつぶされます.</param>
        /// <param name="lineType">線の連結性</param>
        /// <param name="hierarchy">階層に関するオプションの情報.これは,特定の輪郭だけを描画したい場合にのみ必要になります.</param>
        /// <param name="maxLevel">描画される輪郭の最大レベル.0ならば,指定された輪郭のみが描画されます.
        /// 1ならば,指定された輪郭と,それに入れ子になったすべての輪郭が描画されます.2ならば,指定された輪郭と,
        /// それに入れ子になったすべての輪郭,さらにそれに入れ子になったすべての輪郭が描画されます.このパラメータは, 
        /// hierarchy が有効な場合のみ考慮されます.</param>
        /// <param name="offset">輪郭をシフトするオプションパラメータ.指定された offset = (dx,dy) だけ,すべての描画輪郭がシフトされます.</param>
#else
        /// <summary>
        /// draws contours in the image
        /// </summary>
        /// <param name="image">Destination image.</param>
        /// <param name="contours">All the input contours. Each contour is stored as a point vector.</param>
        /// <param name="contourIdx">Parameter indicating a contour to draw. If it is negative, all the contours are drawn.</param>
        /// <param name="color">Color of the contours.</param>
        /// <param name="thickness">Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), 
        /// the contour interiors are drawn.</param>
        /// <param name="lineType">Line connectivity. </param>
        /// <param name="hierarchy">Optional information about hierarchy. It is only needed if you want to draw only some of the contours</param>
        /// <param name="maxLevel">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.</param>
        /// <param name="offset">Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy)</param>
#endif
        public static void DrawContours(
            InputOutputArray image,
            IEnumerable<IEnumerable<Point>> contours,
            int contourIdx,
            Scalar color,
            int thickness = 1,
            LineType lineType = LineType.Link8,
            IEnumerable<HierarchyIndex> hierarchy = null,
            int maxLevel = Int32.MaxValue,
            Point? offset = null)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (contours == null)
                throw new ArgumentNullException("contours");
            image.ThrowIfNotReady();

            CvPoint offset0 = offset.GetValueOrDefault(new Point());
            Point[][] contoursArray = EnumerableEx.SelectToArray(contours, EnumerableEx.ToArray);
            int[] contourSize2 = EnumerableEx.SelectToArray(contoursArray, pts => pts.Length);
            using (var contoursPtr = new ArrayAddress2<Point>(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
                {
                    Vec4i[] hiearchyVecs = EnumerableEx.SelectToArray(hierarchy, hi => hi.ToVec4i());
                    NativeMethods.imgproc_drawContours_vector(image.CvPtr, contoursPtr.Pointer, contoursArray.Length, contourSize2,
                        contourIdx, color, thickness, (int)lineType, hiearchyVecs, hiearchyVecs.Length, maxLevel, offset0);
                }
            }

            image.Fix();
        }
 /// <summary>
 /// Updates a running average.
 /// </summary>
 /// <param name="src">Input image as 1- or 3-channel, 8-bit or 32-bit floating point.</param>
 /// <param name="dst">Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.</param>
 /// <param name="alpha">Weight of the input image.</param>
 /// <param name="mask">Optional operation mask.</param>
 public static void AccumulateWeighted(InputArray src, InputOutputArray dst, double alpha, InputArray mask)
 {
     if (src == null)
         throw new ArgumentNullException("src");
     if (dst == null)
         throw new ArgumentNullException("dst");
     src.ThrowIfDisposed();
     dst.ThrowIfNotReady();
     NativeMethods.imgproc_accumulateWeighted(src.CvPtr, dst.CvPtr, alpha, ToPtr(mask));
     dst.Fix();
 }
Example #21
0
        /// <summary>
        /// finds subpixel-accurate positions of the chessboard corners
        /// </summary>
        /// <param name="img"></param>
        /// <param name="corners"></param>
        /// <param name="regionSize"></param>
        /// <returns></returns>
        public static bool Find4QuadCornerSubpix(InputArray img, InputOutputArray corners, Size regionSize)
        {
            if (img == null)
                throw new ArgumentNullException("img");
            if (corners == null)
                throw new ArgumentNullException("corners");
            img.ThrowIfDisposed();
            corners.ThrowIfNotReady();

            int ret = NativeMethods.calib3d_find4QuadCornerSubpix_InputArray(
                img.CvPtr, corners.CvPtr, regionSize);
            corners.Fix();
            return ret != 0;
        }
 /// <summary>
 /// Computes a Hanning window coefficients in two dimensions.
 /// </summary>
 /// <param name="dst">Destination array to place Hann coefficients in</param>
 /// <param name="winSize">The window size specifications</param>
 /// <param name="type">Created array type</param>
 public static void CreateHanningWindow(InputOutputArray dst, Size winSize, MatType type)
 {
     if (dst == null)
         throw new ArgumentNullException("dst");
     dst.ThrowIfNotReady();
     NativeMethods.imgproc_createHanningWindow(dst.CvPtr, winSize, type);
     dst.Fix();
 }
Example #23
0
        /// <summary>
        /// Renders the detected chessboard corners.
        /// </summary>
        /// <param name="image">Destination image. It must be an 8-bit color image.</param>
        /// <param name="patternSize">Number of inner corners per a chessboard row and column (patternSize = cv::Size(points_per_row,points_per_column)).</param>
        /// <param name="corners">Array of detected corners, the output of findChessboardCorners.</param>
        /// <param name="patternWasFound">Parameter indicating whether the complete board was found or not. The return value of findChessboardCorners() should be passed here.</param>
        public static void DrawChessboardCorners(InputOutputArray image, Size patternSize,
            IEnumerable<Point2f> corners, bool patternWasFound)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (corners == null)
                throw new ArgumentNullException("corners");
            image.ThrowIfNotReady();

            Point2f[] cornersArray = EnumerableEx.ToArray(corners);
            NativeMethods.calib3d_drawChessboardCorners_array(
                image.CvPtr, patternSize, cornersArray, cornersArray.Length, 
                patternWasFound ? 1 : 0);
            image.Fix();
        }
 /// <summary>
 /// Performs a marker-based image segmentation using the watershed algorithm.
 /// </summary>
 /// <param name="image">Input 8-bit 3-channel image.</param>
 /// <param name="markers">Input/output 32-bit single-channel image (map) of markers. 
 /// It should have the same size as image.</param>
 public static void Watershed(InputArray image, InputOutputArray markers)
 {
     if (image == null)
         throw new ArgumentNullException("image");
     if (markers == null)
         throw new ArgumentNullException("markers");
     image.ThrowIfDisposed();
     markers.ThrowIfNotReady();
     NativeMethods.imgproc_watershed(image.CvPtr, markers.CvPtr);
     markers.Fix();
 }
Example #25
0
        /// <summary>
        /// finds intrinsic and extrinsic parameters of a stereo camera
        /// </summary>
        /// <param name="objectPoints">Vector of vectors of the calibration pattern points.</param>
        /// <param name="imagePoints1">Vector of vectors of the projections of the calibration pattern points, observed by the first camera.</param>
        /// <param name="imagePoints2">Vector of vectors of the projections of the calibration pattern points, observed by the second camera.</param>
        /// <param name="cameraMatrix1">Input/output first camera matrix</param>
        /// <param name="distCoeffs1">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.</param>
        /// <param name="cameraMatrix2"> Input/output second camera matrix. The parameter is similar to cameraMatrix1 .</param>
        /// <param name="distCoeffs2">Input/output lens distortion coefficients for the second camera. The parameter is similar to distCoeffs1 .</param>
        /// <param name="imageSize">Size of the image used only to initialize intrinsic camera matrix.</param>
        /// <param name="R">Output rotation matrix between the 1st and the 2nd camera coordinate systems.</param>
        /// <param name="T">Output translation vector between the coordinate systems of the cameras.</param>
        /// <param name="E">Output essential matrix.</param>
        /// <param name="F">Output fundamental matrix.</param>
        /// <param name="criteria">Termination criteria for the iterative optimization algorithm.</param>
        /// <param name="flags">Different flags that may be zero or a combination of the CalibrationFlag values</param>
        /// <returns></returns>
        public static double StereoCalibrate(IEnumerable<InputArray> objectPoints,
                                             IEnumerable<InputArray> imagePoints1,
                                             IEnumerable<InputArray> imagePoints2,
                                             InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
                                             InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
                                             Size imageSize, OutputArray R,
                                             OutputArray T, OutputArray E, OutputArray F,
                                             TermCriteria? criteria = null,
                                             CalibrationFlag flags = CalibrationFlag.FixIntrinsic)
        {
            if (objectPoints == null)
                throw new ArgumentNullException("objectPoints");
            if (imagePoints1 == null)
                throw new ArgumentNullException("imagePoints1");
            if (imagePoints2 == null)
                throw new ArgumentNullException("imagePoints2");
            if (cameraMatrix1 == null)
                throw new ArgumentNullException("cameraMatrix1");
            if (distCoeffs1 == null)
                throw new ArgumentNullException("distCoeffs1");
            if (cameraMatrix2 == null)
                throw new ArgumentNullException("cameraMatrix2");
            if (distCoeffs2 == null)
                throw new ArgumentNullException("distCoeffs2");
            cameraMatrix1.ThrowIfDisposed();
            distCoeffs1.ThrowIfDisposed();
            cameraMatrix2.ThrowIfDisposed();
            distCoeffs2.ThrowIfDisposed();
            cameraMatrix1.ThrowIfNotReady();
            cameraMatrix2.ThrowIfNotReady();
            distCoeffs1.ThrowIfNotReady();
            distCoeffs2.ThrowIfNotReady();

            IntPtr[] opPtrs = EnumerableEx.SelectPtrs(objectPoints);
            IntPtr[] ip1Ptrs = EnumerableEx.SelectPtrs(imagePoints1);
            IntPtr[] ip2Ptrs = EnumerableEx.SelectPtrs(imagePoints2);

            TermCriteria criteria0 = criteria.GetValueOrDefault(
                new TermCriteria(CriteriaType.Iteration | CriteriaType.Epsilon, 30, 1e-6));

            double 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),
                    criteria0, (int)flags
                    );

            cameraMatrix1.Fix();
            distCoeffs1.Fix();
            cameraMatrix2.Fix();
            distCoeffs2.Fix();
            if (R != null)
                R.Fix();
            if (T != null)
                T.Fix();
            if (E != null)
                E.Fix();
            if (F != null)
                F.Fix();

            return result;
        }
 /// <summary>
 /// Segments the image using GrabCut algorithm
 /// </summary>
 /// <param name="img">Input 8-bit 3-channel image.</param>
 /// <param name="mask">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</param>
 /// <param name="rect">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.</param>
 /// <param name="bgdModel">Temporary array for the background model. Do not modify it while you are processing the same image.</param>
 /// <param name="fgdModel">Temporary arrays for the foreground model. Do not modify it while you are processing the same image.</param>
 /// <param name="iterCount">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 .</param>
 /// <param name="mode">Operation mode that could be one of GrabCutFlag value.</param>
 public static void GrabCut(InputArray img, InputOutputArray mask, Rect rect,
                            InputOutputArray bgdModel, InputOutputArray fgdModel,
                            int iterCount, GrabCutFlag mode)
 {
     if (img == null)
         throw new ArgumentNullException("img");
     if (mask == null)
         throw new ArgumentNullException("mask");
     if (bgdModel == null)
         throw new ArgumentNullException("bgdModel");
     if (fgdModel == null)
         throw new ArgumentNullException("fgdModel");
     img.ThrowIfDisposed();
     mask.ThrowIfNotReady();
     bgdModel.ThrowIfNotReady();
     fgdModel.ThrowIfNotReady();
     NativeMethods.imgproc_grabCut(img.CvPtr, mask.CvPtr, rect,
         bgdModel.CvPtr, fgdModel.CvPtr, iterCount, (int)mode);
     mask.Fix();
     bgdModel.Fix();
     fgdModel.Fix();
 }
Example #27
0
        /// <summary>
        /// validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
        /// </summary>
        /// <param name="disparity"></param>
        /// <param name="cost"></param>
        /// <param name="minDisparity"></param>
        /// <param name="numberOfDisparities"></param>
        /// <param name="disp12MaxDisp"></param>
        public static void ValidateDisparity(InputOutputArray disparity, InputArray cost,
            int minDisparity, int numberOfDisparities, int disp12MaxDisp = 1)
        {
            if (disparity == null)
                throw new ArgumentNullException("disparity");
            if (cost == null)
                throw new ArgumentNullException("cost");
            disparity.ThrowIfNotReady();
            cost.ThrowIfDisposed();

            NativeMethods.calib3d_validateDisparity(
                disparity.CvPtr, cost.CvPtr, minDisparity, numberOfDisparities, disp12MaxDisp);
            disparity.Fix();
        }
 /// <summary>
 /// Fills a connected component with the given color.
 /// </summary>
 /// <param name="image">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.</param>
 /// <param name="mask">(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.</param>
 /// <param name="seedPoint">Starting point.</param>
 /// <param name="newVal">New value of the repainted domain pixels.</param>
 /// <returns></returns>
 public static int FloodFill(InputOutputArray image, InputOutputArray mask,
                             Point seedPoint, Scalar newVal)
 {
     Rect rect;
     return FloodFill(image, mask, seedPoint, newVal, out rect);
 }
Example #29
0
 /// <summary>
 /// Segments the image using GrabCut algorithm.
 /// The input is 8-bit 3-channel image.
 /// </summary>
 /// <param name="mask">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</param>
 /// <param name="rect">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.</param>
 /// <param name="bgdModel">Temporary array for the background model. Do not modify it while you are processing the same image.</param>
 /// <param name="fgdModel">Temporary arrays for the foreground model. Do not modify it while you are processing the same image.</param>
 /// <param name="iterCount">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 .</param>
 /// <param name="mode">Operation mode that could be one of GrabCutFlag value.</param>
 public void GrabCut(InputOutputArray mask, Rect rect,
     InputOutputArray bgdModel, InputOutputArray fgdModel,
     int iterCount, GrabCutFlag mode)
 {
     Cv2.GrabCut(this, mask, rect, bgdModel, fgdModel, iterCount, mode);
 }
 /// <summary>
 /// Fills a connected component with the given color.
 /// </summary>
 /// <param name="image">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.</param>
 /// <param name="mask">(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.</param>
 /// <param name="seedPoint">Starting point.</param>
 /// <param name="newVal">New value of the repainted domain pixels.</param>
 /// <param name="rect">Optional output parameter set by the function to the 
 /// minimum bounding rectangle of the repainted domain.</param>
 /// <param name="loDiff">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.</param>
 /// <param name="upDiff">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.</param>
 /// <param name="flags">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. </param>
 /// <returns></returns>
 public static int FloodFill(InputOutputArray image, InputOutputArray mask,
                             Point seedPoint, Scalar newVal, out Rect rect,
                             Scalar? loDiff = null, Scalar? upDiff = null,
                             FloodFillFlag flags = FloodFillFlag.Link4)
 {
     if (image == null)
         throw new ArgumentNullException("image");
     if (mask == null)
         throw new ArgumentNullException("mask");
     image.ThrowIfNotReady();
     mask.ThrowIfNotReady();
     Scalar loDiff0 = loDiff.GetValueOrDefault(new Scalar());
     Scalar upDiff0 = upDiff.GetValueOrDefault(new Scalar());
     CvRect rect0;
     int ret = NativeMethods.imgproc_floodFill(image.CvPtr, mask.CvPtr, seedPoint, 
         newVal, out rect0, loDiff0, upDiff0, (int)flags);
     rect = rect0;
     image.Fix();
     mask.Fix();
     return ret;
 }
Example #31
0
 /// <summary>
 /// 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.
 /// </summary>
 /// <param name="mask">(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.</param>
 /// <param name="seedPoint">Starting point.</param>
 /// <param name="newVal">New value of the repainted domain pixels.</param>
 /// <param name="rect">Optional output parameter set by the function to the 
 /// minimum bounding rectangle of the repainted domain.</param>
 /// <param name="loDiff">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.</param>
 /// <param name="upDiff">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.</param>
 /// <param name="flags">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. </param>
 /// <returns></returns>
 public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal, 
     out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null,
     FloodFillFlag flags = FloodFillFlag.Link4)
 {
     return Cv2.FloodFill(this, mask, seedPoint,
         newVal, out rect, loDiff, upDiff, flags);
 }
        /// <summary>
        /// 2値画像中の輪郭を検出します.
        /// </summary>
        /// <param name="image">入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます.
        /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます.</param>
        /// <param name="contours">検出された輪郭.各輪郭は,点のベクトルとして格納されます.</param>
        /// <param name="hierarchy">画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して,
        /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の 
        /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合,
        /// それに対応する hierarchy[i] の要素は,負の値になります.</param>
        /// <param name="mode">輪郭抽出モード</param>
        /// <param name="method">輪郭の近似手法</param>
        /// <param name="offset">オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます.</param>
#else
        /// <summary>
        /// Finds contours in a binary image.
        /// </summary>
        /// <param name="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.</param> 
        /// <param name="contours">Detected contours. Each contour is stored as a vector of points.</param>
        /// <param name="hierarchy">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.</param>
        /// <param name="mode">Contour retrieval mode</param>
        /// <param name="method">Contour approximation method</param>
        /// <param name="offset"> 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.</param>
#endif
        public static void FindContours(InputOutputArray image, out Point[][] contours,
            out HierarchyIndex[] hierarchy, ContourRetrieval mode, ContourChain method, Point? offset = null)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            image.ThrowIfNotReady();

            CvPoint offset0 = offset.GetValueOrDefault(new Point());
            IntPtr contoursPtr, hierarchyPtr;
            NativeMethods.imgproc_findContours1_vector(image.CvPtr, out contoursPtr, out hierarchyPtr, (int)mode, (int)method, offset0);

            using (var contoursVec = new VectorOfVectorPoint(contoursPtr))
            using (var hierarchyVec = new VectorOfVec4i(hierarchyPtr))
            {
                contours = contoursVec.ToArray();
                Vec4i[] hierarchyOrg = hierarchyVec.ToArray();
                hierarchy = EnumerableEx.SelectToArray(hierarchyOrg, HierarchyIndex.FromVec4i);
            }
            image.Fix();
        }
Example #33
0
 /// <summary>
 /// inserts a single channel to dst (coi is 0-based index)
 /// </summary>
 /// <param name="dst"></param>
 /// <param name="coi"></param>
 public void InsertChannel(InputOutputArray dst, int coi)
 {
     Cv2.InsertChannel(this, dst, coi);
 }
        /// <summary>
        /// 2値画像中の輪郭を検出します.
        /// </summary>
        /// <param name="image">入力画像,8ビット,シングルチャンネル.0以外のピクセルは 1として,0のピクセルは0のまま扱われます.
        /// また,この関数は,輪郭抽出処理中に入力画像 image の中身を書き換えます.</param>
        /// <param name="contours">検出された輪郭.各輪郭は,点のベクトルとして格納されます.</param>
        /// <param name="hierarchy">画像のトポロジーに関する情報を含む出力ベクトル.これは,輪郭数と同じ数の要素を持ちます.各輪郭 contours[i] に対して,
        /// 要素 hierarchy[i]のメンバにはそれぞれ,同じ階層レベルに存在する前後の輪郭,最初の子輪郭,および親輪郭の 
        /// contours インデックス(0 基準)がセットされます.また,輪郭 i において,前後,親,子の輪郭が存在しない場合,
        /// それに対応する hierarchy[i] の要素は,負の値になります.</param>
        /// <param name="mode">輪郭抽出モード</param>
        /// <param name="method">輪郭の近似手法</param>
        /// <param name="offset">オプションのオフセット.各輪郭点はこの値の分だけシフトします.これは,ROIの中で抽出された輪郭を,画像全体に対して位置づけて解析する場合に役立ちます.</param>
#else
        /// <summary>
        /// Finds contours in a binary image.
        /// </summary>
        /// <param name="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.</param> 
        /// <param name="contours">Detected contours. Each contour is stored as a vector of points.</param>
        /// <param name="hierarchy">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.</param>
        /// <param name="mode">Contour retrieval mode</param>
        /// <param name="method">Contour approximation method</param>
        /// <param name="offset"> 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.</param>
#endif
        public static void FindContours(InputOutputArray image, out Mat[] contours,
            OutputArray hierarchy, ContourRetrieval mode, ContourChain method, Point? offset = null)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (hierarchy == null)
                throw new ArgumentNullException("hierarchy");
            image.ThrowIfNotReady();
            hierarchy.ThrowIfNotReady();

            CvPoint offset0 = offset.GetValueOrDefault(new Point());
            IntPtr contoursPtr;
            NativeMethods.imgproc_findContours1_OutputArray(image.CvPtr, out contoursPtr, hierarchy.CvPtr, (int)mode, (int)method, offset0);

            using (var contoursVec = new VectorOfMat(contoursPtr))
            {
                contours = contoursVec.ToArray();
            }
            image.Fix();
            hierarchy.Fix();
        }