Matrix 是一個 C++11/14 相容 的高階矩陣類別,設計理念來源於 Python 的 NumPy ndarray,並透過 Eigen、OpenCV 與 nlohmann/json 進行整合,方便在 C++ 環境下進行:
- 矩陣運算(與 NumPy 操作對齊)
- 影像資料與矩陣的轉換
- JSON 資料序列化與反序列化
此專案特別適合需要將 Python NumPy 程式碼移植至 C++ 的開發場景,例如嵌入式影像處理、數值計算或跨語言整合。
- Linux (Ubuntu 18.04 以上)
- macOS (10.14 以上)
- Windows (Visual Studio 2017 以上)
- C++11 與 C++14
- Eigen3 (≥ 3.3) — 矩陣運算核心
- OpenCV (≥ 3.0) — 影像資料轉換
- nlohmann/json (≥ 3.0) — JSON 支援
- CMake (≥ 3.10) — 建置系統
sudo apt update
sudo apt install libeigen3-dev libopencv-dev nlohmann-json3-dev cmake g++- 將
matrix.hpp與matrix.cpp放入你的專案目錄,例如:
project/
├─ src/
│ ├─ main.cpp
│ ├─ matrix.cpp
│ └─ matrix.hpp
└─ CMakeLists.txt
- 在你的程式中
#include "matrix.hpp"
cmake_minimum_required(VERSION 3.10)
project(MatrixExample CXX)
find_package(Eigen3 REQUIRED)
find_package(OpenCV REQUIRED)
find_package(nlohmann_json REQUIRED)
add_executable(main main.cpp matrix.cpp)
target_link_libraries(main PRIVATE Eigen3::Eigen ${OpenCV_LIBS} nlohmann_json::nlohmann_json)編譯:
mkdir build && cd build
cmake ..
make#include "matrix.hpp"
#include <iostream>
int main() {
// 建立 2×2 矩陣
Matrix A(2, 2, {1, 2, 3, 4});
Matrix B = Matrix::eye(2); // 單位矩陣
// 基本運算
Matrix C = A + B;
Matrix D = A.matmul(B);
// 顯示結果
std::cout << "A:\n" << A << "\n";
std::cout << "C = A + I:\n" << C << "\n";
std::cout << "D = A × I:\n" << D << "\n";
return 0;
}編譯與執行:
g++ -std=c++14 main.cpp matrix.cpp -o main \
`pkg-config --cflags --libs eigen3 opencv4` \
-lnlohmann_json
./mainC++ Matrix 方法 |
NumPy 對應操作 | 說明 |
|---|---|---|
Matrix(r, c, {...}) |
np.array([...]).reshape(r, c) |
建立矩陣 |
Matrix::eye(n) |
np.eye(n) |
單位矩陣 |
operator+/-/* (Matrix) |
+, -, * (element-wise) |
元素運算 |
matmul() |
np.matmul() / @ |
矩陣乘法 |
operator* / / (scalar) |
*, / (scalar) |
標量運算 |
transpose() |
.T |
轉置 |
reshape() |
.reshape() |
改變形狀 |
inverse() |
np.linalg.inv() |
反矩陣 |
cross() |
np.cross() |
向量外積 |
block() |
arr[r:r+nr, c:c+nc] |
子矩陣 |
replicate() |
np.tile() |
重複矩陣 |
maxCoeff() / minCoeff() |
.max() / .min() |
最大最小值 |
sum() |
.sum() |
總和 |
softmax() |
scipy.special.softmax() |
Softmax |
normalize() |
(x - mean) / std |
正規化 |
stack() |
np.hstack() |
水平拼接 |
vstack() |
np.vstack() |
垂直拼接 |
round() |
np.round() |
四捨五入 |
meanColumnWise() |
.mean(axis=0) |
各列平均 |
row() / col() |
索引存取 | 取出行列 |
setRow() / setCol() |
賦值存取 | 設定行列 |
toEigen() |
- | 轉 Eigen 矩陣 |
toCvMat() |
- | 轉 OpenCV Mat |
toJson() |
- | 轉 JSON |
operator()(r, c) |
arr[r, c] |
元素存取 |
- 在
matrix.hpp中新增方法宣告,例如:
Matrix exp() const;- 在
matrix.cpp中實作:
Matrix Matrix::exp() const {
Matrix result(getRows(), getCols());
result.toEigen() = this->toEigen().array().exp();
return result;
}- 重新編譯專案即可使用:
Matrix A(2, 2, {1, 2, 3, 4});
Matrix B = A.exp(); // 對應 np.exp()-
作者:ChatGPT 4o, 蔡旻勳 (MIN-HSUN, TSAI)
-
授權:MIT License(完整授權條款請見
LICENSE檔案) -
靈感來源:
- Python NumPy
- Eigen
- OpenCV
- nlohmann/json
- 此類別的矩陣儲存為 Row-Major 格式 (
Eigen::RowMajor)。 - 若需高效能運算,建議在 Release 模式編譯(
-O3)。 - 與 NumPy 行為一致的情況下,部分運算採用 Eigen 的懶運算(lazy evaluation)以提升效能。
- 若需與 Python 互通,可搭配 pybind11 將
Matrix封裝回 Python。