|
| 1 | +#include <convolution.h> |
| 2 | +#include <pybind11/pybind11.h> |
| 3 | +#include <pybind11/numpy.h> |
| 4 | + |
| 5 | +namespace py = pybind11; |
| 6 | + |
| 7 | +void convolve_func(py::buffer image_buffer, py::buffer kernel_buffer, |
| 8 | + py::buffer new_image_buffer) { |
| 9 | + py::buffer_info image_info = image_buffer.request(); |
| 10 | + if (image_info.format != py::format_descriptor<double>::format()) |
| 11 | + throw std::runtime_error("Incompatible format: expected a double array"); |
| 12 | + if (image_info.ndim != 2) |
| 13 | + throw std::runtime_error("Incompatible buffer dimension"); |
| 14 | + py::buffer_info kernel_info = kernel_buffer.request(); |
| 15 | + if (kernel_info.format != py::format_descriptor<double>::format()) |
| 16 | + throw std::runtime_error("Incompatible format: expected a double array"); |
| 17 | + if (kernel_info.ndim != 2) |
| 18 | + throw std::runtime_error("Incompatible buffer dimension"); |
| 19 | + py::buffer_info result_info = new_image_buffer.request(); |
| 20 | + if (result_info.format != py::format_descriptor<double>::format()) |
| 21 | + throw std::runtime_error("Incompatible format: expected a double array"); |
| 22 | + if (result_info.ndim != 2) |
| 23 | + throw std::runtime_error("Incompatible buffer dimension"); |
| 24 | + if (result_info.shape[0] != image_info.shape[0] + kernel_info.shape[0] - 1 || |
| 25 | + result_info.shape[1] != image_info.shape[1] + kernel_info.shape[1] - 1) |
| 26 | + throw std::runtime_error("Incompatible result buffer shape"); |
| 27 | + Matrix image(image_info.shape[0], image_info.shape[1]); |
| 28 | + Matrix kernel(kernel_info.shape[0], kernel_info.shape[1]); |
| 29 | + std::memcpy(image.data(), image_info.ptr, sizeof(double)*image.rows()*image.cols()); |
| 30 | + std::memcpy(kernel.data(), kernel_info.ptr, sizeof(double)*kernel.rows()*kernel.cols()); |
| 31 | + Matrix result = convolve(image, kernel); |
| 32 | + std::memcpy(result_info.ptr, result.data(), sizeof(double)*result.rows()*result.cols()); |
| 33 | +} |
| 34 | + |
| 35 | +PYBIND11_MODULE(convolve, module) { |
| 36 | + module.doc() = "pybind11 wrapper module for convolution.h"; |
| 37 | + module.def("convolve", &convolve_func, "compute convolution of image with kernel"); |
| 38 | +} |
0 commit comments