影像處理實務

安利自己製作的函式庫

上課是用 C++/CLI,只是我感覺還是用原生 C++ 寫起來比較方便,於是就自己寫了一個函式庫來處理影像。

這個函式庫除了用來繪製邊框的 OutlineRenderer 以外類別的成員函數都沒有 side effect,這樣就可以在不影響原本影像的情況下進行處理。而且都會返回新的影像,這樣就可以很方便的進行鏈式調用,若再配合 auto 自動類型推導的話簡直不要太爽!

簡單演示一下這個函式庫的用法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include "imgProc.hpp"

auto main() -> int {
    auto imgGray = RGBImage::fromFile("photo.bmp").toGray();
    auto mat1 = imgGray.toMatrix();
    
    // 由於這個函式庫的基底是 std::vector,所以可以像在使用 2D Vector 一樣使用它
    for(auto& row : mat1) {
        for(auto& x : row) {
            std::cout << x << " ";
        }
        std::cout << std::endl;
    }

    auto mat2 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for(int i = 0; i <= mat1.width - mat2.width; i++) {
        for(int j = 0; j <= mat1.height - mat2.height; j++) {
            // 切割出一個子矩陣,這個函式庫的 subMatrix 函式會返回一個新的影像
            auto subMat = mat1.subMatrix(i, j, mat2.width, mat2.height);
            if(subMat == mat2) {
                std::cout << "Found at (" << i << ", " << j << ")" << std::endl;
            }
            else {
                mat2 = mat2 + subMat;
            }
        }
    }

    OutlineRenderer renderer;
    renderer.setColor({255, 0, 0})  // 設定邊框顏色為紅色
            .setThickness(2)        // 設定邊框厚度為 2
            .setImage(imgGray)      // 設定要繪製邊框的影像
            .render(); // 繪製邊框
            
    return 0; // 返回程序結束
}

函式庫可以在 GitHub 上找到,文檔網址是 GitHub Pages

更多的用法可以參考這個GitHub。只是有些是使用舊版本的函式庫,等未來有空才會改用最新版本的函式庫重寫。

這個函式庫的設計理念是簡單易用,並且能夠方便的進行鏈式調用。希望大家能夠喜歡!