opencvsharp4 彩图和灰度图像素读写和内存结构

代码参考:

https://github.com/VahidN/OpenCVSharp-Samples

调试学习环境:vs2019 c# 控制台;opencvSharp4

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {
            //此处颜色模式是bgr  蓝  绿  蓝
            using (var src = new Mat(new Size(128, 64), MatType.CV_8UC3, new Scalar(255, 0, 0)))
            using (var dst = new Mat())//使用using,可以让变量占的空间更快释放
            {
                Cv2.ImShow("src", src);
                Cv2.WaitKey();
                for (var y = 0; y < src.Height; y++)//64 src.rows 行
                {
                    for (var x = 0; x < src.Width; x++)//128 src.cols 列
                    {
                        var color = src.Get(y, x);
                        var temp = color.Item0;
                        color.Item0 = color.Item2; // B <- R
                        color.Item2 = temp;        // R <- B
                        src.Set(y, x, color);
                    }
                }

                src.CopyTo(dst);

                Cv2.ImShow("windows", dst);
                Cv2.WaitKey();

            }
            //下面这个图为灰度图:
            //调试可发现DataEnd-Data=0x2000=128*64
            using (var src1 = new Mat(new Size(128, 64), MatType.CV_8UC1, new Scalar(128)))
            using (var src2 = new Mat(new Size(64, 128), MatType.CV_8UC1, new Scalar(255)))
            {
                Cv2.ImShow("src1", src1);
                Cv2.ImShow("src2", src2);
                Cv2.WaitKey();
                //这个如果手动关闭src1,会出错
                Cv2.DestroyWindow("src1");

                for (var y = 0; y < src1.Height; y++)
                {
                    for (var x = 0; x < src1.Width; x++)
                    {
                        var color = src1.Get(y, x);
                        src2.Set(x, y, color);
                    }
                }
                Cv2.ImShow("src2-2", src2);
                Cv2.WaitKey();
            }
        }
    }
}

你可能感兴趣的:(c#,opencvSharp4,vs2019)