Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Numpy to C++

專案介紹

Matrix 是一個 C++11/14 相容 的高階矩陣類別,設計理念來源於 Python 的 NumPy ndarray,並透過 EigenOpenCVnlohmann/json 進行整合,方便在 C++ 環境下進行:

  • 矩陣運算(與 NumPy 操作對齊)
  • 影像資料與矩陣的轉換
  • JSON 資料序列化與反序列化

此專案特別適合需要將 Python NumPy 程式碼移植至 C++ 的開發場景,例如嵌入式影像處理、數值計算或跨語言整合。

1. 需安裝的套件與環境

支援平台

  • Linux (Ubuntu 18.04 以上)
  • macOS (10.14 以上)
  • Windows (Visual Studio 2017 以上)

支援 C++ 標準

  • C++11C++14

必要套件

  • Eigen3 (≥ 3.3) — 矩陣運算核心
  • OpenCV (≥ 3.0) — 影像資料轉換
  • nlohmann/json (≥ 3.0) — JSON 支援
  • CMake (≥ 3.10) — 建置系統

Ubuntu 安裝範例

sudo apt update
sudo apt install libeigen3-dev libopencv-dev nlohmann-json3-dev cmake g++

2. 如何使用

2.1 將專案加入你的程式

  1. matrix.hppmatrix.cpp 放入你的專案目錄,例如:
project/
├─ src/
│  ├─ main.cpp
│  ├─ matrix.cpp
│  └─ matrix.hpp
└─ CMakeLists.txt
  1. 在你的程式中 #include "matrix.hpp"

2.2 編譯方式 (CMake 範例)

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

2.3 範例程式

#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
./main

3. 目前支援的 Python NumPy 對應操作

C++ 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] 元素存取

4. 如何新增其他 NumPy → C++ 操作

  1. matrix.hpp 中新增方法宣告,例如:
Matrix exp() const;
  1. matrix.cpp 中實作:
Matrix Matrix::exp() const {
    Matrix result(getRows(), getCols());
    result.toEigen() = this->toEigen().array().exp();
    return result;
}
  1. 重新編譯專案即可使用:
Matrix A(2, 2, {1, 2, 3, 4});
Matrix B = A.exp(); // 對應 np.exp()

5. 作者與引用

  • 作者:ChatGPT 4o, 蔡旻勳 (MIN-HSUN, TSAI)

  • 授權:MIT License(完整授權條款請見 LICENSE 檔案)

  • 靈感來源:

    • Python NumPy
    • Eigen
    • OpenCV
    • nlohmann/json

6. 其他說明

  • 此類別的矩陣儲存為 Row-Major 格式 (Eigen::RowMajor)。
  • 若需高效能運算,建議在 Release 模式編譯(-O3)。
  • 與 NumPy 行為一致的情況下,部分運算採用 Eigen 的懶運算(lazy evaluation)以提升效能。
  • 若需與 Python 互通,可搭配 pybind11Matrix 封裝回 Python。

About

Convert Numpy into C++ (C++11/14)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages