Mat Basic Processing2 (OpenCV5)

These codes are included in the OpenCVForUnity Example Unity scenes. (MatBasicProcessingExample)

shallow copy and deep copy example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  shallow copy and deep copy example
            // ---------------------------------------------------------------------------------------
            // When working with image and matrix data in OpenCVForUnity, the concepts of shallow copy and deep copy are important. These two methods differ in how they duplicate data, and can significantly affect the behavior of your program.
            // - Shallow copy: Creates a new Mat object that references the same memory region as the original data.
            // - Deep copy: Creates a new Mat object by copying the data into a new memory region, independent of the original data.
            //

            // 3x3 matrix
            Mat mat1 = new Mat(3, 3, CvType.CV_64FC1);
            mat1.put(0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

            // shallow copy — assignment shares the same native buffer (not a data copy).
            Mat mat_shallow = mat1;

            // deep copy (clone, copyTo) — independent buffers; changes to mat1 do not affect these.
            Mat mat_deep1 = mat1.clone();
            Mat mat_deep2 = new Mat();
            mat1.copyTo(mat_deep2);

            Log("mat1 = " + mat1.dump());
            Log("mat_shallow = " + mat_shallow.dump());
            Log("mat_deep1 = " + mat_deep1.dump());
            Log("mat_deep2 = " + mat_deep2.dump());

            // rewrite (0, 0) element of matrix mat1
            mat1.put(0, 0, 100);

            Log("mat1 = " + mat1.dump());
            Log("mat_shallow = " + mat_shallow.dump());
            Log("mat_deep1 = " + mat_deep1.dump());
            Log("mat_deep2 = " + mat_deep2.dump());

            Log("mat1.Equals(mat_shallow) = " + mat1.Equals(mat_shallow));
            Log("mat1.Equals(mat_deep1) = " + mat1.Equals(mat_deep1));
            Log("mat1.Equals(mat_deep2) = " + mat1.Equals(mat_deep2));
            

Execution Result:

mat1 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_shallow = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_deep1 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_deep2 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat1 = [100, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_shallow = [100, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_deep1 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat_deep2 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
mat1.Equals(mat_shallow) = True
mat1.Equals(mat_deep1) = False
mat1.Equals(mat_deep2) = False

merge example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  merge example
            // ---------------------------------------------------------------------------------------
            // Core.merge stacks single-channel Mats into one multi-channel Mat.
            // - Inputs must share the same shape and depth (2D: same rows/cols; 1D: same length / total()).
            // - Output channels() == number of input Mats.
            //

            // 2x2 matrices (classic 2D merge)
            Mat m1 = new Mat(2, 2, CvType.CV_64FC1);
            m1.put(0, 0, 1.0, 2.0, 3.0, 4.0);
            Mat m2 = new Mat(2, 2, CvType.CV_64FC1);
            m2.put(0, 0, 1.1, 2.1, 3.1, 4.1);
            Mat m3 = new Mat(2, 2, CvType.CV_64FC1);
            m3.put(0, 0, 1.2, 2.2, 3.2, 4.2);

            List<Mat> mv = new List<Mat>();
            mv.Add(m1);
            mv.Add(m2);
            mv.Add(m3);

            Mat mat_merged = new Mat();
            Core.merge(mv, mat_merged);
            Log("mat_merged = " + mat_merged.dump());
            Log("mat_merged.channels() = " + mat_merged.channels());

            // 1D merge: match length with total()/cols(), not "image rows x cols"
            Mat a1d = new Mat(new int[] { 3 }, CvType.CV_64FC1);
            a1d.put(0, 0, 1, 2, 3);
            Mat b1d = new Mat(new int[] { 3 }, CvType.CV_64FC1);
            b1d.put(0, 0, 4, 5, 6);
            List<Mat> mv1d = new List<Mat>();
            mv1d.Add(a1d);
            mv1d.Add(b1d);
            Mat merged1d = new Mat();
            Core.merge(mv1d, merged1d);
            Log("merged1d.dims() = " + merged1d.dims());
            Log("merged1d.channels() = " + merged1d.channels());
            Log("merged1d = " + merged1d.dump());

Execution Result:

mat_merged = [1, 1.1, 1.2, 2, 2.1, 2.2;
 3, 3.1, 3.2, 4, 4.1, 4.2]
mat_merged.channels() = 3
merged1d.dims() = 1
merged1d.channels() = 2
merged1d = [1, 4, 2, 5, 3, 6]

mixChannels example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  mixChannels example
            // ---------------------------------------------------------------------------------------
            // The Core.mixChannels function allows you to freely manipulate the channels of a Mat object.
            // It is used to reorder channels or to create a new Mat object from multiple Mat objects.
            //

            // 2x2 matrix
            Mat m1 = new Mat(2, 2, CvType.CV_64FC1);
            m1.put(0, 0, 1.0, 2.0, 3.0, 4.0);
            Mat m2 = new Mat(2, 2, CvType.CV_64FC1);
            m2.put(0, 0, 1.1, 2.1, 3.1, 4.1);
            Mat m3 = new Mat(2, 2, CvType.CV_64FC1);
            m3.put(0, 0, 1.2, 2.2, 3.2, 4.2);

            List<Mat> mv = new List<Mat>();
            mv.Add(m1);
            mv.Add(m2);
            mv.Add(m3);

            // mat for output must be allocated.
            Mat mat_mixed1 = new Mat(2, 2, CvType.CV_64FC2);
            Mat mat_mixed2 = new Mat(2, 2, CvType.CV_64FC2);
            MatOfInt fromTo = new MatOfInt(0, 0, 1, 1, 1, 3, 2, 2); // See MatOf* example: int pairs (from,to) as 1D Mat

            List<Mat> mixv = new List<Mat>();
            mixv.Add(mat_mixed1);
            mixv.Add(mat_mixed2);

            // mix
            Core.mixChannels(mv, mixv, fromTo);

            // dump
            Log("mat_mixed1 = " + mat_mixed1.dump());
            Log("mat_mixed2 = " + mat_mixed2.dump());
            

Execution Result:

mat_mixed1 = [1, 1.1, 2, 2.1;
 3, 3.1, 4, 4.1]
mat_mixed2 = [1.2, 1.1, 2.2, 2.1;
 3.2, 3.1, 4.2, 4.1]

split example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  split example
            // ---------------------------------------------------------------------------------------
            // The Core.split function separates a single multi-channel image (e.g., an RGB image) into its individual channels; it is the counterpart to the Core.merge function.
            //

            // channels=3, 2x3 matrix
            Mat m1 = new Mat(2, 3, CvType.CV_64FC3);
            m1.put(0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);

            List<Mat> planes = new List<Mat>();

            // split
            Core.split(m1, planes);

            // dump
            for (int i = 0; i < planes.Count; i++)
            {
                Log("planes[" + i + "] = " + planes[i].dump());
            }
            

Execution Result:

planes[0] = [1, 4, 7;
 10, 13, 16]
planes[1] = [2, 5, 8;
 11, 14, 17]
planes[2] = [3, 6, 9;
 12, 15, 18]

reduce example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  reduce example
            // ---------------------------------------------------------------------------------------
            // The Core.reduce function compresses (reduces) a multidimensional array (Mat object) along a specified axis. In other words,
            // it can compress multidimensional data into lower dimensional data.
            // Note: reduce results are typically 2D row/column vectors (1xN or Nx1), not true 1D Mats.
            //

            // 3x3 matrix
            Mat m1 = new Mat(3, 3, CvType.CV_64FC1);
            m1.put(0, 0, 1, 5, 3, 4, 2, 6, 7, 8, 9);

            Mat v1 = new Mat();
            Mat v2 = new Mat();
            Mat v3 = new Mat();
            Mat v4 = new Mat();

            // reduce 3 x 3 matrix to one row
            Core.reduce(m1, v1, 0, Core.REDUCE_SUM); // total value of each column
            Core.reduce(m1, v2, 0, Core.REDUCE_AVG); // total average value of each column
            Core.reduce(m1, v3, 0, Core.REDUCE_MIN); // minimum value of each column
            Core.reduce(m1, v4, 0, Core.REDUCE_MAX); // maximum value of each column

            // dump
            Log("m1 = " + m1.dump());
            Log("v1(sum) = " + v1.dump() + " dims = " + v1.dims() + " rows = " + v1.rows() + " cols = " + v1.cols());
            Log("v2(avg) = " + v2.dump());
            Log("v3(min) = " + v3.dump());
            Log("v4(max) = " + v4.dump());

            // reduce 3 x 3 matrix to one col
            Core.reduce(m1, v1, 1, Core.REDUCE_SUM); // total value of each row
            Core.reduce(m1, v2, 1, Core.REDUCE_AVG); // total average value of row
            Core.reduce(m1, v3, 1, Core.REDUCE_MIN); // minimum value of each row
            Core.reduce(m1, v4, 1, Core.REDUCE_MAX); // maximum value of each row

            // dump
            Log("m1 = " + m1.dump());
            Log("v1(sum) = " + v1.dump() + " dims = " + v1.dims() + " rows = " + v1.rows() + " cols = " + v1.cols());
            Log("v2(avg) = " + v2.dump());
            Log("v3(min) = " + v3.dump());
            Log("v4(max) = " + v4.dump());
            

Execution Result:

m1 = [1, 5, 3;
 4, 2, 6;
 7, 8, 9]
v1(sum) = [12, 15, 18] dims = 2 rows = 1 cols = 3
v2(avg) = [4, 5, 6]
v3(min) = [1, 2, 3]
v4(max) = [7, 8, 9]
m1 = [1, 5, 3;
 4, 2, 6;
 7, 8, 9]
v1(sum) = [9;
 12;
 24] dims = 2 rows = 3 cols = 1
v2(avg) = [3;
 4;
 8]
v3(min) = [1;
 2;
 7]
v4(max) = [5;
 6;
 9]

randShuffle example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  randShuffle example
            // ---------------------------------------------------------------------------------------
            // The Core.randShuffle function randomly shuffles the elements in a Mat object. In other words, it can randomly reorder the order of elements in a Mat object.
            // Core.randShuffle randomly reorders elements. Prefer a continuous Mat; shuffling a ROI
            // also rearranges those elements inside the parent Mat.
            //

            // 4x5 matrix
            Mat m1 = new Mat(4, 5, CvType.CV_64FC1);
            m1.put(0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
            Log("m1(original) = " + m1.dump());

            // shuffle
            Core.randShuffle(m1, UnityEngine.Random.value);
            Log("m1(shuffle) = " + m1.dump());

            // submatrix
            Mat m2 = new Mat(m1, new OpenCVForUnity.CoreModule.Rect(1, 1, 3, 2));
            Log("m2(sub-matrix) = " + m2.dump());

            Core.randShuffle(m2, UnityEngine.Random.value);
            Log("m2(sub-matrix) = " + m2.dump());
            Log("m1 = " + m1.dump());
            

Execution Result:

m1(original) = [1, 2, 3, 4, 5;
 6, 7, 8, 9, 10;
 11, 12, 13, 14, 15;
 16, 17, 18, 19, 20]
m1(shuffle) = [4, 12, 6, 18, 10;
 15, 20, 8, 14, 7;
 1, 16, 11, 17, 2;
 5, 3, 9, 13, 19]
m2(sub-matrix) = [20, 8, 14;
 16, 11, 17]
m2(sub-matrix) = [11, 14, 17;
 8, 20, 16]
m1 = [4, 12, 6, 18, 10;
 15, 11, 14, 17, 7;
 1, 8, 20, 16, 2;
 5, 3, 9, 13, 19]

sort example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  sort example
            // ---------------------------------------------------------------------------------------
            // Core.sort sorts each row or each column of a 2D Mat (SORT_EVERY_ROW / SORT_EVERY_COLUMN).
            // Flags combine direction with SORT_ASCENDING or SORT_DESCENDING.
            //

            // 5x5 matrix
            Mat m1 = new Mat(5, 5, CvType.CV_8UC1);
            Core.randu(m1, 0, 25);
            Log("m1 = " + m1.dump());

            Mat dst_mat = new Mat();

            // sort ascending
            Core.sort(m1, dst_mat, Core.SORT_EVERY_ROW | Core.SORT_ASCENDING);
            Log("dst_mat (SORT_EVERY_ROW|SORT_ASCENDING) = " + dst_mat.dump());

            // sort descending
            Core.sort(m1, dst_mat, Core.SORT_EVERY_ROW | Core.SORT_DESCENDING);
            Log("dst_mat (SORT_EVERY_ROW|SORT_DESCENDING) = " + dst_mat.dump());

            // sort ascending
            Core.sort(m1, dst_mat, Core.SORT_EVERY_COLUMN | Core.SORT_ASCENDING);
            Log("dst_mat (SORT_EVERY_COLUMN|SORT_ASCENDING) = " + dst_mat.dump());

            // sort descending
            Core.sort(m1, dst_mat, Core.SORT_EVERY_COLUMN | Core.SORT_DESCENDING);
            Log("dst_mat (SORT_EVERY_COLUMN|SORT_DESCENDING) = " + dst_mat.dump());
            

Execution Result:

m1 = [ 24,  17,  14,   7,  10;
   2,  11,   9,  12,   1;
   6,   0,   8,  16,   6;
   1,  21,  23,   4,   3;
  22,  22,   0,   7,   3]
dst_mat (SORT_EVERY_ROW|SORT_ASCENDING) = [  7,  10,  14,  17,  24;
   1,   2,   9,  11,  12;
   0,   6,   6,   8,  16;
   1,   3,   4,  21,  23;
   0,   3,   7,  22,  22]
dst_mat (SORT_EVERY_ROW|SORT_DESCENDING) = [ 24,  17,  14,  10,   7;
  12,  11,   9,   2,   1;
  16,   8,   6,   6,   0;
  23,  21,   4,   3,   1;
  22,  22,   7,   3,   0]
dst_mat (SORT_EVERY_COLUMN|SORT_ASCENDING) = [  1,   0,   0,   4,   1;
   2,  11,   8,   7,   3;
   6,  17,   9,   7,   3;
  22,  21,  14,  12,   6;
  24,  22,  23,  16,  10]
dst_mat (SORT_EVERY_COLUMN|SORT_DESCENDING) = [ 24,  22,  23,  16,  10;
  22,  21,  14,  12,   6;
   6,  17,   9,   7,   3;
   2,  11,   8,   7,   3;
   1,   0,   0,   4,   1]

comparison example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  comparison example
            // ---------------------------------------------------------------------------------------
            // Core.compare is element-wise; inputs must match in size (and typically depth).
            // True comparisons write 255 to dst; false writes 0 (single-channel 8U result).
            //

            // 3x3 matrix
            Mat m1 = new Mat(3, 3, CvType.CV_64FC1);
            m1.put(0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
            Mat m2 = new Mat(3, 3, CvType.CV_64FC1);
            m2.put(0, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1);

            Log("m1 = " + m1.dump());
            Log("m2 = " + m2.dump());

            Mat dst_mat = new Mat();

            // GT (M1 > M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_GT);
            Log("GT (M1 > M2) = " + dst_mat.dump());

            // GE (M1 >= M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_GE);
            Log("GE (M1 >= M2) = " + dst_mat.dump());

            // EQ (M1 == M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_EQ);
            Log("EQ (M1 == M2) = " + dst_mat.dump());

            // NE (M1 != M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_NE);
            Log("NE (M1 != M2) = " + dst_mat.dump());

            // LE (M1 <= M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_LE);
            Log("LE (M1 <= M2) = " + dst_mat.dump());

            // LT (M1 < M2)
            Core.compare(m1, m2, dst_mat, Core.CMP_LT);
            Log("LT (M1 < M2) = " + dst_mat.dump());
            

Execution Result:

m1 = [1, 2, 3;
 4, 5, 6;
 7, 8, 9]
m2 = [9, 8, 7;
 6, 5, 4;
 3, 2, 1]
GT (M1 > M2) = [  0,   0,   0;
   0,   0, 255;
 255, 255, 255]
GE (M1 >= M2) = [  0,   0,   0;
   0, 255, 255;
 255, 255, 255]
EQ (M1 == M2) = [  0,   0,   0;
   0, 255,   0;
   0,   0,   0]
NE (M1 != M2) = [255, 255, 255;
 255,   0, 255;
 255, 255, 255]
LE (M1 <= M2) = [255, 255, 255;
 255, 255,   0;
   0,   0,   0]
LT (M1 < M2) = [255, 255, 255;
 255,   0,   0;
   0,   0,   0]

get and put example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  get and put example
            // ---------------------------------------------------------------------------------------
            // mat.get() function gets the value of a specific element in a Mat object.
            // mat.put() function sets a new value for a specific element in a Mat object.
            //
            // OpenCVForUnity has several faster and more efficient functions for accessing Mat elements.
            // - Use the MatBufferUtils.CopyFromMat or MatBufferUtils.CopyToMat functions to copy through a data array in one go.
            // - Use the mat.at function to access the element of ​​Mat.
            // - Use the mat.AsSpan function to access the dara memory area of ​​Mat.
            //

            // channels=4 3x3 matrix (RGBA layout: index 0=R, 1=G, 2=B, 3=A)
            Mat m1 = new Mat(3, 3, CvType.CV_8UC4, new Scalar(1, 2, 3, 4));
            Log("m1 = " + m1.dump());

            //
            // Get elements
            //

            // get returns double[] even for CV_8UC4; cast or use mat.at for typed access.
            double[] m1_1_1 = m1.get(1, 1);
            Log("m1[1,1] (use mat.get()) = " + m1_1_1[0] + ", " + m1_1_1[1] + ", " + m1_1_1[2] + ", " + m1_1_1[3]);

            // an even faster, more efficient, non-memory-allocated method using the mat.at function.
            Span<byte> m1_2_2 = m1.at<byte>(2, 2);
            Log("m1[2,2] (use mat.at()) = " + m1_2_2[0] + ", " + m1_2_2[1] + ", " + m1_2_2[2] + ", " + m1_2_2[3]);

            // get an array of all element values.
            byte[] m1_array = new byte[m1.total() * m1.channels()];
            m1.get(0, 0, m1_array);
            string dump_str = "";
            foreach (var i in m1_array)
            {
                dump_str += i + ", ";
            }
            Log("m1_array (use mat.get()) = " + dump_str);

            // a faster and more efficient method using the MatBufferUtils.CopyFromMat function.
            MatBufferUtils.CopyFromMat(m1, m1_array);
            dump_str = "";
            foreach (var i in m1_array)
            {
                dump_str += i + ", ";
            }
            Log("m1_array (use MatBufferUtils.CopyFromMat()) = " + dump_str);

            // an even faster, more efficient, non-memory-allocated method using the mat.AsSpan function.
            Span<byte> m1_span = m1.AsSpan<byte>();
            dump_str = "";
            for (int i = 0; i < m1_span.Length; i++)
            {
                dump_str += m1_span[i] + ", ";
            }
            Log("m1_span (use mat.AsSpan()) = " + dump_str);

            //
            // Put elements
            //

            // put an element value in a matrix.
            Mat m2 = m1.clone();
            m2.put(1, 1, 5, 6, 7, 8);
            Log("m2 (use mat.put()) = " + m2.dump());

            // an even faster, more efficient, non-memory-allocated method using the mat.at function.
            m2.setTo(new Scalar(1, 2, 3, 4));// reset values
            Span<byte> m2_1_1 = m2.at<byte>(1, 1);
            m2_1_1[0] = 5;
            m2_1_1[1] = 6;
            m2_1_1[2] = 7;
            m2_1_1[3] = 8;
            Log("m2 (use mat.at()) = " + m2.dump());

            // put an array of element values in a matrix.
            m2.setTo(new Scalar(1, 2, 3, 4));// reset values
            byte[] m2_arr = new byte[] {
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8,
                5,
                6,
                7,
                8
            };
            m2.put(0, 0, m2_arr);
            Log("m2 (use mat.put()) = " + m2.dump());

            // a faster and more efficient method using the MatBufferUtils.CopyToMat function.
            m2.setTo(new Scalar(1, 2, 3, 4));// reset values
            MatBufferUtils.CopyToMat(m2_arr, m2);
            Log("m2 (use MatBufferUtils.CopyToMat()) = " + m2.dump());

            // an even faster, more efficient, non-memory-allocated method using the mat.AsSpan function.
            m2.setTo(new Scalar(1, 2, 3, 4));// reset values
            Span<byte> m2_span = m2.AsSpan<byte>();
            m2_arr.AsSpan<byte>().CopyTo(m2_span);
            Log("m2 (use mat.AsSpan()) = " + m2.dump());

            // fill element values (setTo method)
            m2.setTo(new Scalar(100, 100, 100, 100));
            Log("m2 (use mat.setTo()) = " + m2.dump());

            //
            // 0D / 1D access (OpenCV 5)
            // Element count is total(); 1D indexes along columns with row fixed at 0 (get(0,i) / put(0,i)).
            // 0D scalar: prefer put(Array.Empty<int>(), value) / get with empty idx; get(0,0)/put(0,0) also work
            // because rows/cols report 1 for a non-empty 0D Mat.
            // AsSpan / MatBufferUtils copy total()*elemSize bytes for any rank (including 0D/1D).
            //
            Mat v = new Mat(new int[] { 3 }, CvType.CV_8UC1);
            v.put(0, 0, 10, 20, 30);
            Log("v = " + v.dump());
            Log("v.get(0,1) = " + v.get(0, 1)[0]);
            Span<byte> vAt1 = v.at<byte>(1);
            Log("v.at(1) = " + vAt1[0]);

            Mat s = new Mat(Array.Empty<int>(), CvType.CV_8UC1, new Scalar(9));
            Log("s = " + s.dump());
            Log("s.get(0,0) = " + s.get(0, 0)[0] + " // also valid for 0D");
            s.put(Array.Empty<int>(), 11); // empty idx = 0D address
            Log("s after put(Array.Empty<int>(), 11) = " + s.dump());
            

Execution Result:

m1 = [  1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4;
   1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4;
   1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4]
m1[1,1] (use mat.get()) = 1, 2, 3, 4
m1[2,2] (use mat.at()) = 1, 2, 3, 4
m1_array (use mat.get()) = 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 
m1_array (use MatBufferUtils.CopyFromMat()) = 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 
m1_span (use mat.AsSpan()) = 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 
m2 (use mat.put()) = [  1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4;
   1,   2,   3,   4,   5,   6,   7,   8,   1,   2,   3,   4;
   1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4]
m2 (use mat.at()) = [  1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4;
   1,   2,   3,   4,   5,   6,   7,   8,   1,   2,   3,   4;
   1,   2,   3,   4,   1,   2,   3,   4,   1,   2,   3,   4]
m2 (use mat.put()) = [  5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8]
m2 (use MatBufferUtils.CopyToMat()) = [  5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8]
m2 (use mat.AsSpan()) = [  5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8;
   5,   6,   7,   8,   5,   6,   7,   8,   5,   6,   7,   8]
m2 (use mat.setTo()) = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100;
 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100;
 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
v = [ 10,  20,  30]
v.get(0,1) = 20
v.at(1) = 20
s = [  9]
s.get(0,0) = 9 // also valid for 0D
s after put(Array.Empty(), 11) = [ 11]

accessing pixel value example

Example Code:


            // ---------------------------------------------------------------------------------------
            //  accessing pixel value example
            // ---------------------------------------------------------------------------------------
            // How access pixel values in an OpenCV Mat (2D image).
            // Pixel channels (e.g. RGBA) are not Mat dims — a color image is still dims==2.
            // - 1. Use get and put method
            // - 2. Use mat.at method
            // - 3. Use MatBufferUtils.CopyFromMat and MatBufferUtils.CopyToMat method
            // - 4. Use mat.AsSpan method
            // - 5. Use pointer access (unsafe)
            //

            // channels=4 512x512 matrix (RGBA color image)
            Mat imgMat = new Mat(512, 512, CvType.CV_8UC4, new Scalar(0, 0, 0, 255));

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            //
            // 1. Use get and put method
            //
            imgMat.setTo(new Scalar(0, 0, 0, 255));

            watch.Start();

            // Per-pixel get/put allocates and crosses the native boundary each iteration (slowest path).
            int rows = imgMat.rows();
            int cols = imgMat.cols();
            for (int i0 = 0; i0 < rows; i0++)
            {
                for (int i1 = 0; i1 < cols; i1++)
                {
                    byte[] p = new byte[4];
                    imgMat.get(i0, i1, p);

                    p[0] = (byte)(p[0] + 127); // R
                    p[1] = (byte)(p[1] + 127); // G
                    p[2] = (byte)(p[2] + 127); // B

                    imgMat.put(i0, i1, p);
                }
            }

            watch.Stop();

            Log("1. Use get and put method. time: " + watch.ElapsedMilliseconds + " ms");

            //
            // 2. Use mat.at method
            //
            imgMat.setTo(new Scalar(0, 0, 0, 255));

            watch.Reset();
            watch.Start();

            rows = imgMat.rows();
            cols = imgMat.cols();
            for (int i0 = 0; i0 < rows; i0++)
            {
                for (int i1 = 0; i1 < cols; i1++)
                {
                    // use the mat.at function to access the element of ​​Mat.
                    Span<byte> p = imgMat.at<byte>(i0, i1);

                    p[0] = (byte)(p[0] + 127); // R
                    p[1] = (byte)(p[1] + 127); // G
                    p[2] = (byte)(p[2] + 127); // B
                }
            }

            watch.Stop();

            Log("2. Use mat.at method. time: " + watch.ElapsedMilliseconds + " ms");

            //
            // 3. Use MatBufferUtils.CopyFromMat and MatBufferUtils.CopyToMat method
            //
            imgMat.setTo(new Scalar(0, 0, 0, 255));

            watch.Reset();
            watch.Start();

            // copies an OpenCV Mat data to a pixel data Array.
            byte[] img_array = new byte[imgMat.total() * imgMat.channels()];
            MatBufferUtils.CopyFromMat(imgMat, img_array);

            long step0 = imgMat.step1(0);
            long step1 = imgMat.step1(1);

            rows = imgMat.rows();
            cols = imgMat.cols();
            for (int i0 = 0; i0 < rows; i0++)
            {
                for (int i1 = 0; i1 < cols; i1++)
                {
                    long p1 = step0 * i0 + step1 * i1;
                    long p2 = p1 + 1;
                    long p3 = p1 + 2;

                    img_array[p1] = (byte)(img_array[p1] + 127); // R
                    img_array[p2] = (byte)(img_array[p2] + 127); // G
                    img_array[p3] = (byte)(img_array[p3] + 127); // B
                }
            }
            // copies a pixel data Array to an OpenCV Mat data.
            MatBufferUtils.CopyToMat(img_array, imgMat);

            watch.Stop();

            Log("3. Use MatBufferUtils.CopyFromMat and MatBufferUtils.CopyToMat method. time: " + watch.ElapsedMilliseconds + " ms");

            //
            // 4. Use mat.AsSpan method
            //
            imgMat.setTo(new Scalar(0, 0, 0, 255));

            watch.Reset();
            watch.Start();

            // use the mat.AsSpan function to access the data memory area of ​​Mat.
            Span<byte> img_span = imgMat.AsSpan<byte>();

            step0 = imgMat.step1(0);
            step1 = imgMat.step1(1);

            rows = imgMat.rows();
            cols = imgMat.cols();
            for (int i0 = 0; i0 < rows; i0++)
            {
                for (int i1 = 0; i1 < cols; i1++)
                {
                    int p1 = (int)(step0 * i0 + step1 * i1);
                    int p2 = p1 + 1;
                    int p3 = p1 + 2;

                    img_span[p1] = (byte)(img_span[p1] + 127); // R
                    img_span[p2] = (byte)(img_span[p2] + 127); // G
                    img_span[p3] = (byte)(img_span[p3] + 127); // B
                }
            }

            watch.Stop();

            Log("4. Use mat.AsSpan method. time: " + watch.ElapsedMilliseconds + " ms");

            //
            // 5. Use pointer access (unsafe)
            //

            imgMat.setTo(new Scalar(0, 0, 0, 255));

            watch.Reset();
            watch.Start();

            step0 = imgMat.step1(0);
            step1 = imgMat.step1(1);
            long ptrVal = imgMat.dataAddr();

            unsafe
            {
                rows = imgMat.rows();
                cols = imgMat.cols();
                for (int i0 = 0; i0 < rows; i0++)
                {
                    for (int i1 = 0; i1 < cols; i1++)
                    {
                        byte* p1 = (byte*)(ptrVal + (step0 * i0) + (step1 * i1));
                        byte* p2 = p1 + 1;
                        byte* p3 = p1 + 2;

                        *p1 = (byte)(*p1 + 127); // R
                        *p2 = (byte)(*p2 + 127); // G
                        *p3 = (byte)(*p3 + 127); // B
                    }
                }
            }

            watch.Stop();

            Log("5. Use pointer access. time: " + watch.ElapsedMilliseconds + " ms");
            

Execution Result:

1. Use get and put method. time: 71 ms
2. Use mat.at method. time: 7 ms
3. Use MatBufferUtils.CopyFromMat and MatBufferUtils.CopyToMat method. time: 1 ms
4. Use mat.AsSpan method. time: 0 ms
5. Use pointer access. time: 0 ms