Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

opencv mat object thread safety

There is some ambiguity about this issue. Some answers here and at stackoverflow say that mat object has some thread safety, while others say that it's not thread safe. Most of those questions about threading are in write context. As in simultaneously modifying mat object. I'm interested in reading different mat objects from different threads. My code is too complex to post here, so I'll do some overview.

Mat objects(basically images) are stored in a Vector. When vector's size reaches a predefined number, I stop adding to the vector and start processing the vector in different threads. So, first mat object in the vector gets assigned to thread 0 (threads are created with c++11 thread), second to thread 1 and so on. No modification to the vector occurs. This is strictly just reading.

Mat processing function is extremely simple, it's just:

Mat& I = image; //image comes from vector
for (int i = 0; i < I.rows; i++){
for (int t = 0; t < I.cols; t++){
    ColorValue = GetColorVal(I.at<Vec3b>(i, t)[0], I.at<Vec3b>(i, t)[1], I.at<Vec3b>(i, t)[2]);
  //do some other stuff here

The problem is results from GetColorVal function is incomplete. It doesn't matter if I use mutex.locks, or limit thread count to 1, it's always incomplete. I'm not modifying anything at all, just reading. It doesn't process the whole image as far as I can tell. If I disable threading, same code gives correct results.

My plan is to at this point, separate image processing code to a smaller app and use tcp or some other process communication library(like nanomsg) to move and process the images. I plan to run 7-8 of these smaller apps.

But before I do all that work, I wanted to be sure that even in read context, opencv mat, is not thread safe.