From bf830d892d5100e0ea6aacdc98ab66cc9312cacf Mon Sep 17 00:00:00 2001 From: pctablet505 <55033230+pctablet505@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:01:25 +0530 Subject: [PATCH] ptcloud: validate input size, setters, and ROI continuity in RgbdNormals - Check points3d_ori.rows == rows and points3d_ori.cols == cols (plus non-empty valid row step) in RgbdNormalsImpl::apply() before cache() and output creation so mismatched inputs throw without touching preallocated output buffers. - Validate positive dimensions in setRows() and setCols() (and >= 2 for SRI in create(), setRows(), setCols(), and cache() to prevent the cols/2 - 1 underflow and zero-denominator division on 1xN / Nx1 grids). - Stage non-packed (ROI / padded-step) outputs and overlapping CrossProduct buffers through a continuous temporary in apply() and copy back into the caller's OutputArray, normalizing 1-D or transposed OutputArray wrappers via reshape(0, rows) while preserving buffer aliasing. - Clone non-packed or overlapping 1-channel depth inputs for LINEMOD (whose computeImpl() steps rows by cols), skip the inner loop early when cols <= 2 * r + 1, and widen pixel-count multiplications to size_t in FALS and SRI. - Add parameterized NormalsInputSize tests covering mismatched sizes, setter validation, 1-D wrappers, overlapping/in-place buffers, cross- depth 4-channel ROIs, non-continuous Mat/UMat/padded-step outputs, and LINEMOD 1-channel depth ROIs across CV_16U, CV_32F, and CV_64F. --- modules/ptcloud/src/normal.cpp | 108 ++++- modules/ptcloud/test/test_normal.cpp | 587 +++++++++++++++++++++++++++ 2 files changed, 682 insertions(+), 13 deletions(-) diff --git a/modules/ptcloud/src/normal.cpp b/modules/ptcloud/src/normal.cpp index 0be55f3d8f..3d940e145f 100644 --- a/modules/ptcloud/src/normal.cpp +++ b/modules/ptcloud/src/normal.cpp @@ -3,10 +3,36 @@ // of this distribution and at http://opencv.org/license.html #include "precomp.hpp" +#include +#include namespace cv { +static bool isPacked2D(const Mat& m) +{ + return m.dims == 2 && m.step[1] == m.elemSize() && + (m.rows <= 1 || m.step[0] == static_cast(m.cols) * m.elemSize()); +} + +static bool hasValidRowStep(const Mat& m) +{ + return m.dims == 2 && m.step[1] == m.elemSize() && + (m.rows <= 1 || m.step[0] >= static_cast(m.cols) * m.elemSize()); +} + +static bool byteSpansOverlap(const Mat& a, const Mat& b) +{ + if (a.empty() || b.empty()) + return false; + CV_Assert(a.dims <= 2 && b.dims <= 2); + const size_t aSpan = static_cast(a.rows - 1) * a.step[0] + static_cast(a.cols) * a.elemSize(); + const size_t bSpan = static_cast(b.rows - 1) * b.step[0] + static_cast(b.cols) * b.elemSize(); + const std::uintptr_t a0 = reinterpret_cast(a.data); + const std::uintptr_t b0 = reinterpret_cast(b.data); + return a0 <= b0 ? (b0 - a0) < aSpan : (a0 - b0) < bSpan; +} + /** Just compute the norm of a vector * @param vec a vector of size 3 and any type T * @return @@ -34,7 +60,7 @@ Mat_ computeRadius(const Mat& points) // Compute the Size size(points.cols, points.rows); Mat_ r(size); - if (points.isContinuous()) + if (points.isContinuous() && isPacked2D(points)) size = Size(points.cols * points.rows, 1); for (int y = 0; y < size.height; ++y) { @@ -195,6 +221,7 @@ public: } virtual void setRows(int val) CV_OVERRIDE { + CV_CheckGT(val, 0, "Invalid number of rows for RgbdNormals"); rows = val; cacheIsDirty = true; } virtual int getCols() const CV_OVERRIDE @@ -203,6 +230,7 @@ public: } virtual void setCols(int val) CV_OVERRIDE { + CV_CheckGT(val, 0, "Invalid number of cols for RgbdNormals"); cols = val; cacheIsDirty = true; } virtual int getWindowSize() const CV_OVERRIDE @@ -261,6 +289,10 @@ public: CV_Error(Error::StsInternal, "Unknown normal computer algorithm"); } + CV_CheckEQ(points3d_ori.rows, rows, "Invalid input height for RgbdNormals"); + CV_CheckEQ(points3d_ori.cols, cols, "Invalid input width for RgbdNormals"); + CV_Assert(!points3d_ori.empty() && hasValidRowStep(points3d_ori)); + // Initialize the pimpl cache(); @@ -277,28 +309,53 @@ public: // Get the normals normals_out.create(points3d_ori.size(), CV_MAKETYPE(dtype, 4)); - if (points3d_ori.empty()) - return; Mat normals = normals_out.getMat(); + // Normalize 1-D / transposed OutputArray wrappers (e.g. std::vector, OutputArray(ptr, n)) + // to the exact 2-D (rows, cols) shape while sharing the caller's underlying buffer. + if (normals.dims != 2 || normals.rows != rows || normals.cols != cols) + { + const size_t nElems = static_cast(rows) * static_cast(cols); + CV_Assert(normals.isContinuous() && normals.total() == nElems); + CV_Assert(nElems <= static_cast(INT_MAX) / static_cast(normals.channels())); + normals = normals.reshape(0, rows); + } + CV_Assert(hasValidRowStep(normals)); + + // FALS and SRI index normals linearly as a rows*cols block; stage non-packed + // (and overlapping CrossProduct) outputs through a continuous temporary. + const bool copyOut = !isPacked2D(normals) || + (method == RGBD_NORMALS_METHOD_CROSS_PRODUCT && byteSpansOverlap(points3d, normals)); + Mat normalsBuf = copyOut + ? Mat(points3d_ori.size(), CV_MAKETYPE(dtype, 4)) + : normals; + if ((method == RGBD_NORMALS_METHOD_FALS) || (method == RGBD_NORMALS_METHOD_SRI)) { // Compute the distance to the points Mat radius = computeRadius(points3d); - compute(radius, normals); + compute(radius, normalsBuf); } else if (method == RGBD_NORMALS_METHOD_LINEMOD) { - compute(points3d_ori, normals); + // LINEMOD::computeImpl() indexes 1-channel depth rows by this->cols. + Mat linemodIn = (points3d_ori.channels() == 1 && + (!isPacked2D(points3d_ori) || byteSpansOverlap(points3d_ori, normalsBuf))) + ? points3d_ori.clone() + : points3d_ori; + compute(linemodIn, normalsBuf); } else if (method == RGBD_NORMALS_METHOD_CROSS_PRODUCT) { - compute(points3d, normals); + compute(points3d, normalsBuf); } else { CV_Error(Error::StsInternal, "Unknown normal computer algorithm"); } + + if (copyOut) + normalsBuf.copyTo(normals); } int rows, cols; @@ -352,7 +409,7 @@ public: Mat_ M(this->rows, this->cols); Mat33T VVt; const Vec3T* vec = V_[0]; - Vec9T* M_ptr = M[0], * M_ptr_end = M_ptr + this->rows * this->cols; + Vec9T* M_ptr = M[0], * M_ptr_end = M_ptr + static_cast(this->rows) * static_cast(this->cols); for (; M_ptr != M_ptr_end; ++vec, ++M_ptr) { VVt = (*vec) * vec->t(); @@ -365,7 +422,7 @@ public: Mat33T M_inv; M_inv_.create(this->rows, this->cols); Vec9T* M_inv_ptr = M_inv_[0]; - for (M_ptr = &M(0); M_ptr != M_ptr_end; ++M_inv_ptr, ++M_ptr) + for (M_ptr = M[0]; M_ptr != M_ptr_end; ++M_inv_ptr, ++M_ptr) { // We have a semi-definite matrix invert(Mat33T(M_ptr->val), M_inv, DECOMP_CHOLESKY); @@ -381,10 +438,11 @@ public: */ virtual void compute(const Mat& r, Mat& normals) const CV_OVERRIDE { + CV_Assert(isPacked2D(r) && isPacked2D(normals)); // Compute B Mat_ B(this->rows, this->cols); - const T* row_r = r.ptr < T >(0), * row_r_end = row_r + this->rows * this->cols; + const T* row_r = r.ptr < T >(0), * row_r_end = row_r + static_cast(this->rows) * static_cast(this->cols); const Vec3T* row_V = V_[0]; Vec3T* row_B = B[0]; for (; row_r != row_r_end; ++row_r, ++row_B, ++row_V) @@ -521,6 +579,7 @@ public: template Mat computeImpl(const Mat_& depthIn, Mat& normals) const { + CV_Assert(isPacked2D(depthIn)); const int r = 5; // used to be 7 const int sample_step = r; const int square_size = ((2 * r / sample_step) + 1); @@ -556,6 +615,8 @@ public: //TODO: fixit, difference threshold should not depend on input type difference_threshold *= (ContainerDepth)(std::is_same::value ? 1000.0 : 1.0); normals.setTo(std::numeric_limits::quiet_NaN()); + if (this->cols <= 2 * r + 1) + return normals; for (int y = r; y < this->rows - r - 1; ++y) { const DepthDepth* p_line = reinterpret_cast(depthIn.ptr(y, r)); @@ -634,6 +695,20 @@ public: theta_step_(0) { } + virtual void setRows(int val) CV_OVERRIDE + { + CV_CheckGE(val, 2, "SRI requires at least 2 rows"); + this->rows = val; + this->cacheIsDirty = true; + } + + virtual void setCols(int val) CV_OVERRIDE + { + CV_CheckGE(val, 2, "SRI requires at least 2 cols"); + this->cols = val; + this->cacheIsDirty = true; + } + /** Compute cached data */ virtual void cache() const CV_OVERRIDE @@ -641,6 +716,9 @@ public: if (!this->cacheIsDirty) return; + CV_CheckGE(this->rows, 2, "SRI requires at least 2 rows"); + CV_CheckGE(this->cols, 2, "SRI requires at least 2 cols"); + Mat_ cos_theta, sin_theta, cos_phi, sin_phi; computeThetaPhi(this->rows, this->cols, this->K, cos_theta, sin_theta, cos_phi, sin_phi); @@ -652,11 +730,12 @@ public: float min_theta = (float)std::asin(sin_theta(0, 0)), max_theta = (float)std::asin(sin_theta(0, this->cols - 1)); float min_phi = (float)std::asin(sin_phi(0, this->cols / 2 - 1)), max_phi = (float)std::asin(sin_phi(this->rows - 1, this->cols / 2 - 1)); - std::vector points3d(this->cols * this->rows); + std::vector points3d(static_cast(this->cols) * static_cast(this->rows)); R_hat_.create(this->rows, this->cols); phi_step_ = float(max_phi - min_phi) / (this->rows - 1); theta_step_ = float(max_theta - min_theta) / (this->cols - 1); - for (int phi_int = 0, k = 0; phi_int < this->rows; ++phi_int) + size_t k = 0; + for (int phi_int = 0; phi_int < this->rows; ++phi_int) { float phi = min_phi + phi_int * phi_step_; float phi_sin = std::sin(phi), phi_cos = std::cos(phi); @@ -723,6 +802,7 @@ public: */ virtual void compute(const Mat& in, Mat& normals_out) const CV_OVERRIDE { + CV_Assert(isPacked2D(in) && isPacked2D(normals_out)); const Mat_& r_non_interp = in; // Interpolate the radial image to make derivatives meaningful @@ -741,7 +821,7 @@ public: // Fill the result matrix Mat_ normals(this->rows, this->cols); - const T* r_theta_ptr = r_theta[0], * r_theta_ptr_end = r_theta_ptr + this->rows * this->cols; + const T* r_theta_ptr = r_theta[0], * r_theta_ptr_end = r_theta_ptr + static_cast(this->rows) * static_cast(this->cols); const T* r_phi_ptr = r_phi[0]; const Mat33T* R = reinterpret_cast(R_hat_[0]); const T* r_ptr = r[0]; @@ -768,7 +848,7 @@ public: remap(normals, normals_out, invxy_, invfxy_, INTER_LINEAR); normal = normals_out.ptr(0); - Vec4T* normal_end = normal + this->rows * this->cols; + Vec4T* normal_end = normal + static_cast(this->rows) * static_cast(this->cols); for (; normal != normal_end; ++normal) signNormal((*normal)[0], (*normal)[1], (*normal)[2], *normal); } @@ -897,6 +977,8 @@ Ptr RgbdNormals::create(int rows, int cols, int depth, InputArray K } case RGBD_NORMALS_METHOD_SRI: { + CV_CheckGE(rows, 2, "SRI requires at least 2 rows"); + CV_CheckGE(cols, 2, "SRI requires at least 2 cols"); if (depth == CV_32F) ptr = makePtr >(rows, cols, windowSize, mK); else diff --git a/modules/ptcloud/test/test_normal.cpp b/modules/ptcloud/test/test_normal.cpp index fff4e02379..70cfec99e0 100644 --- a/modules/ptcloud/test/test_normal.cpp +++ b/modules/ptcloud/test/test_normal.cpp @@ -636,6 +636,593 @@ INSTANTIATE_TEST_CASE_P(RGBD_Normals, RenderedNormals, ::testing::Combine(::test NormalComputerThresholds { RgbdNormals::RGBD_NORMALS_METHOD_CROSS_PRODUCT, { 57.9832, 2531}}), ::testing::Values(true, false))); +const Scalar kSentinelVal(11.0, 22.0, 33.0, 44.0); + +template +void expectNormalsExactT(const Mat& expected, const Mat& actual, const char* label) +{ + if (expected.size() != actual.size()) + { + ADD_FAILURE() << label << " size mismatch: expected " << expected.size() + << ", actual " << actual.size(); + return; + } + if (expected.type() != actual.type()) + { + ADD_FAILURE() << label << " type mismatch: expected " << expected.type() + << ", actual " << actual.type(); + return; + } + const int ch = expected.channels(); + for (int y = 0; y < expected.rows; ++y) + { + const T* ep = expected.ptr(y); + const T* ap = actual.ptr(y); + for (int i = 0; i < expected.cols * ch; ++i) + { + if (cvIsNaN(ep[i]) || cvIsNaN(ap[i])) + { + if (!(cvIsNaN(ep[i]) && cvIsNaN(ap[i]))) + { + ADD_FAILURE() << label << " NaN mismatch at row=" << y << " idx=" << i + << " expected=" << ep[i] << " actual=" << ap[i]; + return; + } + } + else if (ep[i] != ap[i]) + { + ADD_FAILURE() << label << " value mismatch at row=" << y << " idx=" << i + << " expected=" << ep[i] << " actual=" << ap[i]; + return; + } + } + } +} + +void expectNormalsExact(const Mat& expected, const Mat& actual, const char* label) +{ + if (expected.depth() == CV_32F) + expectNormalsExactT(expected, actual, label); + else if (expected.depth() == CV_64F) + expectNormalsExactT(expected, actual, label); + else + ADD_FAILURE() << label << " unsupported depth: " << expected.depth(); +} + +template +void expectBorderSentinelT(const Mat& canvas, const Rect& roi, const Vec& sentinel, const char* label) +{ + if (canvas.dims != 2 || canvas.channels() != 4 || + roi.x < 0 || roi.y < 0 || roi.width < 0 || roi.height < 0 || + roi.x + roi.width > canvas.cols || roi.y + roi.height > canvas.rows) + { + ADD_FAILURE() << label << " invalid canvas/roi shape: dims=" << canvas.dims + << " ch=" << canvas.channels() << " size=" << canvas.size() << " roi=" << roi; + return; + } + for (int y = 0; y < canvas.rows; ++y) + { + const Vec* row = canvas.ptr>(y); + for (int x = 0; x < canvas.cols; ++x) + { + if (x >= roi.x && x < roi.x + roi.width && y >= roi.y && y < roi.y + roi.height) + continue; + if (row[x] != sentinel) + { + ADD_FAILURE() << label << " wrote outside ROI at (" << x << ", " << y + << "): expected=" << sentinel << " actual=" << row[x]; + return; + } + } + } +} + +void expectBorderSentinel(const Mat& canvas, const Rect& roi, const char* label) +{ + if (canvas.depth() == CV_32F) + { + expectBorderSentinelT(canvas, roi, + Vec4f(float(kSentinelVal[0]), float(kSentinelVal[1]), float(kSentinelVal[2]), float(kSentinelVal[3])), + label); + } + else if (canvas.depth() == CV_64F) + { + expectBorderSentinelT(canvas, roi, + Vec4d(kSentinelVal[0], kSentinelVal[1], kSentinelVal[2], kSentinelVal[3]), + label); + } + else + { + ADD_FAILURE() << label << " unsupported depth: " << canvas.depth(); + } +} + +template +int countFiniteUnitNormalsT(const Mat& m) +{ + int count = 0; + for (int y = 0; y < m.rows; ++y) + { + const Vec* row = m.ptr>(y); + for (int x = 0; x < m.cols; ++x) + { + const Vec& v = row[x]; + if (cvIsNaN(v[0]) || cvIsNaN(v[1]) || cvIsNaN(v[2]) || + cvIsInf(v[0]) || cvIsInf(v[1]) || cvIsInf(v[2])) + continue; + const double x0 = double(v[0]), y0 = double(v[1]), z0 = double(v[2]); + const double sq = x0 * x0 + y0 * y0 + z0 * z0; + if (std::abs(sq - 1.0) < 1e-4 && v[3] == T(0)) + ++count; + } + } + return count; +} + +int countFiniteUnitNormals(const Mat& m) +{ + if (m.dims != 2 || m.channels() != 4) + return -1; + if (m.depth() == CV_32F) + return countFiniteUnitNormalsT(m); + if (m.depth() == CV_64F) + return countFiniteUnitNormalsT(m); + return -1; +} + +template +void expectOutsideRectMatchesT(const Mat& before, const Mat& after, const Rect& skip, const char* label) +{ + if (before.size() != after.size() || before.type() != after.type()) + { + ADD_FAILURE() << label << " canvas size/type changed"; + return; + } + const int ch = before.channels(); + for (int y = 0; y < before.rows; ++y) + { + const T* bp = before.ptr(y); + const T* ap = after.ptr(y); + for (int x = 0; x < before.cols; ++x) + { + if (x >= skip.x && x < skip.x + skip.width && y >= skip.y && y < skip.y + skip.height) + continue; + for (int c = 0; c < ch; ++c) + { + const int idx = x * ch + c; + if (cvIsNaN(bp[idx]) || cvIsNaN(ap[idx])) + { + if (!(cvIsNaN(bp[idx]) && cvIsNaN(ap[idx]))) + { + ADD_FAILURE() << label << " corrupted NaN outside ROI at (" << x << ", " << y << ")"; + return; + } + } + else if (bp[idx] != ap[idx]) + { + ADD_FAILURE() << label << " modified pixel outside ROI at (" << x << ", " << y << ")"; + return; + } + } + } + } +} + +void expectOutsideRectMatches(const Mat& before, const Mat& after, const Rect& skip, const char* label) +{ + if (before.depth() == CV_32F) + expectOutsideRectMatchesT(before, after, skip, label); + else if (before.depth() == CV_64F) + expectOutsideRectMatchesT(before, after, skip, label); + else + ADD_FAILURE() << label << " unsupported depth: " << before.depth(); +} + +typedef ::testing::TestWithParam> NormalsInputSize; + +TEST_P(NormalsInputSize, rejects_mismatched_input_size) +{ + const int depth = std::get<0>(GetParam()); + const RgbdNormals::RgbdNormalsMethod method = static_cast(int(std::get<1>(GetParam()))); + const int cfgRows = 48, cfgCols = 64; + const int type4 = CV_MAKETYPE(depth, 4); + Mat intr(Matx33d(262.5, 0.0, 31.5, 0.0, 262.5, 23.5, 0.0, 0.0, 1.0)); + + auto makePoints4 = [&](int r, int c) -> Mat { + if (r == 0 || c == 0) + return Mat(r, c, type4); + Mat depth32(r, c, CV_32FC1); + theRNG().fill(depth32, RNG::UNIFORM, 1.5, 3.0); + Mat pts; + depthTo3d(depth32, intr, pts); + if (depth == CV_64F) + pts.convertTo(pts, CV_64F); + return pts; + }; + + Ptr comp = RgbdNormals::create(cfgRows, cfgCols, depth, intr, 5, 50.f, method); + + const Mat ptsOk = makePoints4(cfgRows, cfgCols); + Mat okOut; + ASSERT_NO_THROW(comp->apply(ptsOk, okOut)); + EXPECT_EQ(Size(cfgCols, cfgRows), okOut.size()); + EXPECT_EQ(type4, okOut.type()); + EXPECT_GT(countFiniteUnitNormals(okOut), 0); + + // setRows() and setCols() must reject non-positive values without corrupting prior state or cache + for (int badDim : { 0, -1, -17 }) + { + SCOPED_TRACE(cv::format("badDim=%d", badDim)); + EXPECT_THROW(comp->setRows(badDim), cv::Exception); + EXPECT_EQ(cfgRows, comp->getRows()); + EXPECT_THROW(comp->setCols(badDim), cv::Exception); + EXPECT_EQ(cfgCols, comp->getCols()); + } + if (method == RgbdNormals::RGBD_NORMALS_METHOD_SRI) + { + // SRI::cache() requires at least 2x2 grids (cols/2 - 1 index & rows-1/cols-1 divisors) + EXPECT_THROW(RgbdNormals::create(1, cfgCols, depth, intr, 5, 50.f, method), cv::Exception); + EXPECT_THROW(RgbdNormals::create(cfgRows, 1, depth, intr, 5, 50.f, method), cv::Exception); + EXPECT_THROW(comp->setRows(1), cv::Exception); + EXPECT_EQ(cfgRows, comp->getRows()); + EXPECT_THROW(comp->setCols(1), cv::Exception); + EXPECT_EQ(cfgCols, comp->getCols()); + } + Mat afterBadSetter; + ASSERT_NO_THROW(comp->apply(ptsOk, afterBadSetter)); + expectNormalsExact(okOut, afterBadSetter, "after_bad_setter"); + + // Empty 0-D Mat, 3-D Mat, wrong channels/depth, and overlapping-row broadcast step[0] == 0 + { + Mat empty0d; + Mat sentinel(1, 1, type4, kSentinelVal); + const uchar* sPtr = sentinel.data; + EXPECT_THROW(comp->apply(empty0d, sentinel), cv::Exception); + EXPECT_EQ(sPtr, sentinel.data); + + const int sz3d[3] = { 2, cfgRows, cfgCols }; + Mat pts3d(3, sz3d, type4, Scalar::all(1.0)); + EXPECT_THROW(comp->apply(pts3d, sentinel), cv::Exception); + EXPECT_EQ(sPtr, sentinel.data); + + Mat wrongCh(cfgRows, cfgCols, CV_MAKETYPE(depth, 3), Scalar::all(1.0)); + EXPECT_THROW(comp->apply(wrongCh, sentinel), cv::Exception); + EXPECT_EQ(sPtr, sentinel.data); + + Mat wrongDepth(cfgRows, cfgCols, CV_8UC4, Scalar::all(1)); + EXPECT_THROW(comp->apply(wrongDepth, sentinel), cv::Exception); + EXPECT_EQ(sPtr, sentinel.data); + + Mat rowBuf(1, cfgCols, type4, Scalar::all(1.0)); + const int sz2d[2] = { cfgRows, cfgCols }; + const size_t zeroSteps[2] = { 0, rowBuf.elemSize() }; + Mat broadcastIn(2, sz2d, type4, rowBuf.data, zeroSteps); + EXPECT_THROW(comp->apply(broadcastIn, sentinel), cv::Exception); + EXPECT_EQ(sPtr, sentinel.data); + Mat broadcastOut(2, sz2d, type4, rowBuf.data, zeroSteps); + EXPECT_THROW(comp->apply(ptsOk, broadcastOut), cv::Exception); + expectNormalsExact(Mat(1, 1, type4, kSentinelVal), sentinel, "sentinel_misc_bad"); + } + + const Size badSizes[7] = { + Size(32, 24), // both smaller + Size(96, 72), // both larger + Size(cfgCols, 24), // height mismatch only + Size(32, cfgRows), // width mismatch only + Size(cfgCols, 0), // zero height + Size(0, cfgRows), // zero width + Size(0, 0) // both zero (2-D typed empty) + }; + for (const Size& sz : badSizes) + { + SCOPED_TRACE(cv::format("badSize=%dx%d", sz.width, sz.height)); + const Mat badPts = makePoints4(sz.height, sz.width); + + Mat sentinel(1, 1, type4, kSentinelVal); + const uchar* sPtr = sentinel.data; + EXPECT_THROW(comp->apply(badPts, sentinel), cv::Exception); + EXPECT_EQ(Size(1, 1), sentinel.size()); + EXPECT_EQ(sPtr, sentinel.data); + expectNormalsExact(Mat(1, 1, type4, kSentinelVal), sentinel, "sentinel_scalar"); + + Mat canvas(cfgRows + 8, cfgCols + 12, type4, kSentinelVal); + Mat roiOut = canvas(Rect(6, 4, cfgCols, cfgRows)); + const uchar* rPtr = roiOut.data; + EXPECT_THROW(comp->apply(badPts, roiOut), cv::Exception); + EXPECT_EQ(Size(cfgCols, cfgRows), roiOut.size()); + EXPECT_EQ(rPtr, roiOut.data); + expectNormalsExact(Mat(canvas.size(), canvas.type(), kSentinelVal), canvas, "sentinel_roi"); + } + + if (method == RgbdNormals::RGBD_NORMALS_METHOD_LINEMOD) + { + for (int dDepth : { CV_16U, CV_32F, CV_64F }) + { + for (const Size& sz : badSizes) + { + SCOPED_TRACE(cv::format("LINEMOD dDepth=%d badSize=%dx%d", dDepth, sz.width, sz.height)); + const Mat badDepth(sz.height, sz.width, CV_MAKETYPE(dDepth, 1), Scalar::all(2000)); + Mat out(1, 1, type4, kSentinelVal); + const uchar* oPtr = out.data; + EXPECT_THROW(comp->apply(badDepth, out), cv::Exception); + EXPECT_EQ(oPtr, out.data); + expectNormalsExact(Mat(1, 1, type4, kSentinelVal), out, "linemod_sentinel"); + } + } + } + + // setRows() and setCols() change the accepted input size + comp->setRows(24); + comp->setCols(32); + Mat outResized; + EXPECT_THROW(comp->apply(ptsOk, outResized), cv::Exception); + EXPECT_TRUE(outResized.empty()); + const Mat ptsResized = makePoints4(24, 32); + ASSERT_NO_THROW(comp->apply(ptsResized, outResized)); + EXPECT_EQ(Size(32, 24), outResized.size()); + EXPECT_EQ(type4, outResized.type()); + + // 1-D-shaped grids (1xN and Nx1) must run safely for FALS, LINEMOD (including rows>=12, cols==1), and CrossProduct; + // SRI accepts a minimum 2x2 grid. + if (method == RgbdNormals::RGBD_NORMALS_METHOD_SRI) + { + const Mat pts2x2 = makePoints4(2, 2); + comp->setRows(2); + comp->setCols(2); + Mat out2x2; + ASSERT_NO_THROW(comp->apply(pts2x2, out2x2)); + EXPECT_EQ(Size(2, 2), out2x2.size()); + EXPECT_EQ(type4, out2x2.type()); + } + else + { + const Mat ptsRow = makePoints4(1, 20); + comp->setRows(1); + comp->setCols(20); + Mat outRow; + ASSERT_NO_THROW(comp->apply(ptsRow, outRow)); + EXPECT_EQ(Size(20, 1), outRow.size()); + + const Mat ptsCol = makePoints4(20, 1); + comp->setRows(20); + comp->setCols(1); + Mat outCol; + ASSERT_NO_THROW(comp->apply(ptsCol, outCol)); + EXPECT_EQ(Size(1, 20), outCol.size()); + + // 1-D OutputArray wrappers (std::vector, _OutputArray(raw, n)) for 20x1 and 1x20 + if (depth == CV_32F) + { + const Vec4f sent(static_cast(kSentinelVal[0]), static_cast(kSentinelVal[1]), + static_cast(kSentinelVal[2]), static_cast(kSentinelVal[3])); + std::vector vec(20, sent); + comp->apply(ptsCol, vec); + expectNormalsExact(outCol, Mat(20, 1, type4, vec.data()), "vector_out_32f"); + ptsCol.copyTo(Mat(20, 1, type4, vec.data())); + comp->apply(Mat(20, 1, type4, vec.data()), vec); + expectNormalsExact(outCol, Mat(20, 1, type4, vec.data()), "vector_inplace_32f"); + + Vec4f rawBuf[20]; + std::fill_n(rawBuf, 20, sent); + comp->apply(ptsCol, _OutputArray(rawBuf, 20)); + expectNormalsExact(outCol, Mat(20, 1, type4, rawBuf), "raw_ptr_out_32f"); + + comp->setRows(1); + comp->setCols(20); + std::fill(vec.begin(), vec.end(), sent); + comp->apply(ptsRow, vec); + expectNormalsExact(outRow, Mat(1, 20, type4, vec.data()), "vector_row_32f"); + } + else + { + const Vec4d sent(kSentinelVal[0], kSentinelVal[1], kSentinelVal[2], kSentinelVal[3]); + std::vector vec(20, sent); + comp->apply(ptsCol, vec); + expectNormalsExact(outCol, Mat(20, 1, type4, vec.data()), "vector_out_64f"); + ptsCol.copyTo(Mat(20, 1, type4, vec.data())); + comp->apply(Mat(20, 1, type4, vec.data()), vec); + expectNormalsExact(outCol, Mat(20, 1, type4, vec.data()), "vector_inplace_64f"); + + Vec4d rawBuf[20]; + std::fill_n(rawBuf, 20, sent); + comp->apply(ptsCol, _OutputArray(rawBuf, 20)); + expectNormalsExact(outCol, Mat(20, 1, type4, rawBuf), "raw_ptr_out_64f"); + + comp->setRows(1); + comp->setCols(20); + std::fill(vec.begin(), vec.end(), sent); + comp->apply(ptsRow, vec); + expectNormalsExact(outRow, Mat(1, 20, type4, vec.data()), "vector_row_64f"); + } + } +} + +TEST_P(NormalsInputSize, roi_input_and_output) +{ + const int depth = std::get<0>(GetParam()); + const RgbdNormals::RgbdNormalsMethod method = static_cast(int(std::get<1>(GetParam()))); + const int cfgRows = 32, cfgCols = 40; + const int type4 = CV_MAKETYPE(depth, 4); + Mat intr(Matx33d(262.5, 0.0, 19.5, 0.0, 262.5, 15.5, 0.0, 0.0, 1.0)); + + // Build non-uniform synthetic depth so any stride bug shifts values measurably + Mat depthBase(cfgRows, cfgCols, CV_32FC1); + theRNG().fill(depthBase, RNG::UNIFORM, 1.0, 4.0); + Mat ptsRef; + depthTo3d(depthBase, intr, ptsRef); + if (depth == CV_64F) + ptsRef.convertTo(ptsRef, CV_64F); + ASSERT_TRUE(ptsRef.isContinuous()); + + Ptr comp = RgbdNormals::create(cfgRows, cfgCols, depth, intr, 5, 50.f, method); + + Mat refOut; + comp->apply(ptsRef, refOut); + ASSERT_EQ(Size(cfgCols, cfgRows), refOut.size()); + ASSERT_EQ(type4, refOut.type()); + ASSERT_GT(countFiniteUnitNormals(refOut), 0); + + // 1. Preallocated non-continuous output ROI (both lvalue header and direct submatrix rvalue) + const Rect outRect(11, 7, cfgCols, cfgRows); + Mat outCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + Mat outRoi = outCanvas(outRect); + const uchar* outRoiPtr = outRoi.data; + ASSERT_FALSE(outRoi.isContinuous()); + comp->apply(ptsRef, outRoi); + EXPECT_EQ(outRoiPtr, outRoi.data); + expectBorderSentinel(outCanvas, outRect, "lvalue_roi_out"); + expectNormalsExact(refOut, outCanvas(outRect), "lvalue_roi_out"); + + Mat outCanvasRv(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + comp->apply(ptsRef, outCanvasRv(outRect)); + expectBorderSentinel(outCanvasRv, outRect, "rvalue_roi_out"); + expectNormalsExact(refOut, outCanvasRv(outRect), "rvalue_roi_out"); + + // 2. Non-continuous 4-channel input ROI surrounded by NaNs -> non-continuous output ROI + const Rect inRect(9, 5, cfgCols, cfgRows); + const double qnan = std::numeric_limits::quiet_NaN(); + Mat inCanvas(cfgRows + 14, cfgCols + 21, type4, Scalar::all(qnan)); + ptsRef.copyTo(inCanvas(inRect)); + Mat inRoi = inCanvas(inRect); + ASSERT_FALSE(inRoi.isContinuous()); + + Mat bothCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + Mat bothOutRoi = bothCanvas(outRect); + comp->apply(inRoi, bothOutRoi); + expectBorderSentinel(bothCanvas, outRect, "both_roi_4ch"); + expectNormalsExact(refOut, bothCanvas(outRect), "both_roi_4ch"); + + // 2b. Cross-depth 4-channel ROI input (CV_64FC4 into CV_32F computer and CV_32FC4 into CV_64F computer) + const int otherDepth = (depth == CV_32F) ? CV_64F : CV_32F; + const int otherType4 = CV_MAKETYPE(otherDepth, 4); + Mat ptsOtherRef; + ptsRef.convertTo(ptsOtherRef, otherDepth); + Mat refOtherOut; + comp->apply(ptsOtherRef, refOtherOut); + ASSERT_EQ(Size(cfgCols, cfgRows), refOtherOut.size()); + ASSERT_EQ(type4, refOtherOut.type()); + ASSERT_GT(countFiniteUnitNormals(refOtherOut), 0); + + Mat otherInCanvas(cfgRows + 14, cfgCols + 21, otherType4, Scalar::all(qnan)); + ptsOtherRef.copyTo(otherInCanvas(inRect)); + Mat otherInRoi = otherInCanvas(inRect); + ASSERT_FALSE(otherInRoi.isContinuous()); + Mat otherOutCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + Mat otherOutRoi = otherOutCanvas(outRect); + comp->apply(otherInRoi, otherOutRoi); + expectBorderSentinel(otherOutCanvas, outRect, "cross_depth_roi_4ch"); + expectNormalsExact(refOtherOut, otherOutCanvas(outRect), "cross_depth_roi_4ch"); + + // 3. Row-padded external buffer (not a submatrix, non-continuous step) + const int paddedCols = cfgCols + 13; + Mat paddedBacking(cfgRows, paddedCols, type4, kSentinelVal); + Mat paddedOut(cfgRows, cfgCols, type4, paddedBacking.data, paddedBacking.step[0]); + ASSERT_FALSE(paddedOut.isContinuous()); + comp->apply(ptsRef, paddedOut); + EXPECT_EQ(paddedBacking.data, paddedOut.data); + expectBorderSentinel(paddedBacking, Rect(0, 0, cfgCols, cfgRows), "padded_step_out"); + expectNormalsExact(refOut, paddedBacking(Rect(0, 0, cfgCols, cfgRows)), "padded_step_out"); + + // 4. Non-continuous UMat input and output ROI + UMat uInCanvas(cfgRows + 14, cfgCols + 21, type4, Scalar::all(qnan)); + ptsRef.copyTo(uInCanvas(inRect)); + UMat uInRoi = uInCanvas(inRect); + ASSERT_FALSE(uInRoi.isContinuous()); + UMat uCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + UMat uRoi = uCanvas(outRect); + ASSERT_FALSE(uRoi.isContinuous()); + comp->apply(uInRoi, uRoi); + Mat uGot; + uCanvas.copyTo(uGot); + expectBorderSentinel(uGot, outRect, "umat_roi_out"); + expectNormalsExact(refOut, uGot(outRect), "umat_roi_out"); + + // 5. Same-canvas overlapping ROIs (shifted ROI, forward/reverse continuous rowRange, and in-place) + Mat sharedCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + ptsRef.copyTo(sharedCanvas(Rect(8, 5, cfgCols, cfgRows))); + const Mat sharedBefore = sharedCanvas.clone(); + const Rect shiftedOut(9, 6, cfgCols, cfgRows); + Mat sharedSrc = sharedCanvas(Rect(8, 5, cfgCols, cfgRows)); + Mat sharedDst = sharedCanvas(shiftedOut); + comp->apply(sharedSrc, sharedDst); + expectOutsideRectMatches(sharedBefore, sharedCanvas, shiftedOut, "overlapping_roi_border"); + expectNormalsExact(refOut, sharedCanvas(shiftedOut), "overlapping_roi"); + + Mat vertCanvas(cfgRows + 4, cfgCols, type4, kSentinelVal); + ptsRef.copyTo(vertCanvas.rowRange(0, cfgRows)); + const Mat vertBefore = vertCanvas.clone(); + Mat vertSrc = vertCanvas.rowRange(0, cfgRows); + Mat vertDst = vertCanvas.rowRange(1, cfgRows + 1); + ASSERT_TRUE(vertSrc.isContinuous() && vertDst.isContinuous()); + comp->apply(vertSrc, vertDst); + expectOutsideRectMatches(vertBefore, vertCanvas, Rect(0, 1, cfgCols, cfgRows), "overlapping_rowrange_fwd_border"); + expectNormalsExact(refOut, vertCanvas.rowRange(1, cfgRows + 1), "overlapping_rowrange_fwd"); + + Mat vertRevCanvas(cfgRows + 4, cfgCols, type4, kSentinelVal); + ptsRef.copyTo(vertRevCanvas.rowRange(1, cfgRows + 1)); + const Mat vertRevBefore = vertRevCanvas.clone(); + Mat vertRevSrc = vertRevCanvas.rowRange(1, cfgRows + 1); + Mat vertRevDst = vertRevCanvas.rowRange(0, cfgRows); + ASSERT_TRUE(vertRevSrc.isContinuous() && vertRevDst.isContinuous()); + comp->apply(vertRevSrc, vertRevDst); + expectOutsideRectMatches(vertRevBefore, vertRevCanvas, Rect(0, 0, cfgCols, cfgRows), "overlapping_rowrange_rev_border"); + expectNormalsExact(refOut, vertRevCanvas.rowRange(0, cfgRows), "overlapping_rowrange_rev"); + + Mat inplace = ptsRef.clone(); + const uchar* inplacePtr = inplace.data; + comp->apply(inplace, inplace); + EXPECT_EQ(inplacePtr, inplace.data); + expectNormalsExact(refOut, inplace, "inplace"); + + // 6. LINEMOD non-continuous & overlapping continuous 1-channel depth across CV_16U, CV_32F, CV_64F + if (method == RgbdNormals::RGBD_NORMALS_METHOD_LINEMOD) + { + const int expectedInterior = (cfgRows - 2 * 5 - 1) * (cfgCols - 2 * 5 - 1); + for (int dDepth : { CV_16U, CV_32F, CV_64F }) + { + SCOPED_TRACE(cv::format("LINEMOD dDepth=%d", dDepth)); + Mat dCont; + if (dDepth == CV_16U) + depthBase.convertTo(dCont, CV_16U, 1000.0); + else + depthBase.convertTo(dCont, dDepth); + ASSERT_TRUE(dCont.isContinuous()); + + Mat refDepthOut; + comp->apply(dCont, refDepthOut); + ASSERT_EQ(Size(cfgCols, cfgRows), refDepthOut.size()); + ASSERT_EQ(type4, refDepthOut.type()); + ASSERT_EQ(expectedInterior, countFiniteUnitNormals(refDepthOut)); + + // Keep border padding below differenceThreshold (50 / 50000) so stray reads perturb gradients + Mat dCanvas(cfgRows + 18, cfgCols + 29, dDepth); + theRNG().fill(dCanvas, RNG::UNIFORM, dDepth == CV_16U ? 5000.0 : 10.0, + dDepth == CV_16U ? 45000.0 : 40.0); + const Rect dRect(13, 9, cfgCols, cfgRows); + dCont.copyTo(dCanvas(dRect)); + Mat dRoi = dCanvas(dRect); + ASSERT_FALSE(dRoi.isContinuous()); + + Mat dOutCanvas(cfgRows + 16, cfgCols + 25, type4, kSentinelVal); + Mat dOutRoi = dOutCanvas(outRect); + comp->apply(dRoi, dOutRoi); + expectBorderSentinel(dOutCanvas, outRect, "linemod_depth_roi"); + expectNormalsExact(refDepthOut, dOutCanvas(outRect), "linemod_depth_roi"); + + // Continuous 1-channel depth overlapping the output 4-channel normals buffer + Mat overlapBuf(cfgRows, cfgCols, type4, kSentinelVal); + Mat dAlias(cfgRows, cfgCols, dDepth, overlapBuf.data); + dCont.copyTo(dAlias); + ASSERT_TRUE(dAlias.isContinuous() && overlapBuf.isContinuous()); + comp->apply(dAlias, overlapBuf); + expectNormalsExact(refDepthOut, overlapBuf, "linemod_depth_overlap"); + } + } +} + +INSTANTIATE_TEST_CASE_P(RGBD_Normals, NormalsInputSize, ::testing::Combine(::testing::Values(CV_32F, CV_64F), + NormalComputers::all())); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class RgbdPlaneGenerate : public ::testing::TestWithParam>