簡體   English   中英

如何在 C++ 向量中解壓多個值

[英]How do I get multiple values unpacked in C++ vectors

我有這個函數可以從這里為我返回 RGB 格式的顏色

std::vector<cv::Vec3b> colors = find_dominant_colors(matImage, count);

但現在我還希望函數find_dominant_colors生成的圖像返回,以便我可以使用它。 它生成我使用cv::imwrite編寫的三個圖像,但我希望將這三個圖像返回給函數調用,以便在返回時可以直接進一步查看它,而不是為它獲取目錄。

如何在該行代碼中解壓縮多個值,例如獲取圖像和顏色,而不僅僅是顏色。 我必須使用多個向量嗎? 我怎么做 ? 這里使用的向量是一個 opencv 向量,用於從圖像中獲取 RGB 值。

編輯 :

    std::vector<cv::Vec3b> find_dominant_colors(cv::Mat img, int count) {
    const int width = img.cols;
    const int height = img.rows;
    std::vector<cv::Vec3b> colors = get_dominant_colors(root);

    cv::Mat quantized = get_quantized_image(classes, root);
    cv::Mat viewable = get_viewable_image(classes);
    cv::Mat dom = get_dominant_palette(colors);

    cv::imwrite("./classification.png", viewable);
    cv::imwrite("./quantized.png", quantized);
    cv::imwrite("./palette.png", dom);

    return colors;
}


上面的函數將顏色返回到這里

std::vector<cv::Vec3b> colors = find_dominant_colors(matImage, count);

我還希望它返回viewable quantized dom ,我該怎么做?

使用std::tuple

定義find_dominant_colors函數以返回std::tuple<cv::Mat, cv::Mat, cv::Mat, cv::Vec3b> ,並在return語句中執行此操作:

return std::make_tuple(quantized, viewable, dom, colors);

在 C++17 中,您可以使用 結構化綁定以方便的方式處理返回值:

auto [quantized, viewable, dom, colors] = find_dominant_colors(matImage, count);

如果您沒有 C++17,請使用std::tie處理返回的std::tuple

cv::Mat quantized;
cv::Mat viewable;
cv::Mat dom;
cv::Vec3b colors;

std::tie(quantized, viewable, dom, colors) = find_dominant_colors(matImage, count);

或者您可以讓類型推導為您工作,並使用std::get訪問返回的std::tuple的成員:

auto values = find_dominant_colors(matImage, count);
auto quantized = std::get<0>(values);
auto viewable = std::get<1>(values);
auto dom = std::get<2>(values);
auto colors = std::get<3>(values);

如果你有一個功能

std::vector<cv::Vec3b> colors = find_dominant_colors(matImage, count);

現在你想改變函數返回“更多”,那么你可以聲明一個數據結構

struct find_dominant_colors_result {
    std::vector<cv::Vec3b> colors;
    cv::Mat quantized;
    cv::Mat viewable;
    cv::Mat dom;
};

現在調用看起來像這樣:

find_dominant_colors_result x = find_dominant_colors(matImage, count);

更確切地說

auto x = find_dominant_colors(matImage, count);

而您必須將函數修改為

find_dominant_colors_result find_dominant_colors(cv::Mat img, int count) {
    find_dominant_color_result result;
    const int width = img.cols;
    const int height = img.rows;
    result.colors = get_dominant_colors(root);

    result.quantized = get_quantized_image(classes, root);
    result.viewable = get_viewable_image(classes);
    result.dom = get_dominant_palette(result.colors);

    cv::imwrite("./classification.png", result.viewable);
    cv::imwrite("./quantized.png", result.quantized);
    cv::imwrite("./palette.png", result.dom);

    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM