Skip to content

Commit 0aa2418

Browse files
committed
Cleanup
1 parent dc5f695 commit 0aa2418

File tree

5 files changed

+86
-129
lines changed

5 files changed

+86
-129
lines changed

examples/create_mask.rs

Lines changed: 52 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
//! # Create Mask
2-
//! Reference: [opencv/samples/cpp/create_mask.cpp](https://github.com/opencv/opencv/blob/4.x/samples/cpp/create_mask.cpp)
3-
4-
use opencv::{
5-
core::{bitwise_and, find_file, CommandLineParser, Point, Scalar, CV_8UC1, CV_8UC3},
6-
highgui::{self, imshow},
7-
imgcodecs::{imread, IMREAD_COLOR},
8-
imgproc,
9-
prelude::*,
10-
};
11-
12-
use std::{
13-
env, process,
14-
sync::{
15-
atomic::{self, AtomicBool},
16-
Arc, Mutex,
17-
},
18-
};
2+
//! Reference: [opencv/samples/cpp/create_mask.cpp](https://github.com/opencv/opencv/blob/4.9.0/samples/cpp/create_mask.cpp)
3+
4+
use std::sync::atomic::{AtomicBool, Ordering};
5+
use std::sync::{Arc, Mutex};
6+
use std::{env, process};
7+
8+
use opencv::core::{bitwise_and, find_file, CommandLineParser, Point, Scalar, Vec3b};
9+
use opencv::highgui::imshow;
10+
use opencv::imgcodecs::{imread, IMREAD_COLOR};
11+
use opencv::prelude::*;
12+
use opencv::{highgui, imgproc, not_opencv_branch_4, opencv_branch_4, Result};
13+
14+
opencv_branch_4! {
15+
use opencv::imgproc::LINE_8;
16+
}
17+
not_opencv_branch_4! {
18+
use opencv::core::LINE_8;
19+
}
1920

2021
const SOURCE_WINDOW: &str = "Source image";
2122

@@ -29,13 +30,13 @@ enum DrawingState {
2930
Resetting,
3031
}
3132

