1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-25 13:23:02 +04:00
Files
opencv/modules/core/test/test_hasnonzero.cpp
Vadim Pisarevsky bdab54f79e Merge pull request #27757 from vpisarev:matshape_inside_mat
Use MatShape instead of MatSize inside cv::Mat/cv::UMat #27757

**Merge together with https://github.com/opencv/opencv_contrib/pull/3996**
---

This PR continues cv::Mat/cv::UMat refactoring. See #26056, where `MatShape` was introduced. Now it's put inside cv::Mat/cv::UMat instead of a weird `MatSize`. MatSize is now an alias for MatShape:

**before:**

```
struct MatShape { ... };
struct MatSize { ... };

struct Mat {
    ...
    int dims;
    int rows;
    int cols;

    ...

    MatShape shape() const { ... /* constructs MatShape out of MatSize and returns it;
                                    layout is always 'unknown', because we don't store it */ }

    MatSize size; // size is not valid without the parent cv::Mat,
                  // because size.p may point to Mat::rows or to Mat::cols,
                  // depending on the dimensionality, and dims() returns Mat::dims.
    MatStep step; // may allocate memory, depending on the dimensionality.
    ...
};
```

**after:**

```
struct MatShape { ... };
typedef MatShape MatSize; // they are now synonyms

struct Mat {
    ...
    int dims;
    int rows;
    int cols;

    ...

    MatShape shape() const { return size; } // just return the embedded shape (including the proper layout information)

    MatSize size; // size is self-contained data structure that can be used without the parent cv::Mat.
                  // size.dims is now a copy of dims; size.p[*] contains copies of Mat::rows and Mat::cols when dims <= 2.
    MatStep step; // does not allocate extra memory buffers.
    ...
};
```

There are several reasons to do that:

1. the main reason is to be able to store data layout (MatShape::layout) inside each cv::Mat/cv::UMat. This is necessary for the proper shape inference in DNN module. In particular, it's necessary for the next step of DNN inference optimization where we introduce block-layout-optimized convolution and other operations. Later on, we can use layout information to support non-interleaved images (e.g. RRR...GGG...BBB...) or even batches of such images in core/imgproc modules.
2. the other reason is to represent 3D/4D/5D etc. tensors as cv::Mat/cv::UMat instances more conveniently, without extra dynamic memory allocation. Before this patch we allocated some memory buffers dynamically to store shape & steps for more than 2D arrays. Now the whole cv::Mat/cv::UMat header can be stored completely on stack/in a container. Creating another copy of Mat/UMat header is now done more efficiently.
3. the third reason is to introduce the new coding pattern: `dst.create(src.size, <dst_type>);`. The pattern is suitable for most of element-wise (including cloning) and filtering operations. This pattern does not only look crisp and self-documenting, it will also automatically copy shape (including layout) from the source tensor into the destination matrix/tensor.
4. in the future we might add `colorspace` member to MatShape that will allow to distinguish RGB from BGR or NV12. `dst.create(src.size, <dst_type>);` will then copy the colorspace information as well.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
2025-09-15 15:03:34 +03:00

209 lines
7.2 KiB
C++

