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

一、获取图片像素

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_<cv::Vec3b>
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);

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

  • 32
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小康师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值