OpenCVSharp入门教程 基础篇②——获得图片像素及数据转换

文章目录

  • 一、获取图片像素
    • 1.1 Get/Set (slow)
    • 1.2 GenericIndexer (reasonably fast)
    • 1.3 TypeSpecificMat (faster)
  • 二、数据转换
    • 2.1 Mat -> System.Drawing.Bitmap
    • 2.2 System.Drawing.Bitmap -> Mat
    • 2.3 Mat -> byte[]
    • 2.4 byte[] -> Mat

一、获取图片像素

1.1 Get/Set (slow)

Mat mat = new Mat("lenna.png", LoadMode.Color);

for (int y = 0; y < mat.Height; y++)
{
    for (int x = 0; x < mat.Width; x++)
    {
        Vec3b color = mat.Get<Vec3b>(y, x);
        byte temp = color.Item0;
        color.Item0 = color.Item2; // B <- R
        color.Item2 = temp;        // R <- B
        mat.Set<Vec3b>(y, x, color);
    }
}

1.2 GenericIndexer (reasonably fast)

Mat mat = new Mat("lenna.png", LoadMode.Color);

var indexer = mat.GetGenericIndexer<Vec3b>();
for (int y = 0; y < mat.Height; y++)
{
    for (int x = 0; x < mat.Width; x++)
    {
        Vec3b color = indexer[y, x];
        byte temp = color.Item0;
        color.Item0 = color.Item2; // B <- R
        color.Item2 = temp;        // R <- B
        indexer[y, x] = color;
    }
}

1.3 TypeSpecificMat (faster)

Mat mat = new Mat("lenna.png", LoadMode.Color);

var mat3 = new Mat<Vec3b>(mat); // cv::Mat_
var indexer = mat3.GetIndexer();

for (int y = 0; y < mat.Height; y++)
{    
    for (int x = 0; x < mat.Width; x++)
    {
        Vec3b color = indexer[y, x];
        byte temp = color.Item0;
        color.Item0 = color.Item2; // B <- R
        color.Item2 = temp;        // R <- B
        indexer[y, x] = color;
    }
}

二、数据转换

2.1 Mat -> System.Drawing.Bitmap

Mat mat = new Mat("foobar.jpg", ImreadModes.Color);

Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);

2.2 System.Drawing.Bitmap -> Mat

Bitmap bitmap = new Bitmap("foobar.jpg");

Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);

2.3 Mat -> byte[]

Mat mat = new Mat("foobar.jpg", ImreadModes.Color);

byte[] bytes1 = mat.ToBytes(".png");

byte[] bytes2;
Cv2.ImEncode(".jpg", mat, out bytes2);

2.4 byte[] -> Mat

byte[] imageData = System.IO.File.ReadAllBytes("foobar.jpg");

Mat colorMat = Mat.FromImageData(imageData, ImreadModes.Color);
Mat grayscaleMat = Mat.FromImageData(imageData, ImreadModes.GrayScale);

Mat alt = Cv2.ImDecode(imageData, ImreadModes.GrayScale);

觉得好,就一键三连呗(点赞+收藏+关注)

你可能感兴趣的:(OpenCVSharp入门教程,OpenCvSharp,OpenCV,c#,数据转换,Mat)