首页 > 其他分享 >[QT]QSharedMemory读写cv::Mat

[QT]QSharedMemory读写cv::Mat

时间:2024-08-27 13:48:06浏览次数:8  
标签:Mat img mem cols char QSharedMemory data cv

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

 

标签:Mat,img,mem,cols,char,QSharedMemory,data,cv
From: https://www.cnblogs.com/pangcoder66/p/18382555

相关文章