mirror of
https://github.com/opencv/opencv.git
synced 2026-12-02 21:22:43 -06:00
1612 lines
65 KiB
C++
1612 lines
65 KiB
C++
// This file is part of OpenCV project.
|
|
// It is subject to the license terms in the LICENSE file found in the
|
|
// top-level directory of this distribution and at http://opencv.org/license.html.
|
|
|
|
// Copyright (C) 2026, BigVision LLC, all rights reserved.
|
|
// Third party copyrights are property of their respective owners.
|
|
|
|
#include "test_precomp.hpp"
|
|
|
|
namespace opencv_test { namespace {
|
|
|
|
static Mat makeTestImage(int type, Size sz, int seed)
|
|
{
|
|
Mat img(sz, type);
|
|
RNG rng(seed);
|
|
rng.fill(img, RNG::UNIFORM, 0, 255);
|
|
return img;
|
|
}
|
|
|
|
TEST(Resize_Params, BackwardCompat)
|
|
{
|
|
const int interpolations[] = { INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA, INTER_LANCZOS4 };
|
|
const Size srcSize(173, 121), dstSize(64, 96);
|
|
|
|
for (int interp : interpolations)
|
|
{
|
|
Mat src = makeTestImage(CV_8UC3, srcSize, 12345 + interp);
|
|
|
|
Mat expected, actual;
|
|
resize(src, expected, dstSize, 0, 0, interp);
|
|
|
|
ResizeParams params(dstSize, 0, 0, interp);
|
|
resize(src, actual, params);
|
|
|
|
EXPECT_EQ(0, cvtest::norm(expected, actual, NORM_INF))
|
|
<< "interpolation=" << interp;
|
|
}
|
|
|
|
{
|
|
const Size bitExactSrcSize(342, 256), bitExactDstSize(171, 128);
|
|
Mat src = makeTestImage(CV_8UC3, bitExactSrcSize, 777);
|
|
|
|
for (int interp : { INTER_LINEAR_EXACT, INTER_NEAREST_EXACT })
|
|
{
|
|
Mat expected, actual;
|
|
resize(src, expected, bitExactDstSize, 0, 0, interp);
|
|
resize(src, actual, ResizeParams(bitExactDstSize, 0, 0, interp));
|
|
EXPECT_EQ(0, cvtest::norm(expected, actual, NORM_INF)) << "interpolation=" << interp;
|
|
}
|
|
}
|
|
|
|
{
|
|
// The batch kinds accept the classic argument list too, and both spellings must agree.
|
|
const int N = 2, C = 3, inH = 20, inW = 16, outH = 8, outW = 12;
|
|
int srcSizes[] = { N, C, inH, inW };
|
|
Mat ndSrc(4, srcSizes, CV_32F);
|
|
RNG rng(99);
|
|
rng.fill(ndSrc, RNG::UNIFORM, 0, 255);
|
|
|
|
Mat viaClassic, viaParams;
|
|
resize(ndSrc, viaClassic, Size(outW, outH), 0, 0, INTER_LINEAR);
|
|
resize(ndSrc, viaParams, ResizeParams(Size(outW, outH)));
|
|
ASSERT_EQ(viaClassic.dims, 4);
|
|
EXPECT_EQ(0, cvtest::norm(viaClassic, viaParams, NORM_INF));
|
|
|
|
const Size vecDstSize(48, 64);
|
|
std::vector<Mat> srcs = {
|
|
makeTestImage(CV_8UC3, Size(100, 100), 4),
|
|
makeTestImage(CV_8UC3, Size(64, 200), 5),
|
|
};
|
|
std::vector<Mat> viaClassicVec, viaParamsVec;
|
|
resize(srcs, viaClassicVec, vecDstSize, 0, 0, INTER_LINEAR);
|
|
resize(srcs, viaParamsVec, ResizeParams(vecDstSize));
|
|
ASSERT_EQ(srcs.size(), viaClassicVec.size());
|
|
ASSERT_EQ(srcs.size(), viaParamsVec.size());
|
|
for (size_t i = 0; i < srcs.size(); i++)
|
|
EXPECT_EQ(0, cvtest::norm(viaClassicVec[i], viaParamsVec[i], NORM_INF)) << "index=" << i;
|
|
}
|
|
}
|
|
|
|
TEST(Resize_Params, RejectsInvalidInputs)
|
|
{
|
|
Mat src = makeTestImage(CV_8UC3, Size(64, 64), 1), dst;
|
|
|
|
// The bit-exact kernels have no coordinate-mode parameter, so they only serve PIXEL_CENTER.
|
|
for (int interp : { INTER_LINEAR_EXACT, INTER_NEAREST_EXACT })
|
|
{
|
|
ResizeParams exactCoordMode(Size(32, 32), 0, 0, interp);
|
|
exactCoordMode.coordMode = ResizeCoord::HALF_PIXEL;
|
|
EXPECT_THROW(resize(src, dst, exactCoordMode), cv::Exception) << "interpolation=" << interp;
|
|
}
|
|
|
|
ResizeParams coordModeArea(Size(32, 32), 0, 0, INTER_AREA);
|
|
coordModeArea.coordMode = ResizeCoord::HALF_PIXEL;
|
|
EXPECT_THROW(resize(src, dst, coordModeArea), cv::Exception);
|
|
|
|
// The separable kernels only exist for the depths classic resize supports, and a coordMode
|
|
// does not add any: CV_8S and CV_32S have no INTER_LINEAR/CUBIC/LANCZOS4 kernel either way.
|
|
for (int type : { CV_8SC1, CV_32SC1 })
|
|
{
|
|
Mat narrow = makeTestImage(type, Size(64, 64), 2), narrowDst;
|
|
for (int interp : { INTER_LINEAR, INTER_CUBIC, INTER_LANCZOS4 })
|
|
{
|
|
ResizeParams params(Size(32, 32), 0, 0, interp);
|
|
params.coordMode = ResizeCoord::HALF_PIXEL;
|
|
EXPECT_THROW(resize(narrow, narrowDst, params), cv::Exception)
|
|
<< typeToString(type) << " interpolation=" << interp;
|
|
}
|
|
// INTER_NEAREST only copies pixels, so it takes any depth.
|
|
ResizeParams nearest(Size(32, 32), 0, 0, INTER_NEAREST);
|
|
nearest.coordMode = ResizeCoord::HALF_PIXEL;
|
|
EXPECT_NO_THROW(resize(narrow, narrowDst, nearest)) << typeToString(type);
|
|
}
|
|
|
|
ResizeParams antialias(Size(32, 32));
|
|
antialias.antialias = true;
|
|
EXPECT_THROW(resize(src, dst, antialias), cv::Exception);
|
|
|
|
ResizeParams antialiasWithCoordMode(Size(32, 32));
|
|
antialiasWithCoordMode.coordMode = ResizeCoord::HALF_PIXEL;
|
|
antialiasWithCoordMode.antialias = true;
|
|
EXPECT_THROW(resize(src, dst, antialiasWithCoordMode), cv::Exception);
|
|
|
|
int ndSizes[] = { 2, 3, 10, 10 };
|
|
Mat ndSrc(4, ndSizes, CV_32F), ndDst;
|
|
EXPECT_THROW(resize(ndSrc, ndDst, ResizeParams()), cv::Exception); // neither dsize nor fx/fy
|
|
|
|
std::vector<Mat> mismatched = {
|
|
makeTestImage(CV_8UC3, Size(64, 64), 1),
|
|
makeTestImage(CV_8UC1, Size(64, 64), 2),
|
|
};
|
|
std::vector<Mat> vecDst;
|
|
EXPECT_THROW(resize(mismatched, vecDst, ResizeParams(Size(32, 32))), cv::Exception);
|
|
|
|
std::vector<Mat> uniform = { makeTestImage(CV_8UC3, Size(64, 64), 3) };
|
|
EXPECT_THROW(resize(uniform, vecDst, ResizeParams()), cv::Exception);
|
|
}
|
|
|
|
// ---- reference: each method from its definition, evaluated per output point ----
|
|
|
|
// One axis of a resize.
|
|
struct AxisGeom
|
|
{
|
|
int inLen, outLen;
|
|
double invScale; // destination units per source unit: the given fx/fy, or out/in
|
|
};
|
|
|
|
/** @brief Output size and per-axis scales under the ResizeParams rules: an empty dsize is
|
|
round(size*f) and a given dsize sets the scale, except that the ONNX modes keep a given fx/fy, since
|
|
their dsize is usually floor(size*f).
|
|
*/
|
|
static Size referenceGeometry(const ResizeParams& p, Size ssize, AxisGeom& gx, AxisGeom& gy)
|
|
{
|
|
const Size dsize = p.dsize.empty() ? Size(saturate_cast<int>(ssize.width*p.fx), saturate_cast<int>(ssize.height*p.fy))
|
|
: p.dsize;
|
|
const bool fromScale = p.dsize.empty() || (p.coordMode != ResizeCoord::PIXEL_CENTER && p.fx > 0 && p.fy > 0);
|
|
gx.inLen = ssize.width; gx.outLen = dsize.width;
|
|
gy.inLen = ssize.height; gy.outLen = dsize.height;
|
|
gx.invScale = fromScale ? p.fx : (double)dsize.width/ssize.width;
|
|
gy.invScale = fromScale ? p.fy : (double)dsize.height/ssize.height;
|
|
return dsize;
|
|
}
|
|
|
|
// The source index INTER_NEAREST reads for every output index of one axis.
|
|
static std::vector<int> nearestAxis(const ResizeParams& p, const AxisGeom& g)
|
|
{
|
|
std::vector<int> idx(g.outLen);
|
|
if (p.coordMode == ResizeCoord::PIXEL_CENTER)
|
|
{
|
|
// Classic INTER_NEAREST: floor(dst*scale), with the reciprocal of the scale taken first.
|
|
const double scale = 1./g.invScale;
|
|
for (int i = 0; i < g.outLen; i++)
|
|
idx[i] = (int)std::floor(std::min(i*scale, g.inLen - 1.0));
|
|
return idx;
|
|
}
|
|
for (int i = 0; i < g.outLen; i++)
|
|
{
|
|
// ONNX x_original, divided by the scale as the operator's reference implementation does.
|
|
double x;
|
|
switch (p.coordMode)
|
|
{
|
|
case ResizeCoord::ASYMMETRIC: x = i/g.invScale; break;
|
|
case ResizeCoord::TF_HALF_PIXEL_FOR_NN: x = (i + 0.5)/g.invScale; break;
|
|
case ResizeCoord::ALIGN_CORNERS: x = g.outLen > 1 ? (double)i*(g.inLen - 1)/(g.outLen - 1) : 0.0; break;
|
|
case ResizeCoord::PYTORCH_HALF_PIXEL: x = g.outLen > 1 ? (i + 0.5)/g.invScale - 0.5 : 0.0; break;
|
|
case ResizeCoord::HALF_PIXEL_SYMMETRIC: x = (g.inLen*0.5 - g.outLen*0.5/g.invScale) + (i + 0.5)/g.invScale - 0.5; break;
|
|
default: x = (i + 0.5)/g.invScale - 0.5; break;
|
|
}
|
|
// ONNX nearest_mode: only a fraction of exactly 0.5 is a tie.
|
|
const double f = std::floor(x);
|
|
double r = f;
|
|
switch (p.nearestMode)
|
|
{
|
|
case ResizeNearest::FLOOR: break;
|
|
case ResizeNearest::CEIL: r = std::ceil(x); break;
|
|
case ResizeNearest::ROUND_PREFER_FLOOR: r = x - f > 0.5 ? f + 1 : f; break;
|
|
default: r = x - f >= 0.5 ? f + 1 : f; break;
|
|
}
|
|
idx[i] = (int)std::min(std::max(r, 0.0), g.inLen - 1.0);
|
|
}
|
|
return idx;
|
|
}
|
|
|
|
// INTER_NEAREST_EXACT follows Pillow: start half a step in and keep adding the step.
|
|
static std::vector<int> nearestExactAxis(const AxisGeom& g)
|
|
{
|
|
std::vector<int> idx(g.outLen);
|
|
const softdouble step = softdouble(g.inLen)/softdouble(g.outLen);
|
|
softdouble x = step*softdouble(0.5);
|
|
for (int i = 0; i < g.outLen; i++, x += step)
|
|
idx[i] = std::min(cvFloor(x), g.inLen - 1);
|
|
return idx;
|
|
}
|
|
|
|
// INTER_LINEAR_EXACT taps: softdouble coordinate, fraction in fracBits bits, edges taken whole.
|
|
struct ExactAxis
|
|
{
|
|
std::vector<int> i0, i1;
|
|
std::vector<int64> c0, c1;
|
|
};
|
|
|
|
static ExactAxis linearExactAxis(const AxisGeom& g, int fracBits)
|
|
{
|
|
ExactAxis a;
|
|
const int64 one = (int64)1 << fracBits;
|
|
const softdouble scale = softdouble::one()/softdouble(g.invScale);
|
|
for (int i = 0; i < g.outLen; i++)
|
|
{
|
|
const softdouble x = scale*(softdouble(i) + softdouble(0.5)) - softdouble(0.5);
|
|
const int f = cvFloor(x);
|
|
const bool inside = f >= 0 && f < g.inLen - 1;
|
|
const int64 frac = !inside ? 0 : fracBits == 32 ? cvRound64((x - softdouble(f))*softdouble(one))
|
|
: cvRound((x - softdouble(f))*softdouble(one));
|
|
a.i0.push_back(std::min(std::max(f, 0), g.inLen - 1));
|
|
a.i1.push_back(inside ? f + 1 : a.i0.back());
|
|
a.c1.push_back(frac);
|
|
a.c0.push_back(one - frac);
|
|
}
|
|
return a;
|
|
}
|
|
|
|
// Per-output taps: output i reads idx[k] weighted by w[k], k in [start[i], start[i+1]).
|
|
struct AxisTaps
|
|
{
|
|
std::vector<int> start, idx;
|
|
std::vector<double> w;
|
|
AxisTaps() : start(1, 0) {}
|
|
void add(int i, double weight) { idx.push_back(i); w.push_back(weight); }
|
|
void next() { start.push_back((int)idx.size()); }
|
|
};
|
|
|
|
static void cubicWeights(float x, float A, float* w)
|
|
{
|
|
w[0] = ((A*(x + 1) - 5*A)*(x + 1) + 8*A)*(x + 1) - 4*A;
|
|
w[1] = ((A + 2)*x - (A + 3))*x*x + 1;
|
|
w[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;
|
|
w[3] = 1.f - w[0] - w[1] - w[2];
|
|
}
|
|
|
|
// OpenCV's truncated Lanczos: unlike Keys cubic it does not reproduce a linear ramp exactly.
|
|
static void lanczos4Weights(float x, float* w)
|
|
{
|
|
const double s45 = 0.70710678118654752440084436210485;
|
|
const double cs[][2] = {{1,0},{-s45,-s45},{0,1},{s45,-s45},{-1,0},{s45,s45},{0,-1},{-s45,s45}};
|
|
const double y0 = -(x + 3)*CV_PI*0.25, s0 = std::sin(y0), c0 = std::cos(y0);
|
|
float sum = 0.f;
|
|
for (int i = 0; i < 8; i++)
|
|
{
|
|
const float yi = x + 3 - i;
|
|
if (std::fabs(yi) >= 1e-6f)
|
|
{
|
|
const double y = -yi*CV_PI*0.25;
|
|
w[i] = (float)((cs[i][0]*s0 + cs[i][1]*c0)/(y*y));
|
|
}
|
|
else
|
|
w[i] = 1e30f;
|
|
sum += w[i];
|
|
}
|
|
sum = 1.f/sum;
|
|
for (int i = 0; i < 8; i++)
|
|
w[i] *= sum;
|
|
}
|
|
|
|
// ResizeCoord for the filters, in double; the kernels then round it to float.
|
|
static double filterCoord(ResizeCoord mode, const AxisGeom& g, int i)
|
|
{
|
|
const double scale = 1./g.invScale;
|
|
switch (mode)
|
|
{
|
|
case ResizeCoord::ASYMMETRIC: return i*scale;
|
|
case ResizeCoord::ALIGN_CORNERS: return i*(g.outLen > 1 ? (double)(g.inLen - 1)/(g.outLen - 1) : 0.0);
|
|
case ResizeCoord::TF_HALF_PIXEL_FOR_NN: return (i + 0.5)*scale;
|
|
case ResizeCoord::HALF_PIXEL_SYMMETRIC: return (g.inLen*0.5 - g.outLen*scale*0.5) + (i + 0.5)*scale - 0.5;
|
|
case ResizeCoord::PYTORCH_HALF_PIXEL: return g.outLen > 1 ? (i + 0.5)*scale - 0.5 : 0.0;
|
|
default: return (i + 0.5)*scale - 0.5;
|
|
}
|
|
}
|
|
|
|
/** @brief Taps of INTER_LINEAR/CUBIC/LANCZOS4 from a float coordinate, as the kernels take it.
|
|
Linear clamps the coordinate to the image; the wider kernels replicate the edge sample or, with
|
|
excludeOutside, drop the taps outside and renormalise the rest.
|
|
*/
|
|
static AxisTaps filterAxis(const ResizeParams& p, const AxisGeom& g)
|
|
{
|
|
const int ksize = p.interpolation == INTER_CUBIC ? 4 : p.interpolation == INTER_LANCZOS4 ? 8 : 2;
|
|
AxisTaps t;
|
|
for (int i = 0; i < g.outLen; i++)
|
|
{
|
|
const float c = (float)filterCoord(p.coordMode, g, i);
|
|
int s = cvFloor(c);
|
|
float f = c - s;
|
|
float w[8];
|
|
if (ksize == 2)
|
|
{
|
|
if (s < 0)
|
|
s = 0, f = 0.f;
|
|
if (s >= g.inLen - 1)
|
|
s = g.inLen - 1, f = 0.f;
|
|
w[0] = 1.f - f;
|
|
w[1] = f;
|
|
}
|
|
else if (ksize == 4)
|
|
cubicWeights(f, p.cubicCoeffA, w);
|
|
else
|
|
lanczos4Weights(f, w);
|
|
|
|
const int first = s - ksize/2 + 1;
|
|
if (p.excludeOutside && ksize > 2)
|
|
{
|
|
float sum = 0.f;
|
|
for (int k = 0; k < ksize; k++)
|
|
{
|
|
if (first + k < 0 || first + k >= g.inLen)
|
|
w[k] = 0.f;
|
|
sum += w[k];
|
|
}
|
|
if (sum != 0.f)
|
|
for (int k = 0; k < ksize; k++)
|
|
w[k] /= sum;
|
|
}
|
|
for (int k = 0; k < ksize; k++)
|
|
t.add(std::min(std::max(first + k, 0), g.inLen - 1), w[k]);
|
|
t.next();
|
|
}
|
|
return t;
|
|
}
|
|
|
|
/** @brief Taps of INTER_AREA when it shrinks: an output averages the source cells it covers,
|
|
weighted by overlap, dropping slivers under 1e-3 of a cell as OpenCV defines it.
|
|
*/
|
|
static AxisTaps areaAxis(const AxisGeom& g)
|
|
{
|
|
const double scale = 1./g.invScale;
|
|
AxisTaps t;
|
|
for (int i = 0; i < g.outLen; i++)
|
|
{
|
|
const double x1 = i*scale, x2 = x1 + scale, cell = std::min(scale, g.inLen - x1);
|
|
int s1 = cvCeil(x1), s2 = cvFloor(x2);
|
|
s2 = std::min(s2, g.inLen - 1);
|
|
s1 = std::min(s1, s2);
|
|
if (s1 - x1 > 1e-3)
|
|
t.add(s1 - 1, (s1 - x1)/cell);
|
|
for (int s = s1; s < s2; s++)
|
|
t.add(s, 1./cell);
|
|
if (x2 - s2 > 1e-3)
|
|
t.add(s2, std::min(std::min(x2 - s2, 1.), cell)/cell);
|
|
t.next();
|
|
}
|
|
return t;
|
|
}
|
|
|
|
// INTER_AREA growing either axis: linear between the cells around each output's right edge.
|
|
static AxisTaps areaGrowAxis(const AxisGeom& g)
|
|
{
|
|
const double scale = 1./g.invScale;
|
|
AxisTaps t;
|
|
for (int i = 0; i < g.outLen; i++)
|
|
{
|
|
int s = cvFloor(i*scale);
|
|
float f = (float)((i + 1) - (s + 1)*g.invScale);
|
|
f = f <= 0 ? 0.f : f - cvFloor(f);
|
|
if (s >= g.inLen - 1)
|
|
s = g.inLen - 1, f = 0.f;
|
|
t.add(s, 1.f - f);
|
|
t.add(std::min(s + 1, g.inLen - 1), f);
|
|
t.next();
|
|
}
|
|
return t;
|
|
}
|
|
|
|
static double sampleAt(const Mat& m, int y, int x, int c)
|
|
{
|
|
const uchar* p = m.ptr(y) + (size_t)x*m.elemSize();
|
|
switch (m.depth())
|
|
{
|
|
case CV_8U: return ((const uchar*)p)[c];
|
|
case CV_8S: return ((const schar*)p)[c];
|
|
case CV_16U: return ((const ushort*)p)[c];
|
|
case CV_16S: return ((const short*)p)[c];
|
|
case CV_32S: return ((const int*)p)[c];
|
|
case CV_32F: return ((const float*)p)[c];
|
|
case CV_16F: return (float)((const hfloat*)p)[c];
|
|
default: return ((const double*)p)[c];
|
|
}
|
|
}
|
|
|
|
/** @brief |a|*b/2^32 rounded half away from zero and saturated, for |a| <= 2^63 and b <= 2^32:
|
|
the product INTER_LINEAR_EXACT takes on CV_32S between its two passes.
|
|
*/
|
|
static int64 mulFixed32(int64 a, int64 b)
|
|
{
|
|
const uint64 ua = a < 0 ? (uint64)0 - (uint64)a : (uint64)a, ub = (uint64)b;
|
|
const uint64 a0 = ua & 0xFFFFFFFF, a1 = ua >> 32, b0 = ub & 0xFFFFFFFF, b1 = ub >> 32;
|
|
const uint64 mag = a1*b0 + ((a0*b0 + 0x80000000u) >> 32) + ua*b1;
|
|
if (mag > (uint64)std::numeric_limits<int64>::max())
|
|
return a < 0 ? std::numeric_limits<int64>::min() : std::numeric_limits<int64>::max();
|
|
return a < 0 ? -(int64)mag : (int64)mag;
|
|
}
|
|
|
|
static int64 addSaturate(int64 a, int64 b)
|
|
{
|
|
const int64 s = (int64)((uint64)a + (uint64)b);
|
|
return ((a ^ s) & (b ^ s)) < 0 ? (a < 0 ? std::numeric_limits<int64>::min() : std::numeric_limits<int64>::max()) : s;
|
|
}
|
|
|
|
/** @brief The INTER_LINEAR_EXACT value of one sample: fixed-point weights, exact products and one
|
|
rounding at the end; CV_32S rounds once more between the passes, as its 64-bit fixed point must.
|
|
*/
|
|
static double linearExactValue(const Mat& src, const ExactAxis& ax, const ExactAxis& ay, int fracBits,
|
|
int x, int y, int c)
|
|
{
|
|
const double s00 = sampleAt(src, ay.i0[y], ax.i0[x], c), s01 = sampleAt(src, ay.i0[y], ax.i1[x], c);
|
|
const double s10 = sampleAt(src, ay.i1[y], ax.i0[x], c), s11 = sampleAt(src, ay.i1[y], ax.i1[x], c);
|
|
const int64 h0 = (int64)s00*ax.c0[x] + (int64)s01*ax.c1[x];
|
|
const int64 h1 = (int64)s10*ax.c0[x] + (int64)s11*ax.c1[x];
|
|
int64 v;
|
|
if (fracBits < 32)
|
|
v = (h0*ay.c0[y] + h1*ay.c1[y] + ((int64)1 << (2*fracBits - 1))) >> (2*fracBits);
|
|
else
|
|
v = (int64)((uint64)addSaturate(mulFixed32(h0, ay.c0[y]), mulFixed32(h1, ay.c1[y])) + 0x80000000u) >> 32;
|
|
return (double)v;
|
|
}
|
|
|
|
static double saturateTo(int depth, double v)
|
|
{
|
|
switch (depth)
|
|
{
|
|
case CV_8U: return saturate_cast<uchar>(v);
|
|
case CV_8S: return saturate_cast<schar>(v);
|
|
case CV_16U: return saturate_cast<ushort>(v);
|
|
case CV_16S: return saturate_cast<short>(v);
|
|
case CV_32S: return saturate_cast<int>(v);
|
|
default: return v;
|
|
}
|
|
}
|
|
|
|
/** @brief Bound on |dst - reference| where the method filters. 8U carries 11-bit fixed-point
|
|
weights, 16U/16S round a float sum, 32F sums in float, and 64F sums float weights in double; the
|
|
bounds leave room for a float weight to differ by an ulp, and for the INTER_AREA weights the reference
|
|
keeps in double.
|
|
*/
|
|
static double filterTolerance(int depth, int interp, double maxAbs)
|
|
{
|
|
switch (depth)
|
|
{
|
|
case CV_8U: return interp == INTER_LANCZOS4 ? 3 : interp == INTER_CUBIC ? 2 : 1;
|
|
case CV_16U:
|
|
case CV_16S: return 1;
|
|
case CV_32F: return 1e-5*maxAbs + 1e-6;
|
|
default: return (interp == INTER_AREA ? 1e-6 : 1e-7)*maxAbs + 1e-12;
|
|
}
|
|
}
|
|
|
|
// The interpolation the kernels run: INTER_LINEAR_EXACT on a float is INTER_LINEAR.
|
|
static int effectiveInterpolation(const ResizeParams& p, int depth)
|
|
{
|
|
if (p.interpolation == INTER_LINEAR_EXACT && (depth == CV_32F || depth == CV_64F))
|
|
return INTER_LINEAR;
|
|
return p.interpolation;
|
|
}
|
|
|
|
/** @brief Compares dst with the reference at the given points, or at every point when there are
|
|
none. When a HAL may have served the call, a filtering method may have taken its coordinates in
|
|
double rather than float and rounded differently: the bound widens by that much, and no more.
|
|
*/
|
|
static void checkAgainstReference(const Mat& src, const Mat& dst, const ResizeParams& p,
|
|
const std::vector<Point>& points, bool halMayServe = false)
|
|
{
|
|
AxisGeom gx, gy;
|
|
const Size dsize = referenceGeometry(p, src.size(), gx, gy);
|
|
ASSERT_EQ(dsize, dst.size());
|
|
ASSERT_EQ(src.type(), dst.type());
|
|
|
|
std::vector<Point> all;
|
|
const std::vector<Point>* pts = &points;
|
|
if (points.empty())
|
|
{
|
|
for (int y = 0; y < dsize.height; y++)
|
|
for (int x = 0; x < dsize.width; x++)
|
|
all.push_back(Point(x, y));
|
|
pts = &all;
|
|
}
|
|
|
|
// As in classic resize, PIXEL_CENTER copies an unchanged size, whatever fx/fy say.
|
|
if (p.coordMode == ResizeCoord::PIXEL_CENTER && dsize == src.size())
|
|
{
|
|
ASSERT_EQ(0, cvtest::norm(src, dst, NORM_INF)) << "an unchanged size is a copy";
|
|
return;
|
|
}
|
|
|
|
const int depth = src.depth(), cn = src.channels(), interp = effectiveInterpolation(p, depth);
|
|
if (interp == INTER_NEAREST || interp == INTER_NEAREST_EXACT)
|
|
{
|
|
// A copy, so it must match bit for bit.
|
|
const std::vector<int> xi = interp == INTER_NEAREST ? nearestAxis(p, gx) : nearestExactAxis(gx);
|
|
const std::vector<int> yi = interp == INTER_NEAREST ? nearestAxis(p, gy) : nearestExactAxis(gy);
|
|
const size_t esz = src.elemSize();
|
|
for (const Point& pt : *pts)
|
|
ASSERT_EQ(0, memcmp(dst.ptr(pt.y) + pt.x*esz, src.ptr(yi[pt.y]) + xi[pt.x]*esz, esz))
|
|
<< "dst(" << pt.y << ", " << pt.x << ") is not source pixel (" << yi[pt.y] << ", " << xi[pt.x] << ")";
|
|
return;
|
|
}
|
|
|
|
if (interp == INTER_LINEAR_EXACT)
|
|
{
|
|
const int fracBits = depth == CV_8U ? 8 : depth == CV_32S ? 32 : 16;
|
|
const ExactAxis ax = linearExactAxis(gx, fracBits), ay = linearExactAxis(gy, fracBits);
|
|
for (const Point& pt : *pts)
|
|
for (int c = 0; c < cn; c++)
|
|
{
|
|
const double expected = saturateTo(depth, linearExactValue(src, ax, ay, fracBits, pt.x, pt.y, c));
|
|
ASSERT_EQ(expected, sampleAt(dst, pt.y, pt.x, c)) << "at (" << pt.y << ", " << pt.x << ") channel " << c;
|
|
}
|
|
return;
|
|
}
|
|
|
|
const bool shrinks = gx.invScale <= 1 && gy.invScale <= 1;
|
|
AxisTaps tx, ty;
|
|
if (interp == INTER_AREA)
|
|
{
|
|
tx = shrinks ? areaAxis(gx) : areaGrowAxis(gx);
|
|
ty = shrinks ? areaAxis(gy) : areaGrowAxis(gy);
|
|
}
|
|
else
|
|
{
|
|
tx = filterAxis(p, gx);
|
|
ty = filterAxis(p, gy);
|
|
}
|
|
|
|
double minVal = 0, maxVal = 0;
|
|
cv::minMaxIdx(src.reshape(1), &minVal, &maxVal);
|
|
const double maxAbs = std::max(std::abs(minVal), std::abs(maxVal));
|
|
double tol = filterTolerance(depth, interp, maxAbs);
|
|
if (halMayServe)
|
|
{
|
|
const double slope = interp == INTER_LANCZOS4 ? 3 : interp == INTER_CUBIC ? 2 : 1;
|
|
tol += std::max(gx.inLen, gy.inLen)*FLT_EPSILON*2*maxAbs*slope + (depth < CV_32F ? 1 : 0);
|
|
}
|
|
for (const Point& pt : *pts)
|
|
for (int c = 0; c < cn; c++)
|
|
{
|
|
double acc = 0;
|
|
for (int j = ty.start[pt.y]; j < ty.start[pt.y + 1]; j++)
|
|
{
|
|
double h = 0;
|
|
for (int i = tx.start[pt.x]; i < tx.start[pt.x + 1]; i++)
|
|
h += tx.w[i]*sampleAt(src, ty.idx[j], tx.idx[i], c);
|
|
acc += ty.w[j]*h;
|
|
}
|
|
const double expected = depth < CV_32F ? saturateTo(depth, cvRound(acc)) : acc;
|
|
const double actual = sampleAt(dst, pt.y, pt.x, c);
|
|
ASSERT_LE(std::abs(actual - expected), tol)
|
|
<< "at (" << pt.y << ", " << pt.x << ") channel " << c << ": " << actual << " vs " << expected;
|
|
}
|
|
}
|
|
|
|
// Resizes one image through a one-element batch, which always runs OpenCV's own kernels.
|
|
static Mat resizeAlone(const Mat& src, const ResizeParams& p)
|
|
{
|
|
std::vector<Mat> one(1, src), out;
|
|
resize(one, out, p);
|
|
return out[0];
|
|
}
|
|
|
|
// ---- random configurations ----
|
|
|
|
// Hands out each value once per shuffled round, so the counts are exact.
|
|
template<class T> struct RandomBag
|
|
{
|
|
std::vector<T> values;
|
|
size_t pos;
|
|
explicit RandomBag(const std::vector<T>& v) : values(v), pos(v.size()) {}
|
|
T next(RNG& rng)
|
|
{
|
|
if (pos == values.size())
|
|
{
|
|
for (int i = (int)values.size() - 1; i > 0; i--)
|
|
std::swap(values[i], values[rng.uniform(0, i + 1)]);
|
|
pos = 0;
|
|
}
|
|
return values[pos++];
|
|
}
|
|
};
|
|
|
|
template<class T> static void repeatInto(std::vector<T>& v, T value, int count)
|
|
{
|
|
v.insert(v.end(), count, value);
|
|
}
|
|
|
|
enum InputKind { KIND_IMAGE, KIND_TENSOR, KIND_VECTOR };
|
|
enum SizeTier { TIER_TINY, TIER_SMALL, TIER_MEDIUM, TIER_LARGER, TIER_LARGE };
|
|
enum ValueKind { VALUES_RANDOM, VALUES_FULL, VALUES_LIMITS, VALUES_CONSTANT, VALUES_GRADIENT, VALUES_SMALL };
|
|
|
|
struct RandomCase
|
|
{
|
|
ResizeParams params;
|
|
int type;
|
|
InputKind kind;
|
|
SizeTier tier;
|
|
std::vector<Size> sizes; // a size per image
|
|
std::vector<int> leadingDims; // KIND_TENSOR: the batch axes in front of height and width
|
|
bool srcRoi, dstRoi, inPlace, legacyApi, tinyDetail;
|
|
ValueKind values;
|
|
|
|
std::string describe() const
|
|
{
|
|
std::ostringstream os;
|
|
os << typeToString(type) << " interpolation=" << params.interpolation
|
|
<< " coordMode=" << (int)params.coordMode << " nearestMode=" << (int)params.nearestMode
|
|
<< " cubicCoeffA=" << params.cubicCoeffA << " excludeOutside=" << params.excludeOutside
|
|
<< " dsize=" << params.dsize << " fx=" << params.fx << " fy=" << params.fy
|
|
<< " kind=" << (int)kind << " tier=" << (int)tier << " srcRoi=" << srcRoi << " dstRoi=" << dstRoi
|
|
<< " inPlace=" << inPlace << " legacyApi=" << legacyApi << " values=" << (int)values
|
|
<< " tinyDetail=" << tinyDetail << " sizes=";
|
|
for (const Size& sz : sizes)
|
|
os << sz << ' ';
|
|
for (int d : leadingDims)
|
|
os << "lead=" << d << ' ';
|
|
return os.str();
|
|
}
|
|
};
|
|
|
|
// A dimension biased towards 1, a few, and vector boundaries of the row.
|
|
static int drawDim(RNG& rng, int lo, int hi, int cn)
|
|
{
|
|
switch (rng.uniform(0, 10))
|
|
{
|
|
case 0: return 1;
|
|
case 1: return rng.uniform(2, 5);
|
|
case 2:
|
|
{
|
|
const int maxLog = (int)std::floor(std::log2((double)hi*cn));
|
|
const int k = rng.uniform(std::min(3, maxLog), maxLog + 1);
|
|
return std::min(std::max(((1 << k) + rng.uniform(-1, 2))/cn, 1), hi);
|
|
}
|
|
default: return rng.uniform(lo, hi + 1);
|
|
}
|
|
}
|
|
|
|
static double drawScale(RNG& rng)
|
|
{
|
|
switch (rng.uniform(0, 10))
|
|
{
|
|
case 0: return 1.;
|
|
case 1: return (double)rng.uniform(2, 5);
|
|
case 2: return 1./rng.uniform(2, 5);
|
|
case 3: return 0.5;
|
|
case 4: return 2.;
|
|
case 5: return 1. + rng.uniform(-0.01, 0.01);
|
|
default: return std::exp(rng.uniform(-2., 2.)*std::log(2.));
|
|
}
|
|
}
|
|
|
|
static int drawDepth(RNG& rng, int interp)
|
|
{
|
|
const int r = rng.uniform(0, 20);
|
|
if (interp == INTER_NEAREST || interp == INTER_NEAREST_EXACT)
|
|
{
|
|
static const int any[] = { CV_8S, CV_16U, CV_16S, CV_32S, CV_64F, CV_16F };
|
|
return r < 8 ? CV_8U : r < 13 ? CV_32F : any[r % 6];
|
|
}
|
|
if (interp == INTER_LINEAR_EXACT)
|
|
{
|
|
static const int exact[] = { CV_8S, CV_16U, CV_16S, CV_32S };
|
|
return r < 8 ? CV_8U : r < 18 ? exact[r % 4] : (r == 18 ? CV_32F : CV_64F);
|
|
}
|
|
return r < 8 ? CV_8U : r < 13 ? CV_32F : r < 15 ? CV_16U : r < 17 ? CV_16S : CV_64F;
|
|
}
|
|
|
|
static int drawChannels(RNG& rng)
|
|
{
|
|
static const int rare[] = { 2, 5, 7, 16 };
|
|
const int r = rng.uniform(0, 10);
|
|
return r < 4 ? 1 : r < 6 ? 3 : r < 8 ? 4 : rare[rng.uniform(0, 4)];
|
|
}
|
|
|
|
static int drawBatch(RNG& rng)
|
|
{
|
|
const int r = rng.uniform(0, 4);
|
|
return r == 0 ? 1 : r == 3 ? rng.uniform(9, 33) : rng.uniform(2, 9);
|
|
}
|
|
|
|
// Splits n into rank-2 leading dimensions in a random factorization.
|
|
static std::vector<int> leadingDimsOf(RNG& rng, int n, int rank)
|
|
{
|
|
std::vector<int> dims(rank - 2, 1);
|
|
int rest = n;
|
|
for (int i = 0; i + 1 < rank - 2; i++)
|
|
{
|
|
std::vector<int> divisors;
|
|
for (int d = 1; d <= rest; d++)
|
|
if (rest % d == 0)
|
|
divisors.push_back(d);
|
|
dims[i] = divisors[rng.uniform(0, (int)divisors.size())];
|
|
rest /= dims[i];
|
|
}
|
|
dims.back() = rest;
|
|
return dims;
|
|
}
|
|
|
|
// Source reads of the full reference, summed over the batch.
|
|
static double referenceWork(const RandomCase& c)
|
|
{
|
|
double work = 0;
|
|
for (const Size& sz : c.sizes)
|
|
{
|
|
AxisGeom gx, gy;
|
|
const Size dsize = referenceGeometry(c.params, sz, gx, gy);
|
|
double taps = 1;
|
|
switch (c.params.interpolation)
|
|
{
|
|
case INTER_LINEAR: case INTER_LINEAR_EXACT: taps = 4; break;
|
|
case INTER_CUBIC: taps = 16; break;
|
|
case INTER_LANCZOS4: taps = 64; break;
|
|
case INTER_AREA: taps = (1/gx.invScale + 2)*(1/gy.invScale + 2); break;
|
|
default: break;
|
|
}
|
|
work += (double)dsize.area()*CV_MAT_CN(c.type)*taps;
|
|
}
|
|
return work;
|
|
}
|
|
|
|
static size_t liveBytes(const RandomCase& c)
|
|
{
|
|
size_t bytes = 0;
|
|
for (const Size& sz : c.sizes)
|
|
{
|
|
AxisGeom gx, gy;
|
|
const Size dsize = referenceGeometry(c.params, sz, gx, gy);
|
|
const size_t s = (size_t)(sz.width + 5)*(sz.height + 3)*CV_ELEM_SIZE(c.type);
|
|
const size_t d = (size_t)(dsize.width + 5)*(dsize.height + 3)*CV_ELEM_SIZE(c.type);
|
|
bytes += s*(c.inPlace ? 2 : 1) + d*(c.dstRoi ? 2 : 1);
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
/** @brief Sets the geometry: dsize alone, fx/fy alone, or both, the way the ONNX layer passes the
|
|
true scale next to the floored size. One case in twenty forces an output axis of length 1.
|
|
*/
|
|
static void drawGeometry(RandomCase& c, RNG& rng)
|
|
{
|
|
ResizeParams& p = c.params;
|
|
double sx = drawScale(rng), sy = rng.uniform(0, 2) ? sx : drawScale(rng);
|
|
if (p.interpolation == INTER_AREA && rng.uniform(0, 4) != 0)
|
|
{
|
|
sx = std::min(sx, 1./sx);
|
|
sy = std::min(sy, 1./sy);
|
|
}
|
|
int minW = INT_MAX, minH = INT_MAX;
|
|
for (const Size& sz : c.sizes)
|
|
minW = std::min(minW, sz.width), minH = std::min(minH, sz.height);
|
|
const Size first = c.sizes[0];
|
|
p.dsize = Size();
|
|
p.fx = p.fy = 0;
|
|
switch (rng.uniform(0, 3))
|
|
{
|
|
case 0:
|
|
p.dsize = Size(std::max(1, cvRound(first.width*sx)), std::max(1, cvRound(first.height*sy)));
|
|
break;
|
|
case 1:
|
|
p.fx = std::max(sx, 1./minW);
|
|
p.fy = std::max(sy, 1./minH);
|
|
break;
|
|
default:
|
|
p.fx = std::max(sx, 1./minW);
|
|
p.fy = std::max(sy, 1./minH);
|
|
p.dsize = Size(std::max(1, cvFloor(first.width*p.fx)), std::max(1, cvFloor(first.height*p.fy)));
|
|
break;
|
|
}
|
|
if (rng.uniform(0, 20) == 0)
|
|
{
|
|
if (p.dsize.empty())
|
|
p.dsize = Size(saturate_cast<int>(first.width*p.fx), saturate_cast<int>(first.height*p.fy));
|
|
(rng.uniform(0, 2) ? p.dsize.width : p.dsize.height) = 1;
|
|
}
|
|
}
|
|
|
|
struct CaseGenerator
|
|
{
|
|
RandomBag<int> interps;
|
|
RandomBag<std::pair<int, int> > nearestModes; // (coordMode, nearestMode) pairs INTER_NEAREST takes
|
|
RandomBag<int> filterModes;
|
|
RandomBag<int> tiers;
|
|
RandomBag<int> largeCases;
|
|
|
|
static std::vector<int> interpBag()
|
|
{
|
|
std::vector<int> v;
|
|
repeatInto(v, (int)INTER_NEAREST, 27);
|
|
repeatInto(v, (int)INTER_NEAREST_EXACT, 10);
|
|
repeatInto(v, (int)INTER_LINEAR, 22);
|
|
repeatInto(v, (int)INTER_LINEAR_EXACT, 15);
|
|
repeatInto(v, (int)INTER_AREA, 16);
|
|
repeatInto(v, (int)INTER_CUBIC, 6);
|
|
repeatInto(v, (int)INTER_LANCZOS4, 4);
|
|
return v;
|
|
}
|
|
static std::vector<std::pair<int, int> > nearestBag()
|
|
{
|
|
std::vector<std::pair<int, int> > v(1, std::make_pair((int)ResizeCoord::PIXEL_CENTER, 0));
|
|
for (int mode = 1; mode <= (int)ResizeCoord::HALF_PIXEL_SYMMETRIC; mode++)
|
|
for (int r = 0; r < 4; r++)
|
|
v.push_back(std::make_pair(mode, r));
|
|
return v;
|
|
}
|
|
static std::vector<int> modeBag()
|
|
{
|
|
std::vector<int> v;
|
|
for (int mode = 0; mode <= (int)ResizeCoord::HALF_PIXEL_SYMMETRIC; mode++)
|
|
v.push_back(mode);
|
|
return v;
|
|
}
|
|
static std::vector<int> tierBag()
|
|
{
|
|
std::vector<int> v;
|
|
repeatInto(v, (int)TIER_TINY, 200);
|
|
repeatInto(v, (int)TIER_SMALL, 175);
|
|
repeatInto(v, (int)TIER_MEDIUM, 100);
|
|
repeatInto(v, (int)TIER_LARGER, 20);
|
|
repeatInto(v, (int)TIER_LARGE, 5);
|
|
return v;
|
|
}
|
|
|
|
CaseGenerator() : interps(interpBag()), nearestModes(nearestBag()), filterModes(modeBag()),
|
|
tiers(tierBag()), largeCases(std::vector<int>({ 0, 1, 2, 3, 4 })) {}
|
|
|
|
// Large workloads keep their geometry; the budget cuts channels, depth or scale instead.
|
|
void drawLarge(RandomCase& c, RNG& rng)
|
|
{
|
|
c.type = CV_MAKETYPE(rng.uniform(0, 4) ? CV_8U : rng.uniform(0, 2) ? CV_16U : CV_32F, rng.uniform(0, 4) ? 1 : 3);
|
|
if (c.params.interpolation == INTER_NEAREST || c.params.interpolation == INTER_NEAREST_EXACT)
|
|
c.type = CV_MAKETYPE(CV_8U, CV_MAT_CN(c.type));
|
|
if (c.params.interpolation == INTER_LINEAR_EXACT && CV_MAT_DEPTH(c.type) == CV_32F)
|
|
c.type = CV_MAKETYPE(CV_16U, CV_MAT_CN(c.type));
|
|
switch (largeCases.next(rng))
|
|
{
|
|
case 0: c.kind = KIND_IMAGE; c.sizes.assign(1, Size(3840, 2160)); break;
|
|
case 1: c.kind = rng.uniform(0, 2) ? KIND_IMAGE : KIND_TENSOR; c.sizes.assign(1, Size(7680, 4320)); break;
|
|
case 2: c.kind = rng.uniform(0, 2) ? KIND_VECTOR : KIND_TENSOR; c.sizes.assign(3, Size(1920, 1080)); break;
|
|
case 3: c.kind = KIND_TENSOR; c.sizes.assign(256, Size(480, 320)); break;
|
|
default:
|
|
c.kind = KIND_VECTOR;
|
|
for (int i = 0; i < 256; i++)
|
|
c.sizes.push_back(Size(rng.uniform(320, 641), rng.uniform(200, 441)));
|
|
break;
|
|
}
|
|
if (c.kind == KIND_TENSOR)
|
|
c.leadingDims = c.sizes.size() == 256 ? leadingDimsOf(rng, 256, rng.uniform(3, 6))
|
|
: std::vector<int>(1, (int)c.sizes.size());
|
|
c.values = VALUES_RANDOM;
|
|
c.tinyDetail = false;
|
|
drawGeometry(c, rng);
|
|
ResizeParams& p = c.params;
|
|
if (!p.dsize.empty() && (p.dsize.width > c.sizes[0].width || p.dsize.height > c.sizes[0].height))
|
|
{
|
|
p.dsize = Size(std::max(1, c.sizes[0].width/3), std::max(1, c.sizes[0].height/3));
|
|
p.fx = p.fy = 0;
|
|
}
|
|
if (p.dsize.empty())
|
|
p.fx = std::min(p.fx, 1.), p.fy = std::min(p.fy, 1.);
|
|
|
|
const size_t kMaxLiveBytes = size_t(256) << 20;
|
|
if (liveBytes(c) > kMaxLiveBytes)
|
|
c.type = CV_MAKETYPE(CV_MAT_DEPTH(c.type), 1);
|
|
if (liveBytes(c) > kMaxLiveBytes)
|
|
c.type = CV_8UC1;
|
|
if (liveBytes(c) > kMaxLiveBytes)
|
|
c.srcRoi = c.dstRoi = c.inPlace = false;
|
|
}
|
|
|
|
RandomCase draw(RNG& rng)
|
|
{
|
|
RandomCase c;
|
|
ResizeParams& p = c.params;
|
|
p.interpolation = interps.next(rng);
|
|
if (p.interpolation == INTER_NEAREST)
|
|
{
|
|
const std::pair<int, int> m = nearestModes.next(rng);
|
|
p.coordMode = (ResizeCoord)m.first;
|
|
p.nearestMode = (ResizeNearest)m.second;
|
|
}
|
|
else if (p.interpolation == INTER_LINEAR || p.interpolation == INTER_CUBIC || p.interpolation == INTER_LANCZOS4)
|
|
p.coordMode = (ResizeCoord)filterModes.next(rng);
|
|
p.cubicCoeffA = rng.uniform(0, 3) ? -0.75f : rng.uniform(0, 2) ? -0.5f : rng.uniform(-1.f, -0.25f);
|
|
p.excludeOutside = rng.uniform(0, 2) == 1;
|
|
|
|
c.tier = (SizeTier)tiers.next(rng);
|
|
const int r = rng.uniform(0, 20);
|
|
c.srcRoi = r < 5;
|
|
c.dstRoi = r >= 5 && r < 10;
|
|
c.inPlace = r >= 10 && r < 12;
|
|
const bool classic = p.coordMode == ResizeCoord::PIXEL_CENTER && p.cubicCoeffA == -0.75f && !p.excludeOutside;
|
|
c.legacyApi = classic && rng.uniform(0, 8) == 0;
|
|
|
|
if (c.tier == TIER_LARGE)
|
|
{
|
|
drawLarge(c, rng);
|
|
return c;
|
|
}
|
|
|
|
c.type = CV_MAKETYPE(drawDepth(rng, p.interpolation), drawChannels(rng));
|
|
c.kind = (InputKind)rng.uniform(0, 3);
|
|
static const int lo[] = { 1, 8, 32, 256 }, hi[] = { 16, 64, 256, 1920 };
|
|
const int cn = CV_MAT_CN(c.type);
|
|
const Size first(drawDim(rng, lo[c.tier], hi[c.tier], cn),
|
|
drawDim(rng, lo[c.tier], std::min(hi[c.tier], 1080), 1));
|
|
const int count = c.kind == KIND_IMAGE ? 1 : drawBatch(rng);
|
|
const bool ragged = c.kind == KIND_VECTOR && rng.uniform(0, 2) == 1;
|
|
c.sizes.push_back(first);
|
|
for (int i = 1; i < count; i++)
|
|
c.sizes.push_back(ragged ? Size(drawDim(rng, lo[c.tier], hi[c.tier], cn),
|
|
drawDim(rng, lo[c.tier], std::min(hi[c.tier], 1080), 1)) : first);
|
|
if (c.kind == KIND_TENSOR)
|
|
c.leadingDims = leadingDimsOf(rng, count, rng.uniform(3, 6));
|
|
|
|
const int v = rng.uniform(0, 20);
|
|
c.values = v < 12 ? VALUES_RANDOM : v < 14 ? VALUES_FULL : v < 16 ? VALUES_LIMITS
|
|
: v < 17 ? VALUES_CONSTANT : v < 18 ? VALUES_GRADIENT : VALUES_SMALL;
|
|
c.tinyDetail = CV_MAT_DEPTH(c.type) == CV_64F && rng.uniform(0, 4) == 0;
|
|
drawGeometry(c, rng);
|
|
|
|
// Keep the full reference cheap: halve the batch, then the images, until it fits.
|
|
const double kMaxReferenceWork = 2e6;
|
|
for (int step = 0; step < 64 && referenceWork(c) > kMaxReferenceWork; step++)
|
|
{
|
|
if (c.sizes.size() > 1)
|
|
{
|
|
c.sizes.resize(c.sizes.size()/2);
|
|
if (c.kind == KIND_TENSOR)
|
|
c.leadingDims = leadingDimsOf(rng, (int)c.sizes.size(), (int)c.leadingDims.size() + 2);
|
|
continue;
|
|
}
|
|
Size& sz = c.sizes[0];
|
|
sz = Size(std::max(1, sz.width/2), std::max(1, sz.height/2));
|
|
if (!p.dsize.empty())
|
|
p.dsize = Size(std::max(1, p.dsize.width/2), std::max(1, p.dsize.height/2));
|
|
if (p.dsize.empty() || (p.fx > 0 && p.fy > 0))
|
|
p.fx = std::max(p.fx, 1./sz.width), p.fy = std::max(p.fy, 1./sz.height);
|
|
}
|
|
return c;
|
|
}
|
|
};
|
|
|
|
static void fillValues(Mat& m, ValueKind kind, bool tinyDetail, RNG& rng)
|
|
{
|
|
const int depth = m.depth(), cn = m.channels();
|
|
double lo = 0, hi = 0, flo = 0, fhi = 0; // [lo, hi) ordinary values, [flo, fhi] the full range
|
|
switch (depth)
|
|
{
|
|
case CV_8U: lo = 0; hi = 256; flo = 0; fhi = 255; break;
|
|
case CV_8S: lo = -128; hi = 128; flo = -128; fhi = 127; break;
|
|
case CV_16U: lo = 0; hi = 4096; flo = 0; fhi = 65535; break;
|
|
case CV_16S: lo = -2048; hi = 2048; flo = -32768; fhi = 32767; break;
|
|
case CV_32S: lo = -1000000; hi = 1000000; flo = INT_MIN; fhi = INT_MAX; break;
|
|
default: lo = -100; hi = 100; flo = -10000; fhi = 10000; break;
|
|
}
|
|
Mat flat = m.reshape(1);
|
|
if (kind == VALUES_RANDOM || (kind == VALUES_FULL && depth != CV_32S))
|
|
{
|
|
const bool full = kind == VALUES_FULL;
|
|
rng.fill(flat, RNG::UNIFORM, full ? flo : lo, full ? (depth < CV_32F ? fhi + 1 : fhi) : hi);
|
|
}
|
|
else if (kind == VALUES_FULL)
|
|
{
|
|
// Two random 16-bit halves per sample cover all of CV_32S.
|
|
Mat halves(flat.rows, flat.cols*2, CV_16U, flat.data, flat.step);
|
|
rng.fill(halves, RNG::UNIFORM, 0, 65536);
|
|
}
|
|
else if (kind == VALUES_CONSTANT)
|
|
flat.setTo(rng.uniform(lo, hi));
|
|
else
|
|
{
|
|
Mat v(flat.size(), CV_64F);
|
|
const double a = rng.uniform(lo, hi), bx = rng.uniform(-2., 2.), by = rng.uniform(-2., 2.);
|
|
for (int y = 0; y < v.rows; y++)
|
|
for (int x = 0; x < v.cols; x++)
|
|
{
|
|
double& d = v.at<double>(y, x);
|
|
if (kind == VALUES_LIMITS) // within a few steps of either end, where filters saturate
|
|
{
|
|
const int r = rng.uniform(0, 8);
|
|
d = r < 4 ? flo + r : fhi - (r - 4);
|
|
}
|
|
else if (kind == VALUES_GRADIENT)
|
|
d = std::min(std::max(a + bx*(x/cn) + by*y, flo), fhi);
|
|
else // small integers, or eighths for the floats
|
|
d = rng.uniform(0, 8)*(depth >= CV_32F ? 0.125 : 1.0);
|
|
}
|
|
v.convertTo(flat, flat.type());
|
|
}
|
|
if (tinyDetail && depth == CV_64F)
|
|
{
|
|
// Variation far below float resolution, which a float intermediate would wipe out.
|
|
for (int y = 0; y < m.rows; y++)
|
|
for (int x = 0; x < m.cols*cn; x++)
|
|
m.ptr<double>(y)[x] = 1.0 + (x + y*m.cols*cn)*1e-12;
|
|
}
|
|
}
|
|
|
|
// The p-th HxW plane of an N-D Mat, as a 2D header.
|
|
static Mat planeOf(const Mat& m, int p)
|
|
{
|
|
const int D = m.dims;
|
|
size_t ofs = 0;
|
|
for (int i = D - 3; i >= 0; i--)
|
|
{
|
|
ofs += (size_t)(p % m.size[i])*m.step[i];
|
|
p /= m.size[i];
|
|
}
|
|
return Mat(m.size[D - 2], m.size[D - 1], m.type(), (void*)(m.data + ofs), m.step[D - 2]);
|
|
}
|
|
|
|
static int planeCount(const Mat& m)
|
|
{
|
|
int n = 1;
|
|
for (int i = 0; i < m.dims - 2; i++)
|
|
n *= m.size[i];
|
|
return n;
|
|
}
|
|
|
|
// An N-D Mat of sz planes, or a view into one 3x5 larger when roi is set.
|
|
static Mat makeTensor(const std::vector<int>& lead, Size sz, int type, bool roi)
|
|
{
|
|
std::vector<int> shape = lead;
|
|
shape.push_back(sz.height + (roi ? 3 : 0));
|
|
shape.push_back(sz.width + (roi ? 5 : 0));
|
|
Mat full((int)shape.size(), shape.data(), type);
|
|
if (!roi)
|
|
return full;
|
|
std::vector<Range> ranges(lead.size(), Range::all());
|
|
ranges.push_back(Range(1, 1 + sz.height));
|
|
ranges.push_back(Range(2, 2 + sz.width));
|
|
return full(ranges.data());
|
|
}
|
|
|
|
static Mat makeImage(Size sz, int type, bool roi)
|
|
{
|
|
if (!roi)
|
|
return Mat(sz, type);
|
|
Mat full(sz.height + 3, sz.width + 5, type);
|
|
return full(Rect(2, 1, sz.width, sz.height));
|
|
}
|
|
|
|
// The parent of a preallocated view gets a marker, checked afterwards outside the view.
|
|
static void fillParent(const Mat& view, uchar marker)
|
|
{
|
|
memset((void*)view.datastart, marker, view.dataend - view.datastart);
|
|
}
|
|
|
|
static void checkParent(const Mat& view, uchar marker)
|
|
{
|
|
std::vector<uchar> inside(view.dataend - view.datastart, 0);
|
|
const int planes = view.dims > 2 ? planeCount(view) : 1;
|
|
for (int p = 0; p < planes; p++)
|
|
{
|
|
const Mat pl = view.dims > 2 ? planeOf(view, p) : view;
|
|
for (int y = 0; y < pl.rows; y++)
|
|
memset(&inside[pl.ptr(y) - view.datastart], 1, pl.cols*pl.elemSize());
|
|
}
|
|
for (size_t i = 0; i < inside.size(); i++)
|
|
ASSERT_TRUE(inside[i] || view.datastart[i] == marker) << "byte " << i << " outside the destination view changed";
|
|
}
|
|
|
|
static void fillSentinel(Mat& m)
|
|
{
|
|
Mat flat = m.reshape(1);
|
|
if (m.depth() == CV_32F || m.depth() == CV_64F)
|
|
flat.setTo(std::numeric_limits<double>::quiet_NaN());
|
|
else
|
|
flat.setTo(0);
|
|
}
|
|
|
|
/** @brief Whether a large case can start its destination as NaN, or as 0 when every input is at
|
|
least 1 and the method cannot undershoot, so that a skipped row stands out where no sample lands.
|
|
*/
|
|
static bool sentinelApplies(const RandomCase& c)
|
|
{
|
|
const int depth = CV_MAT_DEPTH(c.type), interp = c.params.interpolation;
|
|
return depth == CV_32F || depth == CV_64F ||
|
|
(interp != INTER_CUBIC && interp != INTER_LANCZOS4);
|
|
}
|
|
|
|
static void checkSentinel(const Mat& plane, const std::string& where)
|
|
{
|
|
const Mat flat = plane.reshape(1);
|
|
if (plane.depth() == CV_32F || plane.depth() == CV_64F)
|
|
ASSERT_TRUE(checkRange(flat, true)) << where << ": a destination sample was never written";
|
|
else
|
|
ASSERT_EQ((int)flat.total(), countNonZero(flat)) << where << ": a destination sample was never written";
|
|
}
|
|
|
|
// Corners, edge rows and columns, vector tails of a few rows, and random points.
|
|
static std::vector<Point> samplePoints(Size dsize, int randomCount, RNG& rng)
|
|
{
|
|
std::vector<Point> pts;
|
|
const int W = dsize.width, H = dsize.height;
|
|
for (int i = 0; i < 32; i++)
|
|
{
|
|
const int x = (int)((int64)i*(W - 1)/31), y = (int)((int64)i*(H - 1)/31);
|
|
pts.push_back(Point(x, 0));
|
|
pts.push_back(Point(x, H - 1));
|
|
pts.push_back(Point(0, y));
|
|
pts.push_back(Point(W - 1, y));
|
|
}
|
|
for (int r : { 0, H/2, H - 1 })
|
|
for (int x = std::max(0, W - 70); x < W; x++)
|
|
pts.push_back(Point(x, r));
|
|
for (int i = 0; i < randomCount; i++)
|
|
pts.push_back(Point(rng.uniform(0, W), rng.uniform(0, H)));
|
|
return pts;
|
|
}
|
|
|
|
/** @brief Builds the input, resizes it, and checks every plane against the reference. Large cases
|
|
check sampled points and scan for unwritten destination samples instead.
|
|
*/
|
|
static void runCase(const RandomCase& c, RNG& rng)
|
|
{
|
|
const ResizeParams& p = c.params;
|
|
const bool large = c.tier == TIER_LARGE;
|
|
const bool sentinel = large && !c.inPlace && sentinelApplies(c);
|
|
std::vector<Mat> srcPlanes, dstPlanes;
|
|
|
|
// The source, with values drawn per plane.
|
|
Mat tensorSrc;
|
|
std::vector<Mat> vectorSrc;
|
|
if (c.kind == KIND_TENSOR)
|
|
{
|
|
tensorSrc = makeTensor(c.leadingDims, c.sizes[0], c.type, c.srcRoi);
|
|
for (int i = 0, n = planeCount(tensorSrc); i < n; i++)
|
|
srcPlanes.push_back(planeOf(tensorSrc, i));
|
|
}
|
|
else
|
|
{
|
|
for (const Size& sz : c.sizes)
|
|
vectorSrc.push_back(makeImage(sz, c.type, c.srcRoi));
|
|
srcPlanes = vectorSrc;
|
|
}
|
|
for (Mat& plane : srcPlanes)
|
|
{
|
|
fillValues(plane, c.values, c.tinyDetail, rng);
|
|
if (sentinel && plane.depth() < CV_32F)
|
|
{
|
|
Mat flat = plane.reshape(1);
|
|
max(flat, 1, flat); // no input is 0, the sentinel
|
|
}
|
|
}
|
|
|
|
// References need the input as it was; an in-place call overwrites it.
|
|
std::vector<Mat> refPlanes;
|
|
for (const Mat& plane : srcPlanes)
|
|
refPlanes.push_back(c.inPlace ? plane.clone() : plane);
|
|
|
|
// The destination: fresh, a preallocated view whose parent must stay intact, or the source.
|
|
std::vector<Size> dsizes;
|
|
for (const Size& sz : c.sizes)
|
|
{
|
|
AxisGeom gx, gy;
|
|
dsizes.push_back(referenceGeometry(p, sz, gx, gy));
|
|
}
|
|
const uchar marker = 0xA5;
|
|
Mat tensorDst;
|
|
std::vector<Mat> vectorDst;
|
|
if (c.dstRoi || sentinel)
|
|
{
|
|
if (c.kind == KIND_TENSOR)
|
|
{
|
|
tensorDst = makeTensor(c.leadingDims, dsizes[0], c.type, c.dstRoi);
|
|
if (c.dstRoi)
|
|
fillParent(tensorDst, marker);
|
|
if (sentinel)
|
|
for (int i = 0, n = planeCount(tensorDst); i < n; i++)
|
|
{
|
|
Mat pl = planeOf(tensorDst, i);
|
|
fillSentinel(pl);
|
|
}
|
|
}
|
|
else
|
|
for (const Size& d : dsizes)
|
|
{
|
|
Mat m = makeImage(d, c.type, c.dstRoi);
|
|
if (c.dstRoi)
|
|
fillParent(m, marker);
|
|
if (sentinel)
|
|
fillSentinel(m);
|
|
vectorDst.push_back(m);
|
|
}
|
|
}
|
|
|
|
if (c.kind == KIND_TENSOR)
|
|
{
|
|
Mat& dst = c.inPlace ? tensorSrc : tensorDst;
|
|
if (c.legacyApi)
|
|
resize(tensorSrc, dst, p.dsize, p.fx, p.fy, p.interpolation);
|
|
else
|
|
resize(tensorSrc, dst, p);
|
|
ASSERT_FALSE(dst.empty());
|
|
ASSERT_EQ(tensorSrc.dims, dst.dims);
|
|
for (int i = 0; i < dst.dims - 2; i++)
|
|
ASSERT_EQ(c.leadingDims[i], dst.size[i]);
|
|
for (int i = 0, n = planeCount(dst); i < n; i++)
|
|
dstPlanes.push_back(planeOf(dst, i));
|
|
if (c.dstRoi && !c.inPlace)
|
|
{
|
|
ASSERT_NO_FATAL_FAILURE(checkParent(tensorDst, marker));
|
|
}
|
|
}
|
|
else if (c.kind == KIND_VECTOR)
|
|
{
|
|
std::vector<Mat>& dst = c.inPlace ? vectorSrc : vectorDst;
|
|
if (c.legacyApi)
|
|
resize(vectorSrc, dst, p.dsize, p.fx, p.fy, p.interpolation);
|
|
else
|
|
resize(vectorSrc, dst, p);
|
|
ASSERT_EQ(c.sizes.size(), dst.size());
|
|
dstPlanes = dst;
|
|
if (c.dstRoi && !c.inPlace)
|
|
{
|
|
for (const Mat& m : vectorDst)
|
|
ASSERT_NO_FATAL_FAILURE(checkParent(m, marker));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Mat src = vectorSrc[0];
|
|
Mat out = vectorDst.empty() ? Mat() : vectorDst[0];
|
|
Mat& dst = c.inPlace ? src : out;
|
|
if (c.legacyApi)
|
|
resize(src, dst, p.dsize, p.fx, p.fy, p.interpolation);
|
|
else
|
|
resize(src, dst, p);
|
|
dstPlanes.push_back(dst);
|
|
if (c.dstRoi && !c.inPlace)
|
|
{
|
|
ASSERT_EQ(vectorDst[0].data, dst.data) << "a preallocated destination view was reallocated";
|
|
ASSERT_NO_FATAL_FAILURE(checkParent(vectorDst[0], marker));
|
|
}
|
|
}
|
|
ASSERT_EQ(refPlanes.size(), dstPlanes.size());
|
|
|
|
// A HAL may take a whole classic image; a batch of one runs OpenCV's kernels.
|
|
const int method = p.interpolation;
|
|
const bool halMayServe = c.kind == KIND_IMAGE && p.coordMode == ResizeCoord::PIXEL_CENTER &&
|
|
(method != INTER_CUBIC || p.cubicCoeffA == -0.75f) &&
|
|
!(p.excludeOutside && (method == INTER_CUBIC || method == INTER_LANCZOS4));
|
|
for (size_t i = 0; i < refPlanes.size(); i++)
|
|
{
|
|
SCOPED_TRACE(cv::format("plane %d", (int)i));
|
|
std::vector<Point> points;
|
|
if (large)
|
|
{
|
|
if (sentinel)
|
|
{
|
|
ASSERT_NO_FATAL_FAILURE(checkSentinel(dstPlanes[i], cv::format("plane %d", (int)i)));
|
|
}
|
|
points = samplePoints(dstPlanes[i].size(), refPlanes.size() == 1 ? 4096 : 128, rng);
|
|
}
|
|
ASSERT_NO_FATAL_FAILURE(checkAgainstReference(refPlanes[i], dstPlanes[i], p, points, halMayServe));
|
|
if (halMayServe)
|
|
{
|
|
SCOPED_TRACE("OpenCV's kernels, through a batch of one");
|
|
ASSERT_NO_FATAL_FAILURE(checkAgainstReference(refPlanes[i], resizeAlone(refPlanes[i], p), p, points));
|
|
}
|
|
if (c.tinyDetail && refPlanes[i].total()*refPlanes[i].channels() > 1)
|
|
{
|
|
// Some output must keep detail that no float can hold.
|
|
Mat asFloat, back;
|
|
dstPlanes[i].convertTo(asFloat, CV_32F);
|
|
asFloat.convertTo(back, CV_64F);
|
|
ASSERT_GT(cvtest::norm(back, dstPlanes[i], NORM_INF), 0.) << "CV_64F detail lost to float";
|
|
}
|
|
}
|
|
|
|
// Occasionally: a batch must give each image what it gets alone.
|
|
if (!large && c.kind != KIND_IMAGE && rng.uniform(0, 4) == 0)
|
|
{
|
|
for (size_t i = 0; i < refPlanes.size(); i++)
|
|
ASSERT_EQ(0, cvtest::norm(resizeAlone(refPlanes[i], p), dstPlanes[i], NORM_INF))
|
|
<< "plane " << i << " differs from the same image resized alone";
|
|
}
|
|
|
|
// HALF_PIXEL's formula is PIXEL_CENTER's, and the coordinate modes share every kernel.
|
|
const int interp = effectiveInterpolation(p, CV_MAT_DEPTH(c.type));
|
|
if (!large && p.coordMode == ResizeCoord::HALF_PIXEL && p.fx == 0 &&
|
|
(interp == INTER_LINEAR || interp == INTER_CUBIC || interp == INTER_LANCZOS4))
|
|
{
|
|
ResizeParams pixelCenter = p;
|
|
pixelCenter.coordMode = ResizeCoord::PIXEL_CENTER;
|
|
for (size_t i = 0; i < refPlanes.size(); i++)
|
|
{
|
|
if (refPlanes[i].size() == dstPlanes[i].size())
|
|
continue; // PIXEL_CENTER copies an unchanged size
|
|
ASSERT_EQ(0, cvtest::norm(resizeAlone(refPlanes[i], pixelCenter), dstPlanes[i], NORM_INF))
|
|
<< "HALF_PIXEL differs from PIXEL_CENTER on plane " << i;
|
|
}
|
|
}
|
|
|
|
// A view in, or a reversed batch, changes nothing.
|
|
if (!large && c.kind == KIND_VECTOR && rng.uniform(0, 4) == 0)
|
|
{
|
|
std::vector<Mat> reversed, out;
|
|
for (size_t i = refPlanes.size(); i > 0; i--)
|
|
reversed.push_back(c.srcRoi ? refPlanes[i - 1].clone() : refPlanes[i - 1]);
|
|
resize(reversed, out, p);
|
|
for (size_t i = 0; i < out.size(); i++)
|
|
ASSERT_EQ(0, cvtest::norm(out[i], dstPlanes[refPlanes.size() - 1 - i], NORM_INF))
|
|
<< "a reversed batch, from continuous copies, differs at plane " << i;
|
|
}
|
|
}
|
|
|
|
// 500 biased random cases against per-method references; five large ones checked at samples.
|
|
TEST(Resize_Params, RandomConfigs)
|
|
{
|
|
RNG rng(0x7e5a1e);
|
|
CaseGenerator gen;
|
|
const int ncases = 500;
|
|
for (int iter = 0; iter < ncases; iter++)
|
|
{
|
|
const RandomCase c = gen.draw(rng);
|
|
SCOPED_TRACE(cv::format("case %d: ", iter) + c.describe());
|
|
ASSERT_NO_FATAL_FAILURE(runCase(c, rng));
|
|
}
|
|
}
|
|
|
|
// A very uneven batch matches each image resized alone, at several thread counts.
|
|
TEST(Resize_Params, BatchCoversEveryRow)
|
|
{
|
|
const Size sizes[] = { Size(4096, 3), Size(7, 17), Size(300, 1), Size(1, 25), Size(2000, 8), Size(64, 40) };
|
|
std::vector<Mat> srcs;
|
|
RNG rng(31);
|
|
for (const Size& sz : sizes)
|
|
{
|
|
Mat m(sz.height*6, sz.width, CV_32FC1);
|
|
rng.fill(m, RNG::UNIFORM, -100., 100.);
|
|
srcs.push_back(m);
|
|
}
|
|
const int threads0 = getNumThreads();
|
|
for (int interp : { INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA })
|
|
for (int threads : { 1, 3, 8 })
|
|
{
|
|
setNumThreads(threads);
|
|
const double f = interp == INTER_AREA ? 0.75 : 1.5;
|
|
const ResizeParams p(Size(), f, f, interp);
|
|
std::vector<Mat> dsts;
|
|
for (const Mat& s : srcs)
|
|
{
|
|
Mat d(saturate_cast<int>(s.rows*p.fy), saturate_cast<int>(s.cols*p.fx), CV_32FC1);
|
|
fillSentinel(d);
|
|
dsts.push_back(d);
|
|
}
|
|
resize(srcs, dsts, p);
|
|
setNumThreads(threads0);
|
|
for (size_t i = 0; i < srcs.size(); i++)
|
|
{
|
|
ASSERT_TRUE(checkRange(dsts[i], true)) << "image " << i << ", interpolation " << interp
|
|
<< ", threads " << threads << ": unwritten rows";
|
|
ASSERT_EQ(0, cvtest::norm(resizeAlone(srcs[i], p), dsts[i], NORM_INF)) << "image " << i;
|
|
}
|
|
}
|
|
setNumThreads(threads0);
|
|
}
|
|
|
|
// Nearest rounding exactly on a tie and one ulp either side of it.
|
|
TEST(Resize_Params, NearestTies)
|
|
{
|
|
const Mat src = Mat_<uchar>({1, 8}, {10, 20, 30, 40, 50, 60, 70, 80});
|
|
// fx = 2 puts outputs 1 and 3 on ties; neighbouring doubles shift them.
|
|
struct TieCase { double fx; int expected[4][2]; }; // per ResizeNearest, outputs 1 and 3
|
|
const TieCase cases[] = {
|
|
{ 2.0, { {0, 1}, {1, 2}, {1, 2}, {0, 1} } }, // exactly on the tie
|
|
{ std::nextafter(2.0, 3.0), { {0, 1}, {1, 2}, {0, 1}, {0, 1} } }, // just below it
|
|
{ std::nextafter(2.0, 1.0), { {0, 1}, {1, 2}, {1, 2}, {1, 2} } }, // just above it
|
|
};
|
|
for (const TieCase& t : cases)
|
|
for (int mode = 0; mode < 4; mode++)
|
|
{
|
|
ResizeParams p(Size(16, 1), t.fx, 1.0, INTER_NEAREST);
|
|
p.coordMode = ResizeCoord::ASYMMETRIC;
|
|
p.nearestMode = (ResizeNearest)mode;
|
|
Mat dst;
|
|
resize(src, dst, p);
|
|
EXPECT_EQ(src.at<uchar>(0, t.expected[mode][0]), dst.at<uchar>(0, 1)) << "fx=" << t.fx << " mode=" << mode;
|
|
EXPECT_EQ(src.at<uchar>(0, t.expected[mode][1]), dst.at<uchar>(0, 3)) << "fx=" << t.fx << " mode=" << mode;
|
|
}
|
|
|
|
// HALF_PIXEL at fx = 0.5 puts every output on a tie, 2i + 0.5.
|
|
const double halfScales[] = { 0.5, std::nextafter(0.5, 1.0), std::nextafter(0.5, 0.0) };
|
|
const int halfExpected[3][4] = { { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 1 } }; // dst[0] per mode
|
|
for (int s = 0; s < 3; s++)
|
|
for (int mode = 0; mode < 4; mode++)
|
|
{
|
|
ResizeParams p(Size(4, 1), halfScales[s], 1.0, INTER_NEAREST);
|
|
p.coordMode = ResizeCoord::HALF_PIXEL;
|
|
p.nearestMode = (ResizeNearest)mode;
|
|
Mat dst;
|
|
resize(src, dst, p);
|
|
EXPECT_EQ(src.at<uchar>(0, halfExpected[s][mode]), dst.at<uchar>(0, 0)) << "fx=" << halfScales[s] << " mode=" << mode;
|
|
}
|
|
}
|
|
|
|
// Expected values from ONNX's reference implementation of Resize (onnx.reference, opset 19).
|
|
TEST(Resize_Params, OnnxReference)
|
|
{
|
|
const Mat x24 = Mat_<float>({2, 4}, {1, 2, 3, 4, 5, 6, 7, 8});
|
|
const Mat x44 = Mat_<float>({4, 4}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
|
|
const Mat x22 = Mat_<float>({2, 2}, {1, 2, 3, 4});
|
|
struct OnnxCase
|
|
{
|
|
const char* name;
|
|
const Mat* src;
|
|
int interp;
|
|
ResizeCoord coord;
|
|
ResizeNearest nearest;
|
|
Size dsize;
|
|
double fx, fy, cubicA;
|
|
bool exclude;
|
|
std::vector<float> expected;
|
|
};
|
|
const OnnxCase cases[] = {
|
|
{ "nearest_downsample_sizes_tie", &x24, INTER_NEAREST, ResizeCoord::HALF_PIXEL, ResizeNearest::ROUND_PREFER_FLOOR,
|
|
Size(3, 1), 0, 0, -0.75, false, { 1, 2, 4 } },
|
|
{ "nearest_upsample_sizes_asymmetric_ceil", &x44, INTER_NEAREST, ResizeCoord::ASYMMETRIC, ResizeNearest::ROUND_PREFER_CEIL,
|
|
Size(8, 8), 0, 0, -0.75, false,
|
|
{ 1, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 7, 7, 8, 8, 8, 5, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 11, 11, 12, 12, 12,
|
|
9, 10, 10, 11, 11, 12, 12, 12, 13, 14, 14, 15, 15, 16, 16, 16, 13, 14, 14, 15, 15, 16, 16, 16,
|
|
13, 14, 14, 15, 15, 16, 16, 16 } },
|
|
{ "nearest_upsample_sizes_align_corners_floor", &x44, INTER_NEAREST, ResizeCoord::ALIGN_CORNERS, ResizeNearest::FLOOR,
|
|
Size(8, 8), 0, 0, -0.75, false,
|
|
{ 1, 1, 1, 2, 2, 3, 3, 4, 1, 1, 1, 2, 2, 3, 3, 4, 1, 1, 1, 2, 2, 3, 3, 4, 5, 5, 5, 6, 6, 7, 7, 8,
|
|
5, 5, 5, 6, 6, 7, 7, 8, 9, 9, 9, 10, 10, 11, 11, 12, 9, 9, 9, 10, 10, 11, 11, 12,
|
|
13, 13, 13, 14, 14, 15, 15, 16 } },
|
|
{ "nearest_upsample_sizes_half_pixel_ceil", &x44, INTER_NEAREST, ResizeCoord::HALF_PIXEL, ResizeNearest::CEIL,
|
|
Size(8, 8), 0, 0, -0.75, false,
|
|
{ 1, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 7, 7, 8, 8, 8, 5, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 11, 11, 12, 12, 12,
|
|
9, 10, 10, 11, 11, 12, 12, 12, 13, 14, 14, 15, 15, 16, 16, 16, 13, 14, 14, 15, 15, 16, 16, 16,
|
|
13, 14, 14, 15, 15, 16, 16, 16 } },
|
|
{ "linear_upsample_scales_half_pixel_symmetric", &x22, INTER_LINEAR, ResizeCoord::HALF_PIXEL_SYMMETRIC,
|
|
ResizeNearest::ROUND_PREFER_FLOOR, Size(5, 4), 2.94, 2.3, -0.75, false,
|
|
{ 1.f, 1.15986395f, 1.5f, 1.84013605f, 2.f, 1.56521738f, 1.72508132f, 2.06521749f, 2.40535355f, 2.56521749f,
|
|
2.43478251f, 2.59464645f, 2.93478251f, 3.27491856f, 3.43478251f, 3.f, 3.15986395f, 3.5f, 3.84013605f, 4.f } },
|
|
{ "linear_downsample_sizes_pytorch_half_pixel", &x44, INTER_LINEAR, ResizeCoord::PYTORCH_HALF_PIXEL,
|
|
ResizeNearest::ROUND_PREFER_FLOOR, Size(1, 3), 0, 0, -0.75, false, { 1.66666663f, 7.f, 12.333333f } },
|
|
{ "linear_downsample_scales_0p6", &x24, INTER_LINEAR, ResizeCoord::HALF_PIXEL, ResizeNearest::ROUND_PREFER_FLOOR,
|
|
Size(2, 1), 0.6, 0.6, -0.75, false, { 2.66666651f, 4.33333302f } },
|
|
{ "linear_downsample_sizes_same_dsize", &x24, INTER_LINEAR, ResizeCoord::HALF_PIXEL, ResizeNearest::ROUND_PREFER_FLOOR,
|
|
Size(2, 1), 0, 0, -0.75, false, { 3.5f, 5.5f } },
|
|
{ "cubic_upsample_scales_A_n0p5_exclude_outside", &x44, INTER_CUBIC, ResizeCoord::HALF_PIXEL,
|
|
ResizeNearest::ROUND_PREFER_FLOOR, Size(8, 8), 2, 2, -0.5, true,
|
|
{ 0.558823526f, 0.814942062f, 1.35698247f, 1.89705884f, 2.39705873f, 2.93713522f, 3.47917557f, 3.7352941f,
|
|
1.58329761f, 1.83941603f, 2.38145661f, 2.92153287f, 3.42153287f, 3.96160913f, 4.50364971f, 4.75976801f,
|
|
3.75145936f, 4.0075779f, 4.54961824f, 5.0896945f, 5.5896945f, 6.12977076f, 6.67181158f, 6.92792988f,
|
|
5.91176462f, 6.1678834f, 6.70992374f, 7.25f, 7.75f, 8.29007626f, 8.83211708f, 9.0882349f,
|
|
7.91176462f, 8.16788292f, 8.70992374f, 9.25f, 9.75f, 10.2900763f, 10.8321171f, 11.0882349f,
|
|
10.0720701f, 10.3281889f, 10.8702288f, 11.410305f, 11.910305f, 12.4503813f, 12.9924221f, 13.2485409f,
|
|
12.2402315f, 12.4963503f, 13.0383911f, 13.5784674f, 14.0784674f, 14.6185436f, 15.1605835f, 15.4167023f,
|
|
13.2647057f, 13.5208244f, 14.0628653f, 14.6029415f, 15.1029415f, 15.6430178f, 16.1850586f, 16.4411774f } },
|
|
{ "cubic_upsample_scales_asymmetric", &x44, INTER_CUBIC, ResizeCoord::ASYMMETRIC, ResizeNearest::ROUND_PREFER_FLOOR,
|
|
Size(8, 8), 2, 2, -0.75, false,
|
|
{ 1, 1.40625f, 2, 2.5f, 3, 3.59375f, 4, 4.09375f, 2.625f, 3.03125f, 3.625f, 4.125f, 4.625f, 5.21875f, 5.625f, 5.71875f,
|
|
5, 5.40625f, 6, 6.5f, 7, 7.59375f, 8, 8.09375f, 7, 7.40625f, 8, 8.5f, 9, 9.59375f, 10, 10.09375f,
|
|
9, 9.40625f, 10, 10.5f, 11, 11.59375f, 12, 12.09375f, 11.375f, 11.78125f, 12.375f, 12.875f, 13.375f, 13.96875f, 14.375f, 14.46875f,
|
|
13, 13.40625f, 14, 14.5f, 15, 15.59375f, 16, 16.09375f, 13.375f, 13.78125f, 14.375f, 14.875f, 15.375f, 15.96875f, 16.375f, 16.46875f } },
|
|
};
|
|
for (const OnnxCase& t : cases)
|
|
{
|
|
ResizeParams p(t.dsize, t.fx, t.fy, t.interp);
|
|
p.coordMode = t.coord;
|
|
p.nearestMode = t.nearest;
|
|
p.cubicCoeffA = (float)t.cubicA;
|
|
p.excludeOutside = t.exclude;
|
|
Mat dst;
|
|
resize(*t.src, dst, p);
|
|
ASSERT_EQ(t.dsize, dst.size()) << t.name;
|
|
const Mat expected = Mat(t.expected).reshape(1, t.dsize.height);
|
|
const double tol = t.interp == INTER_NEAREST ? 0 : 1e-5;
|
|
EXPECT_LE(cvtest::norm(expected, dst, NORM_INF), tol) << t.name << "\n" << dst << "\nvs\n" << expected;
|
|
}
|
|
}
|
|
|
|
// Hand-worked values, with the scale given as fx/fy where dsize is floor(size*scale).
|
|
TEST(Resize_Params, KnownValues)
|
|
{
|
|
{
|
|
// ONNX test_resize_downsample_scales_linear_align_corners: align_corners divides by the
|
|
// integer output length, so the 0.6 scale does not move the last sample off the corner.
|
|
Mat src = Mat_<float>({2, 4}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}), dst;
|
|
ResizeParams params(Size(2, 1), 0.6, 0.6);
|
|
params.coordMode = ResizeCoord::ALIGN_CORNERS;
|
|
resize(src, dst, params);
|
|
ASSERT_EQ(Size(2, 1), dst.size());
|
|
EXPECT_NEAR(1.f, dst.at<float>(0, 0), 1e-5);
|
|
EXPECT_NEAR(4.f, dst.at<float>(0, 1), 1e-5);
|
|
}
|
|
{
|
|
// ONNX test_resize_downsample_scales_linear_half_pixel_symmetric
|
|
Mat src = Mat_<float>({1, 4}, {1.f, 2.f, 3.f, 4.f}), dst;
|
|
ResizeParams params(Size(2, 1), 0.6, 1.0);
|
|
params.coordMode = ResizeCoord::HALF_PIXEL_SYMMETRIC;
|
|
resize(src, dst, params);
|
|
ASSERT_EQ(Size(2, 1), dst.size());
|
|
EXPECT_NEAR(1.6666666f, dst.at<float>(0, 0), 1e-5);
|
|
EXPECT_NEAR(3.3333333f, dst.at<float>(0, 1), 1e-5);
|
|
}
|
|
{
|
|
// One output sample: ALIGN_CORNERS and PYTORCH_HALF_PIXEL read the first, HALF_PIXEL the middle.
|
|
Mat src = Mat_<float>({1, 4}, {1.f, 2.f, 3.f, 4.f}), dst;
|
|
const struct { ResizeCoord mode; float expected; } modes[] = {
|
|
{ ResizeCoord::ALIGN_CORNERS, 1.f }, { ResizeCoord::PYTORCH_HALF_PIXEL, 1.f }, { ResizeCoord::HALF_PIXEL, 2.5f } };
|
|
for (const auto& m : modes)
|
|
for (int interp : { INTER_LINEAR, INTER_NEAREST })
|
|
{
|
|
ResizeParams params(Size(1, 1), 0, 0, interp);
|
|
params.coordMode = m.mode;
|
|
params.nearestMode = ResizeNearest::CEIL;
|
|
resize(src, dst, params);
|
|
const float expected = interp == INTER_NEAREST && m.mode == ResizeCoord::HALF_PIXEL ? 3.f : m.expected;
|
|
EXPECT_EQ(expected, dst.at<float>(0, 0)) << "mode " << (int)m.mode << " interpolation " << interp;
|
|
}
|
|
}
|
|
{
|
|
// An exact 2x linear downscale averages 2x2 blocks only when sampling at pixel centres;
|
|
// asymmetric samples land on src[2x] itself.
|
|
Mat src = Mat_<float>({2, 8}, {0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f,
|
|
0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f}), dst;
|
|
ResizeParams params(Size(4, 1));
|
|
params.coordMode = ResizeCoord::ASYMMETRIC;
|
|
resize(src, dst, params);
|
|
EXPECT_EQ(0, cvtest::norm(dst, Mat_<float>({1, 4}, {0.f, 2.f, 4.f, 6.f}), NORM_INF));
|
|
params.coordMode = ResizeCoord::HALF_PIXEL;
|
|
resize(src, dst, params);
|
|
EXPECT_EQ(0, cvtest::norm(dst, Mat_<float>({1, 4}, {0.5f, 2.5f, 4.5f, 6.5f}), NORM_INF));
|
|
|
|
// fx/fy pin the scale, so dsize may ask for more than the source covers. The samples past
|
|
// the edge repeat it, at the exact 2x too, where there are no 2x2 blocks left to average.
|
|
Mat ramp4 = repeat(Mat_<float>({1, 4}, {0.f, 1.f, 2.f, 3.f}), 4, 1);
|
|
ResizeParams pinned(Size(4, 4), 0.5, 0.5);
|
|
pinned.coordMode = ResizeCoord::HALF_PIXEL;
|
|
resize(ramp4, dst, pinned);
|
|
EXPECT_EQ(0, cvtest::norm(dst, repeat(Mat_<float>({1, 4}, {0.5f, 2.5f, 3.f, 3.f}), 4, 1), NORM_INF));
|
|
}
|
|
{
|
|
// A lone PIXEL_CENTER image keeps cubicCoeffA and excludeOutside, which classic resize,
|
|
// and the HAL behind it, would drop.
|
|
Mat src = makeTestImage(CV_8UC3, Size(37, 29), 5), single;
|
|
ResizeParams params(Size(23, 17), 0, 0, INTER_CUBIC);
|
|
params.cubicCoeffA = -0.5f;
|
|
params.excludeOutside = true;
|
|
resize(src, single, params);
|
|
EXPECT_EQ(0, cvtest::norm(single, resizeAlone(src, params), NORM_INF));
|
|
}
|
|
{
|
|
// CV_64F accumulates in double, as classic cv::resize does, though its weights are float:
|
|
// detail far below float resolution survives, the level is only float-weight accurate.
|
|
Mat src(1, 9, CV_64FC1), dst;
|
|
for (int x = 0; x < src.cols; x++)
|
|
src.at<double>(0, x) = 1.0 + x * 1e-12;
|
|
for (int interp : { INTER_LINEAR, INTER_CUBIC })
|
|
{
|
|
ResizeParams params(Size(5, 1), 0, 0, interp);
|
|
params.coordMode = ResizeCoord::HALF_PIXEL;
|
|
resize(src, dst, params);
|
|
ASSERT_EQ(CV_64F, dst.depth());
|
|
double lo, hi;
|
|
minMaxLoc(dst, &lo, &hi);
|
|
EXPECT_GT(hi - lo, 1e-13) << "interpolation=" << interp << ": detail lost to float";
|
|
EXPECT_LT(std::abs(hi - 1.0), 1e-6) << "interpolation=" << interp;
|
|
EXPECT_LT(std::abs(lo - 1.0), 1e-6) << "interpolation=" << interp;
|
|
}
|
|
}
|
|
}
|
|
|
|
// A vector of UMat goes image by image through the OpenCL path.
|
|
TEST(Resize_Params, UMatVector)
|
|
{
|
|
const Size dstSize(48, 64);
|
|
std::vector<UMat> srcs(2);
|
|
makeTestImage(CV_8UC3, Size(120, 90), 11).copyTo(srcs[0]);
|
|
makeTestImage(CV_8UC3, Size(90, 120), 22).copyTo(srcs[1]);
|
|
|
|
std::vector<UMat> actual;
|
|
resize(srcs, actual, ResizeParams(dstSize));
|
|
|
|
ASSERT_EQ(srcs.size(), actual.size());
|
|
for (size_t i = 0; i < srcs.size(); i++)
|
|
{
|
|
UMat expected;
|
|
resize(srcs[i], expected, dstSize, 0, 0, INTER_LINEAR);
|
|
EXPECT_EQ(0, cvtest::norm(expected.getMat(ACCESS_READ), actual[i].getMat(ACCESS_READ), NORM_INF)) << "index=" << i;
|
|
}
|
|
}
|
|
|
|
}} // namespace
|