32-
fn main() {
33+
fn main() -> Result<()> {
3334
let args: Vec<String> = env::args().collect();
3435
let (argc, argv) = (args.len() as i32, args.iter().map(|s| s.as_str()).collect::<Vec<&str>>());
3536

36-
let mut parser = CommandLineParser::new(argc, &argv, "{@input | lena.jpg | input image}").unwrap();
37-
parser.about("This program demonstrates using mouse events\n").unwrap();
38-
parser.print_message().unwrap();
37+
let mut parser = CommandLineParser::new(argc, &argv, "{@input | lena.jpg | input image}")?;
38+
parser.about("This program demonstrates using mouse events\n")?;
39+
parser.print_message()?;
3940
println!(
4041
"\n\tleft mouse button - set a point to create mask shape\n\
4142
\tright mouse button - create mask from points\n\
@@ -52,13 +53,13 @@ fn main() {
5253
.unwrap_or_else(|_| panic!("Cannot find input_image: {}", input_image));
5354

5455
let [src, mut next_frame, mut mask, mut final_img]: [Mat; 4];
55-
src = imread(&input_image_path, IMREAD_COLOR).unwrap();
56+
src = imread(&input_image_path, IMREAD_COLOR)?;
5657
if src.empty() {
5758
eprintln!("Error opening image: {}", input_image);
5859
process::exit(-1);
5960
}
6061

61-
highgui::named_window(SOURCE_WINDOW, highgui::WINDOW_AUTOSIZE).unwrap();
62+
highgui::named_window(SOURCE_WINDOW, highgui::WINDOW_AUTOSIZE)?;
6263
let mouse_event_data = (highgui::MouseEventTypes::EVENT_MOUSEWHEEL, 0, 0, 0);
6364
let (mouse_event_data, should_handle_mouse_event) = (Arc::new(Mutex::new(mouse_event_data)), Arc::new(AtomicBool::new(false)));
6465

@@ -71,28 +72,28 @@ fn main() {
7172
if let Ok(mut mouse_data) = mouse_data.lock() {
7273
*mouse_data = (mouse_event_from_i32(event), x, y, flags);
7374
}
74-
should_handle_mouse_event.store(true, atomic::Ordering::Relaxed);
75+
should_handle_mouse_event.store(true, Ordering::Relaxed);
7576
}
7677
};
7778
highgui::set_mouse_callback(SOURCE_WINDOW, Some(Box::new(mouse_event_dispatcher))).expect("Cannot set mouse callback");
7879

79-
highgui::imshow(SOURCE_WINDOW, &src).unwrap();
80+
imshow(SOURCE_WINDOW, &src)?;
8081

8182
let (mut marker_points, mut drawing_state) = (Vec::<Point>::new(), DrawingState::Init);
8283

83-
next_frame = Mat::zeros_size(src.size().unwrap(), CV_8UC3).unwrap().to_mat().unwrap();
84+
next_frame = Mat::zeros_size(src.size()?, Vec3b::opencv_type())?.to_mat()?;
8485

8586
loop {
8687
// Press Esc to exit
87-
if highgui::wait_key(10).unwrap() == 27 {
88-
break;
88+
if highgui::wait_key(10)? == 27 {
89+
break Ok(());
8990
}
9091

9192
let (mouse_event, x, y, _) = {
92-
if !should_handle_mouse_event.load(atomic::Ordering::Relaxed) {
93+
if !should_handle_mouse_event.load(Ordering::Relaxed) {
9394
continue;
9495
} else {
95-
should_handle_mouse_event.store(false, atomic::Ordering::Relaxed);
96+
should_handle_mouse_event.store(false, Ordering::Relaxed);
9697

9798
if let Ok(mouse_event_data) = mouse_event_data.lock() {
9899
*mouse_event_data
@@ -102,7 +103,7 @@ fn main() {
102103
}
103104
};
104105

105-
drawing_state = self::state_transform(drawing_state, mouse_event);
106+
drawing_state = state_transform(drawing_state, mouse_event);
106107

107108
match drawing_state {
108109
DrawingState::Init | DrawingState::DrawingMarkerPointFinished => { /* do nothing */ }
@@ -112,16 +113,7 @@ fn main() {
112113
}
113114

114115
let point = Point::new(x, y);
115-
imgproc::circle(
116-
&mut next_frame,
117-
point,
118-
2,
119-
Scalar::new(0., 0., 255., 0.),
120-
-1,
121-
imgproc::LINE_8,
122-
0,
123-
)
124-
.unwrap();
116+
imgproc::circle(&mut next_frame, point, 2, Scalar::new(0., 0., 255., 0.), -1, LINE_8, 0)?;
125117
marker_points.push(point);
126118

127119
if marker_points.len() > 1 {
@@ -131,60 +123,50 @@ fn main() {
131123
point,
132124
Scalar::new(0., 0., 255., 0.),
133125
2,
134-
imgproc::LINE_8,
126+
LINE_8,
135127
0,
136-
)
137-
.unwrap();
128+
)?;
138129
}
139130

140-
imshow(SOURCE_WINDOW, &next_frame).unwrap();
131+
imshow(SOURCE_WINDOW, &next_frame)?;
141132
}
142133
DrawingState::DrawingMask => {
143134
if !marker_points.is_empty() {
144135
next_frame = src.clone();
145136

146137
imgproc::polylines(
147138
&mut next_frame,
148-
&Mat::from_slice(marker_points.as_slice()).unwrap(),
139+
&Mat::from_slice(marker_points.as_slice())?,
149140
true,
150141
Scalar::new(0., 0., 0., 0.),
151142
2,
152-
imgproc::LINE_8,
143+
LINE_8,
153144
0,
154-
)
155-
.unwrap();
145+
)?;
156146

157-
imshow(SOURCE_WINDOW, &next_frame).unwrap();
147+
imshow(SOURCE_WINDOW, &next_frame)?;
158148
}
159149
}
160150
DrawingState::DrawingMaskFinished => {
161151
if !marker_points.is_empty() {
162-
final_img = Mat::zeros_size(src.size().unwrap(), CV_8UC3).unwrap().to_mat().unwrap();
163-
mask = Mat::zeros_size(src.size().unwrap(), CV_8UC1).unwrap().to_mat().unwrap();
164-
165-
imgproc::fill_poly(
166-
&mut mask,
167-
&Mat::from_slice(marker_points.as_slice()).unwrap(),
168-
Scalar::new(255., 255., 255., 255.),
169-
imgproc::LINE_8,
170-
0,
171-
Point::default(),
172-
)
173-
.unwrap();
152+
final_img = Mat::zeros_size(src.size()?, Vec3b::opencv_type())?.to_mat()?;
153+
mask = Mat::zeros_size(src.size()?, u8::opencv_type())?.to_mat()?;
154+
155+
imgproc::fill_poly_def(&mut mask, &Mat::from_slice(marker_points.as_slice())?, Scalar::all(255.))?;
174156

175-
bitwise_and(&src, &src, &mut final_img, &mask).unwrap();
157+
bitwise_and(&src, &src, &mut final_img, &mask)?;
176158

177-
imshow("Mask", &mask).unwrap();
178-
imshow("Result", &final_img).unwrap();
179-
imshow(SOURCE_WINDOW, &next_frame).unwrap();
159+
imshow("Mask", &mask)?;
160+
imshow("Result", &final_img)?;
161+
imshow(SOURCE_WINDOW, &next_frame)?;
180162
}
181163
}
182164
DrawingState::Resetting => {
183165
if !marker_points.is_empty() {
184166
marker_points.clear();
185167
next_frame = src.clone();
186168

187-
imshow(SOURCE_WINDOW, &next_frame).unwrap();
169+
imshow(SOURCE_WINDOW, &next_frame)?;
188170
}
189171
}
190172
}
@@ -196,9 +178,9 @@ fn main() {
196178
/// # Panics
197179
///
198180
/// Panics if the argument less than 0 or greater than 11.
199-
fn mouse_event_from_i32(value: i32) -> opencv::highgui::MouseEventTypes {
200-
(value.gt(&(opencv::highgui::MouseEventTypes::EVENT_MOUSEHWHEEL as i32/* 11 */))
201-
|| (value.lt(&(opencv::highgui::MouseEventTypes::EVENT_MOUSEMOVE as i32/* 0 */))))
181+
fn mouse_event_from_i32(value: i32) -> highgui::MouseEventTypes {
182+
(value.gt(&(highgui::MouseEventTypes::EVENT_MOUSEHWHEEL as i32/* 11 */))
183+
|| (value.lt(&(highgui::MouseEventTypes::EVENT_MOUSEMOVE as i32/* 0 */))))
202184
.then(|| panic!("Invalid cv::highgui::MouseEventTypes value: {}", value));
203185

204186
// Safe because of the previous check

examples/video_facedetect.rs

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
use std::thread;
22
use std::time::Duration;
33

4+
use opencv::core::{Rect, Size, Vector};
45
use opencv::prelude::*;
5-
use opencv::{core, highgui, imgproc, objdetect, types, videoio, Result};
6+
use opencv::{core, highgui, imgproc, objdetect, videoio, Result};
67

78
fn main() -> Result<()> {
8-
let window = "video capture";
9-
highgui::named_window_def(window)?;
10-
let (xml, mut cam) = {
11-
(
12-
core::find_file_def("haarcascades/haarcascade_frontalface_alt.xml")?,
13-
videoio::VideoCapture::new(0, videoio::CAP_ANY)?, // 0 is the default camera
14-
)
15-
};
16-
let opened = videoio::VideoCapture::is_opened(&cam)?;
17-
if !opened {
9+
const WINDOW: &str = "video capture";
10+
highgui::named_window_def(WINDOW)?;
11+
let xml = core::find_file_def("haarcascades/haarcascade_frontalface_alt.xml")?;
12+
let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera
13+
if !cam.is_opened()? {
1814
panic!("Unable to open default camera!");
1915
}
2016
let mut face = objdetect::CascadeClassifier::new(&xml)?;
@@ -28,31 +24,24 @@ fn main() -> Result<()> {
2824
let mut gray = Mat::default();
2925
imgproc::cvt_color_def(&frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
3026
let mut reduced = Mat::default();
31-
imgproc::resize(
32-
&gray,
33-
&mut reduced,
34-
core::Size { width: 0, height: 0 },
35-
0.25f64,
36-
0.25f64,
37-
imgproc::INTER_LINEAR,
38-
)?;
39-
let mut faces = types::VectorOfRect::new();
27+
imgproc::resize(&gray, &mut reduced, Size::new(0, 0), 0.25, 0.25, imgproc::INTER_LINEAR)?;
28+
let mut faces = Vector::new();
4029
face.detect_multi_scale(
4130
&reduced,
4231
&mut faces,
4332
1.1,
4433
2,
4534
objdetect::CASCADE_SCALE_IMAGE,
46-
core::Size { width: 30, height: 30 },
47-
core::Size { width: 0, height: 0 },
35+
Size::new(30, 30),
36+
Size::new(0, 0),
4837
)?;
4938
println!("faces: {}", faces.len());
5039
for face in faces {
5140
println!("face {face:?}");
52-
let scaled_face = core::Rect::new(face.x * 4, face.y * 4, face.width * 4, face.height * 4);
41+
let scaled_face = Rect::new(face.x * 4, face.y * 4, face.width * 4, face.height * 4);
5342
imgproc::rectangle_def(&mut frame, scaled_face, (0, 255, 0).into())?;
5443
}
55-
highgui::imshow(window, &frame)?;
44+
highgui::imshow(WINDOW, &frame)?;
5645
if highgui::wait_key(10)? > 0 {
5746
break;
5847
}

examples/video_features.rs

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,25 @@
1+
use opencv::core::Vector;
12
use opencv::prelude::*;
2-
use opencv::{core, features2d, highgui, imgproc, videoio, Result};
3+
use opencv::{features2d, highgui, imgproc, videoio, Result};
34

45
fn main() -> Result<()> {
56
let window = "video capture";
67
highgui::named_window(window, 1)?;
78
let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera
8-
let opened = videoio::VideoCapture::is_opened(&cam)?;
9-
if !opened {
9+
if !cam.is_opened()? {
1010
panic!("Unable to open default camera!");
1111
}
1212
let mut orb = features2d::ORB::create_def()?;
1313
loop {
1414
let mut frame = Mat::default();
1515
cam.read(&mut frame)?;
16-
if frame.size()?.width > 0 {
16+
if frame.cols() > 0 {
1717
let mut gray = Mat::default();
18-
imgproc::cvt_color(&frame, &mut gray, imgproc::COLOR_BGR2GRAY, 0)?;
19-
let mut kps = opencv::types::VectorOfKeyPoint::new();
20-
let mask = Mat::default();
21-
orb.detect(&gray, &mut kps, &mask)?;
18+
imgproc::cvt_color_def(&frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
19+
let mut kps = Vector::new();
20+
orb.detect_def(&gray, &mut kps)?;
2221
let mut display = Mat::default();
23-
opencv::opencv_branch_4! {
24-
let default_draw_matches_flags = features2d::DrawMatchesFlags::DEFAULT;
25-
}
26-
opencv::not_opencv_branch_4! {
27-
let default_draw_matches_flags = features2d::DrawMatchesFlags_DEFAULT;
28-
}
29-
features2d::draw_keypoints(
30-
&gray,
31-
&kps,
32-
&mut display,
33-
core::Scalar::all(-1f64),
34-
default_draw_matches_flags,
35-
)?;
22+
features2d::draw_keypoints_def(&gray, &kps, &mut display)?;
3623
highgui::imshow(window, &display)?;
3724
}
3825
if highgui::wait_key(10)? > 0 {

examples/video_to_gray.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
use opencv::{highgui, imgproc, prelude::*, videoio, Result};
1+
use opencv::prelude::*;
2+
use opencv::{highgui, imgproc, videoio, Result};
23

34
fn main() -> Result<()> {
45
let window = "video capture";
56
highgui::named_window(window, 1)?;
67
let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera
7-
let opened = videoio::VideoCapture::is_opened(&cam)?;
8-
if !opened {
8+
if !cam.is_opened()? {
99
panic!("Unable to open default camera!");
1010
}
1111
loop {
1212
let mut frame = Mat::default();
1313
cam.read(&mut frame)?;
1414
if frame.size()?.width > 0 {
1515
let mut gray = Mat::default();
16-
imgproc::cvt_color(&frame, &mut gray, imgproc::COLOR_BGR2GRAY, 0)?;
16+
imgproc::cvt_color_def(&frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
1717
highgui::imshow(window, &gray)?;
1818
}
1919
if highgui::wait_key(10)? > 0 {

tests/features2d.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,21 @@ fn orb_bruteforce_match() -> Result<()> {
2727
let mut orb = features2d::ORB::create_def()?;
2828
let mut kp_a = Vector::new();
2929
let mut des_a = Mat::default();
30-
orb.detect_and_compute(&img_a, &Mat::default(), &mut kp_a, &mut des_a, false)?;
30+
orb.detect_and_compute_def(&img_a, &Mat::default(), &mut kp_a, &mut des_a)?;
3131

3232
let mut kp_b = Vector::new();
3333
let mut des_b = Mat::default();
34-
orb.detect_and_compute(&img_b, &Mat::default(), &mut kp_b, &mut des_b, false)?;
34+
orb.detect_and_compute_def(&img_b, &Mat::default(), &mut kp_b, &mut des_b)?;
3535

36-
let size = 290;
37-
assert_eq!(size, kp_a.len());
38-
assert_eq!(Size::new(32, size as i32), des_a.size()?);
39-
assert_eq!(size, kp_b.len());
40-
assert_eq!(Size::new(32, size as i32), des_b.size()?);
36+
assert_eq!(kp_a.len(), kp_b.len());
37+
assert_eq!(des_a.size()?, des_b.size()?);
38+
assert_eq!(290, kp_a.len());
39+
assert_eq!(Size::new(32, 290), des_a.size()?);
4140

42-
let bf_matcher = features2d::BFMatcher::create(NORM_HAMMING, true).unwrap();
41+
let bf_matcher = features2d::BFMatcher::create(NORM_HAMMING, true)?;
4342

44-
let mut matches = opencv::types::VectorOfDMatch::new();
45-
bf_matcher.train_match(&des_a, &des_b, &mut matches, &no_array()).unwrap();
43+
let mut matches = Vector::new();
44+
bf_matcher.train_match(&des_a, &des_b, &mut matches, &no_array())?;
4645

4746
assert_ne!(matches.len(), 0); // expected many matches since images are equal
4847
Ok(())

0 commit comments

Comments
 (0)