简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM