简体   繁体   English

如何使用 BGR2HSV 和 opencv:highgui::create_trackbar 在 Rust 中使用 OpenCV 实现 HSV slider

[英]How to implement HSV slider with OpenCV using BGR2HSV and opencv:highgui::create_trackbar in Rust

Please bear with me as this is my first post to stack overflow.请耐心等待,因为这是我的第一篇关于堆栈溢出的文章。

I am attempting to learn rust with a fairly elementary background in OpenCV through python.我正在尝试在 OpenCV 到 python 中学习具有相当初级背景的 rust。

In my original python script I could use createTrackbar() pretty easily but when converting to rust I am having trouble understanding how to use the "value", and "on_change" parameters from the Rust OpenCV documentation here在我原来的 python 脚本中,我可以很容易地使用 createTrackbar() 但在转换为 rust 时,我无法理解如何使用 Rust OpenCV 文档中的“value”和“ on_change ”参数

pub fn create_trackbar(
    trackbarname: &str,
    winname: &str,
    value: Option<&mut i32>,
    count: i32,
    on_change: TrackbarCallback
) -> Result<i32>

My end goal is to then use opencv::highgui::get_trackbar_pos to control Hue max and min, saturation max and min, and value max and min like I do in the python example below:我的最终目标是然后使用 opencv::highgui::get_trackbar_pos 来控制色相最大值和最小值、饱和度最大值和最小值以及值最大值和最小值,就像我在下面的 python 示例中所做的那样:

while True:

    cv2.namedWindow("HSV")
    cv2.resizeWindow("HSV",640,480)
    cv2.createTrackbar("HUE MIN","HSV",0,179,empty)
    cv2.createTrackbar("HUE MAX","HSV",0,179,empty)
    cv2.createTrackbar("SAT MIN","HSV",0,255,empty)
    cv2.createTrackbar("SAT MAX","HSV",0,255,empty)
    cv2.createTrackbar("VAL MIN","HSV",0,255,empty)
    cv2.createTrackbar("VAL MAX","HSV",0,255,empty)

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            
            hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            h_min = cv2.getTrackbarPos("HUE MIN","HSV")
            h_max = cv2.getTrackbarPos("HUE MAX","HSV")
            s_min = cv2.getTrackbarPos("SAT MIN","HSV")
            s_max = cv2.getTrackbarPos("SAT MAX","HSV")
            v_min = cv2.getTrackbarPos("VAL MIN","HSV")
            v_max = cv2.getTrackbarPos("VAL MAX","HSV")
        

            lower = np.array([h_min,s_min,v_min])
            upper = np.array([h_max,s_max,v_max])
            mask = cv2.inRange(hsvframe,lower,upper)
            result = cv2.bitwise_and(frame,frame,mask=mask)

            print(lower,upper)

            out.write(mask)
            cv2.imshow('mask',mask)
            pass
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

I understand that trackbar name is going to be a string that I choose myself, winname is the hsv window I created, I know count is 179 as I want 180 values from 0 to 179, but don't really understand what Option and TrackbarCallback are supposed to be put in as.我知道轨迹栏名称将是我自己选择的字符串,winname 是我创建的 hsv window,我知道计数是 179,因为我想要从 0 到 179 的 180 个值,但不太了解 Option 和 TrackbarCallback 是什么应该放在 as.

Here is my code below.下面是我的代码。


use opencv::{ highgui::{self, WINDOW_AUTOSIZE}, imgproc, prelude::*, videoio, Result};

fn run() -> Result<()> {

    let window = "video capture";
    let hsv = "HSV";

    
    highgui::named_window(window, 1)?;
    
    highgui::named_window(hsv, WINDOW_AUTOSIZE)?;
    highgui::create_trackbar("HUE MAX", hsv, )?;
    highgui::create_trackbar("HUE MIN", hsv, )?;

    opencv::opencv_branch_32! {
        let mut cam = videoio::VideoCapture::new_default(0)?; // 0 is the default camera
    }
    opencv::not_opencv_branch_32! {
        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 {
            let mut gray = Mat::default();
            imgproc::cvt_color(&frame, &mut gray, imgproc::COLOR_BGR2HSV, 0)?;
            highgui::imshow(window, &gray)?;
        }
        if highgui::wait_key(10)? > 0 {
            break;
        }
    }
    Ok(())

}

fn main() {

    run().unwrap()

}


As far as I can tell, Option seems to be an arbitrary starting position so I think i32 = 0 could work but I'm not sure, then when going through the TrackbarCallback documentation I'm not sure if I should be putting in the word "pos"据我所知,Option 似乎是一个任意的开始 position 所以我认为 i32 = 0 可以工作但我不确定,然后在浏览TrackbarCallback 文档时我不确定我是否应该输入这个词“位置”

Im sure the answer is rather simple but please understand my exposure is very limited and I am doing my best to learn as much as I can without getting overwhelmed too fast.我确定答案很简单,但请理解我的曝光率非常有限,我正在尽我所能学习尽可能多的知识,而不会太快不知所措。

If you intend to read the value with get_trackbar_pos , then you can put None for both value and on_change .如果您打算使用get_trackbar_pos读取值,那么您可以将None用于valueon_change

In C/C++, value is intended to be a variable in which OpenCV writes the value each time it changes so that you can read it instead of calling get_trackbar_pos .在 C/C++ 中, value旨在成为一个变量,其中 OpenCV 每次更改时写入该值,以便您可以读取它而不是调用get_trackbar_pos Not sure how that translates to Rust since the existence of a mutable reference to it in OpenCV makes it undefined behaviour to read it elsewhere.不确定它是如何转换为 Rust 的,因为在 OpenCV 中存在对它的可变引用使得在其他地方读取它成为未定义的行为。

on_change is intended to be the address of a function that OpenCV will call when the value changes, so that you can process the change immediately. on_change旨在成为一个 function 的地址,当值发生变化时 OpenCV 将调用该地址,以便您可以立即处理更改。 You don't need it if you read the value with get_trackbar_pos .如果您使用get_trackbar_pos读取值,则不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM