From cc07c72547910db79357da62be134811142aca94 Mon Sep 17 00:00:00 2001 From: Abhishek Gola Date: Tue, 1 Dec 2026 23:18:38 +0530 Subject: [PATCH] Add Batch Resize Support (#29830) batch resize support --- modules/dnn/src/layers/resize2_layer.cpp | 215 +-- modules/imgproc/CMakeLists.txt | 1 + modules/imgproc/include/opencv2/imgproc.hpp | 141 ++ .../imgproc/misc/python/test/test_imgproc.py | 33 + modules/imgproc/perf/perf_resize_params.cpp | 193 ++ modules/imgproc/src/resize.avx2.cpp | 261 --- modules/imgproc/src/resize.cpp | 1429 +++++++++++---- modules/imgproc/src/resize.hpp | 84 - modules/imgproc/src/resize.lasx.cpp | 249 --- modules/imgproc/src/resize.simd.hpp | 170 ++ modules/imgproc/src/resize.sse4_1.cpp | 230 --- modules/imgproc/test/test_imgwarp.cpp | 6 +- modules/imgproc/test/test_resize_bitexact.cpp | 138 +- modules/imgproc/test/test_resize_params.cpp | 1611 +++++++++++++++++ modules/java/generator/gen_java.py | 7 +- 15 files changed, 3452 insertions(+), 1316 deletions(-) create mode 100644 modules/imgproc/perf/perf_resize_params.cpp delete mode 100644 modules/imgproc/src/resize.avx2.cpp delete mode 100644 modules/imgproc/src/resize.hpp delete mode 100644 modules/imgproc/src/resize.lasx.cpp create mode 100644 modules/imgproc/src/resize.simd.hpp delete mode 100644 modules/imgproc/src/resize.sse4_1.cpp create mode 100644 modules/imgproc/test/test_resize_params.cpp diff --git a/modules/dnn/src/layers/resize2_layer.cpp b/modules/dnn/src/layers/resize2_layer.cpp index 838946ec1e..7fcc0fc123 100644 --- a/modules/dnn/src/layers/resize2_layer.cpp +++ b/modules/dnn/src/layers/resize2_layer.cpp @@ -29,68 +29,61 @@ namespace cv { namespace dnn { namespace { -enum class CoordTransMode { - HALF_PIXEL, - PYTORCH_HALF_PIXEL, - TF_HALF_PIXEL_FOR_NN, - TF_CROP_AND_RESIZE, - HALF_PIXEL_SYMMETRIC, - ASYMMETRIC -}; - -static inline CoordTransMode parseCoordTransMode(const String& s) +// ONNX coordinate_transformation_mode as the cv::ResizeCoord that cv::resize takes as well. +// tf_crop_and_resize has no ResizeCoord: it maps the ROI input rather than the whole axis, so the +// layer keeps it as a separate flag (see isCropAndResize). +static inline ResizeCoord parseCoordTransMode(const String& s) { - if (s == "half_pixel") return CoordTransMode::HALF_PIXEL; - if (s == "pytorch_half_pixel") return CoordTransMode::PYTORCH_HALF_PIXEL; - if (s == "tf_half_pixel_for_nn") return CoordTransMode::TF_HALF_PIXEL_FOR_NN; - if (s == "tf_crop_and_resize") return CoordTransMode::TF_CROP_AND_RESIZE; - if (s == "half_pixel_symmetric") return CoordTransMode::HALF_PIXEL_SYMMETRIC; - return CoordTransMode::ASYMMETRIC; + if (s == "half_pixel") return ResizeCoord::HALF_PIXEL; + if (s == "pytorch_half_pixel") return ResizeCoord::PYTORCH_HALF_PIXEL; + if (s == "tf_half_pixel_for_nn") return ResizeCoord::TF_HALF_PIXEL_FOR_NN; + if (s == "half_pixel_symmetric") return ResizeCoord::HALF_PIXEL_SYMMETRIC; + if (s == "align_corners") return ResizeCoord::ALIGN_CORNERS; + return ResizeCoord::ASYMMETRIC; } -enum class NearestMode { - FLOOR, - CEIL, - ROUND_PREFER_CEIL, - ROUND_PREFER_FLOOR -}; +static inline bool isCropAndResize(const String& s) +{ + return s == "tf_crop_and_resize"; +} using std::clamp; -static inline NearestMode parseNearestMode(const String& s) +static inline ResizeNearest parseNearestMode(const String& s) { - if (s == "floor") return NearestMode::FLOOR; - if (s == "ceil") return NearestMode::CEIL; - if (s == "round_prefer_ceil") return NearestMode::ROUND_PREFER_CEIL; - return NearestMode::ROUND_PREFER_FLOOR; + if (s == "floor") return ResizeNearest::FLOOR; + if (s == "ceil") return ResizeNearest::CEIL; + if (s == "round_prefer_ceil") return ResizeNearest::ROUND_PREFER_CEIL; + return ResizeNearest::ROUND_PREFER_FLOOR; } static constexpr int kResizeNumStripes = 16; inline float computeSrcGeneric(int dst, float scale, int limit, int len, - CoordTransMode coordTransMode, bool /*halfPixelCenters*/, + ResizeCoord coordMode, bool cropAndResize, float start_coord = 0.0f, float end_coord = 1.0f) { - if (coordTransMode == CoordTransMode::TF_CROP_AND_RESIZE) + if (cropAndResize) { if (len > 1) return start_coord * (limit - 1) + dst * (end_coord - start_coord) * (limit - 1) / float(len - 1); else return 0.5f * (start_coord + end_coord) * (limit - 1); } - if (coordTransMode == CoordTransMode::PYTORCH_HALF_PIXEL) + if (coordMode == ResizeCoord::PYTORCH_HALF_PIXEL) return (len > 1) ? (dst + 0.5f)*scale - 0.5f : 0.f; - if (coordTransMode == CoordTransMode::HALF_PIXEL) + if (coordMode == ResizeCoord::HALF_PIXEL) return (dst + 0.5f)*scale - 0.5f; - if (coordTransMode == CoordTransMode::TF_HALF_PIXEL_FOR_NN) + if (coordMode == ResizeCoord::TF_HALF_PIXEL_FOR_NN) return (dst + 0.5f)*scale; - if (coordTransMode == CoordTransMode::HALF_PIXEL_SYMMETRIC) + if (coordMode == ResizeCoord::HALF_PIXEL_SYMMETRIC) { // ONNX half_pixel_symmetric: offset = center*(1 - len_resized/(len_orig*x_scale)), // with scale == 1/x_scale and limit == input length. const float offset = limit*0.5f - len*scale*0.5f; return offset + (dst + 0.5f)*scale - 0.5f; } + // ASYMMETRIC, and ALIGN_CORNERS, whose scale updateOutSizeAndScale() set to (in-1)/(out-1) return dst*scale; } @@ -101,18 +94,18 @@ static inline void buildNearestIndexMap(std::vector& map, int len, float start_coord, float end_coord, - CoordTransMode coordTransMode, - NearestMode nearestMode, - bool halfPixelCenters) + ResizeCoord coordMode, + ResizeNearest nearestMode, + bool cropAndResize) { auto nearestIndex = [&](float src) { const int f = cvFloor(src); const float frac = src - f; const float eps = 1e-6f; int idx; - if (nearestMode == NearestMode::FLOOR) idx = cvFloor(src); - else if (nearestMode == NearestMode::CEIL) idx = cvCeil(src); - else if (nearestMode == NearestMode::ROUND_PREFER_CEIL) { + if (nearestMode == ResizeNearest::FLOOR) idx = cvFloor(src); + else if (nearestMode == ResizeNearest::CEIL) idx = cvCeil(src); + else if (nearestMode == ResizeNearest::ROUND_PREFER_CEIL) { idx = (abs(frac - 0.5f) <= eps) ? (f + 1) : cvRound(src); } else { idx = (abs(frac - 0.5f) <= eps) ? f : cvRound(src); @@ -124,8 +117,8 @@ static inline void buildNearestIndexMap(std::vector& map, for (int i = 0; i < outLen; ++i) { float src = computeSrcGeneric(i, scale, inLen, len, - coordTransMode, halfPixelCenters, start_coord, end_coord); - if (coordTransMode == CoordTransMode::TF_CROP_AND_RESIZE) { + coordMode, cropAndResize, start_coord, end_coord); + if (cropAndResize) { if (src < 0.f || src >= float(inLen)) { map[i] = -1; // out of bounds continue; @@ -147,8 +140,7 @@ static inline void buildBilinearIndexAndLerp(std::vector& i0, int len, float start_coord, float end_coord, - CoordTransMode coordTransMode, - bool halfPixelCenters, + ResizeCoord coordMode, bool tf_crop_and_resize_mode) { i0.resize(outLen); @@ -159,7 +151,7 @@ static inline void buildBilinearIndexAndLerp(std::vector& i0, for (int o = 0; o < outLen; ++o) { float src = computeSrcGeneric(o, scale, inLen, len, - coordTransMode, halfPixelCenters, start_coord, end_coord); + coordMode, tf_crop_and_resize_mode, start_coord, end_coord); if (tf_crop_and_resize_mode) { if (src < 0.f || src > float(inLen - 1)) { @@ -202,8 +194,7 @@ static inline void buildCubicIndexAndWeights(std::vector>& ids int len, float start_coord, float end_coord, - CoordTransMode coordTransMode, - bool halfPixelCenters, + ResizeCoord coordMode, bool tf_crop_and_resize_mode, bool excludeOutside, float cubicA) @@ -215,7 +206,7 @@ static inline void buildCubicIndexAndWeights(std::vector>& ids for (int o = 0; o < outLen; ++o) { float src = computeSrcGeneric(o, scale, inLen, len, - coordTransMode, halfPixelCenters, start_coord, end_coord); + coordMode, tf_crop_and_resize_mode, start_coord, end_coord); int i = int(std::floor(src)); float d = src - i; float sw = 0.f; @@ -272,9 +263,9 @@ template void resizeNearest(const Mat &inp, Mat &out, float scaleH, float scaleW, int lenY, int lenX, - NearestMode nearestMode, - const String &coordTransMode, - bool halfPixelCenters, + ResizeNearest nearestMode, + ResizeCoord coordMode, + bool tf_crop_and_resize_mode, float start_y = 0.0f, float end_y = 1.0f, float start_x = 0.0f, float end_x = 1.0f, float extrapolation_value = 0.0f) @@ -283,16 +274,13 @@ void resizeNearest(const Mat &inp, Mat &out, int outH = out.size[2], outW = out.size[3]; CV_Assert(inp.isContinuous() && out.isContinuous()); - CoordTransMode coordMode = parseCoordTransMode(coordTransMode); - const bool tf_crop_and_resize_mode = (coordMode == CoordTransMode::TF_CROP_AND_RESIZE); - std::vector mapY(outH); buildNearestIndexMap(mapY, outH, inH, scaleH, lenY, start_y, end_y, - coordMode, nearestMode, halfPixelCenters); + coordMode, nearestMode, tf_crop_and_resize_mode); std::vector mapX(outW); buildNearestIndexMap(mapX, outW, inW, scaleW, lenX, start_x, end_x, - coordMode, nearestMode, halfPixelCenters); + coordMode, nearestMode, tf_crop_and_resize_mode); if (inp.shape().layout == DATA_LAYOUT_BLOCK) { CV_Assert(inp.dims == 5 && out.dims == 5); @@ -393,8 +381,8 @@ template void resizeBilinear(const Mat &inp, Mat &out, float scaleH, float scaleW, int lenY, int lenX, - const String &coordTransMode, - bool halfPixelCenters, + ResizeCoord coordMode, + bool tf_crop_and_resize_mode, float start_y = 0.0f, float end_y = 1.0f, float start_x = 0.0f, float end_x = 1.0f, float extrapolation_value = 0.0f) @@ -403,22 +391,19 @@ void resizeBilinear(const Mat &inp, Mat &out, int outH = out.size[2], outW = out.size[3]; CV_Assert(inp.isContinuous() && out.isContinuous()); - CoordTransMode coordMode = parseCoordTransMode(coordTransMode); - const bool tf_crop_and_resize_mode = (coordMode == CoordTransMode::TF_CROP_AND_RESIZE); - std::vector x0(outW), x1(outW); std::vector lx(outW); std::vector outOfBoundsX(outW); buildBilinearIndexAndLerp(x0, x1, lx, outOfBoundsX, outW, inW, scaleW, lenX, start_x, end_x, - coordMode, halfPixelCenters, tf_crop_and_resize_mode); + coordMode, tf_crop_and_resize_mode); std::vector y0(outH), y1(outH); std::vector ly(outH); std::vector outOfBoundsY(outH); buildBilinearIndexAndLerp(y0, y1, ly, outOfBoundsY, outH, inH, scaleH, lenY, start_y, end_y, - coordMode, halfPixelCenters, tf_crop_and_resize_mode); + coordMode, tf_crop_and_resize_mode); if (inp.shape().layout == DATA_LAYOUT_BLOCK) { CV_Assert(inp.dims == 5 && out.dims == 5); @@ -556,7 +541,7 @@ void resizeCubic(const Mat &inp, Mat &out, float scaleH, float scaleW, int lenY, int lenX, float cubicA, bool excludeOutside, - const String &coordTransMode, bool halfPixelCenters, + ResizeCoord coordMode, bool tf_crop_and_resize_mode, float start_y = 0.0f, float end_y = 1.0f, float start_x = 0.0f, float end_x = 1.0f, float extrapolation_value = 0.0f) @@ -564,15 +549,12 @@ void resizeCubic(const Mat &inp, Mat &out, int inH = inp.size[2], inW = inp.size[3]; int outH = out.size[2], outW = out.size[3]; - CoordTransMode coordMode = parseCoordTransMode(coordTransMode); - const bool tf_crop_and_resize_mode = (coordMode == CoordTransMode::TF_CROP_AND_RESIZE); - std::vector> x_id(outW); std::vector> x_w (outW); std::vector outOfBoundsX(outW); buildCubicIndexAndWeights(x_id, x_w, outOfBoundsX, outW, inW, scaleW, lenX, start_x, end_x, - coordMode, halfPixelCenters, tf_crop_and_resize_mode, + coordMode, tf_crop_and_resize_mode, excludeOutside, cubicA); std::vector> y_id(outH); @@ -580,7 +562,7 @@ void resizeCubic(const Mat &inp, Mat &out, std::vector outOfBoundsY(outH); buildCubicIndexAndWeights(y_id, y_w, outOfBoundsY, outH, inH, scaleH, lenY, start_y, end_y, - coordMode, halfPixelCenters, tf_crop_and_resize_mode, + coordMode, tf_crop_and_resize_mode, excludeOutside, cubicA); if (inp.shape().layout == DATA_LAYOUT_BLOCK) { @@ -800,7 +782,7 @@ struct AAWeights }; static void buildAAWeights(AAWeights& p, int inS, int outS, float xscale, - bool cubic, float cubicA, CoordTransMode coordMode) + bool cubic, float cubicA, ResizeCoord coordMode, bool cropAndResize) { const float scaleC = 1.f / xscale; // input/output direction const float radius = cubic ? 2.f : 1.f; @@ -812,7 +794,7 @@ static void buildAAWeights(AAWeights& p, int inS, int outS, float xscale, std::vector tmp; for (int y = 0; y < outS; y++) { - const float center = computeSrcGeneric(y, scaleC, inS, outS, coordMode, true); + const float center = computeSrcGeneric(y, scaleC, inS, outS, coordMode, cropAndResize); const int xmin = (int)std::floor(center - support + 0.5f); const int xmax = (int)std::floor(center + support + 0.5f); // inclusive const int lo = std::min(std::max(xmin, 0), inS - 1); @@ -837,7 +819,7 @@ static void buildAAWeights(AAWeights& p, int inS, int outS, float xscale, template void resizeAntialias(const Mat& inp, Mat& out, float xscaleH, float xscaleW, - bool cubic, float cubicA, CoordTransMode coordMode) + bool cubic, float cubicA, ResizeCoord coordMode, bool cropAndResize) { CV_Assert(inp.dims == 4 && out.dims == 4 && inp.isContinuous() && out.isContinuous()); const int N = inp.size[0], C = inp.size[1]; @@ -845,8 +827,8 @@ void resizeAntialias(const Mat& inp, Mat& out, const int outH = out.size[2], outW = out.size[3]; AAWeights px, py; - buildAAWeights(px, inW, outW, xscaleW, cubic, cubicA, coordMode); - buildAAWeights(py, inH, outH, xscaleH, cubic, cubicA, coordMode); + buildAAWeights(px, inW, outW, xscaleW, cubic, cubicA, coordMode, cropAndResize); + buildAAWeights(py, inH, outH, xscaleH, cubic, cubicA, coordMode, cropAndResize); const int planes = N * C; parallel_for_(Range(0, planes), [&](const Range& r) { @@ -918,10 +900,13 @@ public: excludeOutside = params.get("exclude_outside", false); dynamicROI = params.get("dynamic_roi", false); - alignCorners = params.get("align_corners", false); - halfPixelCenters = params.get("half_pixel_centers", false); - coordTransMode = params.get("coordinate_transformation_mode", "half_pixel"); + const String coordTransMode = params.get("coordinate_transformation_mode", "half_pixel"); coordTransModeE = parseCoordTransMode(coordTransMode); + cropAndResize = isCropAndResize(coordTransMode); + // The importer sets align_corners from the mode as well; params built by hand may only + // name the mode. + alignCorners = params.get("align_corners", coordTransModeE == ResizeCoord::ALIGN_CORNERS); + halfPixelCenters = params.get("half_pixel_centers", false); if (interpolation == "opencv_linear") halfPixelCenters = true; @@ -1191,7 +1176,7 @@ public: updateOutSizeAndScale(inpShape, outShape); // Read ROI if dynamicROI is enabled - if (dynamicROI && coordTransModeE == CoordTransMode::TF_CROP_AND_RESIZE && ninputs >= 2) + if (dynamicROI && cropAndResize && ninputs >= 2) { Mat roiTensor = inputs[1]; std::vector roi; @@ -1250,8 +1235,7 @@ public: // align_corners maps the output corners onto the input corners, so it keeps the // shape-derived (in - 1) / (out - 1) set by updateOutSizeAndScale(); "sizes" and // tf_crop_and_resize do not use the scale either. - if (sizes.empty() && !alignCorners && onnxScaleH > 0 && onnxScaleW > 0 && - coordTransModeE != CoordTransMode::TF_CROP_AND_RESIZE) + if (sizes.empty() && !alignCorners && onnxScaleH > 0 && onnxScaleW > 0 && !cropAndResize) { scaleHeight = 1.f / onnxScaleH; scaleWidth = 1.f / onnxScaleW; @@ -1315,36 +1299,59 @@ public: const float xsH = onnxScaleH > 0.f ? onnxScaleH : float(outShape[2]) / inpShape[2]; const float xsW = onnxScaleW > 0.f ? onnxScaleW : float(outShape[3]) / inpShape[3]; switch (depth) { - case CV_8S: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE); break; - case CV_8U: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE); break; - case CV_16F: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE); break; - case CV_16BF: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE); break; - case CV_32F: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE); break; + case CV_8S: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE, cropAndResize); break; + case CV_8U: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE, cropAndResize); break; + case CV_16F: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE, cropAndResize); break; + case CV_16BF: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE, cropAndResize); break; + case CV_32F: resizeAntialias(inp, out, xsH, xsW, cubic, cubicCoeffA, coordTransModeE, cropAndResize); break; default: CV_Error(Error::StsUnsupportedFormat, "Unsupported depth"); } } + else if ((interpolation == "nearest" || interpolation == "bilinear" || interpolation == "opencv_linear" || interpolation == "cubic") && + inp.dims == 4 && inp.shape().layout != DATA_LAYOUT_BLOCK && + !cropAndResize && + (!alignCorners || coordTransModeE == ResizeCoord::ASYMMETRIC || + coordTransModeE == ResizeCoord::ALIGN_CORNERS) && + (depth == CV_32F || (depth == CV_8U && interpolation == "nearest"))) + { + // cv::resize treats inp's N,C dims as a batch; other kernels handle remaining cases. + ResizeParams params; + params.interpolation = (interpolation == "nearest") ? INTER_NEAREST + : (interpolation == "cubic") ? INTER_CUBIC : INTER_LINEAR; + params.coordMode = alignCorners ? ResizeCoord::ALIGN_CORNERS : coordTransModeE; + params.nearestMode = nearestModeE; + params.excludeOutside = excludeOutside; + params.cubicCoeffA = cubicCoeffA; + + // The true scale, not out/in: ONNX steps by 1/scale. align_corners ignores it and + // uses (in-1)/(out-1), as the layer's own kernels do. + params.dsize = Size(out.size[3], out.size[2]); + params.fx = onnxScaleW > 0.f ? onnxScaleW : (double)out.size[3] / inp.size[3]; + params.fy = onnxScaleH > 0.f ? onnxScaleH : (double)out.size[2] / inp.size[2]; + resize(inp, out, params); + } else if(interpolation=="nearest"){ switch(depth){ case CV_8S: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_8U: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16F: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16BF: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_32F: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_32S: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_64S: - resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeNearest(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,nearestModeE,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; default: CV_Error(Error::StsUnsupportedFormat,"Unsupported depth"); } @@ -1352,19 +1359,19 @@ public: else if(interpolation=="bilinear"||interpolation=="opencv_linear"){ switch(depth){ case CV_8S: - resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_8U: - resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16F: - resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16BF: - resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_32F: - resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeBilinear(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; default: CV_Error(Error::StsUnsupportedFormat,"Unsupported depth"); } @@ -1372,19 +1379,19 @@ public: else if(interpolation=="cubic"){ switch (depth) { case CV_8S: - resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_8U: - resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16F: - resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_16BF: - resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; case CV_32F: - resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransMode,halfPixelCenters,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); + resizeCubic(inp,out,scaleHeight,scaleWidth,length_resized_y,length_resized_x,cubicCoeffA,excludeOutside,coordTransModeE,cropAndResize,roi_start_y,roi_end_y,roi_start_x,roi_end_x,extrapolation_value); break; default: CV_Error(Error::StsUnsupportedFormat, "Unsupported depth"); @@ -1549,9 +1556,9 @@ protected: bool alignCorners; bool dynamicROI; bool halfPixelCenters; - String coordTransMode; - CoordTransMode coordTransModeE; - NearestMode nearestModeE; // ONNX "nearest_mode" attribute + ResizeCoord coordTransModeE; // ONNX "coordinate_transformation_mode" attribute + bool cropAndResize; // ... when it is "tf_crop_and_resize" + ResizeNearest nearestModeE; // ONNX "nearest_mode" attribute bool excludeOutside; // ONNX attribute for cubic float cubicCoeffA; float roi_start_y, roi_end_y, roi_start_x, roi_end_x; diff --git a/modules/imgproc/CMakeLists.txt b/modules/imgproc/CMakeLists.txt index 2ff7c5ceaa..5b858175cd 100644 --- a/modules/imgproc/CMakeLists.txt +++ b/modules/imgproc/CMakeLists.txt @@ -16,6 +16,7 @@ ocv_add_dispatched_file(remap SSE2 SSE4_1 AVX2 AVX512_SKX AVX512_ICL) ocv_add_dispatched_file(undistort SSE2 AVX2) ocv_add_dispatched_file(equalize_hist AVX512_ICL) ocv_add_dispatched_file(pyramids_avx512_vbmi AVX512_ICL) +ocv_add_dispatched_file(resize SSE4_1 AVX2 LASX) ocv_define_module(imgproc opencv_core opencv_geometry WRAP java objc python js) diff --git a/modules/imgproc/include/opencv2/imgproc.hpp b/modules/imgproc/include/opencv2/imgproc.hpp index fd52122d11..3c7abdf679 100644 --- a/modules/imgproc/include/opencv2/imgproc.hpp +++ b/modules/imgproc/include/opencv2/imgproc.hpp @@ -2133,12 +2133,153 @@ src.size(), fx, and fy; the type of dst is the same as of src. \f[\texttt{(double)dsize.height/src.rows}\f] @param interpolation interpolation method, see #InterpolationFlags +@note `src` may also be an N-D tensor or `std::vector`/`std::vector` -- see the +@ref resize(InputArray,OutputArray,const ResizeParams&) overload below. + @sa warpAffine, warpPerspective, remap */ CV_EXPORTS_W void resize( InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR ); +/** @brief Coordinate mapping convention used to align source and destination samples during resize. + +#ResizeCoord::PIXEL_CENTER is classic #resize's convention; the others are ONNX Resize's +`coordinate_transformation_mode` values. All of them are resolved while the interpolation tables +are built, so they all run the same kernels at the same speed. #INTER_AREA is the exception: its +decimation geometry is tied to #ResizeCoord::PIXEL_CENTER, so it accepts no other mode. + +@note The bit-exact kernels behind #INTER_NEAREST_EXACT and #INTER_LINEAR_EXACT exist only for +#ResizeCoord::PIXEL_CENTER, so those two flags are rejected with any other mode. + +@note #ResizeCoord::HALF_PIXEL_SYMMETRIC needs the true scale -- pass it via +@ref cv::ResizeParams::fx "ResizeParams::fx" / @ref cv::ResizeParams::fy "ResizeParams::fy". +#ResizeCoord::ALIGN_CORNERS uses only the input and output sizes, as ONNX defines it. +*/ +enum class ResizeCoord +{ + PIXEL_CENTER = 0, //!< OpenCV's fixed pixel-center formula (default, matches classic #resize) + HALF_PIXEL, //!< ONNX Resize "half_pixel": `src = (dst + 0.5) * scale - 0.5` + PYTORCH_HALF_PIXEL, //!< ONNX Resize "pytorch_half_pixel": #ResizeCoord::HALF_PIXEL, but `src = 0` when the output axis has length 1 + ALIGN_CORNERS, //!< ONNX Resize "align_corners": `src = dst * (srcLen-1)/(dstLen-1)` + ASYMMETRIC, //!< ONNX Resize "asymmetric": `src = dst * scale` + TF_HALF_PIXEL_FOR_NN, //!< ONNX Resize "tf_half_pixel_for_nn": `src = (dst + 0.5) * scale` + HALF_PIXEL_SYMMETRIC //!< ONNX Resize "half_pixel_symmetric"; see @ref ResizeCoord note +}; + +/** @brief Index-rounding rule used by #cv::INTER_NEAREST in non-default coordinate modes. + +Applies when @ref cv::ResizeParams::coordMode "ResizeParams::coordMode" is not +#ResizeCoord::PIXEL_CENTER; matches ONNX Resize's `nearest_mode` attribute. #ResizeCoord::PIXEL_CENTER +always rounds down, which is what classic #resize does. + +The source coordinate is computed as ONNX Resize defines it, dividing by the scale, and a tie is +only a coordinate whose fractional part is exactly 0.5: with `f = floor(x)`, +#ResizeNearest::ROUND_PREFER_FLOOR picks `f + (x - f > 0.5)` and #ResizeNearest::ROUND_PREFER_CEIL +picks `f + (x - f >= 0.5)`. The index is then clamped to the image. +*/ +enum class ResizeNearest +{ + FLOOR = 0, //!< always round down + CEIL, //!< always round up + ROUND_PREFER_CEIL, //!< round to nearest, ties go up + ROUND_PREFER_FLOOR //!< round to nearest, ties go down (ONNX Resize's default) +}; + +/** @brief Parameters of the struct-based and batched #resize overload. + +Collects the output geometry and every interpolation flag in one place, like +@ref cv::dnn::Image2BlobParams, so that #resize does not need a growing argument list. + +@sa resize +*/ +struct CV_EXPORTS_W_SIMPLE ResizeParams +{ + CV_WRAP ResizeParams(); + + /** @brief Constructs the parameters from the output geometry. + @param dsize output spatial size, see @ref dsize. + @param fx horizontal scale factor, see @ref fx. + @param fy vertical scale factor, see @ref fy. + @param interpolation interpolation method, see @ref interpolation. + */ + CV_WRAP ResizeParams(Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR); + + //! output spatial size: the height/width of the last two dimensions for a batch, or of the whole + //! image for a single 2D input. When empty, it is computed from #fx and #fy, which then must be + //! positive. + CV_PROP_RW Size dsize; + + //! scale factor along the horizontal axis; when it equals 0, it is computed as + //! `(double)dsize.width/src.cols`. For a @ref coordMode other than #ResizeCoord::PIXEL_CENTER, + //! pass the scale you already know (an ONNX "scales" input, say): dividing a floored @ref dsize + //! back out only recovers it when @ref dsize was itself `round(srcSize * scale)`. + CV_PROP_RW double fx; + + //! scale factor along the vertical axis; see @ref fx. + CV_PROP_RW double fy; + + //! interpolation method, see #InterpolationFlags. #INTER_NEAREST_EXACT and + //! #INTER_LINEAR_EXACT ask for the bit-exact kernels and need #ResizeCoord::PIXEL_CENTER. + CV_PROP_RW int interpolation; + + //! coordinate mapping convention; see #ResizeCoord + CV_PROP_RW ResizeCoord coordMode; + + //! index-rounding rule for #INTER_NEAREST; see #ResizeNearest + CV_PROP_RW ResizeNearest nearestMode; + + //! Keys cubic coefficient for #INTER_CUBIC (ONNX `cubic_coeff_a`). Default -0.75, which is + //! what classic #resize uses. + CV_PROP_RW float cubicCoeffA; + + //! Zero-weight the taps that fall outside the image and renormalise the rest, instead of + //! replicating the edge sample (ONNX `exclude_outside`). Only #INTER_CUBIC and #INTER_LANCZOS4 + //! are affected: with two taps the two rules agree. + CV_PROP_RW bool excludeOutside; + + //! apply antialiasing filter when downscaling (not yet implemented) + CV_PROP_RW bool antialias; + + //! precision/speed hint, consistent with #warpAffine/#warpPerspective/#remap/#cvtColor. + //! Reserved -- resize has no approximate path yet. + CV_PROP_RW AlgorithmHint hint; +}; + +/** @overload + +Accepts the same three `src` kinds, picked at runtime from `src.kind()`: + +- a single 2D image; +- an N-D tensor (`dims >= 3`): the leading dimensions are batch axes and the last two are height and + width. Every plane is resized to the same size, so the interpolation tables are computed once and + shared by the whole batch; +- a `std::vector`/`std::vector`, whose elements may differ in size. Tables are shared + between the elements that happen to have the same size. C++ only, not usable from Python. + +A batch is scheduled as one unit rather than image by image: its rows are split into groups of +about equal estimated work, which depends on the interpolation and the scale as well as on the +output size, so the threads are used evenly whether it holds two large images or hundreds of small +ones. A single image is scheduled by the same rule. + +@ref ResizeParams::coordMode "coordMode", @ref ResizeParams::nearestMode "nearestMode", +@ref ResizeParams::cubicCoeffA "cubicCoeffA" and @ref ResizeParams::excludeOutside "excludeOutside" +only change the interpolation tables, so every combination of them runs at the same speed. + +@note A `std::vector` is resized element by element on the OpenCL device; the shared tables +and the single parallel loop apply to the two host-memory kinds. + +@note A batch always runs OpenCV's own kernels: a custom HAL takes whole images only, so using it +would give up both the shared tables and the even split. With such a HAL installed (IPP, for +instance) a batch can therefore differ from the same images resized one at a time, by however +much the two kernels round differently. + +@param src input image, N-D batch tensor, or `std::vector`/`std::vector` (see above). +@param dst output image or batch, matching `src`'s kind; see #resize. +@param params output geometry and interpolation parameters, see @ref ResizeParams. +*/ +CV_EXPORTS_W void resize( InputArray src, OutputArray dst, const ResizeParams& params ); + /** @brief Applies an affine transformation to an image. The function warpAffine transforms the source image using the specified matrix: diff --git a/modules/imgproc/misc/python/test/test_imgproc.py b/modules/imgproc/misc/python/test/test_imgproc.py index b213783323..3a5ca9e2a8 100644 --- a/modules/imgproc/misc/python/test/test_imgproc.py +++ b/modules/imgproc/misc/python/test/test_imgproc.py @@ -64,3 +64,36 @@ class Imgproc_Tests(NewOpenCVTests): # a single HWC image is still accepted res = cv.remap(batch[0], map_x, map_y, cv.INTER_NEAREST) self.assertEqual(res.shape, (3, 5, 3)) + + def test_resize_params(self): + img = np.random.randint(0, 256, size=(37, 51, 3), dtype=np.uint8) + + # The default parameters are classic resize, given a size or a scale. + params = cv.ResizeParams((24, 17)) + self.assertEqual(params.coordMode, cv.ResizeCoord_PIXEL_CENTER) + np.testing.assert_array_equal(cv.resize(img, params), cv.resize(img, (24, 17))) + np.testing.assert_array_equal(cv.resize(img, cv.ResizeParams((0, 0), 0.5, 0.5)), + cv.resize(img, None, fx=0.5, fy=0.5)) + + # A 4-D array is a batch: every (n, c) plane is resized to dsize. + batch = np.random.rand(2, 3, 16, 16).astype(np.float32) + params = cv.ResizeParams((32, 8), interpolation=cv.INTER_NEAREST) + params.coordMode = cv.ResizeCoord_ASYMMETRIC + params.nearestMode = cv.ResizeNearest_FLOOR + out = cv.resize(batch, params) + self.assertEqual(out.shape, (2, 3, 8, 32)) + # asymmetric + floor takes src[floor(dst * in / out)] on each axis + rows = np.arange(8) * 2 + cols = np.arange(32) // 2 + np.testing.assert_array_equal(out, batch[:, :, rows][:, :, :, cols]) + + # Each plane of a batch comes out exactly as it does on its own. + params = cv.ResizeParams((12, 9), interpolation=cv.INTER_CUBIC) + params.coordMode = cv.ResizeCoord_HALF_PIXEL + params.cubicCoeffA = -0.5 + params.excludeOutside = True + out = cv.resize(batch, params) + self.assertEqual(out.shape, (2, 3, 9, 12)) + for n in range(2): + for c in range(3): + np.testing.assert_array_equal(out[n, c], cv.resize(batch[n, c], params)) diff --git a/modules/imgproc/perf/perf_resize_params.cpp b/modules/imgproc/perf/perf_resize_params.cpp new file mode 100644 index 0000000000..6695200cb6 --- /dev/null +++ b/modules/imgproc/perf/perf_resize_params.cpp @@ -0,0 +1,193 @@ +// 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 "perf_precomp.hpp" + +namespace opencv_test { + +// ResizeCoord as an int, so the report lists the mode next to its timing: +// 0 PIXEL_CENTER, 1 HALF_PIXEL, 2 PYTORCH_HALF_PIXEL, 3 ALIGN_CORNERS, +// 4 ASYMMETRIC, 5 TF_HALF_PIXEL_FOR_NN, 6 HALF_PIXEL_SYMMETRIC. +typedef tuple Type_Interp_Coord_t; +typedef TestBaseWithParam ResizeParams_CoordMode; + +// The modes only change tables; an outlier means a mode left the fast path. +PERF_TEST_P(ResizeParams_CoordMode, coord_modes_1080p_to_VGA, + testing::Values( + Type_Interp_Coord_t(CV_8UC3, INTER_LINEAR, 1), + Type_Interp_Coord_t(CV_8UC3, INTER_LINEAR, 3), + Type_Interp_Coord_t(CV_8UC3, INTER_NEAREST, 4), + Type_Interp_Coord_t(CV_32FC1, INTER_CUBIC, 1), + Type_Interp_Coord_t(CV_32FC1, INTER_CUBIC, 6), + Type_Interp_Coord_t(CV_32FC1, INTER_LANCZOS4, 2))) +{ + const int matType = get<0>(GetParam()); + const int interp = get<1>(GetParam()); + const int coord = get<2>(GetParam()); + + Mat src(sz1080p, matType), dst(szVGA, matType); + RNG(0x5eed).fill(src, RNG::UNIFORM, 0, 255); + declare.in(src).out(dst); + + ResizeParams params(szVGA, 0, 0, interp); + params.coordMode = (ResizeCoord)coord; + + TEST_CYCLE() resize(src, dst, params); + + SANITY_CHECK_NOTHING(); +} + +typedef TestBaseWithParam > ResizeParams_NearestMode; + +// nearest_mode picks the rounding rule while the table is built. +PERF_TEST_P(ResizeParams_NearestMode, nearest_modes_1080p_to_VGA, + testing::Values( + make_tuple(MatType(CV_8UC3), (int)ResizeNearest::ROUND_PREFER_FLOOR), + make_tuple(MatType(CV_16UC1), (int)ResizeNearest::FLOOR))) +{ + const int matType = get<0>(GetParam()); + const int round = get<1>(GetParam()); + + Mat src(sz1080p, matType), dst(szVGA, matType); + RNG(0x5eed).fill(src, RNG::UNIFORM, 0, 255); + declare.in(src).out(dst); + + ResizeParams params(szVGA, 0, 0, INTER_NEAREST); + params.coordMode = ResizeCoord::HALF_PIXEL; + params.nearestMode = (ResizeNearest)round; + + TEST_CYCLE() resize(src, dst, params); + + SANITY_CHECK_NOTHING(); +} + +typedef TestBaseWithParam ResizeParams_ExcludeOutside; + +// exclude_outside only zeroes and renormalises weights in the table, so it is free at run time. +PERF_TEST_P(ResizeParams_ExcludeOutside, exclude_outside_cubic_1080p_to_VGA, testing::Bool()) +{ + const bool exclude = GetParam(); + + Mat src(sz1080p, CV_8UC3), dst(szVGA, CV_8UC3); + RNG(0x5eed).fill(src, RNG::UNIFORM, 0, 255); + declare.in(src).out(dst); + + ResizeParams params(szVGA, 0, 0, INTER_CUBIC); + params.coordMode = ResizeCoord::HALF_PIXEL; + params.excludeOutside = exclude; + + TEST_CYCLE() resize(src, dst, params); + + SANITY_CHECK_NOTHING(); +} + +// RAGGED cycles input widths 64 to 4096, which only a vector can hold. +enum BatchLayout { TENSOR, VECTOR, RAGGED }; +typedef tuple BatchCase_t; // N, type, from, to, interpolation, layout + +// The first six hold equal total pixels, so throughput should stay level across N. +#define RESIZE_BATCH_CASES \ + testing::Values( \ + BatchCase_t(1, CV_8UC3, Size(2048, 2048), Size(1536, 1536), INTER_LINEAR, TENSOR), \ + BatchCase_t(2, CV_8UC3, Size(2048, 1024), Size(1536, 768), INTER_LINEAR, VECTOR), \ + BatchCase_t(4, CV_8UC3, Size(1024, 1024), Size(768, 768), INTER_LINEAR, TENSOR), \ + BatchCase_t(16, CV_8UC3, Size(512, 512), Size(384, 384), INTER_LINEAR, VECTOR), \ + BatchCase_t(256, CV_8UC3, Size(128, 128), Size(96, 96), INTER_LINEAR, TENSOR), \ + BatchCase_t(4096, CV_8UC3, Size(32, 32), Size(24, 24), INTER_LINEAR, VECTOR), \ + BatchCase_t(64, CV_32FC1, Size(128, 128), Size(224, 224), INTER_LINEAR, TENSOR), \ + BatchCase_t(3, CV_8UC3, Size(1920, 1080), Size(640, 480), INTER_CUBIC, VECTOR), \ + BatchCase_t(128, CV_32FC1, Size(224, 224), Size(112, 112), INTER_NEAREST, TENSOR), \ + BatchCase_t(4, CV_8UC3, Size(2048, 2048), Size(224, 224), INTER_AREA, VECTOR), \ + BatchCase_t(32, CV_8UC3, Size(0, 256), Size(0, 192), INTER_LINEAR, RAGGED) \ + ) + +static void makeBatch(const BatchCase_t& p, std::vector& src, std::vector& dst) +{ + const int n = get<0>(p), matType = get<1>(p), layout = get<5>(p); + const Size from = get<2>(p), to = get<3>(p); + static const int raggedWidths[] = { 64, 256, 1024, 4096 }; + RNG rng(0x5eed); + src.resize(n); + dst.resize(n); + for (int i = 0; i < n; i++) + { + const int w = layout == RAGGED ? raggedWidths[i % 4] : from.width; + src[i].create(from.height, w, matType); + rng.fill(src[i], RNG::UNIFORM, 0, 255); + dst[i].create(to.height, layout == RAGGED ? w*3/4 : to.width, matType); + } +} + +// Resizes images [r.start, r.end) one by one, as a caller's own parallel loop does. +class PerImageResize : public ParallelLoopBody +{ +public: + PerImageResize(const std::vector& _src, std::vector& _dst, int _interp) + : src(_src), dst(_dst), interp(_interp) {} + + void operator()(const Range& r) const CV_OVERRIDE + { + for (int i = r.start; i < r.end; i++) + resize(src[i], dst[i], dst[i].size(), 0, 0, interp); + } + +private: + const std::vector& src; + std::vector& dst; + int interp; +}; + +typedef TestBaseWithParam ResizeBatch; + +// Baseline: what callers write today, one cv::resize per image, spread over the threads. +PERF_TEST_P(ResizeBatch, per_image, RESIZE_BATCH_CASES) +{ + const int n = get<0>(GetParam()), interp = get<4>(GetParam()); + std::vector src, dst; + makeBatch(GetParam(), src, dst); + + const PerImageResize body(src, dst, interp); + TEST_CYCLE() + { + if (n == 1) + resize(src[0], dst[0], dst[0].size(), 0, 0, interp); + else + parallel_for_(Range(0, n), body); + } + + SANITY_CHECK_NOTHING(); +} + +// The batched overload: shared tables, one parallel loop over the batch. +PERF_TEST_P(ResizeBatch, batched, RESIZE_BATCH_CASES) +{ + const int n = get<0>(GetParam()), matType = get<1>(GetParam()), interp = get<4>(GetParam()); + const int layout = get<5>(GetParam()); + const Size from = get<2>(GetParam()), to = get<3>(GetParam()); + + if (layout == TENSOR) + { + int shape[] = { n, from.height, from.width }; + Mat src(3, shape, matType), dst; + RNG(0x5eed).fill(src, RNG::UNIFORM, 0, 255); + const ResizeParams params(to, 0, 0, interp); + TEST_CYCLE() resize(src, dst, params); + } + else + { + std::vector src, dst; + makeBatch(GetParam(), src, dst); + // A ragged batch gets one output size per image only through the scale. + const ResizeParams params = layout == RAGGED ? ResizeParams(Size(), 0.75, (double)to.height/from.height, interp) + : ResizeParams(to, 0, 0, interp); + TEST_CYCLE() resize(src, dst, params); + } + + SANITY_CHECK_NOTHING(); +} + +} // namespace diff --git a/modules/imgproc/src/resize.avx2.cpp b/modules/imgproc/src/resize.avx2.cpp deleted file mode 100644 index c9f53dc622..0000000000 --- a/modules/imgproc/src/resize.avx2.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2014-2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* //////////////////////////////////////////////////////////////////// -// -// Geometrical transforms on images and matrices: rotation, zoom etc. -// -// */ - -#include "precomp.hpp" -#include "resize.hpp" - -namespace cv -{ -namespace opt_AVX2 -{ - -class resizeNNInvokerAVX4 CV_FINAL : - public ParallelLoopBody -{ -public: - resizeNNInvokerAVX4(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } - -#if defined(__INTEL_COMPILER) -#pragma optimization_parameter target_arch=AVX -#endif - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - int avxWidth = width - (width & 0x7); - const __m256i CV_DECL_ALIGNED(64) mask = _mm256_set1_epi32(-1); - if(((int64)(dst.data + dst.step) & 0x1f) == 0) - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 8) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) indices = _mm256_lddqu_si256(addr); - __m256i CV_DECL_ALIGNED(64) pixels = _mm256_i32gather_epi32((const int*)S, indices, 1); - _mm256_maskstore_epi32((int*)D, mask, pixels); - D += 32; - } - for(; x < width; x++) - { - *(int*)(Dstart + x*4) = *(int*)(S + x_ofs[x]); - } - } - } - else - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 8) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) indices = _mm256_lddqu_si256(addr); - __m256i CV_DECL_ALIGNED(64) pixels = _mm256_i32gather_epi32((const int*)S, indices, 1); - _mm256_storeu_si256((__m256i*)D, pixels); - D += 32; - } - for(; x < width; x++) - { - *(int*)(Dstart + x*4) = *(int*)(S + x_ofs[x]); - } - } - } - _mm256_zeroupper(); - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerAVX4(const resizeNNInvokerAVX4&); - resizeNNInvokerAVX4& operator=(const resizeNNInvokerAVX4&); -}; - -class resizeNNInvokerAVX2 CV_FINAL : - public ParallelLoopBody -{ -public: - resizeNNInvokerAVX2(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } - -#if defined(__INTEL_COMPILER) -#pragma optimization_parameter target_arch=AVX -#endif - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - //int avxWidth = (width - 1) - ((width - 1) & 0x7); - int avxWidth = width - (width & 0xf); - const __m256i CV_DECL_ALIGNED(64) mask = _mm256_set1_epi32(-1); - const __m256i CV_DECL_ALIGNED(64) shuffle_mask = _mm256_set_epi8(15,14,11,10,13,12,9,8,7,6,3,2,5,4,1,0, - 15,14,11,10,13,12,9,8,7,6,3,2,5,4,1,0); - const __m256i CV_DECL_ALIGNED(64) permute_mask = _mm256_set_epi32(7, 5, 3, 1, 6, 4, 2, 0); - //const __m256i CV_DECL_ALIGNED(64) shift_shuffle_mask = _mm256_set_epi8(13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2, - // 13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2); - if(((int64)(dst.data + dst.step) & 0x1f) == 0) - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - const uchar* S2 = S - 2; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 16) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) indices = _mm256_lddqu_si256(addr); - __m256i CV_DECL_ALIGNED(64) pixels1 = _mm256_i32gather_epi32((const int*)S, indices, 1); - const __m256i CV_DECL_ALIGNED(64) *addr2 = (__m256i*)(x_ofs + x + 8); - __m256i CV_DECL_ALIGNED(64) indices2 = _mm256_lddqu_si256(addr2); - __m256i CV_DECL_ALIGNED(64) pixels2 = _mm256_i32gather_epi32((const int*)S2, indices2, 1); - __m256i CV_DECL_ALIGNED(64) unpacked = _mm256_blend_epi16(pixels1, pixels2, 0xaa); - - __m256i CV_DECL_ALIGNED(64) bytes_shuffled = _mm256_shuffle_epi8(unpacked, shuffle_mask); - __m256i CV_DECL_ALIGNED(64) ints_permuted = _mm256_permutevar8x32_epi32(bytes_shuffled, permute_mask); - _mm256_maskstore_epi32((int*)D, mask, ints_permuted); - D += 32; - } - for(; x < width; x++) - { - *(ushort*)(Dstart + x*2) = *(ushort*)(S + x_ofs[x]); - } - - } - } - else - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - const uchar* S2 = S - 2; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 16) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) indices = _mm256_lddqu_si256(addr); - __m256i CV_DECL_ALIGNED(64) pixels1 = _mm256_i32gather_epi32((const int*)S, indices, 1); - const __m256i CV_DECL_ALIGNED(64) *addr2 = (__m256i*)(x_ofs + x + 8); - __m256i CV_DECL_ALIGNED(64) indices2 = _mm256_lddqu_si256(addr2); - __m256i CV_DECL_ALIGNED(64) pixels2 = _mm256_i32gather_epi32((const int*)S2, indices2, 1); - __m256i CV_DECL_ALIGNED(64) unpacked = _mm256_blend_epi16(pixels1, pixels2, 0xaa); - - __m256i CV_DECL_ALIGNED(64) bytes_shuffled = _mm256_shuffle_epi8(unpacked, shuffle_mask); - __m256i CV_DECL_ALIGNED(64) ints_permuted = _mm256_permutevar8x32_epi32(bytes_shuffled, permute_mask); - _mm256_storeu_si256((__m256i*)D, ints_permuted); - D += 32; - } - for(; x < width; x++) - { - *(ushort*)(Dstart + x*2) = *(ushort*)(S + x_ofs[x]); - } - } - } - _mm256_zeroupper(); - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerAVX2(const resizeNNInvokerAVX2&); - resizeNNInvokerAVX2& operator=(const resizeNNInvokerAVX2&); -}; - -void resizeNN2_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerAVX2 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -void resizeNN4_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerAVX4 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -} -} -/* End of file. */ diff --git a/modules/imgproc/src/resize.cpp b/modules/imgproc/src/resize.cpp index 66f4ef22bc..4cbf445699 100644 --- a/modules/imgproc/src/resize.cpp +++ b/modules/imgproc/src/resize.cpp @@ -53,12 +53,14 @@ #include "opencv2/core/hal/intrin.hpp" #include "opencv2/core/utils/buffer_area.private.hpp" -#include "resize.hpp" +#include "resize.simd.hpp" +#include "resize.simd_declarations.hpp" #include "opencv2/core/softfloat.hpp" #include "fixedpoint.inl.hpp" #include +#include using namespace cv; @@ -645,7 +647,7 @@ public: virtual void operator() (const Range& range) const CV_OVERRIDE { - AutoBuffer linebuf(interp_y_len * dst_width * cn); + AutoBuffer linebuf((size_t)interp_y_len * dst_width * cn); int last_eval = - interp_y_len; int evalbuf_start = 0; int rmin_y = std::max(min_y, range.start); @@ -705,51 +707,147 @@ private: resize_bitExactInvoker& operator=(const resize_bitExactInvoker&); }; -template -void resize_bitExact(const uchar* src, size_t src_step, int src_width, int src_height, - uchar* dst, size_t dst_step, int dst_width, int dst_height, - int cn, double inv_scale_x, double inv_scale_y) +// One resize geometry, ready to run. Whoever creates a kernel picks the interpolation code and +// builds every table up front; run() then fills any range of destination rows, from any thread. +// runResize() owns the only parallel loop. +class ResizeKernel { - typedef typename fixedtype::type fixedpoint; - void(*hResize)(ET* src, int cn, int *ofst, fixedpoint* m, fixedpoint* dst, int dst_min, int dst_max, int dst_width); - switch (cn) +public: + /** @brief Binds a geometry to a kernel. + @param workPerSample estimated cost of one output sample, in source samples read or + multiply-adds; only its ratio to other kernels' figures matters to the scheduler. + */ + ResizeKernel(int _type, Size _ssize, Size _dsize, double workPerSample) + : type(_type), ssize(_ssize), dsize(_dsize), + rowWork(workPerSample * _dsize.width * CV_MAT_CN(_type)) {} + virtual ~ResizeKernel() {} + + void run(const uchar* srcData, size_t srcStep, uchar* dstData, size_t dstStep, + const Range& rows) const { - case 1: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; - case 2: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; - case 3: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; - case 4: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; - default: hResize = src_width > interpolation::len ? hlineResize : hlineResize ; break; + if (rows.start >= rows.end) + return; + Mat src(ssize, type, const_cast(srcData), srcStep); + Mat dst(dsize, type, dstData, dstStep); + apply(src, dst, rows); } - interpolation interp_x(inv_scale_x, src_width, dst_width); - interpolation interp_y(inv_scale_y, src_height, dst_height); + /** @brief Estimated cost of one destination row, which the scheduler balances on. */ + double work() const { return rowWork; } - AutoBuffer buf( dst_width * sizeof(int) + - dst_height * sizeof(int) + - dst_width * interp_x.len*sizeof(fixedpoint) + - dst_height * interp_y.len * sizeof(fixedpoint) ); - int* xoffsets = (int*)buf.data(); - int* yoffsets = xoffsets + dst_width; - fixedpoint* xcoeffs = (fixedpoint*)(yoffsets + dst_height); - fixedpoint* ycoeffs = xcoeffs + dst_width * interp_x.len; +protected: + // Fills dst rows [rows.start, rows.end) serially. + virtual void apply(const Mat& src, Mat& dst, const Range& rows) const = 0; + int type; + Size ssize, dsize; + double rowWork; +}; + +// Where a kernel gets built: in storage the caller provides, when it fits, or else on the heap. A +// lone image keeps its kernel on the stack, so the classic single-image path allocates nothing for +// it; the batch cache passes no storage and keeps heap kernels for as long as the batch runs. +class KernelSlot +{ +public: + KernelSlot() : storage(0), capacity(0), placed(0) {} + KernelSlot(void* _storage, size_t _capacity) : storage(_storage), capacity(_capacity), placed(0) {} + ~KernelSlot() + { + if (placed) + placed->~ResizeKernel(); + } + + template + ResizeKernel* emplace(Args&&... args) + { + if (sizeof(K) <= capacity) + return placed = new (storage) K(std::forward(args)...); + heap = makePtr(std::forward(args)...); + return heap.get(); + } + + Ptr heap; + +private: + void* storage; + size_t capacity; + ResizeKernel* placed; + + KernelSlot(const KernelSlot&); + KernelSlot& operator=(const KernelSlot&); +}; + +template +class LinearExactKernel CV_FINAL : public ResizeKernel +{ +public: + typedef typename fixedtype::type fixedpoint; + typedef void (*HResizeFunc)(ET* src, int cn, int *ofst, fixedpoint* m, fixedpoint* dst, + int dst_min, int dst_max, int dst_width); + + LinearExactKernel(int _type, Size _ssize, Size _dsize, double inv_scale_x, double inv_scale_y) + : ResizeKernel(_type, _ssize, _dsize, 2*interpolation::len) + { + const int src_width = ssize.width, src_height = ssize.height; + const int dst_width = dsize.width, dst_height = dsize.height; + CV_Assert((int64)std::max(src_width, dst_width)*CV_MAT_CN(type)*interpolation::len <= INT_MAX); + switch (CV_MAT_CN(type)) + { + case 1: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; + case 2: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; + case 3: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; + case 4: hResize = src_width > interpolation::len ? hlineResizeCn : hlineResizeCn; break; + default: hResize = src_width > interpolation::len ? hlineResize : hlineResize ; break; + } + + interpolation interp_x(inv_scale_x, src_width, dst_width); + interpolation interp_y(inv_scale_y, src_height, dst_height); + + buf.allocate( dst_width * sizeof(int) + + dst_height * sizeof(int) + + dst_width * interp_x.len*sizeof(fixedpoint) + + dst_height * interp_y.len * sizeof(fixedpoint) ); + xoffsets = (int*)buf.data(); + yoffsets = xoffsets + dst_width; + xcoeffs = (fixedpoint*)(yoffsets + dst_height); + ycoeffs = xcoeffs + dst_width * interp_x.len; + + for (int dx = 0; dx < dst_width; dx++) + interp_x.getCoeffs(dx, xoffsets+dx, xcoeffs+dx*interp_x.len); + interp_x.getMinMax(min_x, max_x); + for (int dy = 0; dy < dst_height; dy++) + interp_y.getCoeffs(dy, yoffsets+dy, ycoeffs+dy*interp_y.len); + interp_y.getMinMax(min_y, max_y); + } + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + resize_bitExactInvoker invoker( + src.data, src.step, ssize.width, ssize.height, dst.data, dst.step, dsize.width, dsize.height, + CV_MAT_CN(type), xoffsets, yoffsets, xcoeffs, ycoeffs, min_x, max_x, min_y, max_y, hResize); + invoker(rows); + } + +private: + AutoBuffer buf; + int *xoffsets, *yoffsets; + fixedpoint *xcoeffs, *ycoeffs; int min_x, max_x, min_y, max_y; - for (int dx = 0; dx < dst_width; dx++) - interp_x.getCoeffs(dx, xoffsets+dx, xcoeffs+dx*interp_x.len); - interp_x.getMinMax(min_x, max_x); - for (int dy = 0; dy < dst_height; dy++) - interp_y.getCoeffs(dy, yoffsets+dy, ycoeffs+dy*interp_y.len); - interp_y.getMinMax(min_y, max_y); + HResizeFunc hResize; +}; - resize_bitExactInvoker invoker(src, src_step, src_width, src_height, dst, dst_step, dst_width, dst_height, cn, - xoffsets, yoffsets, xcoeffs, ycoeffs, min_x, max_x, min_y, max_y, hResize); - Range range(0, dst_height); - parallel_for_(range, invoker, dst_width * dst_height / (double)(1 << 16)); +template +ResizeKernel* createLinearExactKernel(KernelSlot& slot, int type, Size ssize, Size dsize, + double inv_scale_x, double inv_scale_y) +{ + return slot.emplace > >(type, ssize, dsize, + inv_scale_x, inv_scale_y); } -typedef void(*be_resize_func)(const uchar* src, size_t src_step, int src_width, int src_height, - uchar* dst, size_t dst_step, int dst_width, int dst_height, - int cn, double inv_scale_x, double inv_scale_y); +typedef ResizeKernel* (*LinearExactFactory)(KernelSlot& slot, int type, Size ssize, Size dsize, + double inv_scale_x, double inv_scale_y); } @@ -761,10 +859,8 @@ namespace cv const int INTER_RESIZE_COEF_BITS=11; const int INTER_RESIZE_COEF_SCALE=1 << INTER_RESIZE_COEF_BITS; -static inline void interpolateCubic( float x, float* coeffs ) +static inline void interpolateCubic( float x, float* coeffs, float A = -0.75f ) { - const float A = -0.75f; - coeffs[0] = ((A*(x + 1) - 5*A)*(x + 1) + 8*A)*(x + 1) - 4*A; coeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1; coeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1; @@ -827,22 +923,21 @@ class resizeNNInvoker : public ParallelLoopBody { public: - resizeNNInvoker(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : + resizeNNInvoker(const Mat& _src, Mat &_dst, int *_x_ofs, const int* _y_ofs) : ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) + y_ofs(_y_ofs) { } virtual void operator() (const Range& range) const CV_OVERRIDE { - Size ssize = src.size(), dsize = dst.size(); + Size dsize = dst.size(); int y, x, pix_size = (int)src.elemSize(); for( y = range.start; y < range.end; y++ ) { uchar* D = dst.data + dst.step*y; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.ptr(sy); + const uchar* S = src.ptr(y_ofs[y]); switch( pix_size ) { @@ -912,62 +1007,25 @@ private: const Mat& src; Mat& dst; int* x_ofs; - double ify; + const int* y_ofs; resizeNNInvoker(const resizeNNInvoker&); resizeNNInvoker& operator=(const resizeNNInvoker&); }; -static void -resizeNN( const Mat& src, Mat& dst, double fx, double fy ) +static bool +resizeNN2or4( const Mat& src, Mat& dst, int* x_ofs, const int* y_ofs, const Range& range ) { - Size ssize = src.size(), dsize = dst.size(); - AutoBuffer _x_ofs(dsize.width); - int* x_ofs = _x_ofs.data(); - int pix_size = (int)src.elemSize(); - double ifx = 1./fx, ify = 1./fy; - int x; + CV_CPU_DISPATCH(resizeNN2or4, (src, dst, x_ofs, y_ofs, range), CV_CPU_DISPATCH_MODES_ALL); +} - for( x = 0; x < dsize.width; x++ ) +static void +resizeNN( const Mat& src, Mat& dst, int* x_ofs, const int* y_ofs, const Range& range ) +{ + if (!resizeNN2or4(src, dst, x_ofs, y_ofs, range)) { - int sx = cvFloor(x*ifx); - x_ofs[x] = std::min(sx, ssize.width-1)*pix_size; - } - - Range range(0, dsize.height); -#if CV_TRY_AVX2 - if(CV_CPU_HAS_SUPPORT_AVX2 && ((pix_size == 2) || (pix_size == 4))) - { - if(pix_size == 2) - opt_AVX2::resizeNN2_AVX2(range, src, dst, x_ofs, ify); - else - opt_AVX2::resizeNN4_AVX2(range, src, dst, x_ofs, ify); - } - else -#endif -#if CV_TRY_SSE4_1 - if(CV_CPU_HAS_SUPPORT_SSE4_1 && ((pix_size == 2) || (pix_size == 4))) - { - if(pix_size == 2) - opt_SSE4_1::resizeNN2_SSE4_1(range, src, dst, x_ofs, ify); - else - opt_SSE4_1::resizeNN4_SSE4_1(range, src, dst, x_ofs, ify); - } - else -#endif -#if CV_TRY_LASX - if(CV_CPU_HAS_SUPPORT_LASX && ((pix_size == 2) || (pix_size == 4))) - { - if(pix_size == 2) - opt_LASX::resizeNN2_LASX(range, src, dst, x_ofs, ify); - else - opt_LASX::resizeNN4_LASX(range, src, dst, x_ofs, ify); - } - else -#endif - { - resizeNNInvoker invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total()/(double)(1<<16)); + resizeNNInvoker invoker(src, dst, x_ofs, y_ofs); + invoker(range); } } @@ -1076,23 +1134,11 @@ static void resizeNN_bitexact_tab(int src_dim, int dst_dim, int* ofse) } } -static void resizeNN_bitexact( const Mat& src, Mat& dst, double /*fx*/, double /*fy*/ ) +static void resizeNN_bitexact( const Mat& src, Mat& dst, int* x_ofse, int* y_ofse, + const Range& range ) { - Size ssize = src.size(), dsize = dst.size(); - - cv::utils::BufferArea area; - int* x_ofse = 0; - int* y_ofse = 0; - area.allocate(x_ofse, dsize.width, CV_SIMD_WIDTH); - area.allocate(y_ofse, dsize.height, CV_SIMD_WIDTH); - area.commit(); - - resizeNN_bitexact_tab(ssize.width, dsize.width, x_ofse); - resizeNN_bitexact_tab(ssize.height, dsize.height, y_ofse); - - Range range(0, dsize.height); resizeNN_bitexactInvoker invoker(src, dst, x_ofse, y_ofse); - parallel_for_(range, invoker, dst.total()/(double)(1<<16)); + invoker(range); } struct VResizeNoVec @@ -1269,10 +1315,7 @@ struct VResizeLanczos4Vec_32f16u { int operator()(const float** src, ushort* dst, const float* beta, int width) const { - if (CV_CPU_HAS_SUPPORT_SSE4_1) - return opt_SSE4_1::VResizeLanczos4Vec_32f16u_SSE41(src, dst, beta, width); - else - return 0; + CV_CPU_DISPATCH(vresizeLanczos4_32f16u, (src, dst, beta, width), CV_CPU_DISPATCH_MODES_ALL); } }; @@ -1864,7 +1907,7 @@ template static void resizeGeneric_( const Mat& src, Mat& dst, const int* xofs, const void* _alpha, const int* yofs, const void* _beta, - int xmin, int xmax, int ksize ) + int xmin, int xmax, int ksize, const Range& range ) { typedef typename HResize::alpha_type AT; @@ -1877,10 +1920,9 @@ static void resizeGeneric_( const Mat& src, Mat& dst, xmax *= cn; // image resize is a separable operation. In case of not too strong - Range range(0, dsize.height); resizeGeneric_Invoker invoker(src, dst, xofs, yofs, (const AT*)_alpha, beta, ssize, dsize, ksize, xmin, xmax); - parallel_for_(range, invoker, dst.total()/(double)(1<<16)); + invoker(range); } template @@ -2651,12 +2693,11 @@ private: template static void resizeAreaFast_( const Mat& src, Mat& dst, const int* ofs, const int* xofs, - int scale_x, int scale_y ) + int scale_x, int scale_y, const Range& range ) { - Range range(0, dst.rows); resizeAreaFast_Invoker invoker(src, dst, scale_x, scale_y, ofs, xofs); - parallel_for_(range, invoker, dst.total()/(double)(1<<16)); + invoker(range); } struct DecimateAlpha @@ -2904,27 +2945,26 @@ template static void resizeArea_( const Mat& src, Mat& dst, const DecimateAlpha* xtab, int xtab_size, const DecimateAlpha* ytab, int ytab_size, - const int* tabofs ) + const int* tabofs, const Range& range ) { - parallel_for_(Range(0, dst.rows), - ResizeArea_Invoker(src, dst, xtab, xtab_size, ytab, ytab_size, tabofs), - dst.total()/((double)(1 << 16))); + ResizeArea_Invoker invoker(src, dst, xtab, xtab_size, ytab, ytab_size, tabofs); + invoker(range); } typedef void (*ResizeFunc)( const Mat& src, Mat& dst, const int* xofs, const void* alpha, const int* yofs, const void* beta, - int xmin, int xmax, int ksize ); + int xmin, int xmax, int ksize, const Range& range ); typedef void (*ResizeAreaFastFunc)( const Mat& src, Mat& dst, const int* ofs, const int *xofs, - int scale_x, int scale_y ); + int scale_x, int scale_y, const Range& range ); typedef void (*ResizeAreaFunc)( const Mat& src, Mat& dst, const DecimateAlpha* xtab, int xtab_size, const DecimateAlpha* ytab, int ytab_size, - const int* yofs); + const int* yofs, const Range& range); // Shared resize-area coefficient-table math for the CPU and OpenCL callers; the @@ -3207,29 +3247,410 @@ static bool ocl_resize( InputArray _src, OutputArray _dst, Size dsize, //================================================================================================== -namespace hal { +namespace { -void resize(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - double inv_scale_x, double inv_scale_y, int interpolation) +// ---- ResizeParams: validation, output geometry, and the dst->src coordinate map ---- + +// The flag the kernel tables are indexed by. As in classic cv::resize, INTER_LINEAR_EXACT on a +// float degrades to INTER_LINEAR, which has no fixed-point kernel to be exact about. +int resolveInterpolation(const ResizeParams& params, int depth) { - CV_INSTRUMENT_REGION(); + if (params.interpolation == INTER_LINEAR_EXACT && (depth == CV_32F || depth == CV_64F)) + return INTER_LINEAR; + return params.interpolation; +} - CV_Assert((dst_width > 0 && dst_height > 0) || (inv_scale_x > 0 && inv_scale_y > 0)); - if (inv_scale_x < DBL_EPSILON || inv_scale_y < DBL_EPSILON) +// Rejects what no kernel covers. Called once per resize(), before any kernel is built. +void checkResizeParams(const ResizeParams& params) +{ + if (params.antialias) + CV_Error(Error::StsNotImplemented, "ResizeParams::antialias is not implemented yet"); + // The bit-exact kernels have no coordinate-mode parameter, so they only serve PIXEL_CENTER. + if (params.coordMode != ResizeCoord::PIXEL_CENTER && + params.interpolation != INTER_NEAREST && params.interpolation != INTER_LINEAR && + params.interpolation != INTER_CUBIC && params.interpolation != INTER_LANCZOS4) + CV_Error(Error::StsNotImplemented, + "a ResizeParams::coordMode other than ResizeCoord::PIXEL_CENTER needs " + "INTER_NEAREST, INTER_LINEAR, INTER_CUBIC or INTER_LANCZOS4 " + "(the _EXACT flags included)"); +} + +/** @brief Whether the OpenCL kernels and a custom HAL can serve these parameters. They take no +coordinate mode, Keys coefficient or exclude_outside, so only when those make no difference. +*/ +bool isClassicResize(const ResizeParams& params) +{ + if (params.coordMode != ResizeCoord::PIXEL_CENTER) + return false; + const int interp = params.interpolation; + if (params.excludeOutside && (interp == INTER_CUBIC || interp == INTER_LANCZOS4)) + return false; + return interp != INTER_CUBIC || params.cubicCoeffA == -0.75f; +} + +// Follows classic cv::resize's rule for deriving the output size from fx/fy. +Size resolveDstSize(Size ssize, const ResizeParams& params) +{ + CV_Assert(!ssize.empty()); + if (!params.dsize.empty()) + return params.dsize; + CV_Assert(params.fx > 0 && params.fy > 0); + Size dsize(saturate_cast(ssize.width*params.fx), saturate_cast(ssize.height*params.fy)); + CV_Assert(!dsize.empty()); + return dsize; +} + +// dst/src per axis. A given dsize overrides fx/fy, as in classic cv::resize, except for the ONNX +// modes: their dsize is usually floor(size*scale), which does not divide back to the true scale. +void resolveScales(Size ssize, Size dsize, const ResizeParams& params, + double& inv_scale_x, double& inv_scale_y) +{ + const bool fromScale = params.dsize.empty() || + (params.coordMode != ResizeCoord::PIXEL_CENTER && params.fx > 0 && params.fy > 0); + inv_scale_x = fromScale ? params.fx : (double)dsize.width /ssize.width; + inv_scale_y = fromScale ? params.fy : (double)dsize.height/ssize.height; + CV_Assert(inv_scale_x > 0 && inv_scale_y > 0); +} + +// dst -> src along one axis for the separable kernels, which never see the mode itself. +struct AxisMap +{ + ResizeCoord mode; + double scale; // source units per destination unit + double symOffset; // HALF_PIXEL_SYMMETRIC's recentering shift + bool degenerate; // PYTORCH_HALF_PIXEL on a one-sample output axis + + double operator ()(int dst) const { - inv_scale_x = static_cast(dst_width) / src_width; - inv_scale_y = static_cast(dst_height) / src_height; + switch (mode) + { + case ResizeCoord::ASYMMETRIC: + case ResizeCoord::ALIGN_CORNERS: // scale already rewritten by makeAxisMap() + return dst*scale; + case ResizeCoord::TF_HALF_PIXEL_FOR_NN: + return (dst + 0.5)*scale; + case ResizeCoord::HALF_PIXEL_SYMMETRIC: + return symOffset + (dst + 0.5)*scale - 0.5; + case ResizeCoord::PYTORCH_HALF_PIXEL: + return degenerate ? 0.0 : (dst + 0.5)*scale - 0.5; + default: // PIXEL_CENTER and HALF_PIXEL agree + return (dst + 0.5)*scale - 0.5; + } + } +}; + +// ALIGN_CORNERS divides by the integer output length, as the ONNX operator defines it, so it +// ignores the scale. +AxisMap makeAxisMap(ResizeCoord mode, double scale, int inLen, int outLen) +{ + AxisMap m; + m.mode = mode; + m.scale = scale; + m.symOffset = 0; + m.degenerate = false; + if (mode == ResizeCoord::ALIGN_CORNERS) + m.scale = outLen > 1 ? (double)(inLen - 1)/(outLen - 1) : 0.0; + else if (mode == ResizeCoord::HALF_PIXEL_SYMMETRIC) + m.symOffset = inLen*0.5 - outLen*scale*0.5; + else if (mode == ResizeCoord::PYTORCH_HALF_PIXEL) + m.degenerate = outLen <= 1; + return m; +} + +/** @brief One axis of the classic INTER_NEAREST table: src = floor(dst*scale), multiplying by the +reciprocal as classic resize always has. mul turns an index into the byte offset the x axis needs, +or is 1 for y. +*/ +void buildLegacyNearestTab(int* tab, int outLen, int inLen, double scale, int mul) +{ + const double last = inLen - 1; + for (int i = 0; i < outLen; i++) + tab[i] = (int)std::min(i*scale, last)*mul; +} + +/** @brief ONNX Resize's source coordinate, dividing by the scale as the operator does: a coordinate +that is exactly a half-integer is then computed exactly, whatever the scale's reciprocal rounds to. +*/ +double onnxNearestCoord(ResizeCoord mode, int i, double invScale, int inLen, int outLen) +{ + switch (mode) + { + case ResizeCoord::ASYMMETRIC: + return i/invScale; + case ResizeCoord::TF_HALF_PIXEL_FOR_NN: + return (i + 0.5)/invScale; + case ResizeCoord::ALIGN_CORNERS: + return outLen > 1 ? (double)((int64)i*(inLen - 1))/(outLen - 1) : 0.0; + case ResizeCoord::PYTORCH_HALF_PIXEL: + return outLen > 1 ? (i + 0.5)/invScale - 0.5 : 0.0; + case ResizeCoord::HALF_PIXEL_SYMMETRIC: + return (inLen*0.5 - outLen*0.5/invScale) + (i + 0.5)/invScale - 0.5; + default: // HALF_PIXEL + return (i + 0.5)/invScale - 0.5; + } +} + +// ONNX nearest_mode on the coordinate as computed: only an exact .5 fraction is a tie. +int onnxNearestIndex(double x, ResizeNearest mode, int last) +{ + const double f = std::floor(x); + double idx = f; + if (mode == ResizeNearest::CEIL) + idx = std::ceil(x); + else if (mode == ResizeNearest::ROUND_PREFER_FLOOR) + idx += x - f > 0.5 ? 1 : 0; + else if (mode == ResizeNearest::ROUND_PREFER_CEIL) + idx += x - f >= 0.5 ? 1 : 0; + return (int)std::min(std::max(idx, 0.0), (double)last); +} + +// One axis of the INTER_NEAREST table under an ONNX coordinate mode. +void buildNearestTab(int* tab, int outLen, int inLen, double invScale, + ResizeCoord coord, ResizeNearest mode, int mul) +{ + for (int i = 0; i < outLen; i++) + tab[i] = onnxNearestIndex(onnxNearestCoord(coord, i, invScale, inLen, outLen), mode, inLen - 1)*mul; +} + +// ONNX exclude_outside: zero the taps that fall off the edge and renormalise the rest. The taps +// span [first, first+ksize) and the kernels clamp them to the edge, so a zeroed weight is inert. +void excludeOutsideTaps(float* coeffs, int ksize, int first, int len) +{ + float sum = 0.f; + for (int k = 0; k < ksize; k++) + { + if ((unsigned)(first + k) >= (unsigned)len) + coeffs[k] = 0.f; + sum += coeffs[k]; + } + if (sum != 0.f) + for (int k = 0; k < ksize; k++) + coeffs[k] /= sum; +} + +// ---- kernels: one per interpolation method, each bound to its tables ---- + +// Equal sizes under PIXEL_CENTER: a row copy, the shortcut classic cv::resize takes too. +class CopyKernel CV_FINAL : public ResizeKernel +{ +public: + CopyKernel(int _type, Size size) : ResizeKernel(_type, size, size, 1) {} + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + src.rowRange(rows).copyTo(dst.rowRange(rows)); + } +}; + +// INTER_NEAREST in every coordinate mode: a source byte offset per output column and a source +// row per output row. +class NearestKernel CV_FINAL : public ResizeKernel +{ +public: + NearestKernel(int _type, Size _ssize, Size _dsize, double inv_scale_x, double inv_scale_y, + ResizeCoord coord, ResizeNearest rounding) + : ResizeKernel(_type, _ssize, _dsize, 1) + { + const int esz = (int)CV_ELEM_SIZE(type); + CV_Assert((int64)ssize.width*esz <= INT_MAX); + buf.allocate((size_t)dsize.width + dsize.height); + xofs = buf.data(); + yofs = xofs + dsize.width; + if (coord == ResizeCoord::PIXEL_CENTER) + { + buildLegacyNearestTab(xofs, dsize.width, ssize.width, 1./inv_scale_x, esz); + buildLegacyNearestTab(yofs, dsize.height, ssize.height, 1./inv_scale_y, 1); + } + else + { + buildNearestTab(xofs, dsize.width, ssize.width, inv_scale_x, coord, rounding, esz); + buildNearestTab(yofs, dsize.height, ssize.height, inv_scale_y, coord, rounding, 1); + } } - CALL_HAL(resize, cv_hal_resize, src_type, src_data, src_step, src_width, src_height, dst_data, dst_step, dst_width, dst_height, inv_scale_x, inv_scale_y, interpolation); +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + resizeNN(src, dst, xofs, yofs, rows); + } - int depth = CV_MAT_DEPTH(src_type), cn = CV_MAT_CN(src_type); - Size dsize = Size(saturate_cast(src_width*inv_scale_x), - saturate_cast(src_height*inv_scale_y)); - CV_Assert( !dsize.empty() ); +private: + AutoBuffer buf; + int *xofs, *yofs; +}; +class NearestExactKernel CV_FINAL : public ResizeKernel +{ +public: + NearestExactKernel(int _type, Size _ssize, Size _dsize) + : ResizeKernel(_type, _ssize, _dsize, 1), xofs(0), yofs(0) + { + area.allocate(xofs, dsize.width, CV_SIMD_WIDTH); + area.allocate(yofs, dsize.height, CV_SIMD_WIDTH); + area.commit(); + resizeNN_bitexact_tab(ssize.width, dsize.width, xofs); + resizeNN_bitexact_tab(ssize.height, dsize.height, yofs); + } + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + resizeNN_bitexact(src, dst, xofs, yofs, rows); + } + +private: + cv::utils::BufferArea area; + int *xofs, *yofs; +}; + +// INTER_AREA at an integer decimation factor on both axes. +class AreaFastKernel CV_FINAL : public ResizeKernel +{ +public: + AreaFastKernel(int _type, Size _ssize, size_t _srcStep, Size _dsize, int _iscale_x, int _iscale_y) + : ResizeKernel(_type, _ssize, _dsize, (double)_iscale_x*_iscale_y), + srcStep(_srcStep), iscale_x(_iscale_x), iscale_y(_iscale_y) + { + static ResizeAreaFastFunc areafast_tab[CV_DEPTH_MAX] = + { + resizeAreaFast_ >, + 0, + resizeAreaFast_ >, + resizeAreaFast_ >, + 0, + resizeAreaFast_, + resizeAreaFast_ >, + 0 + }; + func = areafast_tab[CV_MAT_DEPTH(type)]; + CV_Assert( func != 0 ); + + const int cn = CV_MAT_CN(type), area = iscale_x*iscale_y; + buf.allocate((size_t)area + (size_t)dsize.width*cn); + ofs = buf.data(); + xofs = ofs + area; + + // The source step is baked into ofs, which is why the batch cache keys on it. + const size_t srcstep = srcStep / CV_ELEM_SIZE1(type); + CV_Assert((int64)(iscale_y - 1)*srcstep + (int64)iscale_x*cn <= INT_MAX); + int k = 0; + for( int sy = 0; sy < iscale_y; sy++ ) + for( int sx = 0; sx < iscale_x; sx++ ) + ofs[k++] = (int)(sy*srcstep + sx*cn); + + for( int dx = 0; dx < dsize.width; dx++ ) + { + const int j = dx*cn, sx = iscale_x*j; + for( k = 0; k < cn; k++ ) + xofs[j + k] = sx + k; + } + } + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + CV_DbgAssert(src.step == srcStep); + func(src, dst, ofs, xofs, iscale_x, iscale_y, rows); + } + +private: + ResizeAreaFastFunc func; + AutoBuffer buf; + int *ofs, *xofs; + size_t srcStep; + int iscale_x, iscale_y; +}; + +// INTER_AREA at a non-integer decimation factor. +class AreaKernel CV_FINAL : public ResizeKernel +{ +public: + AreaKernel(int _type, Size _ssize, Size _dsize, double scale_x, double scale_y) + : ResizeKernel(_type, _ssize, _dsize, std::max(scale_x, 1.)*std::max(scale_y, 1.)) + { + static ResizeAreaFunc area_tab[CV_DEPTH_MAX] = + { + resizeArea_, 0, resizeArea_, + resizeArea_, 0, resizeArea_, + resizeArea_, 0 + }; + const int cn = CV_MAT_CN(type); + func = area_tab[CV_MAT_DEPTH(type)]; + CV_Assert( func != 0 ); + + buf.allocate(((size_t)ssize.width + ssize.height)*2); + xtab = buf.data(); + ytab = xtab + (size_t)ssize.width*2; + + xtab_size = computeResizeAreaTab(ssize.width, dsize.width, cn, scale_x, xtab); + ytab_size = computeResizeAreaTab(ssize.height, dsize.height, 1, scale_y, ytab); + + tabofsBuf.allocate(dsize.height + 1); + tabofs = tabofsBuf.data(); + int dy = 0; + for( int k = 0; k < ytab_size; k++ ) + { + if( k == 0 || ytab[k].di != ytab[k-1].di ) + { + CV_Assert( ytab[k].di == dy ); + tabofs[dy++] = k; + } + } + tabofs[dy] = ytab_size; + } + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + func(src, dst, xtab, xtab_size, ytab, ytab_size, tabofs, rows); + } + +private: + ResizeAreaFunc func; + AutoBuffer buf; + AutoBuffer tabofsBuf; + DecimateAlpha *xtab, *ytab; + int xtab_size, ytab_size; + int* tabofs; +}; + +// Taps per axis of a separable kernel; INTER_AREA upscales with linear taps. +int separableTaps(int interpolation) +{ + return interpolation == INTER_CUBIC ? 4 : interpolation == INTER_LANCZOS4 ? 8 : 2; +} + +// Separable INTER_LINEAR, INTER_CUBIC and INTER_LANCZOS4, and INTER_AREA when it upscales. +// The coordinate mode, the Keys coefficient and exclude_outside only change the tables. +class SeparableKernel CV_FINAL : public ResizeKernel +{ +public: + SeparableKernel(int _type, Size _ssize, Size _dsize, int interpolation, + double inv_scale_x, double inv_scale_y, + const AxisMap& mapX, const AxisMap& mapY, float cubicA, bool excludeOutside); + +protected: + void apply(const Mat& src, Mat& dst, const Range& rows) const CV_OVERRIDE + { + func(src, dst, xofs, alpha, yofs, beta, xmin, xmax, ksize, rows); + } + +private: + ResizeFunc func; + AutoBuffer buf; + int *xofs, *yofs; + const void *alpha, *beta; + int xmin, xmax, ksize; +}; + +SeparableKernel::SeparableKernel(int _type, Size _ssize, Size _dsize, int interpolation, + double inv_scale_x, double inv_scale_y, + const AxisMap& mapX, const AxisMap& mapY, + float cubicA, bool excludeOutside) + : ResizeKernel(_type, _ssize, _dsize, 2*separableTaps(interpolation)), + func(0), xofs(0), yofs(0), alpha(0), beta(0), xmin(0), xmax(_dsize.width), ksize(0) +{ static ResizeFunc linear_tab[CV_DEPTH_MAX] = { resizeGeneric_< @@ -3315,148 +3736,16 @@ void resize(int src_type, 0 }; - static ResizeAreaFastFunc areafast_tab[CV_DEPTH_MAX] = - { - resizeAreaFast_ >, - 0, - resizeAreaFast_ >, - resizeAreaFast_ >, - 0, - resizeAreaFast_, - resizeAreaFast_ >, - 0 - }; - - static ResizeAreaFunc area_tab[CV_DEPTH_MAX] = - { - resizeArea_, 0, resizeArea_, - resizeArea_, 0, resizeArea_, - resizeArea_, 0 - }; - - static be_resize_func linear_exact_tab[CV_DEPTH_MAX] = - { - resize_bitExact >, - resize_bitExact >, - resize_bitExact >, - resize_bitExact >, - resize_bitExact >, - 0, - 0, - 0 - }; - - double scale_x = 1./inv_scale_x, scale_y = 1./inv_scale_y; - - int iscale_x = saturate_cast(scale_x); - int iscale_y = saturate_cast(scale_y); - - bool is_area_fast = std::abs(scale_x - iscale_x) < DBL_EPSILON && - std::abs(scale_y - iscale_y) < DBL_EPSILON; - - Mat src(Size(src_width, src_height), src_type, const_cast(src_data), src_step); - Mat dst(dsize, src_type, dst_data, dst_step); - - if (interpolation == INTER_LINEAR_EXACT) - { - // in case of inv_scale_x && inv_scale_y is equal to 0.5 - // INTER_AREA (fast) is equal to bit exact INTER_LINEAR - if (is_area_fast && iscale_x == 2 && iscale_y == 2 && cn != 2)//Area resize implementation for 2-channel images isn't bit-exact - interpolation = INTER_AREA; - else - { - be_resize_func func = linear_exact_tab[depth]; - CV_Assert(func != 0); - func(src_data, src_step, src_width, src_height, - dst_data, dst_step, dst_width, dst_height, - cn, inv_scale_x, inv_scale_y); - return; - } - } - - if( interpolation == INTER_NEAREST ) - { - resizeNN( src, dst, inv_scale_x, inv_scale_y ); - return; - } - - if( interpolation == INTER_NEAREST_EXACT ) - { - resizeNN_bitexact( src, dst, inv_scale_x, inv_scale_y ); - return; - } - + const int depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); + const double scale_x = 1./inv_scale_x, scale_y = 1./inv_scale_y; int k, sx, sy, dx, dy; - - - { - // in case of scale_x && scale_y is equal to 2 - // INTER_AREA (fast) also is equal to INTER_LINEAR - if( interpolation == INTER_LINEAR && is_area_fast && iscale_x == 2 && iscale_y == 2 ) - interpolation = INTER_AREA; - - // true "area" interpolation is only implemented for the case (scale_x >= 1 && scale_y >= 1). - // In other cases it is emulated using some variant of bilinear interpolation - if( interpolation == INTER_AREA && scale_x >= 1 && scale_y >= 1 ) - { - if( is_area_fast ) - { - int area = iscale_x*iscale_y; - size_t srcstep = src_step / src.elemSize1(); - AutoBuffer _ofs(area + dsize.width*cn); - int* ofs = _ofs.data(); - int* xofs = ofs + area; - ResizeAreaFastFunc func = areafast_tab[depth]; - CV_Assert( func != 0 ); - - for( sy = 0, k = 0; sy < iscale_y; sy++ ) - for( sx = 0; sx < iscale_x; sx++ ) - ofs[k++] = (int)(sy*srcstep + sx*cn); - - for( dx = 0; dx < dsize.width; dx++ ) - { - int j = dx * cn; - sx = iscale_x * j; - for( k = 0; k < cn; k++ ) - xofs[j + k] = sx + k; - } - - func( src, dst, ofs, xofs, iscale_x, iscale_y ); - return; - } - - ResizeAreaFunc func = area_tab[depth]; - CV_Assert( func != 0 ); - - AutoBuffer _xytab((src_width + src_height)*2); - DecimateAlpha* xtab = _xytab.data(), *ytab = xtab + src_width*2; - - int xtab_size = computeResizeAreaTab(src_width, dsize.width, cn, scale_x, xtab); - int ytab_size = computeResizeAreaTab(src_height, dsize.height, 1, scale_y, ytab); - - AutoBuffer _tabofs(dsize.height + 1); - int* tabofs = _tabofs.data(); - for( k = 0, dy = 0; k < ytab_size; k++ ) - { - if( k == 0 || ytab[k].di != ytab[k-1].di ) - { - CV_Assert( ytab[k].di == dy ); - tabofs[dy++] = k; - } - } - tabofs[dy] = ytab_size; - - func( src, dst, xtab, xtab_size, ytab, ytab_size, tabofs ); - return; - } - } - - int xmin = 0, xmax = dsize.width, width = dsize.width*cn; + // The tables and row kernels index samples times taps with int. + CV_Assert((int64)dsize.width*cn*separableTaps(interpolation) <= INT_MAX && + (int64)ssize.width*cn <= INT_MAX); + int width = dsize.width*cn; bool area_mode = interpolation == INTER_AREA; bool fixpt = depth == CV_8U; float fx, fy; - ResizeFunc func=0; - int ksize=0, ksize2; if( interpolation == INTER_CUBIC ) ksize = 4, func = cubic_tab[depth]; else if( interpolation == INTER_LANCZOS4 ) @@ -3465,24 +3754,27 @@ void resize(int src_type, ksize = 2, func = linear_tab[depth]; else CV_Error( cv::Error::StsBadArg, "Unknown interpolation method" ); - ksize2 = ksize/2; + int ksize2 = ksize/2; + // With two taps, dropping the outside one and renormalising is edge replication, which the + // kernels already do; only the wider kernels see a difference. + const bool exclude = excludeOutside && ksize > 2; CV_Assert( func != 0 ); - AutoBuffer _buffer((width + dsize.height)*(sizeof(int) + sizeof(float)*ksize)); - int* xofs = (int*)_buffer.data(); - int* yofs = xofs + width; - float* alpha = (float*)(yofs + dsize.height); - short* ialpha = (short*)alpha; - float* beta = alpha + width*ksize; - short* ibeta = ialpha + width*ksize; + buf.allocate(((size_t)width + dsize.height)*(sizeof(int) + sizeof(float)*ksize)); + xofs = (int*)buf.data(); + yofs = xofs + width; + float* alphaf = (float*)(yofs + dsize.height); + short* ialpha = (short*)alphaf; + float* betaf = alphaf + (size_t)width*ksize; + short* ibeta = ialpha + (size_t)width*ksize; float cbuf[MAX_ESIZE] = {0}; for( dx = 0; dx < dsize.width; dx++ ) { if( !area_mode ) { - fx = (float)((dx+0.5)*scale_x - 0.5); + fx = (float)mapX(dx); sx = cvFloor(fx); fx -= sx; } @@ -3500,18 +3792,19 @@ void resize(int src_type, fx = 0, sx = 0; } - if( sx + ksize2 >= src_width ) + if( sx + ksize2 >= ssize.width ) { xmax = std::min( xmax, dx ); - if( sx >= src_width-1 && (interpolation != INTER_CUBIC && interpolation != INTER_LANCZOS4)) - fx = 0, sx = src_width-1; + if( sx >= ssize.width-1 && (interpolation != INTER_CUBIC && interpolation != INTER_LANCZOS4)) + fx = 0, sx = ssize.width-1; } + const int sx0 = sx; for( k = 0, sx *= cn; k < cn; k++ ) xofs[dx*cn + k] = sx + k; if( interpolation == INTER_CUBIC ) - interpolateCubic( fx, cbuf ); + interpolateCubic( fx, cbuf, cubicA ); else if( interpolation == INTER_LANCZOS4 ) interpolateLanczos4( fx, cbuf ); else @@ -3519,6 +3812,8 @@ void resize(int src_type, cbuf[0] = 1.f - fx; cbuf[1] = fx; } + if( exclude ) + excludeOutsideTaps( cbuf, ksize, sx0 - ksize2 + 1, ssize.width ); if( fixpt ) { for( k = 0; k < ksize; k++ ) @@ -3529,9 +3824,9 @@ void resize(int src_type, else { for( k = 0; k < ksize; k++ ) - alpha[dx*cn*ksize + k] = cbuf[k]; + alphaf[dx*cn*ksize + k] = cbuf[k]; for( ; k < cn*ksize; k++ ) - alpha[dx*cn*ksize + k] = alpha[dx*cn*ksize + k - ksize]; + alphaf[dx*cn*ksize + k] = alphaf[dx*cn*ksize + k - ksize]; } } @@ -3539,7 +3834,7 @@ void resize(int src_type, { if( !area_mode ) { - fy = (float)((dy+0.5)*scale_y - 0.5); + fy = (float)mapY(dy); sy = cvFloor(fy); fy -= sy; } @@ -3552,7 +3847,7 @@ void resize(int src_type, yofs[dy] = sy; if( interpolation == INTER_CUBIC ) - interpolateCubic( fy, cbuf ); + interpolateCubic( fy, cbuf, cubicA ); else if( interpolation == INTER_LANCZOS4 ) interpolateLanczos4( fy, cbuf ); else @@ -3560,6 +3855,8 @@ void resize(int src_type, cbuf[0] = 1.f - fy; cbuf[1] = fy; } + if( exclude ) + excludeOutsideTaps( cbuf, ksize, sy - ksize2 + 1, ssize.height ); if( fixpt ) { @@ -3569,15 +3866,469 @@ void resize(int src_type, else { for( k = 0; k < ksize; k++ ) - beta[dy*ksize + k] = cbuf[k]; + betaf[dy*ksize + k] = cbuf[k]; } } - func( src, dst, xofs, fixpt ? (void*)ialpha : (void*)alpha, yofs, - fixpt ? (void*)ibeta : (void*)beta, xmin, xmax, ksize ); + alpha = fixpt ? (const void*)ialpha : (const void*)alphaf; + beta = fixpt ? (const void*)ibeta : (const void*)betaf; } +// Picks the kernel for one geometry and builds its tables. This is the only code that reads +// ResizeParams: coordMode, nearestMode, cubicCoeffA and excludeOutside all end up in the tables, +// so every combination of them runs the same kernels at the same speed. +ResizeKernel* createResizeKernel(KernelSlot& slot, int type, Size ssize, size_t srcStep, Size dsize, + const ResizeParams& params) +{ + const int depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); + const bool classicCoord = params.coordMode == ResizeCoord::PIXEL_CENTER; + + // Classic cv::resize short-circuits an equal-size resize to a copy. Most coordinate modes + // are not the identity at scale 1, so only PIXEL_CENTER gets the shortcut. + if (classicCoord && ssize == dsize) + return slot.emplace(type, ssize); + + double inv_scale_x, inv_scale_y; + resolveScales(ssize, dsize, params, inv_scale_x, inv_scale_y); + int interpolation = resolveInterpolation(params, depth); + + const double scale_x = 1./inv_scale_x, scale_y = 1./inv_scale_y; + const int iscale_x = saturate_cast(scale_x); + const int iscale_y = saturate_cast(scale_y); + const bool is_area_fast = std::abs(scale_x - iscale_x) < DBL_EPSILON && + std::abs(scale_y - iscale_y) < DBL_EPSILON; + const bool halving = is_area_fast && iscale_x == 2 && iscale_y == 2; + const bool fullBlocks = (int64)dsize.width*2 <= ssize.width && (int64)dsize.height*2 <= ssize.height; + + if (interpolation == INTER_LINEAR_EXACT) + { + // For these types INTER_AREA rounds a whole 2x2 block as the bit-exact formula does. + if (halving && fullBlocks && (depth == CV_8U || depth == CV_16U || depth == CV_16S) && + (cn == 1 || cn == 3 || cn == 4)) + interpolation = INTER_AREA; + else + { + static LinearExactFactory linear_exact_tab[CV_DEPTH_MAX] = + { + createLinearExactKernel, + createLinearExactKernel, + createLinearExactKernel, + createLinearExactKernel, + createLinearExactKernel, + 0, + 0, + 0 + }; + LinearExactFactory create = linear_exact_tab[depth]; + CV_Assert(create != 0); + return create(slot, type, ssize, dsize, inv_scale_x, inv_scale_y); + } + } + + if (interpolation == INTER_NEAREST) + return slot.emplace(type, ssize, dsize, inv_scale_x, inv_scale_y, + params.coordMode, params.nearestMode); + + if (interpolation == INTER_NEAREST_EXACT) + return slot.emplace(type, ssize, dsize); + + // At an exact 2x decimation, linear interpolation between pixel centres averages 2x2 blocks, + // which is what the INTER_AREA fast kernel does, as long as every block keeps a pixel inside the + // image (an fx/fy given next to a larger dsize can push blocks out). The modes that sample + // anywhere else do not average, so they keep the linear kernel. + const bool blocksInside = (int64)dsize.width*2 <= (int64)ssize.width + 1 && + (int64)dsize.height*2 <= (int64)ssize.height + 1; + if (interpolation == INTER_LINEAR && halving && blocksInside && + (classicCoord || params.coordMode == ResizeCoord::HALF_PIXEL)) + interpolation = INTER_AREA; + + // true "area" interpolation is only implemented for the case (scale_x >= 1 && scale_y >= 1). + // In other cases it is emulated using some variant of bilinear interpolation + if (interpolation == INTER_AREA && scale_x >= 1 && scale_y >= 1) + { + if (is_area_fast) + return slot.emplace(type, ssize, srcStep, dsize, iscale_x, iscale_y); + return slot.emplace(type, ssize, dsize, scale_x, scale_y); + } + + // INTER_AREA keeps its own decimation geometry; every other kernel reads its coordinates here. + return slot.emplace(type, ssize, dsize, interpolation, inv_scale_x, inv_scale_y, + makeAxisMap(params.coordMode, scale_x, ssize.width, dsize.width), + makeAxisMap(params.coordMode, scale_y, ssize.height, dsize.height), + params.cubicCoeffA, params.excludeOutside); +} + + +// ---- batch scheduling ---- + +// One image of a batch, bound to the kernel its geometry resolved to. +struct BatchItem +{ + const uchar* srcData; + size_t srcStep; + uchar* dstData; + size_t dstStep; + const ResizeKernel* kernel; + int firstRow; // this image's first destination row in the batch-wide row list + int rows; + double firstWork; // estimated work of all the images before this one +}; + +/** @brief Cuts a batch into groups of about equal estimated work and runs them. Every destination +row of every image forms one flat list and a group is a contiguous slice of it, so it may hold +several small images whole, or a stripe of a large one. A single image is a batch of one. +*/ +class ResizeGroups CV_FINAL : public ParallelLoopBody +{ +public: + ResizeGroups(const BatchItem* _items, size_t _count, int _totalRows, double _totalWork, int _groups) + : items(_items), count(_count), totalRows(_totalRows), totalWork(_totalWork), groups(_groups) {} + + void operator()(const Range& range) const CV_OVERRIDE + { + runRows(groupStart(range.start), groupStart(range.end)); + } + + /** @brief First flat row of group g, from its share of the total work. An image of at most 1/8 + of a share goes whole to the group holding most of it, which moves the cut by 1/16 of a share at + most; a larger one is cut at the nearest row. Every row thus belongs to exactly one group. + */ + int groupStart(int g) const + { + if (g <= 0) + return 0; + if (g >= groups) + return totalRows; + const double w = totalWork*g/groups; + const BatchItem& it = items[itemOfWork(w)]; + const double rowWork = it.kernel->work(), imageWork = rowWork*it.rows, offset = w - it.firstWork; + int row; + if (8*imageWork <= totalWork/groups) + row = 2*offset < imageWork ? 0 : it.rows; + else + row = std::min(cvRound(offset/rowWork), it.rows); + return it.firstRow + row; + } + + /** @brief Runs flat rows [start, end) serially, image by image. */ + void runRows(int start, int end) const + { + for (size_t i = itemOfRow(start); i < count && items[i].firstRow < end; i++) + { + const BatchItem& it = items[i]; + const Range rows(std::max(start - it.firstRow, 0), std::min(end - it.firstRow, it.rows)); + it.kernel->run(it.srcData, it.srcStep, it.dstData, it.dstStep, rows); + } + } + +private: + // Last image whose first row is <= row. + size_t itemOfRow(int row) const + { + size_t lo = 0, hi = count; + while (hi - lo > 1) + { + const size_t mid = (lo + hi)/2; + if (items[mid].firstRow <= row) + lo = mid; + else + hi = mid; + } + return lo; + } + + // Last image whose preceding work is <= w. + size_t itemOfWork(double w) const + { + size_t lo = 0, hi = count; + while (hi - lo > 1) + { + const size_t mid = (lo + hi)/2; + if (items[mid].firstWork <= w) + lo = mid; + else + hi = mid; + } + return lo; + } + + const BatchItem* items; + size_t count; + int totalRows; + double totalWork; + int groups; +}; + +/** @brief The only parallel loop in resize, with one rule for a single image and any batch: a group +per kMinGroupWork units of estimated work, at most kGroupsPerThread per thread and one per row, +rounded up to whole rounds once there are more groups than threads. +*/ +void runResize(const BatchItem* items, size_t count, int totalRows, double totalWork) +{ + if (count == 0 || totalRows <= 0) + return; + + const double kMinGroupWork = 1 << 15, kGroupsPerThread = 2; + const double threads = std::max(getNumThreads(), 1); + double groups = std::min(kGroupsPerThread*threads, std::ceil(totalWork/kMinGroupWork)); + if (groups > threads) + groups = std::ceil(groups/threads)*threads; + groups = std::max(1., std::min(groups, (double)totalRows)); + ResizeGroups body(items, count, totalRows, totalWork, (int)groups); + if (groups == 1) + body.runRows(0, totalRows); + else + parallel_for_(Range(0, (int)groups), body, groups); +} + +// One kernel per distinct geometry. A uniform batch -- the common case, and the whole of the +// tensor path -- leaves the linear scan a single entry, so the tables are built exactly once. +struct KernelCache +{ + struct Key + { + Size ssize, dsize; + size_t srcStep; + int type; + bool operator == (const Key& o) const + { return ssize == o.ssize && dsize == o.dsize && srcStep == o.srcStep && type == o.type; } + }; + + std::vector keys; + std::vector > kernels; + + // The returned kernel lives as long as the cache. + const ResizeKernel* get(const ResizeParams& params, int type, Size ssize, size_t srcStep, Size dsize) + { + Key key; key.ssize = ssize; key.dsize = dsize; key.srcStep = srcStep; key.type = type; + for (size_t i = 0; i < keys.size(); i++) + if (keys[i] == key) + return kernels[i].get(); + + KernelSlot slot; + createResizeKernel(slot, type, ssize, srcStep, dsize, params); + keys.push_back(key); + kernels.push_back(slot.heap); + return slot.heap.get(); + } +}; + +// Collects a batch: hands out kernels, lays the images onto the flat row list, totals the work. +// The two batch kinds then differ only in where their pixels come from. +struct BatchBuilder +{ + KernelCache cache; + AutoBuffer items; + size_t count; + int totalRows; + double totalWork; + + explicit BatchBuilder(size_t n) : items(n), count(0), totalRows(0), totalWork(0) {} + + void add(const ResizeKernel* kernel, const uchar* srcData, size_t srcStep, + uchar* dstData, size_t dstStep, Size dsize) + { + CV_Assert((int64)totalRows + dsize.height <= INT_MAX); + + BatchItem& it = items[count++]; + it.kernel = kernel; + it.srcData = srcData; + it.srcStep = srcStep; + it.dstData = dstData; + it.dstStep = dstStep; + it.firstRow = totalRows; + it.rows = dsize.height; + it.firstWork = totalWork; + + totalRows += dsize.height; + totalWork += kernel->work()*dsize.height; + } + + // Same, resolving the geometry to a cached kernel first. + void add(const ResizeParams& params, int type, const uchar* srcData, size_t srcStep, Size ssize, + uchar* dstData, size_t dstStep, Size dsize) + { + add(cache.get(params, type, ssize, srcStep, dsize), srcData, srcStep, dstData, dstStep, dsize); + } + + void run() const { runResize(items.data(), count, totalRows, totalWork); } +}; + +// One image: a batch of one, with its kernel on the stack rather than in the cache. +void resizeOne(int type, const uchar* srcData, size_t srcStep, Size ssize, + uchar* dstData, size_t dstStep, Size dsize, const ResizeParams& params) +{ + CV_DECL_ALIGNED(64) uchar storage[4096]; + KernelSlot slot(storage, sizeof(storage)); + const ResizeKernel* kernel = createResizeKernel(slot, type, ssize, srcStep, dsize, params); + + BatchBuilder batch(1); + batch.add(kernel, srcData, srcStep, dstData, dstStep, dsize); + batch.run(); +} + +/** @brief Whether two Mats may share memory. A kernel reads source rows after it has written +destination rows, so a source that dst overlaps (an in-place call that kept the size) is copied first. +*/ +bool sharesMemory(const Mat& a, const Mat& b) +{ + return a.datastart < b.dataend && b.datastart < a.dataend; +} + +// Byte offset of the p-th 2D plane. Walks the axes rather than assuming a dense buffer, so +// views work too. +size_t planeOffset(const Mat& m, int p) +{ + size_t ofs = 0; + for (int i = m.dims - 3; i >= 0; i--) + { + ofs += (size_t)(p % m.size[i]) * m.step[i]; + p /= m.size[i]; + } + return ofs; +} + +// N-D tensor batch: the leading dimensions are batch axes, the last two are height and width. +void resizeTensorBatch(Mat src, const ResizeParams& params, OutputArray _dst) +{ + const int D = src.dims; + const Size ssize(src.size[D - 1], src.size[D - 2]); + const Size dsize = resolveDstSize(ssize, params); + + int64 planes = 1; + for (int i = 0; i < D - 2; i++) + planes *= src.size[i]; + CV_Assert(planes > 0 && planes * dsize.height <= INT_MAX); + const int numPlanes = (int)planes; + + int dstShape[CV_MAX_DIM]; + for (int i = 0; i < D; i++) + dstShape[i] = src.size[i]; + dstShape[D - 2] = dsize.height; + dstShape[D - 1] = dsize.width; + _dst.create(D, dstShape, src.type()); + Mat dst = _dst.getMat(); + if (sharesMemory(src, dst)) + src = src.clone(); + + const size_t srcStep = src.step[D - 2], dstStep = dst.step[D - 2]; + + // Every plane shares one geometry, so the cache builds one kernel for the whole tensor. + BatchBuilder batch(numPlanes); + for (int p = 0; p < numPlanes; p++) + batch.add(params, src.type(), src.data + planeOffset(src, p), srcStep, ssize, + dst.data + planeOffset(dst, p), dstStep, dsize); + batch.run(); +} + +// vector batch: the elements may differ in size, so only the matching ones share a kernel. +// srcs holds its own headers, so an element that dst reallocates keeps its pixels. +void resizeMatVectorBatch(std::vector& srcs, const ResizeParams& params, OutputArray _dst) +{ + const size_t n = srcs.size(); + CV_Assert(n > 0); + CV_Assert((int64)n <= INT_MAX); + + const int type = srcs[0].type(); + _dst.create((int)n, 1, 0); + + // getMatRef() is an out-of-line call into core; over thousands of elements that dispatch costs + // more than the resizing, so take it once here. Any other output kind keeps the accessor. + std::vector* dstv = _dst.kind() == _InputArray::STD_VECTOR_MAT + ? (std::vector*)_dst.getObj() : 0; + + // Kernels are built here, before any thread runs; a same-shape batch shares a single one. + BatchBuilder batch(n); + for (size_t i = 0; i < n; i++) + { + Mat& src = srcs[i]; + CV_Assert(src.dims == 2 && !src.empty() && src.type() == type); + const Size dsize = resolveDstSize(src.size(), params); + Mat& dst = dstv ? (*dstv)[i] : _dst.getMatRef((int)i); + dst.create(dsize, type); + if (sharesMemory(src, dst)) + src = src.clone(); + + batch.add(params, type, src.data, src.step, src.size(), dst.data, dst.step, dsize); + } + batch.run(); +} + +/** @brief Resizes a single 2D image. Classic parameters keep classic resize's OpenCL and HAL paths, +its copy for an unchanged size and its handling of src == dst; anything else runs OpenCV's own kernels. +*/ +void resizeImage(InputArray _src, OutputArray _dst, const ResizeParams& params) +{ + const Size ssize = _src.size(); + const Size dsize = resolveDstSize(ssize, params); + double inv_scale_x, inv_scale_y; + resolveScales(ssize, dsize, params, inv_scale_x, inv_scale_y); + const int interpolation = resolveInterpolation(params, _src.depth()); + const bool classic = isClassicResize(params); + + CV_OCL_RUN(classic && _src.dims() <= 2 && _dst.isUMat() && _src.cols() > 10 && _src.rows() > 10, + ocl_resize(_src, _dst, dsize, inv_scale_x, inv_scale_y, interpolation)) + + // Fake reference to source. Resolves issue 13577 in case of src == dst. + UMat srcUMat; + if (_src.isUMat()) + srcUMat = _src.getUMat(); + + Mat src = _src.getMat(); + _dst.create(dsize, src.type()); + Mat dst = _dst.getMat(); + + if (classic) + { + if (dsize == ssize) + src.copyTo(dst); + else + hal::resize(src.type(), src.data, src.step, src.cols, src.rows, dst.data, dst.step, + dst.cols, dst.rows, inv_scale_x, inv_scale_y, interpolation); + return; + } + + if (sharesMemory(src, dst)) + src = src.clone(); + resizeOne(src.type(), src.data, src.step, ssize, dst.data, dst.step, dsize, params); +} + +} // namespace + +namespace hal { + +void resize(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + double inv_scale_x, double inv_scale_y, int interpolation) +{ + CV_INSTRUMENT_REGION(); + + CV_Assert((dst_width > 0 && dst_height > 0) || (inv_scale_x > 0 && inv_scale_y > 0)); + if (inv_scale_x < DBL_EPSILON || inv_scale_y < DBL_EPSILON) + { + inv_scale_x = static_cast(dst_width) / src_width; + inv_scale_y = static_cast(dst_height) / src_height; + } + + CALL_HAL(resize, cv_hal_resize, src_type, src_data, src_step, src_width, src_height, dst_data, dst_step, dst_width, dst_height, inv_scale_x, inv_scale_y, interpolation); + + // This entry point is given the scale, so leave dsize empty and let the kernel derive it. + ResizeParams params; + params.fx = inv_scale_x; + params.fy = inv_scale_y; + params.interpolation = interpolation; + + const Size ssize(src_width, src_height); + const Size dsize = resolveDstSize(ssize, params); + CV_Assert( !dsize.empty() ); + + resizeOne(src_type, src_data, src_step, ssize, dst_data, dst_step, dsize, params); +} + + } // cv::hal:: + } // cv:: //================================================================================================== @@ -3587,44 +4338,56 @@ void cv::resize( InputArray _src, OutputArray _dst, Size dsize, { CV_INSTRUMENT_REGION(); - Size ssize = _src.size(); + cv::resize(_src, _dst, ResizeParams(dsize, inv_scale_x, inv_scale_y, interpolation)); +} - CV_Assert( !ssize.empty() ); - if( dsize.empty() ) +//================================================================================================== + +cv::ResizeParams::ResizeParams() + : dsize(), fx(0), fy(0), interpolation(INTER_LINEAR), + coordMode(ResizeCoord::PIXEL_CENTER), nearestMode(ResizeNearest::ROUND_PREFER_FLOOR), + cubicCoeffA(-0.75f), excludeOutside(false), antialias(false), hint(cv::ALGO_HINT_DEFAULT) +{ +} + +cv::ResizeParams::ResizeParams(Size _dsize, double _fx, double _fy, int _interpolation) + : dsize(_dsize), fx(_fx), fy(_fy), interpolation(_interpolation), + coordMode(ResizeCoord::PIXEL_CENTER), nearestMode(ResizeNearest::ROUND_PREFER_FLOOR), + cubicCoeffA(-0.75f), excludeOutside(false), antialias(false), hint(cv::ALGO_HINT_DEFAULT) +{ +} + +void cv::resize( InputArray _src, OutputArray _dst, const ResizeParams& params ) +{ + CV_INSTRUMENT_REGION(); + + checkResizeParams(params); + + if (_src.isUMatVector()) { - CV_Assert(inv_scale_x > 0); CV_Assert(inv_scale_y > 0); - dsize = Size(saturate_cast(ssize.width*inv_scale_x), - saturate_cast(ssize.height*inv_scale_y)); - CV_Assert( !dsize.empty() ); - } - else - { - inv_scale_x = (double)dsize.width/ssize.width; - inv_scale_y = (double)dsize.height/ssize.height; - CV_Assert(inv_scale_x > 0); CV_Assert(inv_scale_y > 0); - } - - if (interpolation == INTER_LINEAR_EXACT && (_src.depth() == CV_32F || _src.depth() == CV_64F)) - interpolation = INTER_LINEAR; // If depth isn't supported fallback to generic resize - - CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat() && _src.cols() > 10 && _src.rows() > 10, - ocl_resize(_src, _dst, dsize, inv_scale_x, inv_scale_y, interpolation)) - - // Fake reference to source. Resolves issue 13577 in case of src == dst. - UMat srcUMat; - if (_src.isUMat()) - srcUMat = _src.getUMat(); - - Mat src = _src.getMat(); - _dst.create(dsize, _src.type()); - Mat dst = _dst.getMat(); - - if (dsize == ssize) - { - // Source and destination are of same size. Use simple copy. - src.copyTo(dst); + // OpenCL elements go one at a time: the kernels below address host memory. + std::vector srcs; + _src.getUMatVector(srcs); + CV_Assert(!srcs.empty() && (int64)srcs.size() <= INT_MAX); + _dst.create((int)srcs.size(), 1, 0); + for (size_t i = 0; i < srcs.size(); i++) + resizeImage(srcs[i], _dst.getUMatRef((int)i), params); return; } - hal::resize(_src.type(), src.data, src.step, src.cols, src.rows, dst.data, dst.step, dst.cols, dst.rows, inv_scale_x, inv_scale_y, interpolation); + if (_src.isMatVector()) + { + std::vector srcs; + _src.getMatVector(srcs); + resizeMatVectorBatch(srcs, params, _dst); + return; + } + + if (_src.dims() > 2) + { + resizeTensorBatch(_src.getMat(), params, _dst); + return; + } + + resizeImage(_src, _dst, params); } diff --git a/modules/imgproc/src/resize.hpp b/modules/imgproc/src/resize.hpp deleted file mode 100644 index 1636e7585e..0000000000 --- a/modules/imgproc/src/resize.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2014-2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* //////////////////////////////////////////////////////////////////// -// -// Geometrical transforms on images and matrices: rotation, zoom etc. -// -// */ - -#ifndef OPENCV_IMGPROC_RESIZE_HPP -#define OPENCV_IMGPROC_RESIZE_HPP -#include "precomp.hpp" - -namespace cv -{ -namespace opt_AVX2 -{ -#if CV_TRY_AVX2 -void resizeNN2_AVX2(const Range&, const Mat&, Mat&, int*, double); -void resizeNN4_AVX2(const Range&, const Mat&, Mat&, int*, double); -#endif -} - -namespace opt_SSE4_1 -{ -#if CV_TRY_SSE4_1 -void resizeNN2_SSE4_1(const Range&, const Mat&, Mat&, int*, double); -void resizeNN4_SSE4_1(const Range&, const Mat&, Mat&, int*, double); - -int VResizeLanczos4Vec_32f16u_SSE41(const float** src, ushort* dst, const float* beta, int width); -#endif -} - -namespace opt_LASX -{ -#if CV_TRY_LASX -void resizeNN2_LASX(const Range&, const Mat&, Mat&, int*, double); -void resizeNN4_LASX(const Range&, const Mat&, Mat&, int*, double); -#endif -} - -} -#endif -/* End of file. */ diff --git a/modules/imgproc/src/resize.lasx.cpp b/modules/imgproc/src/resize.lasx.cpp deleted file mode 100644 index fece47087d..0000000000 --- a/modules/imgproc/src/resize.lasx.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2014-2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* //////////////////////////////////////////////////////////////////// -// -// Geometrical transforms on images and matrices: rotation, zoom etc. -// -// */ - -#include "precomp.hpp" -#include "resize.hpp" -#include "opencv2/core/hal/intrin.hpp" - -namespace cv -{ -namespace opt_LASX -{ - -class resizeNNInvokerLASX4 CV_FINAL : - public ParallelLoopBody -{ -public: - resizeNNInvokerLASX4(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } - - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - int avxWidth = width - (width & 0x7); - if(((int64)(dst.data + dst.step) & 0x1f) == 0) - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 8) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) pixels = v256_lut_quads((schar *)S, (int *)addr).val; - __lasx_xvst(pixels, (int*)D, 0); - D += 32; - } - for(; x < width; x++) - { - *(int*)(Dstart + x*4) = *(int*)(S + x_ofs[x]); - } - } - } - else - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 8) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) pixels = v256_lut_quads((schar *)S, (int *)addr).val; - __lasx_xvst(pixels, (int*)D, 0); - D += 32; - } - for(; x < width; x++) - { - *(int*)(Dstart + x*4) = *(int*)(S + x_ofs[x]); - } - } - } - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerLASX4(const resizeNNInvokerLASX4&); - resizeNNInvokerLASX4& operator=(const resizeNNInvokerLASX4&); -}; - -class resizeNNInvokerLASX2 CV_FINAL : - public ParallelLoopBody -{ -public: - resizeNNInvokerLASX2(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } - - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - int avxWidth = width - (width & 0xf); - const __m256i CV_DECL_ALIGNED(64) shuffle_mask = _v256_set_b(15,14,11,10,13,12,9,8,7,6,3,2,5,4,1,0, - 15,14,11,10,13,12,9,8,7,6,3,2,5,4,1,0); - const __m256i CV_DECL_ALIGNED(64) permute_mask = _v256_set_w(7, 5, 3, 1, 6, 4, 2, 0); - if(((int64)(dst.data + dst.step) & 0x1f) == 0) - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - const uchar* S2 = S - 2; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 16) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) pixels1 = v256_lut_quads((schar *)S, (int *)addr).val; - - const __m256i CV_DECL_ALIGNED(64) *addr2 = (__m256i*)(x_ofs + x + 8); - __m256i CV_DECL_ALIGNED(64) pixels2 = v256_lut_quads((schar *)S2, (int *)addr2).val; - - const __m256i h_mask = __lasx_xvreplgr2vr_w(0xFFFF0000); - __m256i CV_DECL_ALIGNED(64) unpacked = __lasx_xvbitsel_v(pixels1, pixels2, h_mask); - - __m256i CV_DECL_ALIGNED(64) bytes_shuffled = __lasx_xvshuf_b(unpacked, unpacked, shuffle_mask); - __m256i CV_DECL_ALIGNED(64) ints_permuted = __lasx_xvperm_w(bytes_shuffled, permute_mask); - __lasx_xvst(ints_permuted, (int*)D, 0); - D += 32; - } - for(; x < width; x++) - { - *(ushort*)(Dstart + x*2) = *(ushort*)(S + x_ofs[x]); - } - - } - } - else - { - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - const uchar* S2 = S - 2; -#ifdef CV_ICC -#pragma unroll(4) -#endif - for(x = 0; x < avxWidth; x += 16) - { - const __m256i CV_DECL_ALIGNED(64) *addr = (__m256i*)(x_ofs + x); - __m256i CV_DECL_ALIGNED(64) pixels1 = v256_lut_quads((schar *)S, (int *)addr).val; - - const __m256i CV_DECL_ALIGNED(64) *addr2 = (__m256i*)(x_ofs + x + 8); - __m256i CV_DECL_ALIGNED(64) pixels2 = v256_lut_quads((schar *)S2, (int *)addr2).val; - - const __m256i h_mask = __lasx_xvreplgr2vr_w(0xFFFF0000); - __m256i CV_DECL_ALIGNED(64) unpacked = __lasx_xvbitsel_v(pixels1, pixels2, h_mask); - - __m256i CV_DECL_ALIGNED(64) bytes_shuffled = __lasx_xvshuf_b(unpacked, unpacked, shuffle_mask); - __m256i CV_DECL_ALIGNED(64) ints_permuted = __lasx_xvperm_w(bytes_shuffled, permute_mask); - __lasx_xvst(ints_permuted, (int*)D, 0); - D += 32; - } - for(; x < width; x++) - { - *(ushort*)(Dstart + x*2) = *(ushort*)(S + x_ofs[x]); - } - } - } - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerLASX2(const resizeNNInvokerLASX2&); - resizeNNInvokerLASX2& operator=(const resizeNNInvokerLASX2&); -}; - -void resizeNN2_LASX(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerLASX2 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -void resizeNN4_LASX(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerLASX4 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -} -} -/* End of file. */ diff --git a/modules/imgproc/src/resize.simd.hpp b/modules/imgproc/src/resize.simd.hpp new file mode 100644 index 0000000000..4c3430bdc4 --- /dev/null +++ b/modules/imgproc/src/resize.simd.hpp @@ -0,0 +1,170 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2014-2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include "precomp.hpp" +#include "opencv2/core/hal/intrin.hpp" + +namespace cv { +CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN + +// Nearest-neighbour resize of dst rows [range) for 2- and 4-byte pixels. x_ofs holds a source byte +// offset per dst column, y_ofs a source row per dst row. Returns false when this target has no +// vector path, and the caller then runs the generic scalar loop. +bool resizeNN2or4(const Mat& src, Mat& dst, int* x_ofs, const int* y_ofs, const Range& range); +int vresizeLanczos4_32f16u(const float** src, ushort* dst, const float* beta, int width); + +#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY + +// Nearest neighbour is a pure gather, so only targets with a gather instruction get a vector path: +// the 256- and 512-bit ones and RVV. On 128-bit targets the vector would be assembled from the +// same scalar loads the plain loop does. +#if (CV_SIMD || CV_SIMD_SCALABLE) && CV_SIMD_WIDTH >= 32 + +static void resizeNN4(const Mat& src, Mat& dst, const int* x_ofs, const int* y_ofs, const Range& range) +{ + const int width = dst.cols, VECSZ = VTraits::vlanes(); + for (int y = range.start; y < range.end; y++) + { + const int* S = (const int*)(src.data + src.step*y_ofs[y]); + int* D = (int*)(dst.data + dst.step*y); + int x = 0; + // x_ofs is in bytes; v_lut indexes 32-bit elements + for (; x <= width - VECSZ; x += VECSZ) + v_store(D + x, v_lut(S, v_shr<2>(vx_load(x_ofs + x)))); + for (; x < width; x++) + D[x] = S[x_ofs[x] >> 2]; + } + vx_cleanup(); +} + +// There is no 16-bit gather, so this fetches the 32-bit word that ends with each pixel, keeps its +// upper half and packs two such vectors into one. The word starts 2 bytes before the pixel, which +// leaves the pixels taken from source column 0 to the scalar loop; x_ofs never decreases, so they +// are a prefix of every row. +static void resizeNN2(const Mat& src, Mat& dst, const int* x_ofs, const int* y_ofs, const Range& range) +{ + const int width = dst.cols; + const int VECSZ = VTraits::vlanes(), HALF = VTraits::vlanes(); + int x0 = 0; + while (x0 < width && x_ofs[x0] < 2) + x0++; + + for (int y = range.start; y < range.end; y++) + { + const uchar* S = src.data + src.step*y_ofs[y]; + ushort* D = (ushort*)(dst.data + dst.step*y); + int x = 0; + for (; x < x0; x++) + D[x] = *(const ushort*)(S + x_ofs[x]); + for (; x <= width - VECSZ; x += VECSZ) + { + v_uint32 a = v_shr<16>(v_reinterpret_as_u32(vx_lut_quads((const schar*)(S - 2), x_ofs + x))); + v_uint32 b = v_shr<16>(v_reinterpret_as_u32(vx_lut_quads((const schar*)(S - 2), x_ofs + x + HALF))); + v_store(D + x, v_pack_u(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b))); + } + for (; x < width; x++) + D[x] = *(const ushort*)(S + x_ofs[x]); + } + vx_cleanup(); +} + +#endif + +bool resizeNN2or4(const Mat& src, Mat& dst, int* x_ofs, const int* y_ofs, const Range& range) +{ +#if (CV_SIMD || CV_SIMD_SCALABLE) && CV_SIMD_WIDTH >= 32 + const size_t pix_size = src.elemSize(); + if (pix_size == 4) + { + resizeNN4(src, dst, x_ofs, y_ofs, range); + return true; + } + if (pix_size == 2) + { + resizeNN2(src, dst, x_ofs, y_ofs, range); + return true; + } +#else + CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(x_ofs); CV_UNUSED(y_ofs); CV_UNUSED(range); +#endif + return false; +} + +// Vertical Lanczos4 pass, float rows to ushort. Returns how many elements it wrote; the caller +// finishes the row. +int vresizeLanczos4_32f16u(const float** src, ushort* dst, const float* beta, int width) +{ +#if (CV_SIMD || CV_SIMD_SCALABLE) + const int VECSZ = VTraits::vlanes(); + const float *S0 = src[0], *S1 = src[1], *S2 = src[2], *S3 = src[3], + *S4 = src[4], *S5 = src[5], *S6 = src[6], *S7 = src[7]; + const v_float32 b0 = vx_setall_f32(beta[0]), b1 = vx_setall_f32(beta[1]), + b2 = vx_setall_f32(beta[2]), b3 = vx_setall_f32(beta[3]), + b4 = vx_setall_f32(beta[4]), b5 = vx_setall_f32(beta[5]), + b6 = vx_setall_f32(beta[6]), b7 = vx_setall_f32(beta[7]); + int x = 0; + for (; x <= width - 2*VECSZ; x += 2*VECSZ) + { + const int x1 = x + VECSZ; + v_float32 d0 = v_mul(vx_load(S0 + x), b0), d1 = v_mul(vx_load(S0 + x1), b0); + d0 = v_muladd(vx_load(S1 + x), b1, d0); d1 = v_muladd(vx_load(S1 + x1), b1, d1); + d0 = v_muladd(vx_load(S2 + x), b2, d0); d1 = v_muladd(vx_load(S2 + x1), b2, d1); + d0 = v_muladd(vx_load(S3 + x), b3, d0); d1 = v_muladd(vx_load(S3 + x1), b3, d1); + d0 = v_muladd(vx_load(S4 + x), b4, d0); d1 = v_muladd(vx_load(S4 + x1), b4, d1); + d0 = v_muladd(vx_load(S5 + x), b5, d0); d1 = v_muladd(vx_load(S5 + x1), b5, d1); + d0 = v_muladd(vx_load(S6 + x), b6, d0); d1 = v_muladd(vx_load(S6 + x1), b6, d1); + d0 = v_muladd(vx_load(S7 + x), b7, d0); d1 = v_muladd(vx_load(S7 + x1), b7, d1); + v_store(dst + x, v_pack_u(v_round(d0), v_round(d1))); + } + vx_cleanup(); + return x; +#else + CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(beta); CV_UNUSED(width); + return 0; +#endif +} + +#endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY + +CV_CPU_OPTIMIZATION_NAMESPACE_END +} // namespace cv diff --git a/modules/imgproc/src/resize.sse4_1.cpp b/modules/imgproc/src/resize.sse4_1.cpp deleted file mode 100644 index 311a0036f4..0000000000 --- a/modules/imgproc/src/resize.sse4_1.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2014-2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* //////////////////////////////////////////////////////////////////// -// -// Geometrical transforms on images and matrices: rotation, zoom etc. -// -// */ - -#include "precomp.hpp" -#include "resize.hpp" - -namespace cv -{ -namespace opt_SSE4_1 -{ - -class resizeNNInvokerSSE2 : - public ParallelLoopBody -{ -public: - resizeNNInvokerSSE2(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } - -#if defined(__INTEL_COMPILER) -#pragma optimization_parameter target_arch=SSE4.2 -#endif - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - int sseWidth = width - (width & 0x7); - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - __m128i CV_DECL_ALIGNED(64) pixels = _mm_set1_epi16(0); - for(x = 0; x < sseWidth; x += 8) - { - ushort imm = *(ushort*)(S + x_ofs[x + 0]); - pixels = _mm_insert_epi16(pixels, imm, 0); - imm = *(ushort*)(S + x_ofs[x + 1]); - pixels = _mm_insert_epi16(pixels, imm, 1); - imm = *(ushort*)(S + x_ofs[x + 2]); - pixels = _mm_insert_epi16(pixels, imm, 2); - imm = *(ushort*)(S + x_ofs[x + 3]); - pixels = _mm_insert_epi16(pixels, imm, 3); - imm = *(ushort*)(S + x_ofs[x + 4]); - pixels = _mm_insert_epi16(pixels, imm, 4); - imm = *(ushort*)(S + x_ofs[x + 5]); - pixels = _mm_insert_epi16(pixels, imm, 5); - imm = *(ushort*)(S + x_ofs[x + 6]); - pixels = _mm_insert_epi16(pixels, imm, 6); - imm = *(ushort*)(S + x_ofs[x + 7]); - pixels = _mm_insert_epi16(pixels, imm, 7); - _mm_storeu_si128((__m128i*)D, pixels); - D += 16; - } - for(; x < width; x++) - { - *(ushort*)(Dstart + x*2) = *(ushort*)(S + x_ofs[x]); - } - } - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerSSE2(const resizeNNInvokerSSE2&); - resizeNNInvokerSSE2& operator=(const resizeNNInvokerSSE2&); -}; - -class resizeNNInvokerSSE4 : - public ParallelLoopBody -{ -public: - resizeNNInvokerSSE4(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) : - ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), - ify(_ify) - { - } -#if defined(__INTEL_COMPILER) -#pragma optimization_parameter target_arch=SSE4.2 -#endif - virtual void operator() (const Range& range) const CV_OVERRIDE - { - Size ssize = src.size(), dsize = dst.size(); - int y, x; - int width = dsize.width; - int sseWidth = width - (width & 0x3); - for(y = range.start; y < range.end; y++) - { - uchar* D = dst.data + dst.step*y; - uchar* Dstart = D; - int sy = std::min(cvFloor(y*ify), ssize.height-1); - const uchar* S = src.data + sy*src.step; - __m128i CV_DECL_ALIGNED(64) pixels = _mm_set1_epi16(0); - for(x = 0; x < sseWidth; x += 4) - { - int imm = *(int*)(S + x_ofs[x + 0]); - pixels = _mm_insert_epi32(pixels, imm, 0); - imm = *(int*)(S + x_ofs[x + 1]); - pixels = _mm_insert_epi32(pixels, imm, 1); - imm = *(int*)(S + x_ofs[x + 2]); - pixels = _mm_insert_epi32(pixels, imm, 2); - imm = *(int*)(S + x_ofs[x + 3]); - pixels = _mm_insert_epi32(pixels, imm, 3); - _mm_storeu_si128((__m128i*)D, pixels); - D += 16; - } - for(; x < width; x++) - { - *(int*)(Dstart + x*4) = *(int*)(S + x_ofs[x]); - } - } - } - -private: - const Mat& src; - Mat& dst; - int* x_ofs; - double ify; - - resizeNNInvokerSSE4(const resizeNNInvokerSSE4&); - resizeNNInvokerSSE4& operator=(const resizeNNInvokerSSE4&); -}; - -void resizeNN2_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerSSE2 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -void resizeNN4_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify) -{ - resizeNNInvokerSSE4 invoker(src, dst, x_ofs, ify); - parallel_for_(range, invoker, dst.total() / (double)(1 << 16)); -} - -int VResizeLanczos4Vec_32f16u_SSE41(const float** src, ushort* dst, const float* beta, int width) -{ - const float *S0 = src[0], *S1 = src[1], *S2 = src[2], *S3 = src[3], - *S4 = src[4], *S5 = src[5], *S6 = src[6], *S7 = src[7]; - int x = 0; - __m128 v_b0 = _mm_set1_ps(beta[0]), v_b1 = _mm_set1_ps(beta[1]), - v_b2 = _mm_set1_ps(beta[2]), v_b3 = _mm_set1_ps(beta[3]), - v_b4 = _mm_set1_ps(beta[4]), v_b5 = _mm_set1_ps(beta[5]), - v_b6 = _mm_set1_ps(beta[6]), v_b7 = _mm_set1_ps(beta[7]); - - for (; x <= width - 8; x += 8) - { - __m128 v_dst0 = _mm_mul_ps(v_b0, _mm_loadu_ps(S0 + x)); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b1, _mm_loadu_ps(S1 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b2, _mm_loadu_ps(S2 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b3, _mm_loadu_ps(S3 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b4, _mm_loadu_ps(S4 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b5, _mm_loadu_ps(S5 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b6, _mm_loadu_ps(S6 + x))); - v_dst0 = _mm_add_ps(v_dst0, _mm_mul_ps(v_b7, _mm_loadu_ps(S7 + x))); - - __m128 v_dst1 = _mm_mul_ps(v_b0, _mm_loadu_ps(S0 + x + 4)); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b1, _mm_loadu_ps(S1 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b2, _mm_loadu_ps(S2 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b3, _mm_loadu_ps(S3 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b4, _mm_loadu_ps(S4 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b5, _mm_loadu_ps(S5 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b6, _mm_loadu_ps(S6 + x + 4))); - v_dst1 = _mm_add_ps(v_dst1, _mm_mul_ps(v_b7, _mm_loadu_ps(S7 + x + 4))); - - __m128i v_dsti0 = _mm_cvtps_epi32(v_dst0); - __m128i v_dsti1 = _mm_cvtps_epi32(v_dst1); - - _mm_storeu_si128((__m128i *)(dst + x), _mm_packus_epi32(v_dsti0, v_dsti1)); - } - - return x; -} - -} -} -/* End of file. */ diff --git a/modules/imgproc/test/test_imgwarp.cpp b/modules/imgproc/test/test_imgwarp.cpp index f3e919c0ad..d431ba033e 100644 --- a/modules/imgproc/test/test_imgwarp.cpp +++ b/modules/imgproc/test/test_imgwarp.cpp @@ -854,7 +854,7 @@ TEST(Resize, Area_fractional_shared_rows) TEST(Resize, Area_half) { - const int size = 1000; + const Size size(258, 130); int types[] = { CV_8UC1, CV_8UC4, CV_16UC1, CV_16UC4, CV_16SC1, CV_16SC3, CV_16SC4, @@ -870,8 +870,8 @@ TEST(Resize, Area_half) SCOPED_TRACE(depth); SCOPED_TRACE(cn); - cv::Mat src(size, size, type), dst_actual(size >> 1, size >> 1, type), - dst_reference(size >> 1, size >> 1, type); + cv::Mat src(size, type), dst_actual(size.height >> 1, size.width >> 1, type), + dst_reference(size.height >> 1, size.width >> 1, type); rng.fill(src, cv::RNG::UNIFORM, -1000, 1000, true); diff --git a/modules/imgproc/test/test_resize_bitexact.cpp b/modules/imgproc/test/test_resize_bitexact.cpp index 299706683e..bb66f1dc9c 100644 --- a/modules/imgproc/test/test_resize_bitexact.cpp +++ b/modules/imgproc/test/test_resize_bitexact.cpp @@ -22,61 +22,65 @@ TEST(Resize_Bitexact, Linear8U) { static const int64_t fixedOne = (1L << fixedShiftU8); + // Each source keeps the original ratio to its output; the 1024-wide ones keep fractional ratios + // whose phase period spans the width, and 1/256 needs the full size for a valid output. struct testmode { int type; - Size sz; + Size src, dst; } modes[] = { - { CV_8UC1, Size( 512, 768) }, // 1/2 1 - { CV_8UC3, Size( 512, 768) }, - { CV_8UC1, Size(1024, 384) }, // 1 1/2 - { CV_8UC4, Size(1024, 384) }, - { CV_8UC1, Size( 512, 384) }, // 1/2 1/2 - { CV_8UC2, Size( 512, 384) }, - { CV_8UC3, Size( 512, 384) }, - { CV_8UC4, Size( 512, 384) }, - { CV_8UC1, Size( 256, 192) }, // 1/4 1/4 - { CV_8UC2, Size( 256, 192) }, - { CV_8UC3, Size( 256, 192) }, - { CV_8UC4, Size( 256, 192) }, - { CV_8UC1, Size( 4, 3) }, // 1/256 1/256 - { CV_8UC2, Size( 4, 3) }, - { CV_8UC3, Size( 4, 3) }, - { CV_8UC4, Size( 4, 3) }, - { CV_8UC1, Size( 342, 384) }, // 1/3 1/2 - { CV_8UC1, Size( 342, 256) }, // 1/3 1/3 - { CV_8UC2, Size( 342, 256) }, - { CV_8UC3, Size( 342, 256) }, - { CV_8UC4, Size( 342, 256) }, - { CV_8UC1, Size( 512, 256) }, // 1/2 1/3 - { CV_8UC1, Size( 146, 110) }, // 1/7 1/7 - { CV_8UC3, Size( 146, 110) }, - { CV_8UC4, Size( 146, 110) }, - { CV_8UC1, Size( 931, 698) }, // 10/11 10/11 - { CV_8UC2, Size( 931, 698) }, - { CV_8UC3, Size( 931, 698) }, - { CV_8UC4, Size( 931, 698) }, - { CV_8UC1, Size( 853, 640) }, // 10/12 10/12 - { CV_8UC3, Size( 853, 640) }, - { CV_8UC4, Size( 853, 640) }, - { CV_8UC1, Size(1004, 753) }, // 251/256 251/256 - { CV_8UC2, Size(1004, 753) }, - { CV_8UC3, Size(1004, 753) }, - { CV_8UC4, Size(1004, 753) }, - { CV_8UC1, Size(2048,1536) }, // 2 2 - { CV_8UC2, Size(2048,1536) }, - { CV_8UC4, Size(2048,1536) }, - { CV_8UC1, Size(3072,2304) }, // 3 3 - { CV_8UC3, Size(3072,2304) }, - { CV_8UC1, Size(7168,5376) } // 7 7 + { CV_8UC1, Size( 256, 192), Size( 128, 192) }, // 1/2 1 + { CV_8UC3, Size( 256, 192), Size( 128, 192) }, + { CV_8UC1, Size( 256, 192), Size( 256, 96) }, // 1 1/2 + { CV_8UC4, Size( 256, 192), Size( 256, 96) }, + { CV_8UC1, Size( 256, 192), Size( 128, 96) }, // 1/2 1/2 + { CV_8UC2, Size( 256, 192), Size( 128, 96) }, + { CV_8UC3, Size( 256, 192), Size( 128, 96) }, + { CV_8UC4, Size( 256, 192), Size( 128, 96) }, + { CV_8UC1, Size( 256, 192), Size( 64, 48) }, // 1/4 1/4 + { CV_8UC2, Size( 256, 192), Size( 64, 48) }, + { CV_8UC3, Size( 256, 192), Size( 64, 48) }, + { CV_8UC4, Size( 256, 192), Size( 64, 48) }, + { CV_8UC1, Size(1024, 768), Size( 4, 3) }, // 1/256 1/256 + { CV_8UC2, Size(1024, 768), Size( 4, 3) }, + { CV_8UC3, Size(1024, 768), Size( 4, 3) }, + { CV_8UC4, Size(1024, 768), Size( 4, 3) }, + { CV_8UC1, Size( 512, 384), Size( 171, 192) }, // 171/512 1/2 + { CV_8UC1, Size( 512, 384), Size( 171, 128) }, // 171/512 1/3 + { CV_8UC2, Size( 512, 384), Size( 171, 128) }, + { CV_8UC3, Size( 512, 384), Size( 171, 128) }, + { CV_8UC4, Size( 512, 384), Size( 171, 128) }, + { CV_8UC1, Size( 512, 384), Size( 256, 128) }, // 1/2 1/3 + { CV_8UC1, Size( 512, 384), Size( 73, 55) }, // 73/512 55/384 + { CV_8UC3, Size( 512, 384), Size( 73, 55) }, + { CV_8UC4, Size( 512, 384), Size( 73, 55) }, + { CV_8UC1, Size(1024, 384), Size( 931, 349) }, // 931/1024 349/384 + { CV_8UC2, Size(1024, 384), Size( 931, 349) }, + { CV_8UC3, Size(1024, 384), Size( 931, 349) }, + { CV_8UC4, Size(1024, 384), Size( 931, 349) }, + { CV_8UC1, Size(1024, 384), Size( 853, 320) }, // 853/1024 5/6 + { CV_8UC3, Size(1024, 384), Size( 853, 320) }, + { CV_8UC4, Size(1024, 384), Size( 853, 320) }, + { CV_8UC1, Size( 512, 256), Size( 502, 251) }, // 251/256 251/256 + { CV_8UC2, Size( 512, 256), Size( 502, 251) }, + { CV_8UC3, Size( 512, 256), Size( 502, 251) }, + { CV_8UC4, Size( 512, 256), Size( 502, 251) }, + { CV_8UC1, Size( 256, 192), Size( 512, 384) }, // 2 2 + { CV_8UC2, Size( 256, 192), Size( 512, 384) }, + { CV_8UC4, Size( 256, 192), Size( 512, 384) }, + { CV_8UC1, Size( 256, 192), Size( 768, 576) }, // 3 3 + { CV_8UC3, Size( 256, 192), Size( 768, 576) }, + { CV_8UC1, Size( 128, 96), Size( 896, 672) } // 7 7 }; - Mat srcByCn[CV_CN_MAX + 1]; // the source depends only on the channel count + std::map >, Mat> sources; // keyed by channels and size for (int modeind = 0, _modecnt = sizeof(modes) / sizeof(modes[0]); modeind < _modecnt; ++modeind) { int type = modes[modeind].type, depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); - int dcols = modes[modeind].sz.width, drows = modes[modeind].sz.height; - int cols = 1024, rows = 768; + int dcols = modes[modeind].dst.width, drows = modes[modeind].dst.height; + int cols = modes[modeind].src.width, rows = modes[modeind].src.height; + // Pattern blocks scale with the source; at 1024x768 they are the original 128 pixels. + const int bx = cols / 8, by = rows / 6; double inv_scale_x = (double)dcols / cols; double inv_scale_y = (double)drows / rows; @@ -84,7 +88,7 @@ TEST(Resize_Bitexact, Linear8U) softdouble scale_y = softdouble::one() / softdouble(inv_scale_y); Mat refdst(drows, dcols, type), dst; - Mat& src = srcByCn[cn]; + Mat& src = sources[std::make_pair(cn, std::make_pair(cols, rows))]; if (src.empty()) { src.create(rows, cols, type); @@ -95,10 +99,10 @@ TEST(Resize_Bitexact, Linear8U) for (int i = 0; i < cols; i++) for (int c = 0; c < cn; c++) { - double val = j < rows / 2 ? ( i < cols / 2 ? ((sin((i + 1)*CV_PI / 256.)*sin((j + 1)*CV_PI / 256.)*sin((cn + 4)*CV_PI / 8.) + 1.)*128.) : - (((i / 128 + j / 128) % 2) * 250 + (j / 128) % 2) ) : - ( i < cols / 2 ? ((i / 128) * (85 - j / 256 * 40) * ((j / 128) % 2) + (7 - i / 128) * (85 - j / 256 * 40) * ((j / 128 + 1) % 2)) : - ((uchar)rnd) ) ; + double val = j < rows / 2 ? ( i < cols / 2 ? ((sin((i + 1)*CV_PI / (2*bx))*sin((j + 1)*CV_PI / (2*by))*sin((cn + 4)*CV_PI / 8.) + 1.)*128.) : + (((i / bx + j / by) % 2) * 250 + (j / by) % 2) ) : + ( i < cols / 2 ? ((i / bx) * (85 - j / (2*by) * 40) * ((j / by) % 2) + (7 - i / bx) * (85 - j / (2*by) * 40) * ((j / by + 1) % 2)) : + ((uchar)rnd) ) ; if (depth == CV_8U) line[i*cn + c] = (uint8_t)val; else if (depth == CV_16U) @@ -166,6 +170,38 @@ TEST(Resize_Bitexact, Linear8U) } } +// At 2x, INTER_LINEAR_EXACT averages 2x2 blocks bit-exactly for every depth and channel count. +TEST(Resize_Bitexact, LinearExactHalving) +{ + for (int depth : { CV_8U, CV_8S, CV_16U, CV_16S, CV_32S }) + for (int cn : { 1, 2, 3, 4, 5 }) + for (const Size& ssize : { Size(36, 10), Size(35, 11) }) + { + Mat src(ssize, CV_MAKETYPE(depth, cn)), dst; + RNG rng(depth*16 + cn); + const double lo = depth == CV_8U || depth == CV_16U ? 0 : depth == CV_8S ? -128 : depth == CV_16S ? -32768 : -1e9; + const double hi = depth == CV_8U ? 256 : depth == CV_8S ? 128 : depth == CV_16U ? 65536 : depth == CV_16S ? 32768 : 1e9; + rng.fill(src, RNG::UNIFORM, lo, hi); + resize(src, dst, Size(), 0.5, 0.5, INTER_LINEAR_EXACT); + ASSERT_EQ(Size(cvRound(ssize.width*0.5), cvRound(ssize.height*0.5)), dst.size()); + + Mat s32, d32; + src.convertTo(s32, CV_32S); + dst.convertTo(d32, CV_32S); + for (int y = 0; y < dst.rows; y++) + for (int x = 0; x < dst.cols; x++) + for (int c = 0; c < cn; c++) + { + const int x0 = 2*x, x1 = std::min(2*x + 1, ssize.width - 1); + const int y0 = 2*y, y1 = std::min(2*y + 1, ssize.height - 1); + const int64 sum = (int64)s32.ptr(y0)[x0*cn + c] + s32.ptr(y0)[x1*cn + c] + + s32.ptr(y1)[x0*cn + c] + s32.ptr(y1)[x1*cn + c]; + ASSERT_EQ((sum + 2) >> 2, d32.ptr(y)[x*cn + c]) + << typeToString(src.type()) << " " << ssize << " at (" << y << ", " << x << ") channel " << c; + } + } +} + PARAM_TEST_CASE(Resize_Bitexact, int) { public: diff --git a/modules/imgproc/test/test_resize_params.cpp b/modules/imgproc/test/test_resize_params.cpp new file mode 100644 index 0000000000..4bc6029684 --- /dev/null +++ b/modules/imgproc/test/test_resize_params.cpp @@ -0,0 +1,1611 @@ +// 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 srcs = { + makeTestImage(CV_8UC3, Size(100, 100), 4), + makeTestImage(CV_8UC3, Size(64, 200), 5), + }; + std::vector 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 mismatched = { + makeTestImage(CV_8UC3, Size(64, 64), 1), + makeTestImage(CV_8UC1, Size(64, 64), 2), + }; + std::vector vecDst; + EXPECT_THROW(resize(mismatched, vecDst, ResizeParams(Size(32, 32))), cv::Exception); + + std::vector 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(ssize.width*p.fx), saturate_cast(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 nearestAxis(const ResizeParams& p, const AxisGeom& g) +{ + std::vector 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 nearestExactAxis(const AxisGeom& g) +{ + std::vector 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 i0, i1; + std::vector 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 start, idx; + std::vector 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::max()) + return a < 0 ? std::numeric_limits::min() : std::numeric_limits::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::min() : std::numeric_limits::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(v); + case CV_8S: return saturate_cast(v); + case CV_16U: return saturate_cast(v); + case CV_16S: return saturate_cast(v); + case CV_32S: return saturate_cast(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& 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 all; + const std::vector* 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 xi = interp == INTER_NEAREST ? nearestAxis(p, gx) : nearestExactAxis(gx); + const std::vector 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 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 struct RandomBag +{ + std::vector values; + size_t pos; + explicit RandomBag(const std::vector& 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 static void repeatInto(std::vector& 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 sizes; // a size per image + std::vector 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 leadingDimsOf(RNG& rng, int n, int rank) +{ + std::vector dims(rank - 2, 1); + int rest = n; + for (int i = 0; i + 1 < rank - 2; i++) + { + std::vector 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(first.width*p.fx), saturate_cast(first.height*p.fy)); + (rng.uniform(0, 2) ? p.dsize.width : p.dsize.height) = 1; + } +} + +struct CaseGenerator +{ + RandomBag interps; + RandomBag > nearestModes; // (coordMode, nearestMode) pairs INTER_NEAREST takes + RandomBag filterModes; + RandomBag tiers; + RandomBag largeCases; + + static std::vector interpBag() + { + std::vector 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 > nearestBag() + { + std::vector > 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 modeBag() + { + std::vector v; + for (int mode = 0; mode <= (int)ResizeCoord::HALF_PIXEL_SYMMETRIC; mode++) + v.push_back(mode); + return v; + } + static std::vector tierBag() + { + std::vector 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({ 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(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 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(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(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& lead, Size sz, int type, bool roi) +{ + std::vector 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 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 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::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 samplePoints(Size dsize, int randomCount, RNG& rng) +{ + std::vector 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 srcPlanes, dstPlanes; + + // The source, with values drawn per plane. + Mat tensorSrc; + std::vector 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 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 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 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& 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 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 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 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 dsts; + for (const Mat& s : srcs) + { + Mat d(saturate_cast(s.rows*p.fy), saturate_cast(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_({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(0, t.expected[mode][0]), dst.at(0, 1)) << "fx=" << t.fx << " mode=" << mode; + EXPECT_EQ(src.at(0, t.expected[mode][1]), dst.at(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(0, halfExpected[s][mode]), dst.at(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_({2, 4}, {1, 2, 3, 4, 5, 6, 7, 8}); + const Mat x44 = Mat_({4, 4}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); + const Mat x22 = Mat_({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 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_({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(0, 0), 1e-5); + EXPECT_NEAR(4.f, dst.at(0, 1), 1e-5); + } + { + // ONNX test_resize_downsample_scales_linear_half_pixel_symmetric + Mat src = Mat_({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(0, 0), 1e-5); + EXPECT_NEAR(3.3333333f, dst.at(0, 1), 1e-5); + } + { + // One output sample: ALIGN_CORNERS and PYTORCH_HALF_PIXEL read the first, HALF_PIXEL the middle. + Mat src = Mat_({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(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_({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_({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_({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_({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_({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(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 srcs(2); + makeTestImage(CV_8UC3, Size(120, 90), 11).copyTo(srcs[0]); + makeTestImage(CV_8UC3, Size(90, 120), 22).copyTo(srcs[1]); + + std::vector 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 diff --git a/modules/java/generator/gen_java.py b/modules/java/generator/gen_java.py index 0d46721846..82aff95d34 100755 --- a/modules/java/generator/gen_java.py +++ b/modules/java/generator/gen_java.py @@ -1054,7 +1054,12 @@ class JavaWrapperGenerator(object): name = prop_name + ";//" cvname = fi.fullNameCPP() - retval = self.fullTypeNameCPP(fi.ctype) + " _retval_ = " if ret else "return " + # A scoped enum ('enum class') has no implicit conversion to the JNI integer type, + # so the int it is mapped to has to be named explicitly. + enum_cast = "" + if fi.ctype in type_dict and "cast_from" in type_dict[fi.ctype]: + enum_cast = "(%s)" % cast_from(fi.ctype) + retval = self.fullTypeNameCPP(fi.ctype) + " _retval_ = " + enum_cast if ret else "return " + enum_cast if fi.ctype == "void": retval = "" elif fi.ctype == "String":