/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
namespace opencv_test { namespace {
typedef testing::TestWithParam<std::tuple<int, Size> > HasNonZeroAllZeros;
TEST_P(HasNonZeroAllZeros, hasNonZeroAllZeros)
{
const int type = std::get<0>(GetParam());
const Size size = std::get<1>(GetParam());
Mat m = Mat::zeros(size, type);
EXPECT_FALSE(hasNonZero(m));
}
INSTANTIATE_TEST_CASE_P(Core, HasNonZeroAllZeros,
testing::Combine(
testing::Values(CV_8UC1, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32FC1, CV_64FC1),
testing::Values(Size(1, 1), Size(320, 240), Size(127, 113), Size(1, 113))
)
);
typedef testing::TestWithParam<std::tuple<int, Size> > HasNonZeroNegZeros;
TEST_P(HasNonZeroNegZeros, hasNonZeroNegZeros)
{
const int type = std::get<0>(GetParam());
const Size size = std::get<1>(GetParam());
Mat m = Mat(size, type);
m.setTo(Scalar::all(-0.));
EXPECT_FALSE(hasNonZero(m));
}
INSTANTIATE_TEST_CASE_P(Core, HasNonZeroNegZeros,
testing::Combine(
testing::Values(CV_32FC1, CV_64FC1, CV_16FC1, CV_16BFC1),
testing::Values(Size(1, 1), Size(320, 240), Size(127, 113), Size(1, 113))
)
);
typedef testing::TestWithParam<std::tuple<int, Size> > HasNonZeroLimitValues;
TEST_P(HasNonZeroLimitValues, hasNonZeroLimitValues)
{
const int type = std::get<0>(GetParam());
const Size size = std::get<1>(GetParam());
Mat m = Mat(size, type);
m.setTo(Scalar::all(std::numeric_limits<double>::infinity()));
EXPECT_TRUE(hasNonZero(m));
m.setTo(Scalar::all(-std::numeric_limits<double>::infinity()));
EXPECT_TRUE(hasNonZero(m));
m.setTo(Scalar::all(std::numeric_limits<double>::quiet_NaN()));
EXPECT_TRUE(hasNonZero(m));
m.setTo((CV_MAT_DEPTH(type) == CV_64F) ? Scalar::all(std::numeric_limits<double>::epsilon()) : Scalar::all(std::numeric_limits<float>::epsilon()));
EXPECT_TRUE(hasNonZero(m));
m.setTo((CV_MAT_DEPTH(type) == CV_64F) ? Scalar::all(std::numeric_limits<double>::min()) : Scalar::all(std::numeric_limits<float>::min()));
EXPECT_TRUE(hasNonZero(m));
m.setTo((CV_MAT_DEPTH(type) == CV_64F) ? Scalar::all(std::numeric_limits<double>::denorm_min()) : Scalar::all(std::numeric_limits<float>::denorm_min()));
EXPECT_TRUE(hasNonZero(m));
}
INSTANTIATE_TEST_CASE_P(Core, HasNonZeroLimitValues,
testing::Combine(
testing::Values(CV_32FC1, CV_64FC1),
testing::Values(Size(1, 1), Size(320, 240), Size(127, 113), Size(1, 113))
)
);
typedef testing::TestWithParam<std::tuple<int, Size> > HasNonZeroRandom;
TEST_P(HasNonZeroRandom, hasNonZeroRandom)
{
const int type = std::get<0>(GetParam());
const Size size = std::get<1>(GetParam());
RNG& rng = theRNG();
const size_t N = std::min(100, size.area());
for(size_t i = 0 ; i<N ; ++i)
{
const int nz_pos_x = rng.uniform(0, size.width);
const int nz_pos_y = rng.uniform(0, size.height);
Mat m = Mat::zeros(size, type);
Mat nzROI = Mat(m, Rect(nz_pos_x, nz_pos_y, 1, 1));
nzROI.setTo(Scalar::all(1));
EXPECT_TRUE(hasNonZero(m));
}
}
INSTANTIATE_TEST_CASE_P(Core, HasNonZeroRandom,
testing::Combine(
testing::Values(CV_8UC1, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32FC1, CV_64FC1),
testing::Values(Size(1, 1), Size(320, 240), Size(127, 113), Size(1, 113))
)
);
typedef testing::TestWithParam<tuple<int, int, bool> > HasNonZeroNd;
TEST_P(HasNonZeroNd, hasNonZeroNd)
{
const int type = get<0>(GetParam());
const int ndims = get<1>(GetParam());
const bool continuous = get<2>(GetParam());
RNG& rng = theRNG();
const size_t N = 10;
for(size_t i = 0 ; i<N ; ++i)
{
std::vector<size_t> steps(ndims);
std::vector<int> sizes(ndims);
size_t totalBytes = 1;
for(int dim = ndims-1; dim >= 0; --dim)
{
const bool isFirstDim = (dim == 0);
const bool isLastDim = (dim+1 == ndims);
const int length = rng.uniform(1, 64);
steps[dim] = isLastDim ? CV_ELEM_SIZE(type) : sizes[dim+1]*steps[dim+1];
sizes[dim] = (isFirstDim || continuous) ? length : rng.uniform(1, length);
totalBytes *= steps[dim];
}
totalBytes *= sizes[0];
unsigned char magicval = 153;
size_t border = 128;
std::vector<unsigned char> buffer(totalBytes+border*2, magicval);
void* data = buffer.data() + border;
Mat m = Mat(ndims, sizes.data(), type, data, steps.data());
std::vector<Range> nzRange(ndims);
for(int dim = 0; dim < ndims ; ++dim)
{
const int pos = rng.uniform(0, sizes[dim]);
nzRange[dim] = Range(pos, pos+1);
}
Mat nzROI = Mat(m, nzRange.data());
nzROI.setTo(Scalar::all(1));
const int nzCount = countNonZero(m);
EXPECT_EQ((nzCount>0), hasNonZero(m));
for (size_t j = 0; j < border; j++) {
ASSERT_EQ(buffer[j], magicval);
ASSERT_EQ(buffer[border + totalBytes + j], magicval);
}
}
}
INSTANTIATE_TEST_CASE_P(Core, HasNonZeroNd,
testing::Combine(
testing::Values(CV_8UC1),
testing::Values(2, 3),
testing::Values(true, false)
)
);
}} // namespace