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

微笑、不失礼 提交于 2020-01-23 18:28:29

问题


I'm storing and reading image files from SQLite database in C++, the storing is working fine, but I have failed reading and converting the bytes to OpenCV cv::Mat using imdecode. Here is my code:

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;
    }
}

The problem is that the imdecode does not build the cv::Mat but it returns empty one .. Thanks in advance.


回答1:


The problem is in this line:

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

where you are not constructing the vector correctly.

You should use the range constructor:

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

and your code will be then:

// 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);


来源:https://stackoverflow.com/questions/32542853/what-is-the-best-way-to-read-binary-image-from-blob-sqlite-and-decode-it-using-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!