VISR  0.11.6
Versatile Interactive Scene Renderer
matrix_from_ndarray.hpp
Go to the documentation of this file.
1 /* Copyright Institute of Sound and Vibration Research - All rights reserved */
2 
3 #include <libefl/basic_matrix.hpp>
4 
5 #include <pybind11/pybind11.h>
6 #include <pybind11/numpy.h>
7 
8 namespace visr
9 {
10 
11 namespace python
12 {
13 namespace bindinghelpers
14 {
15 
23 template<typename DataType>
24 efl::BasicMatrix<DataType> matrixFromNdArray( pybind11::array_t<SampleType> const & array, std::size_t alignment = 0 )
25 {
26  if( array.ndim() != 2 )
27  {
28  throw std::invalid_argument( "efl::BasicMatrix from numpy ndarray: Input array must be 2D" );
29  }
30  // Should not happen, because we use the typed array_t template type.
31  if( not array.dtype().is( pybind11::dtype::of<DataType>() ) )
32  {
33  throw std::invalid_argument( "efl::BasicMatrix from numpy ndarray: Input matrix has a different data type (dtype)." );
34  }
35  std::size_t const numRows = static_cast<pybind11::ssize_t>(array.shape()[0]);
36  std::size_t const numCols = static_cast<pybind11::ssize_t>(array.shape()[1]);
37  efl::BasicMatrix<DataType> ret( numRows, numCols, alignment );
38  for( std::size_t rowIdx( 0 ); rowIdx < numRows; ++rowIdx )
39  {
40  for( std::size_t colIdx( 0 ); colIdx < numCols; ++colIdx )
41  {
42  ret( rowIdx, colIdx ) = *static_cast<DataType const *>(array.data( rowIdx, colIdx ));
43  }
44  }
45  return ret;
46 }
47 
48 } // namepace bindinghelpers
49 } // namespace python
50 } // namespace visr
efl::BasicMatrix< DataType > matrixFromNdArray(pybind11::array_t< SampleType > const &array, std::size_t alignment=0)
Definition: matrix_from_ndarray.hpp:24
Definition: options.cpp:10