从 blob SQLite 读取二进制图像并使用 OpenCV imdecode 对其进行解码的最佳方法是什么?

What is the best way to read binary image from blob SQLite and decode it using OpenCV imdecode?

我正在使用 C++ 存储和读取 SQLite 数据库中的图像文件,存储工作正常,但我无法使用 imdecode 读取字节并将字节转换为 OpenCV cv::Mat。这是我的代码:

std::vector<cv::Mat> images;
std::vector<string> names;
std::vector<int> ids;

sqlite3 *db;
if (sqlite3_open("fr.db", &db) != SQLITE_OK)
{
    printf("Open database failed\n");
    return 0;
}

sqlite3_stmt *statement;
const char* sql = "SELECT * FROM Friends";
if (sqlite3_prepare_v2(db, sql, strlen(sql), &statement, 0) != SQLITE_OK)
{
    printf("Open database failed\n");
    return 0;
}

int result = 0;
while (true)
{
    result = sqlite3_step(statement);

    if (result == SQLITE_ROW)
    {
        int id = sqlite3_column_int(statement, 0);
        ids.push_back(id);

        int size = sqlite3_column_bytes(statement, 1);
        std::vector<byte> data((byte)sqlite3_column_blob(statement, 1), size);
        images.push_back(cv::imdecode(data, CV_LOAD_IMAGE_COLOR));

        char* name = (char*)sqlite3_column_text(statement, 2);
        names.push_back(name);
    }
    else
    {
        break;
    }
}

问题是 imdecode 不构建 cv::Mat 但它 returns 是空的 .. 提前致谢。

问题出在这一行:

std::vector<byte> data((byte)sqlite3_column_blob(statement, 1), size);

您没有正确构建 vector

您应该使用范围构造函数:

template <class InputIterator>
     vector (InputIterator first, InputIterator last,
             const allocator_type& alloc = allocator_type()); 

然后您的代码将是:

// Get the size of the vector
int size = sqlite3_column_bytes(statement, 1);

// Get the pointer to data
uchar* p = (uchar*)sqlite3_column_blob(statement,1);

// Initialize the vector with the data
vector<uchar> data(p, p+size);