vb.net 教程 5-16 图像处理之ImageAttributes 类2 颜色矩阵2

来源:互联网 发布:牙签弩淘宝20¥ 编辑:程序博客网 时间:2024/06/14 05:54
上一节讲了原理,本节主要讲颜色矩阵的运用。

首先学习ColorMatrix (颜色矩阵)类
ColorMatrix是一个包含 RGBAW 空间坐标的 5 x 5 矩阵,关于RGBAW这5个分量的含义在上一节《vb.net 教程 5-16 图像处理之ImageAttributes 类1 颜色矩阵1》已经说明了,这里不再累述。

它的构造函数包括
1、ColorMatrix()
2、ColorMatrix(Single()())
属性包括
Item:ColorMatrix 中位于指定的行和列的元素
Matrix00:Single,单精度浮点数。 ColorMatrix 第 0行第 0 列的元素 (注意,同数组,矩阵行列的起始从0开始)
Matrix01:Single,单精度浮点数。ColorMatrix 第 0行第 1 列的元素
……
Matrix44:Single,单精度浮点数。ColorMatrix 第 4行第4 列的元素
Matrix00-Matrix44的位置如下图:

具体在使用颜色矩阵的时候也是两种方法
第一种方法是声明一个ColorMatrix实例,然后使对它的属性Matrix00-Matrix44赋值。
常用的是第二种,定义并初始化一个二位数组,然后用构造函数 ColorMatrix(Single()()) 直接初始化一个Matrix:
        Dim imgMatrixElement()() As Single = {          New Single() {1, 0, 0, 0, 0},          New Single() {0, 0, 0, 0, 0},          New Single() {0, 0, 0, 0, 0},          New Single() {0, 0, 0, 1, 0},          New Single() {0, 0, 0, 0, 0}        }        Dim imgMatrix As New ColorMatrix(imgMatrixElement)
然后使用imageAttributes.SetColorMatrix()方法,为指定类别设置颜色调整矩阵,例如:
imageAttributes.SetColorMatrix(imgMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap)
第一个参数是要进行颜色调整的矩阵
第二个参数是ColorMatrixFlag 枚举,包含:
    AltGrays:仅调整灰色底纹。
    Default:指定所有的颜色值(包括灰色底纹)都由同样的颜色调整矩阵来调整。
    SkipGrays:指定调整所有颜色,但不调整灰色底纹。 灰色底纹是指其红色、绿色和蓝色分量的值都相同的任何颜色。
  通常情况下使用的是 ColorMatrixFlag.Default。
第三个参数是ColorAdjustType 枚举,包括:
    Any:指定的类型的数目。
    Bitmap:Bitmap 对象的颜色调整信息。
    Brush:Brush 对象的颜色调整信息。
    Count:指定的类型的数目。
    Default:自身没有颜色调整信息的所有 GDI+ 对象所使用的颜色调整信息。
    Pen:Pen 对象的颜色调整信息。
    Text:文本的颜色调整信息。
  通常情况下我们对图像的颜色进行调整,使用ColorAdjustType.Bitmap。

以仅保留红色分量为例,看看具体代码,注意:使用代码前,必须 Imports System.Drawing.Imaging
   '矩阵    Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click        Dim imageAttributes As New ImageAttributes()        '仅红色分量        Dim imgMatrixElement()() As Single = {          New Single() {1, 0, 0, 0, 0},          New Single() {0, 0, 0, 0, 0},          New Single() {0, 0, 0, 0, 0},          New Single() {0, 0, 0, 1, 0},          New Single() {0, 0, 0, 0, 0}        }        Dim imgMatrix As New ColorMatrix(imgMatrixElement)        imageAttributes.SetColorMatrix(imgMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap)        Dim destImg As New Bitmap(sourceImg.Width, sourceImg.Height)        Dim g As Graphics = Graphics.FromImage(destImg)        g.DrawImage(sourceImg, New Rectangle(0, 0, sourceImg.Width, sourceImg.Height), 0, 0, sourceImg.Width, sourceImg.Height,                    GraphicsUnit.Pixel, imageAttributes)        picDest.Image = destImg    End Sub

运行效果如下:



由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看vb.net 教程 目录



阅读全文
0 0