我的情况是下一个:我正在开发一个多线程应用程序,其中不同的线程从套接字接收字节形式的图像,将它们存储在 a 中vector<char>
并且应该用它生成 acv::Mat
以便能够进行处理开放式简历。好吧,复杂性主要是因为为了将每个线程的私有数据与其他线程分开,我使用了一个structs 数组,我用每个线程可能需要的所有数据结构声明了它。因此,我还必须声明它的vector<char>
和cv::Mat
内部,一旦向量接收到所有图像字节,我必须找到一种方法在内部适当地“加载它们”cv::Mat
无需创建任何额外的,因为为每个线程保留的内存空间是固定的。
到目前为止我已经尝试过:
struct thread_data { //private data for threads
std::vector<char> buf_img;
Mat img_scene;
Mat img_temp;
//...
thread_data() {
buf_img.reserve(65000), // initialization with enough space
img_scene.create(700,500, CV_8U),
img_temp.create(700,500, CV_8U);
}
};
thread_data *tdata;
// declare array of structs
tdata = (thread_data * ) calloc(nthreads, sizeof(thread_data));
//...
// And the thread function, once received the image:
private_tm->img_temp = cv::Mat(private_tm->buf_img,true).clone(); //from vector to Mat
if( !private_tm->img_temp.data ) {
std::cout<< " --(!) Image could not be read " << std::endl;
private_tm->answer = "error";
}
else {
// decode image and call the function passing the pointer to the struct:
private_tm->img_scene = cv::Mat(cv::imdecode(private_tm->temp,1)).clone();
private_tm->answer = OCV_func((void*)private_tm);
}
收到一张图片后的结果:
> Thread 2:
> ==12142== Invalid write of size 4
> ==12142== at 0x804B869: cv::Mat::release() (mat.hpp:369)
> ==12142== by 0x804EEDD: cv::Mat::operator=(cv::Mat const&) (mat.hpp:287)
> ==12142== by 0x804E8A2: thread_main(void*) (threads.cpp:408)
> ==12142== by 0x45A4D4B: start_thread (pthread_create.c:308)
> ==12142== by 0x46A7DDD: clone (clone.S:130)
> ==12142== Address 0x0 is not stack'd, malloc'd or (recently) free'd
> ==12142==
> ==12142==
> ==12142== Process terminating with default action of signal 11 (SIGSEGV)
> ==12142== Access not within mapped region at address 0x0
> ==12142== at 0x804B869: cv::Mat::release() (mat.hpp:369)
> ==12142== by 0x804EEDD: cv::Mat::operator=(cv::Mat const&) (mat.hpp:287)
> ==12142== by 0x804E8A2: thread_main(void*) (threads.cpp:408)
> ==12142== by 0x45A4D4B: start_thread (pthread_create.c:308)
> ==12142== by 0x46A7DDD: clone (clone.S:130)
我真的需要帮助,因为我觉得可能存在一个我看不到的简单解决方案。
一些研究:
- 我在 OpenCV 文档中的 cv::Mat 声明中搜索了一个可以解决问题的函数,但我没有运气。我找不到一个函数,如果不创建新的 Mat就可以获取图像(来自矢量、char* 或文件)。垫子文档
- 这是一个与我需要的类似的问题(答案非常不令人满意):链接
提前致谢。