[QT]QSharedMemory讀寫cv::Mat

PangCoder發表於2024-08-27

1.寫入共享記憶體

void WriteMat(const char* section,const cv::Mat &img)
{
    QSharedMemory *mem = new QSharedMemory();
    mem->setKey(section);

    int size = img.cols * img.rows *img.channels();

    //cols + rows + channels +data
    //if exist return false
    mem->create(size + 5);
    //attach memory
    if(!mem->isAttached())
        mem->attach();

    mem->lock();

    //m_memory ptr
    char * data = (char * )mem->data();
    //high
    data[0] = (char)((img.cols >> 8) & 0xFF);
    //low
    data[1] = (char)(img.cols & 0xFF);
    //high
    data[2] = (char)((img.rows >> 8) & 0xFF);
    //low
    data[3] = (char)(img.rows & 0xFF);
    //channel
    data[4]=img.channels();
    //image data
    memcpy((void*)(data +5), (void*)img.data, size);

    mem->unlock();
}

2.從共享記憶體中讀取

cv::Mat ReadMat(const char *section)
{
    QSharedMemory *mem =new QSharedMemory();
    mem->setKey(section);

    if(!mem->attach(QSharedMemory::ReadWrite))
        return cv::Mat();

    int size = mem->size();
    if(size == 0)
        return cv::Mat();

    int rows, cols, channels;

    mem->lock();

    const char *data = (const char *)mem->constData();

    cols = (data[0]<<8) | (data[1] &0xFF);
    rows = (data[2]<<8) | (data[3] &0xFF);
    channels = data[4];

    cv::Mat img(rows,cols,CV_MAKETYPE(8U,channels),(void*)(data + 5));

    mem->unlock();
    //memcpy((void*)img.data,(void*)(data +5), cols * rows * channels);
    return img;
}

相關文章