python - Pybind11 默认参数 numpy 数组或 None

标签 python c++ numpy binding pybind11

我正在包装一些 C++ 代码以从 Python 中使用它。我想用一个可以接受 None 的参数调用一个 C++ 函数。值或 numpy.array与另一个输入变量的大小相同。这是示例:

import example

# Let I a numpy array containing a 2D or 3D image
M = I > 0
# Calling the C++ function with no mask
example.fit(I, k, mask=None)
# Calling the C++ function with mask as a Numpy array of the same size of I
example.fit(I, k, mask=M)

如何使用 pybind11 在 C++ 中对其进行编码?我有以下函数签名和代码:
void fit(const py::array_t<float, py::array::c_style | py::array::forcecast> &input, 
         int k,
         const py::array_t<bool, py::array::c_style | py::array::forcecast> &mask)
{
    ...
}

PYBIND11_MODULE(example, m)
{
    m.def("fit", &fit,
        py::arg("input"),
        py::arg("k"),
        py::arg("mask") = nullptr // Don't know what to put here?
    );

非常感谢!

最佳答案

使用 C++17 的 std::optional ,这是一个应该有效的示例。对于早期版本的 C++,你可能需要一个向后移植的 optional.h并实现您自己的 optional_caster类似于 pybind11/stl.h 中的那个.
说你想要这个功能:

def add(a, b=None):
    # Assuming a, b are int.
    if b is None:
        return a
    else:
        return a + b
这是等效的 C++ pybind 实现:
m.def("add",
    [](int a, std::optional<int> b) {
        if (!b.has_value()) {
            return a;
        } else {
            return a + b.value();
        }
    },
    py::arg("a"), py::arg("b") = py::none()
);
在 python 中,可以使用以下命令调用此函数:
add(1)
add(1, 2)
add(1, b=2)
add(1, b=None)
对于 numpy 数组,只需修改 std::optional<int>std::optional<py:array>std::optional<py:array_t<your_custom_type>>在示例中。

关于python - Pybind11 默认参数 numpy 数组或 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59270590/

相关文章:

python - Select_Analysis 工具上的循环(Python 和 ArcGIS 9.3)

c++ - 如何在 OS X Yosemite 上安装 FreeGlut(3.0.0 或 2.8.0)

python - python中的欧拉法

python-3.x - 不支持的格式字符串传递给 numpy.ndarray

python - 在 cygwin 中安装 scipy

python - Django 中的默认外键值

python - 在现有的 python 系统上安装 anaconda?

c++ - C++11 中的别名结构

c++ - EasyBMP c++ 的 RGBApixel 内存问题

python - 图像处理练习和 np.array 索引