1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-30 15:53:03 +04:00

Implimentation "cv::Mat::forEach"

I propose forEach method for cv::Mat and cv::Mat_.
This is solution for the overhead of MatIterator_<_Tp>.

I runs a test that micro opecode runs all over the pixel of cv::Mat_<cv::Point3_<uint8_t>>.
And this implementation 40% faster than the simple pointer, 80% faster than iterator.
With OpenMP, 70% faster than simple pointer, 95% faster than iterator (Core i7 920).

Above all, code is more readable.

My test code is here.
    https://gist.github.com/kazuki-ma/8285876

Thanks.
This commit is contained in:
Kazuki Matsuda
2014-01-06 01:42:45 +09:00
parent cafcfc4d0f
commit fa292c3d8d
5 changed files with 239 additions and 0 deletions
+49
View File
@@ -649,6 +649,16 @@ static void setValue(SparseMat& M, const int* idx, double value, RNG& rng)
CV_Error(CV_StsUnsupportedFormat, "");
}
template<typename Pixel>
struct InitializerFunctor{
/// Initializer for cv::Mat::forEach test
void operator()(Pixel & pixel, const int * idx) const {
pixel.x = idx[0];
pixel.y = idx[1];
pixel.z = idx[2];
}
};
void Core_ArrayOpTest::run( int /* start_from */)
{
int errcount = 0;
@@ -686,6 +696,45 @@ void Core_ArrayOpTest::run( int /* start_from */)
errcount++;
}
}
// test cv::Mat::forEach
{
const int dims[3] = { 101, 107, 7 };
typedef cv::Point3i Pixel;
cv::Mat a = cv::Mat::zeros(3, dims, CV_32SC3);
InitializerFunctor<Pixel> initializer;
a.forEach<Pixel>(initializer);
uint64 total = 0;
bool error_reported = false;
for (int i0 = 0; i0 < dims[0]; ++i0) {
for (int i1 = 0; i1 < dims[1]; ++i1) {
for (int i2 = 0; i2 < dims[2]; ++i2) {
Pixel& pixel = a.at<Pixel>(i0, i1, i2);
if (pixel.x != i0 || pixel.y != i1 || pixel.z != i2) {
if (!error_reported) {
ts->printf(cvtest::TS::LOG, "forEach is not correct.\n"
"First error detected at (%d, %d, %d).\n", pixel.x, pixel.y, pixel.z);
error_reported = true;
}
errcount++;
}
total += pixel.x;
total += pixel.y;
total += pixel.z;
}
}
}
uint64 total2 = 0;
for (size_t i = 0; i < sizeof(dims) / sizeof(dims[0]); ++i) {
total2 += ((dims[i] - 1) * dims[i] / 2) * dims[0] * dims[1] * dims[2] / dims[i];
}
if (total != total2) {
ts->printf(cvtest::TS::LOG, "forEach is not correct because total is invalid.\n");
errcount++;
}
}
RNG rng;
const int MAX_DIM = 5, MAX_DIM_SZ = 10;