【Emgu】一起学EmguCV(二)Image和Matrix的使用

时间:2022-07-23
本文章向大家介绍【Emgu】一起学EmguCV(二)Image和Matrix的使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

  本文链接:https://www.cnblogs.com/bomo/archive/2013/03/28/2986573.html

上一篇简单介绍了EmguCV库的简单配置,并演示了Hello World程序,本篇继续介绍关于Emgu的基本使用

1、关于Image类的使用

  Image<TColor, TDepth>用两个参数定义:Color 和 Depth

例如:创建一个8位的灰度图像

//创建一张灰度图
        Image<Gray, Byte> img1 = new Image<Gray, Byte>(480, 320);
        //创建一张蓝色的图片
        Image<Bgr, Byte> img2 = new Image<Bgr, Byte>(480, 320, new Bgr(255, 0, 0));
        //从文件创建Image
        Image<Bgr, Byte> img3 = new Image<Bgr, Byte>("MyImage.jpg");
        //从Bitmap创建Image
        Bitmap bmp = new Bitmap("MyImage.jpg");
        Image<Bgr, Byte> img4 = new Image<Bgr, Byte>(bmp);

 .Net会自动完成垃圾回收,对于比较大的图片,我们可以使用using关键字在不需要的时候自动对其进行回收

 using (Image<Gray, Single> image = new Image<Gray, Single>(1000, 800))
        {
            //对image操作
        }

获取和设置像素颜色

  有两种方式对图片的像素进行直接操作

Image<Bgr, byte> img = new Image<Bgr, byte>(480, 320, new Bgr(0, 255, 0));

        //直接通过索引访问,速度较慢,返回TColor类型
        Bgr color = img[100, 100];
        img[100, 100] = color;

        //通过Data索引访问,速度快
        //最后一个参数为通道数,例如Bgr图片的 0:蓝色,1:绿色,2:红色,Gray的0:灰度,返回TDepth类型
        Byte blue = img.Data[100, 100, 0];
        Byte green = img.Data[100, 100, 1];
        Byte red = img.Data[100, 100, 2];

 Image<TColor, TDepth>还对操作运算符进行了重载( + - * / )

  Image<Bgr, byte> img1 = new Image<Bgr, byte>(480, 320, new Bgr(255, 0, 0));
        Image<Bgr, byte> img2 = new Image<Bgr, byte>(480, 320, new Bgr(0, 255, 0));

        //img3 == new Image<Bgr, byte>(480, 320, new Bgr(255, 255, 0));
        Image<Bgr, byte> img3 = img1 + img2;

 Image<TColor, TDepth>有一个Not函数,可以让图片反色

  Image<TColor, TDepth>还提供了转换器,可以让我们更方便的编写转换逻辑

  Image<TColor, TDepth>还有一个 ToBitmap() 函数可以转换为Bitmap

    Image<Bgr, byte> img1 = new Image<Bgr, byte>(@"test.jpg");
        Image<Bgr, byte> img2 = img1.Not();
        //下面转换效果与Not()函数相同
        Image<Bgr, Byte> img3 = img1.Convert<byte>(delegate(Byte b) { return (Byte)(255 - b); });
        pictureBox1.Image = img3.ToBitmap();

2、关于Matrix矩阵类的使用

  Martix的使用与Image类似,这里就不阐述了

 Matrix<Single> matrix = new Matrix<Single>(480, 320);

        float f = matrix[100, 100];
        float df = matrix.Data[100, 100];

举例子:

Matrix<Byte> mat1 = new Matrix<byte>(new Size(500, 200));

            for (int i = 0; i < 200; i++)
                for (int j = 0; j < 500; j++)
                    mat1[i, j] = 100;
            imageBox1.Image = mat1.Mat;
            mat1.Save("mei.jpg"); //图片
————————————————