You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenCV(C++)中高效拼接两个cv::String类型vector?

Efficiently Concatenate cv::String Vectors from Multiple Directories in OpenCV

Got it, let's tackle this problem. You're using cv::glob to pull filenames from single directories, but now need to handle a vector of directories and combine all resulting filenames into one efficient std::vector<cv::String>. Here's a clean, performant way to do it:

Key Steps for Efficiency

The biggest win here is avoiding repeated reallocations of your final vector. We'll precompute the total number of files first, then reserve space upfront before collecting all filenames.

  1. Calculate total file count (no storage yet)
    Use cv::glob with the GLOB_COUNT flag to quickly get the number of files in each directory without storing the actual filenames. This is lightweight and fast.
  2. Reserve space in the final vector
    Once you know the total number of files, reserve that exact space to eliminate costly reallocations as you add elements.
  3. Collect and concatenate all filenames
    Iterate through each directory again, pull the filenames, and append them to the pre-reserved vector in one go per directory.

Full Code Example

#include <opencv2/core.hpp>
#include <vector>
#include <algorithm>

std::vector<cv::String> concatenateFilesFromDirectories(const std::vector<cv::String>& directories) {
    std::vector<cv::String> allFiles;
    size_t totalFileCount = 0;

    // Step 1: Get total number of files across all directories
    for (const auto& dir : directories) {
        size_t dirFileCount;
        // Use GLOB_COUNT to fetch only the count, not filenames
        cv::glob(dir + "/*", dirFileCount, cv::GlobFlags::GLOB_COUNT);
        totalFileCount += dirFileCount;
    }

    // Reserve space to avoid repeated reallocations
    allFiles.reserve(totalFileCount);

    // Step 2: Collect all filenames and append to the main vector
    for (const auto& dir : directories) {
        std::vector<cv::String> dirFiles;
        cv::glob(dir + "/*", dirFiles);
        // Insert all files from this directory in a single operation
        allFiles.insert(allFiles.end(), dirFiles.begin(), dirFiles.end());
    }

    return allFiles;
}

Notes for Customization

  • Filter by file type: If you only want specific extensions (e.g., JPGs), modify the glob pattern to dir + "/*.jpg" instead of dir + "/*".
  • Handle hidden files: Add cv::GlobFlags::GLOB_HIDDEN to the cv::glob call if you need to include hidden files.
  • Alternative for smaller datasets: If you're working with a tiny number of directories/files, you can skip the pre-count step and just use insert directly—but pre-reserving is always better for performance with larger datasets.

内容的提问来源于stack exchange,提问作者sixfeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:19:57