如何在C++向量中解压缩多个值

How do I get multiple values unpacked in C++ vectors

本文关键字:解压缩 向量 C++      更新时间:2023-10-16

我有这个函数,可以从这里为我返回 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;
}