### Install OpenCV on Opensuse Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs OpenCV development packages and clang on Opensuse using zypper. ```bash zypper install opencv-devel clang-devel gcc-c++ ``` -------------------------------- ### Install OpenCV on Ubuntu Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs the OpenCV development package and related libraries on Ubuntu using apt. ```bash apt install libopencv-dev clang libclang-dev ``` -------------------------------- ### Install OpenCV and LLVM on Windows with vcpkg Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs OpenCV and LLVM using vcpkg on Windows. Consider setting VCPKGRS_DYNAMIC to "1" for dynamic builds. ```shell vcpkg install llvm opencv4[contrib,nonfree] ``` -------------------------------- ### Install LLVM on macOS with Homebrew Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs LLVM using Homebrew on macOS, as an alternative if system LLVM is not working. ```shell brew install llvm ``` -------------------------------- ### Install OpenCV on Arch Linux Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs the OpenCV package and additional modules on Arch Linux using pacman. ```bash pacman -S clang qt6-base opencv ``` ```bash pacman -S vtk glew fmt openmpi ``` -------------------------------- ### Check C++ Standard Library Installation Source: https://github.com/twistedfall/opencv-rust/blob/master/TROUBLESHOOTING.md If you encounter a 'limits' file not found error, verify your C++ standard library installation by running clang with specific flags. ```shell clang -E -x c++ - -v ``` -------------------------------- ### Install OpenCV and LLVM on Windows with Chocolatey Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs OpenCV and LLVM using Chocolatey on Windows. Environment variables for linking and include paths may need to be set. ```shell choco install llvm opencv ``` -------------------------------- ### Install OpenCV on macOS with Homebrew Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Installs OpenCV using Homebrew on macOS. Ensure C++ compiler and libclang are available. ```shell brew install opencv ``` -------------------------------- ### Construct Mat objects in opencv-rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Provides examples of creating `Mat` objects, including empty matrices, matrices filled with zeros or a constant value, and matrices created from Rust slices or iterators. ```rust use opencv::core::{Mat, Scalar, Size}; use opencv::prelude::*; fn main() -> opencv::Result<()> { // Empty matrix (default) let empty = Mat::default(); println!("empty rows={}", empty.rows()); // 0 // Allocate a 3×4 f32 matrix filled with zeros let zeros = Mat::zeros(3, 4, f32::opencv_type())?.to_mat()?; println!("zeros size={:?}", zeros.size()?); // Size { width: 4, height: 3 } // Allocate with a constant value (Scalar fills all channels) let ones = Mat::new_rows_cols_with_default(2, 2, f64::opencv_type(), Scalar::all(1.0)?); // From a flat Rust slice (zero-copy borrow) let data: Vec = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let mat = Mat::new_rows_cols_with_data(2, 3, &data)?; println!("mat at (0,2) = {}", mat.at_2d::(0, 2)?); // 3.0 // From a 2D slice-of-slices (copies data) let mat2d = Mat::from_slice_2d(&[[1i32, 2, 3], [4, 5, 6]])?; println!("mat2d rows={} cols={}", mat2d.rows(), mat2d.cols()); // 2 3 // Owned copy of an iterator let it_mat = Mat::from_exact_iter(0i32..6)?; println!("it_mat total={}", it_mat.total()); // 6 Ok(()) } ``` -------------------------------- ### Configure OpenCV Environment Variables on macOS Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Sets environment variables for library paths and linker flags on macOS when using Homebrew's OpenCV installation. ```shell export DYLD_FALLBACK_LIBRARY_PATH="$(xcode-select --print-path)/Toolchains/XcodeDefault.xctoolchain/usr/lib/" export LDFLAGS=-L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/lib ``` -------------------------------- ### Displaying Images and Handling Input with `highgui` in Rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Shows how to create windows, display images, and handle user input like keyboard presses and mouse events. Includes trackbar functionality. Requires an input image file. ```rust use opencv::{highgui, Result}; use opencv::prelude::*; fn main() -> Result<()> { let img = opencv::imgcodecs::imread("photo.jpg", opencv::imgcodecs::IMREAD_COLOR)?; // Create named window and show image highgui::named_window("demo", highgui::WINDOW_AUTOSIZE)?; highgui::imshow("demo", &img)?; // Wait indefinitely for a key press highgui::wait_key(0)?; // Trackbar with callback let mut value = 50i32; highgui::create_trackbar( "threshold", "demo", Some(&mut value), 100, Some(Box::new(|v| println!("trackbar = {v}"))), )?; // Mouse callback highgui::set_mouse_callback( "demo", Some(Box::new(|event, x, y, _flags| { if event == highgui::EVENT_LBUTTONDOWN { println!("clicked at ({x},{y})"); } })), )?; loop { highgui::imshow("demo", &img)?; let key = highgui::wait_key(30)?; if key == 27 { break; } // ESC } highgui::destroy_all_windows()?; Ok(()) } ``` -------------------------------- ### Build Cross-compilation Docker Image Source: https://github.com/twistedfall/opencv-rust/blob/master/INSTALL.md Builds a Docker image for cross-compilation. Ensure qemu-arm and binfmt-misc are set up on the host system. ```shell docker build -t rpi-xcompile -f tools/docker/rpi-xcompile.Dockerfile tools ``` -------------------------------- ### Get OpenCV Type from Rust Type Source: https://github.com/twistedfall/opencv-rust/blob/master/README.md Use the `::opencv_type()` function on Rust types to get their corresponding OpenCV type, equivalent to `CV_MAKETYPE` macros. ```rust let t = u16::opencv_type(); // equivalent to CV_MAKETYPE(CV_16U, 1) let t = Vec2f::opencv_type(); // equivalent to CV_MAKETYPE(CV_32F, 2) ``` -------------------------------- ### Video Capture and Writing with `videoio` in Rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates capturing video from a webcam or file, reading frame properties, and writing video streams to a file. Includes window display and basic loop control. ```rust use opencv::{videoio, highgui, Result}; use opencv::prelude::*; use opencv::core::Mat; fn main() -> Result<()> { // Open default webcam (index 0) let mut cap = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; if !cap.is_opened()? { panic!("cannot open camera"); } // Query properties let fps = cap.get(videoio::CAP_PROP_FPS)?; let width = cap.get(videoio::CAP_PROP_FRAME_WIDTH)? as i32; let height = cap.get(videoio::CAP_PROP_FRAME_HEIGHT)? as i32; println!("{width}×{height} @ {fps}fps"); // Open video file instead let mut file_cap = videoio::VideoCapture::default()?; file_cap.open_file_def("video.mp4")?; // Write output video let fourcc = videoio::VideoWriter::fourcc('m' as i8, 'p' as i8, '4' as i8, 'v' as i8)?; let mut writer = videoio::VideoWriter::new( "out.mp4", fourcc, 30.0, opencv::core::Size::new(width, height), true, )?; highgui::named_window("cam", highgui::WINDOW_AUTOSIZE)?; loop { let mut frame = Mat::default(); if !cap.read(&mut frame)? { break; } if frame.size()?.width > 0 { writer.write(&frame)?; highgui::imshow("cam", &frame)?; } if highgui::wait_key(10)? > 0 { break; } } Ok(()) } ``` -------------------------------- ### Import OpenCV Prelude Source: https://github.com/twistedfall/opencv-rust/blob/master/README.md Import the prelude module from the opencv crate to bring essential traits and types into scope. ```rust use opencv::prelude::*; ``` -------------------------------- ### Mat Views with BoxedRef and BoxedRefMut Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates creating zero-copy views into Mat data using BoxedRef and BoxedRefMut. Shows how to obtain mutable regions and clone owned Mats. ```rust use opencv::core::{Mat, Rect}; use opencv::prelude::*; fn main() -> opencv::Result<()> { let data: Vec = (0..12).map(|x| x as f32).collect(); // BoxedRef: zero-copy view, borrows `data` let mat_ref = Mat::new_rows_cols_with_data(3, 4, &data)?; println!("via ref: {}", mat_ref.at_2d::(1, 2)?); // 6.0 // Cloning the underlying Mat when ownership is needed let owned: Mat = mat_ref.clone_pointee(); drop(mat_ref); // original borrow released // Two non-overlapping mutable ROIs from one Mat let mut canvas = Mat::new_rows_cols_with_default(4, 4, u8::opencv_type(), 0.into())?; let (mut top_left, mut bot_right) = Mat::roi_2_mut( &mut canvas, Rect::new(0, 0, 2, 2), Rect::new(2, 2, 2, 2), )?; *top_left.at_2d_mut::(0, 0)? = 1; *bot_right.at_2d_mut::(0, 0)? = 2; drop((top_left, bot_right)); println!("canvas[0,0]={} canvas[2,2]={}", canvas.at_2d::(0, 0)?, canvas.at_2d::(2, 2)?); // 1 2 Ok(()) } ``` -------------------------------- ### Set DYLD_FALLBACK_LIBRARY_PATH on macOS Source: https://github.com/twistedfall/opencv-rust/blob/master/TROUBLESHOOTING.md On macOS, set DYLD_FALLBACK_LIBRARY_PATH to help the system find libclang.dylib. Adjust the path based on your Xcode installation. ```shell export DYLD_FALLBACK_LIBRARY_PATH="$(xcode-select --print-path)/usr/lib/" ``` ```shell export DYLD_FALLBACK_LIBRARY_PATH="$(xcode-select --print-path)/Toolchains/XcodeDefault.xctoolchain/usr/lib/" ``` -------------------------------- ### Mat Element Access Source: https://context7.com/twistedfall/opencv-rust/llms.txt Provides methods for accessing individual elements or slices of a Mat object. It includes functions for flat indexing, 2D indexing, accessing by Point, retrieving entire rows, and getting the raw data as a typed slice. These methods perform bounds and type checks, returning a Result. ```APIDOC ## `Mat` — element access Typed element access uses `.at::()` (flat index), `.at_2d::(row, col)`, `.at_pt::(Point)`, `.at_3d`, and `.at_nd`. All perform bounds and type checks and return `Result<&T>` / `Result<&mut T>`. ```rust use opencv::core::{Mat, Point}; use opencv::prelude::*; fn main() -> opencv::Result<()> { let mut m = Mat::from_slice_2d(&[[1u8, 2, 3], [4, 5, 6]])?; // Read a single element let v: &u8 = m.at_2d(1, 2)?; println!("m[1,2] = {v}"); // 6 // Write via mutable access *m.at_2d_mut::(0, 0)? = 99; println!("m[0,0] = {}", m.at_2d::(0, 0)?); // 99 // Access by Point let p = Point::new(1, 0); // x=col, y=row println!("at_pt(1,0) = {}", m.at_pt::(p)?); // 2 // Whole row as a slice let row: &[u8] = m.at_row(1)?; println!("row 1 = {row:?}"); // [4, 5, 6] // All data as typed slice (requires continuous mat) let all: &[u8] = m.data_typed()?; println!("all = {all:?}"); // [99, 2, 3, 4, 5, 6] // Iterator: yields (Point, value) pairs for (pt, val) in m.iter::()? { print!("({},{})={val} ", pt.x, pt.y); } Ok(()) } ``` ``` -------------------------------- ### Import OpenCV Prelude Traits Source: https://github.com/twistedfall/opencv-rust/blob/master/TROUBLESHOOTING.md Ensure you import `opencv::prelude::*` to access traits that might otherwise appear missing for specific structs. ```rust use opencv::prelude::*; ``` -------------------------------- ### VecN Fixed-Size Vector Type Source: https://context7.com/twistedfall/opencv-rust/llms.txt Details the `VecN` type, which represents fixed-size vectors and pixel types in Rust, analogous to OpenCV's `cv::Vec`. It supports `Copy`, `Deref` to slices, arithmetic operations, and `DataType`. Examples include constructing vectors, performing element-wise multiplication, calculating cross products, casting element types, and using `VecN` as a `Mat` element type. ```APIDOC ## `VecN` — fixed-size vector / pixel type `VecN` (type aliases: `Vec2f`, `Vec3b`, `Vec4i`, etc.) is the Rust counterpart of OpenCV's `cv::Vec`. It implements `Copy`, `Deref`, arithmetic operators, and `DataType`. ```rust use opencv::core::{VecN, Vec3b, Vec2f, Vec4i}; use opencv::prelude::*; fn main() -> opencv::Result<()> { // Construct let bgr: Vec3b = VecN::from_array([255u8, 128, 0]); println!("B={} G={} R={}", bgr[0], bgr[1], bgr[2]); // Per-element multiply let a = VecN::::from_array([1.0, 2.0, 3.0]); let b = VecN::::from_array([2.0, 3.0, 4.0]); let c = a.mul(b); println!("mul = {:?}", *c); // [2.0, 6.0, 12.0] // Cross product (3D float vecs) let x = VecN::::from_array([1.0, 0.0, 0.0]); let y = VecN::::from_array([0.0, 1.0, 0.0]); let z = x.cross(y); println!("cross = {:?}", *z); // [0.0, 0.0, 1.0] // Cast element type let fi: Vec2f = VecN::from_array([3.7f32, -1.2]); let ii: VecN = fi.to::().unwrap(); println!("cast = {:?}", *ii); // [3, -1] // Use as Mat element type let mat = opencv::core::Mat::from_slice_2d(&[ [VecN::::from_array([1, 2, 3])], [VecN::::from_array([4, 5, 6])], ])?; println!("channels={}", mat.channels()); // 3 Ok(()) } ``` ``` -------------------------------- ### imgcodecs Image Reading and Writing Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates how to use the `imgcodecs` module for reading and writing image files. It covers reading images in color or grayscale, writing images to files (with format inferred from extension), encoding images into memory buffers, and decoding images from memory buffers. ```APIDOC ## `imgcodecs` — reading and writing images ```rust use opencv::{imgcodecs, highgui, Result}; use opencv::prelude::*; fn main() -> Result<()> { // Read image (BGR by default) let img = imgcodecs::imread("photo.jpg", imgcodecs::IMREAD_COLOR)?; if img.empty() { panic!("could not load image"); } println!("loaded {}×{}", img.cols(), img.rows()); // Read as grayscale let gray = imgcodecs::imread("photo.jpg", imgcodecs::IMREAD_GRAYSCALE)?; // Write (format determined by extension) imgcodecs::imwrite_def("output.png", &img)?; // Encode to memory buffer (e.g. JPEG) let mut buf = opencv::core::Vector::::new(); let params = opencv::core::Vector::::new(); imgcodecs::imencode(".jpg", &img, &mut buf, ¶ms)?; println!("encoded {} bytes", buf.len()); // Decode from memory buffer let decoded = imgcodecs::imdecode(&buf, imgcodecs::IMREAD_COLOR)?; println!("decoded {}×{}", decoded.cols(), decoded.rows()); Ok(()) } ``` ``` -------------------------------- ### Image Processing with `imgproc` in Rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates various image processing operations such as color conversion, blurring, edge detection, resizing, and drawing shapes. Requires an input image file. ```rust use opencv::{imgproc, core::{Mat, Size, Scalar}, Result}; use opencv::prelude::*; fn main() -> Result<()> { let src = opencv::imgcodecs::imread("photo.jpg", opencv::imgcodecs::IMREAD_COLOR)?; // Color conversion let mut gray = Mat::default(); imgproc::cvt_color_def(&src, &mut gray, imgproc::COLOR_BGR2GRAY)?; // Gaussian blur let mut blurred = Mat::default(); imgproc::gaussian_blur_def(&gray, &mut blurred, Size::new(5, 5), 0.0)?; // Canny edge detection let mut edges = Mat::default(); imgproc::canny_def(&blurred, &mut edges, 50.0, 150.0)?; // Resize let mut small = Mat::default(); imgproc::resize(&src, &mut small, Size::new(320, 240), 0.0, 0.0, imgproc::INTER_LINEAR)?; // Draw rectangle on image let mut canvas = src.clone(); let rect = opencv::core::Rect::new(10, 10, 100, 80); imgproc::rectangle_def(&mut canvas, rect, Scalar::new(0.0, 255.0, 0.0, 0.0))?; // Draw circle imgproc::circle(&mut canvas, opencv::core::Point::new(160, 120), 40, (0.0, 0.0, 255.0).into(), 2, imgproc::LINE_8, 0)?; // Warp perspective let src_pts = Mat::from_slice(&[ opencv::core::Point2f::new(0.0, 0.0), opencv::core::Point2f::new(100.0, 0.0), opencv::core::Point2f::new(100.0, 100.0), opencv::core::Point2f::new(0.0, 100.0), ])?; let dst_pts = Mat::from_slice(&[ opencv::core::Point2f::new(10.0, 10.0), opencv::core::Point2f::new(90.0, 10.0), opencv::core::Point2f::new(90.0, 90.0), opencv::core::Point2f::new(10.0, 90.0), ])?; let m = imgproc::get_perspective_transform_def(&src_pts, &dst_pts)?; let mut warped = Mat::default(); imgproc::warp_perspective_def(&src, &mut warped, &m, src.size()?)?; Ok(()) } ``` -------------------------------- ### Configure OpenCVProbe Project with CMake Source: https://github.com/twistedfall/opencv-rust/blob/master/cmake/CMakeLists.txt This CMake script configures a project to find and link against the OpenCV library for a Rust executable. It sets the minimum CMake version, names the project, finds the OpenCV package, and adds an executable that uses OpenCV's include directories and libraries. ```cmake cmake_minimum_required(VERSION 3.6) project(OpenCVProbe) find_package(${OCVRS_PACKAGE_NAME} REQUIRED) message("OCVRS_INCLUDE_DIRS:${OpenCV_INCLUDE_DIRS}") message("OCVRS_VERSION:${OpenCV_VERSION}") include_directories(${OpenCV_INCLUDE_DIRS}) add_executable(ocvrs_probe ocvrs_probe.cpp) target_link_libraries(ocvrs_probe ${OpenCV_LIBS}) ``` -------------------------------- ### Version-Conditional Compilation for OpenCV Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates using version-conditional macros like `opencv_branch_5!` and `not_opencv_branch_34!` to write code compatible with different OpenCV versions within the same source file. ```rust use opencv::prelude::*; fn load_classifier() -> opencv::Result<()> { let xml = opencv::core::find_file_def("haarcascades/haarcascade_frontalface_alt.xml")?; // objdetect::CascadeClassifier moved to xobjdetect in OpenCV 5 opencv::opencv_branch_5! { use opencv::xobjdetect::CascadeClassifier; } opencv::not_opencv_branch_5! { use opencv::objdetect::CascadeClassifier; } let _clf = CascadeClassifier::new(&xml)?; // LINE_AA moved from core to imgproc between 3.4 and 4.x let _line_type = opencv::not_opencv_branch_34! { opencv::imgproc::LINE_AA }; let _line_type = opencv::opencv_branch_34! { opencv::core::LINE_AA }; Ok(()) } ``` -------------------------------- ### Reading and Writing Images with `imgcodecs` in Rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Shows how to use the `imgcodecs` module to load images from files into `Mat` objects (in color or grayscale), save `Mat` objects to files, and encode/decode images to/from memory buffers. ```rust use opencv::{imgcodecs, highgui, Result}; use opencv::prelude::*; fn main() -> Result<()> { // Read image (BGR by default) let img = imgcodecs::imread("photo.jpg", imgcodecs::IMREAD_COLOR)?; if img.empty() { panic!("could not load image"); } println!("loaded {}×{}", img.cols(), img.rows()); // Read as grayscale let gray = imgcodecs::imread("photo.jpg", imgcodecs::IMREAD_GRAYSCALE)?; // Write (format determined by extension) imgcodecs::imwrite_def("output.png", &img)?; // Encode to memory buffer (e.g. JPEG) let mut buf = opencv::core::Vector::::new(); let params = opencv::core::Vector::::new(); imgcodecs::imencode(".jpg", &img, &mut buf, ¶ms)?; println!("encoded {} bytes", buf.len()); // Decode from memory buffer let decoded = imgcodecs::imdecode(&buf, imgcodecs::IMREAD_COLOR)?; println!("decoded {}×{}", decoded.cols(), decoded.rows()); Ok(()) } ``` -------------------------------- ### Set OPENCV_LINK_LIBS for VCPKG Source: https://github.com/twistedfall/opencv-rust/blob/master/TROUBLESHOOTING.md When using VCPKG on Windows, add missing linked libraries to the OPENCV_LINK_LIBS environment variable, prepended with '+'. ```shell OPENCV_LINK_LIBS="+user32,gdi32,comdlg32" ``` -------------------------------- ### Append user values to OpenCV build configurations Source: https://github.com/twistedfall/opencv-rust/blob/master/CHANGES.md Use this to append user-defined values to detected OpenCV build configurations, such as include or link paths. ```bash OPENCV_INCLUDE_PATHS=",+" ``` -------------------------------- ### Camera Calibration and Undistortion Source: https://context7.com/twistedfall/opencv-rust/llms.txt Calibrates a camera using a chessboard image and undistorts a new image. Requires a chessboard image. The calibration results (camera matrix and distortion coefficients) are used to undistort an image and save it. ```rust use opencv::{ core::{no_array, Point2f, Point3f, Size, TermCriteria, TermCriteria_EPS, TermCriteria_MAX_ITER, Vector}, imgcodecs, imgproc, prelude::*, Result, }; #[cfg(not(ocvrs_opencv_branch_5))] use opencv::calib3d::{calibrate_camera, find_chessboard_corners_def, draw_chessboard_corners, undistort}; fn main() -> Result<()> { let criteria = TermCriteria { typ: TermCriteria_EPS + TermCriteria_MAX_ITER, max_count: 30, epsilon: 0.001 }; let objp: Vector = Vector::from_iter( (0..42).map(|i| Point3f::new((i % 7) as f32, (i / 7) as f32, 0.0)) ); let img = imgcodecs::imread_def("chessboard.jpg")?; let mut gray = opencv::core::Mat::default(); imgproc::cvt_color_def(&img, &mut gray, imgproc::COLOR_BGR2GRAY)?; let mut corners = Vector::::default(); if find_chessboard_corners_def(&gray, Size::new(7, 6), &mut corners)? { imgproc::corner_sub_pix(&gray, &mut corners, Size::new(11, 11), Size::new(-1, -1), criteria)?; let mut obj_pts = Vector::>::new(); obj_pts.push(objp); let mut img_pts = Vector::>::new(); img_pts.push(corners); let mut camera_matrix = opencv::core::Mat::default(); let mut dist_coeffs = opencv::core::Mat::default(); let (mut rvecs, mut tvecs) = (Vector::::new(), Vector::::new()); calibrate_camera(&obj_pts, &img_pts, gray.size()?, &mut camera_matrix, &mut dist_coeffs, &mut rvecs, &mut tvecs, 0, TermCriteria::new(opencv::core::TermCriteria_Type::COUNT as i32 + opencv::core::TermCriteria_Type::EPS as i32, 30, f64::EPSILON)?); let mut undistorted = opencv::core::Mat::default(); undistort(&img, &mut undistorted, &camera_matrix, &dist_coeffs, &no_array())?; imgcodecs::imwrite_def("undistorted.jpg", &undistorted)?; println!("calibration complete"); } Ok(()) } ``` -------------------------------- ### Manage Mat Ownership with Boxed Trait Source: https://context7.com/twistedfall/opencv-rust/llms.txt Illustrates using the `Boxed` trait to manage heap-allocated C++ objects, specifically `Mat`. Shows how to transfer ownership to a raw pointer and reclaim it. ```rust use opencv::core::Mat; use opencv::prelude::*; use opencv::traits::Boxed; fn main() -> opencv::Result<()> { let mat = Mat::new_rows_cols_with_default(2, 2, f64::opencv_type(), 7.0.into())?; // Transfer ownership to raw pointer (no destructor runs) let raw: *mut std::ffi::c_void = mat.into_raw(); // Reclaim ownership (destructor will run when `mat2` drops) let mat2 = unsafe { Mat::from_raw(raw) }; println!("reclaimed: {}×{}", mat2.rows(), mat2.cols()); // 2×2 Ok(()) } ``` -------------------------------- ### Add opencv Dependency to Cargo.toml Source: https://github.com/twistedfall/opencv-rust/blob/master/README.md Specify the opencv crate version in your Cargo.toml file to include it in your project. ```toml opencv = "0.98.2" ``` -------------------------------- ### Select Specific OpenCV Modules Source: https://github.com/twistedfall/opencv-rust/blob/master/README.md To select a specific set of OpenCV modules, disable default features and provide the required feature set in your Cargo.toml. ```toml opencv = { version = "...", default-features = false, features = ["calib3d", "features2d", "flann"]} ``` -------------------------------- ### Deep Neural Network Inference with ONNX Model Source: https://context7.com/twistedfall/opencv-rust/llms.txt Loads an ONNX model and performs inference on an image. Requires an ONNX model file and an input image. The output is processed to find the class with the highest score. ```rust use opencv::{dnn, core::{Mat, Scalar, Size, Vector}, imgproc, imgcodecs, Result}; use opencv::prelude::*; fn main() -> Result<()> { // Load an ONNX model let mut net = dnn::read_net_from_onnx("model.onnx")?; net.set_preferable_backend(dnn::DNN_BACKEND_OPENCV)?; net.set_preferable_target(dnn::DNN_TARGET_CPU)?; let img = imgcodecs::imread("cat.jpg", imgcodecs::IMREAD_COLOR)?; // Pre-process: resize → float blob [1,3,224,224] let blob = dnn::blob_from_image( &img, 1.0 / 255.0, // scale Size::new(224, 224), // spatial size Scalar::default(), // mean subtraction true, // swap RB channels false, // crop opencv::core::CV_32F, )?; net.set_input_def(&blob)?; // Run forward pass let output = net.forward_def()?; // output is a Mat; find the class with highest score let scores: &[f32] = output.data_typed()?; let (best_class, best_score) = scores .iter() .enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) .unwrap(); println!("class={best_class} score={best_score:.4}"); Ok(()) } ``` -------------------------------- ### Using `VecN` for Pixel Types in Rust Source: https://context7.com/twistedfall/opencv-rust/llms.txt Demonstrates the construction and usage of `VecN` (e.g., `Vec3b`, `Vec2f`) for representing fixed-size vectors and pixel data. Supports arithmetic operations, casting, and use as `Mat` element types. ```rust use opencv::core::{VecN, Vec3b, Vec2f, Vec4i}; use opencv::prelude::*; fn main() -> opencv::Result<()> { // Construct let bgr: Vec3b = VecN::from_array([255u8, 128, 0]); println!("B={} G={} R={}", bgr[0], bgr[1], bgr[2]); // Per-element multiply let a = VecN::::from_array([1.0, 2.0, 3.0]); let b = VecN::::from_array([2.0, 3.0, 4.0]); let c = a.mul(b); println!("mul = {:?}", *c); // [2.0, 6.0, 12.0] // Cross product (3D float vecs) let x = VecN::::from_array([1.0, 0.0, 0.0]); let y = VecN::::from_array([0.0, 1.0, 0.0]); let z = x.cross(y); println!("cross = {:?}", *z); // [0.0, 0.0, 1.0] // Cast element type let fi: Vec2f = VecN::from_array([3.7f32, -1.2]); let ii: VecN = fi.to::().unwrap(); println!("cast = {:?}", *ii); // [3, -1] // Use as Mat element type let mat = opencv::core::Mat::from_slice_2d(&[ [VecN::::from_array([1, 2, 3])], [VecN::::from_array([4, 5, 6])], ])?; println!("channels={}", mat.channels()); // 3 Ok(()) } ```