[VB.NET]使用 ColorMatrix 做簡單的影像處理

  • 16992
  • 0
  • 2010-08-02

介紹如何使用 ColorMatrix 做簡單的影像處理,而影像處理的功能為影像彩色轉灰階與影像反向

 

1. 說明

在此文介紹如何使用 ColorMatrix 做簡單的影像處理,而影像處理的功能為影像彩色轉灰階與影像反向。

 

2. 方法

2.1 方法介紹

我們主要使用到

ColorMatrix 類別 : 定義含有 RGBA 空間座標的 5 x 5 矩陣。ImageAttributes 類別的多個方法會使用色彩矩陣來調整影像色彩。

而 ColorMatrix 是 5 x 5 的轉換矩陣,可供影像做線性轉換。而 RGBAW向量是表示為 紅、綠、藍、Alpha和 w,其中 w 永遠為 1。

想要更近一步暸解這部份,可以參考

HOW TO:使用色彩矩陣轉換單一色彩

在影像處理中,透過轉換函數的方式是相當常見的,也就是

新影像 = 轉換函式( 原始影像 )

而 ColorMatrix 我把它視為轉換矩陣,則

新影像 = 原始影像 * 轉換矩陣  ( 其中 * 是矩陣運算 )

 

2.2 程式碼


Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.PictureBoxOrg.Image = Image.FromFile("pic.jpg")
        Gray()
        Negative()
    End Sub

    Sub Gray()
        ' 0.299*R+ 0.587*G + 0.114*B
        Dim bmp As New Drawing.Bitmap(PictureBoxOrg.Image)
        Dim ia As New Drawing.Imaging.ImageAttributes
        Dim cm As New Drawing.Imaging.ColorMatrix(New Single()() _
                        {New Single() {0.299, 0.299, 0.299, 0, 0}, _
                         New Single() {0.587, 0.587, 0.587, 0, 0}, _
                         New Single() {0.114, 0.114, 0.114, 0, 0}, _
                         New Single() {0, 0, 0, 1, 0}, _
                         New Single() {0, 0, 0, 0, 1}})

        ia.SetColorMatrix(cm, Imaging.ColorMatrixFlag.Default, Imaging.ColorAdjustType.Bitmap)
        Dim g As Graphics = Drawing.Graphics.FromImage(bmp)
        g.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, ia)
        PictureBoxGray.Image = bmp
    End Sub

    Sub Negative()
        ' RGB 值 * -1
        Dim bmp As New Drawing.Bitmap(PictureBoxOrg.Image)
        Dim ia As New Drawing.Imaging.ImageAttributes
        Dim cm As New Drawing.Imaging.ColorMatrix(New Single()() _
               {New Single() {-1, 0, 0, 0, 0}, _
                New Single() {0, -1, 0, 0, 0}, _
                New Single() {0, 0, -1, 0, 0}, _
                New Single() {0, 0, 0, 1, 0}, _
                New Single() {1, 1, 1, 1, 1}})

        ia.SetColorMatrix(cm, Imaging.ColorMatrixFlag.Default, Imaging.ColorAdjustType.Bitmap)
        Dim g As Graphics = Drawing.Graphics.FromImage(bmp)
        g.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, ia)
        PictureBoxNegative.Image = bmp
    End Sub
End Class

 

2.3 執行結果

image

 

2.4 範例下載

[VB.NET]ColorMatrix.rar