機械学習でC++の代わりのコンパイル言語の『Rust』の開発環境を構築したのでその備忘録。
目次
1.ubuntuでJupyter notebook
2. opencvでカメラを使ってみる
1.ubuntuでJupyter notebook
# rustをubuntuにinstall curl https://sh.rustup.rs -sSf | sh source $HOME/.cargo/env cargo --version ## cargo 1.67.1 # rust & cargo install $ rustup install nightly $ rustup default nightly # Evcxr Jupyter のinstall rustup component add rust-src evcxr_jupyter --install rustup component add rust-src sudo apt install jupyter-notebook cmake build-essential cargo install evcxr_jupyter evcxr_jupyter --install # 起動 jupyter notebook
うまく動いた。
use std::fmt::Debug; pub struct Matrix<T> {pub values: Vec<T>, pub row_size: usize} impl<T: Debug> Matrix<T> { pub fn evcxr_display(&self) { let mut html = String::new(); html.push_str("<table>"); for r in 0..(self.values.len() / self.row_size) { html.push_str("<tr>"); for c in 0..self.row_size { html.push_str("<td>"); html.push_str(&format!("{:?}", self.values[r * self.row_size + c])); html.push_str("</td>"); } html.push_str("</tr>"); } html.push_str("</table>"); println!("EVCXR_BEGIN_CONTENT text/html\n{}\nEVCXR_END_CONTENT", html); } } let m = Matrix {values: vec![1,2,3,4,5,6,7,8,9], row_size: 3};
2. opencvでカメラを使ってみる
opencvを使ったrustのタスクをしてみる
# rustのtaskを作成 # binary で作る cargo new --bin rust-opencv cd rust-opencv
opencvのversionを調べる
googleから「carates.io」にアクセスしてopencvで検索。
最新のversionを確認。Cargo.tomlに追記
Cargo.toml
[package] name = "rust-opencv" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] opencv = "0.77.0"
main.rs
use opencv::{highgui, prelude::*, videoio, Result}; fn main() -> Result<()> { let window = "video capture"; highgui::named_window(window, highgui::WINDOW_AUTOSIZE)?; let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera let opened = videoio::VideoCapture::is_opened(&cam)?; if !opened { panic!("Unable to open default camera!"); } loop { let mut frame = Mat::default(); cam.read(&mut frame)?; if frame.size()?.width > 0 { highgui::imshow(window, &frame)?; } let key = highgui::wait_key(10)?; if key > 0 && key != 255 { break; } } Ok(()) }
## コンパイル $ cargo run #Compiling rust-opencv v0.1.0 (/home/parallels/rust-opencv) # Finished dev [unoptimized + debuginfo] target(s) in 4.24s # Running `target/debug/rust-opencv` #[ WARN:0] global ./modules/videoio/src/cap_gstreamer.cpp (1100) open #OpenCV | GStreamer warning: Cannot query video position: #status=0, #value=-1, duration=-1
動いた。
参考
・opencv-rust・evcxr
・Jupyter で Rust を動かせる