Introduce `Mat::from_slice_rows_cols`
MODIFY
src/manual/core/mat.rs
src/manual/core/mat.rs
@@ -169,6 +169,30 @@ impl Mat {
Ok(out)
}
+ /// Create a new `Mat` by copying the data from a single-dimensional slice with custom shape
+ #[inline]
+ pub fn from_slice_rows_cols<T: DataType>(s: &[T], row_count: usize, col_count: usize) -> Result<Self> {
+ if row_count * col_count != s.len() {
+ return Err(Error::new(
+ core::StsUnmatchedSizes,
+ format!(
+ "The length of the slice: {} must match the passed row count: {row_count} and column count: {col_count} exactly",
+ s.len()
+ ),
+ ));
+ }
+ unsafe {
+ Self::new_rows_cols_with_data(
+ row_count_i32(row_count)?,
+ col_count_i32(col_count)?,
+ T::typ(),
+ s.as_ptr() as *mut c_void,
+ core::Mat_AUTO_STEP,
+ )
+ }?
+ .try_clone()
+ }
+
#[inline]
pub fn try_into_typed<T: DataType>(self) -> Result<Mat_<T>>
where

MODIFY
tests/mat.rs
tests/mat.rs
@@ -2,12 +2,10 @@ use std::ffi::c_void;
use matches::assert_matches;
-use opencv::{
- core::{self, MatConstIterator, Point, Rect, Scalar, Size, Vec2b, Vec3d, Vec3f, Vec4w},
- prelude::*,
- types::{VectorOfMat, VectorOfi32},
- Error, Result,
-};
+use opencv::core::{MatConstIterator, Point, Point2d, Rect, Scalar, Size, Vec2b, Vec3d, Vec3f, Vec4w};
+use opencv::prelude::*;
+use opencv::types::{VectorOfMat, VectorOfi32};
+use opencv::{core, Error, Result};
const PIXEL: &[u8] = include_bytes!("pixel.png");
@@ -832,3 +830,49 @@ fn mat_rgb() -> Result<()> {
);
Ok(())
}
+
+#[test]
+fn mat_from_slice() -> Result<()> {
+ let src_u8 = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+ let src_point = [
+ Point2d::new(10.1, 20.2),
+ Point2d::new(30.3, 40.4),
+ Point2d::new(50.5, 60.6),
+ Point2d::new(70.7, 80.8),
+ ];
+
+ {
+ let mat = Mat::from_slice(&src_u8)?;
+ assert_eq!(10, mat.total());
+ assert_eq!(5u8, *mat.at(5)?);
+
+ let mat = Mat::from_slice(&src_point)?;
+ assert_eq!(4, mat.total());
+ assert_eq!(Point2d::new(30.3, 40.4), *mat.at(1)?);
+ }
+
+ {
+ let mat = Mat::from_slice_rows_cols(&src_u8, 2, 5)?;
+ assert_eq!(10, mat.total());
+ assert_eq!(2, mat.rows());
+ assert_eq!(5, mat.cols());
+ assert_eq!(6u8, *mat.at_2d(1, 1)?);
+
+ let mat_res = Mat::from_slice_rows_cols(&src_u8, 3, 3);
+ assert_matches!(
+ mat_res,
+ Err(Error {
+ code: core::StsUnmatchedSizes,
+ ..
+ })
+ );
+
+ let mat = Mat::from_slice_rows_cols(&src_point, 2, 2)?;
+ assert_eq!(4, mat.total());
+ assert_eq!(2, mat.rows());
+ assert_eq!(2, mat.cols());
+ assert_eq!(Point2d::new(50.5, 60.6), *mat.at_2d(1, 0)?);
+ }
+
+ Ok(())
+}

Introduce `Mat::from_slice_rows_cols`