mirror of
https://github.com/opencv/opencv.git
synced 2026-11-24 18:27:56 -06:00
vectorized and parallel DFT/DCT + matchTemplate - #30061 (Made with a help from Claude Code Fable 5.1) ## Summary This PR replaces the scalar 1D DFT/DCT kernels in `modules/core/src/dxt.cpp` with a new engine built on universal intrinsics and compiled per ISA through `ocv_add_dispatched_file`, and makes the 2D transforms, the `DFT_ROWS`/`DCT_ROWS` batches and `matchTemplate` (`crossCorr`) multi-threaded. The public API, the output formats (CCS packing of real spectra, `DFT_COMPLEX_OUTPUT` layout, DCT ordering and normalization) and the IPP/OpenCL paths are unchanged. Only floating-point rounding may differ (the new twiddle tables are more accurate than the old recurrence-generated ones, so the error goes down, not up). Measured on Apple M4 Max (16 cores, NEON), macOS 26.5.x, Xcode 26.6, Release build (`-O3`, no IPP). All numbers are the minimum over repeated runs, `5.x` vs this PR. ## Changes ### New 1D engine (`dxt.hpp`, `dxt.simd.hpp`, `dxt.cpp`) - **Split re/im layout.** The input pass gathers the data into separate `re[]`/`im[]` workspace arrays; all middle stages operate on the split arrays, so a complex multiplication is four independent vector FMAs with no lane shuffling. The output pass interleaves back (or packs the CCS / DCT layout) with the scaling fused in. - **Mixed-radix decimation-in-time with a fused first stage.** The plan chooses the first stage (radix 1/2/4/8, twiddle-free, fused with the gather and the digit-reversal permutation) from the power of two in the length, then radix-4 stages, then radix-3, radix-5 and a generic odd radix. There are no radix-2 middle stages. - **Vectorized butterflies with universal intrinsics** (`v_float32`/`v_float64`, VLA-safe): one flat loop per stage with a single clamped counter for both the data and the twiddle offsets (the back-off clamp handles spans that are not multiples of the vector width; such stages run out of place, ping-ponging between two workspace pairs, the others run in place). - **Vectorized first stage.** The radix-2/4/8 first stage reads the input columns contiguously (`v_load_deinterleave`), runs the small DFT in registers and scatters the outputs of every lane with one 4-channel interleaved store. Only odd lengths use a scalar table-driven gather. - **Vectorized edge passes**: interleave/deinterleave, the real-FFT untangling in both directions (with `v_reverse` for the mirrored half), DCT-II post-twiddle and DCT-III pre-twiddle, the Makhoul permutations. - **Inverse = conjugation trick**: the middle stages are direction-free and use forward twiddles only; the inverse conjugates on the gather and negates the imaginary scale on the output. - **Immutable plan + per-executor workspace, zero allocations per transform.** The plan (radix sequence, permutation table, per-stage split twiddle tables) is built once in `init()` and shared by all rows of a batch; every executor owns a workspace. Twiddles are generated in double precision from a two-level exact table (a few ulps, much cheaper to build than the old N-point recurrence, which matters because `cv::dft()` builds a plan on every call). - **Per-ISA dispatch**: `ocv_add_dispatched_file(dxt SSE2 AVX2 AVX512_ICL RVV)`; the kernels are reached through a function-pointer table resolved once per depth, following the pattern of `arithm.simd.hpp` / `warp_kernels.simd.hpp`. The plan is built with the vector width of the dispatched kernels (never with the baseline `VTraits`). - The legacy scalar engine, `DFTInit`, the SSE3 `DFT_VecR*` butterflies and the `noPermute`/ `factors[0] >>= 1` machinery are removed (−1400 lines). The legacy `cv_hal_dft` hook (which took the old tables) is no longer called from the 1D path; the in-tree RISC-V HAL implementation of it will be updated in a separate PR. ### Parallelism - `crossCorr` (`matchTemplate`): the correlation tiles are independent and are now distributed with `parallel_for_`; every worker creates its DFT buffers and `DFT2D` contexts once per range. (The tile loop had been sequential since the C++ rewrite in 2010, which dropped the OpenMP pragma of `icvCrossCorr`.) - 2D DFT/DCT and `DFT_ROWS`/`DCT_ROWS` batches: the row pass, the column pass and the DCT line loop distribute their lines over threads; the 1D plan is shared, each worker allocates its workspace once per range. The number of stripes is derived from the N log N cost, so a 256x256 transform stays on the calling thread and 1024x1024 gets ~20 stripes. Nested calls (the 2D DFTs inside the parallel `crossCorr` tiles) are serialized by `parallel_for_` itself. - The column pass copies columns in batches (`CopyFromColumns`/`CopyToColumns`, 4..16 adjacent columns copied row by row into contiguous buffers sized to stay within 128 KB) instead of two at a time: with power-of-two row steps the old strided copies aliased in the cache and took 60-70% of the 2D time. ### Tests - `Core_DFT.sweep_1d`, `Core_DCT.sweep_1d`: every 5-smooth length up to 2048 plus odd, prime and "awkward" lengths, both depths, C2C forward/inverse, R2C (CCS and complex output), C2R (CCS and complex input), DCT/IDCT, in-place, column vectors, round trips; compared against the naive O(N^2) references of `test_dxt.cpp` with a tolerance of `32*eps*(log2(N) + 2 + maxfactor/16)`. - `Core_DFT.sweep_rows`: `DFT_ROWS` batches sharing one plan. - `Core_DFT.nonzero_rows`: 2D transforms with `nonzero_rows` (previously uncovered). - `Core_DFT.parallel_large`: large 2D / rows / DCT transforms, multi-threaded result vs the single-threaded one. - The naive DCT reference reduces the angle exactly before `cos()` (its accuracy was limiting the comparison for n > 100 in double precision). - Perf: `perf_dft.cpp` gains 1D row/column cases for `dft` and `dct`. - Existing `opencv_test_core` (incl. `Core_DFT*`, `Core_DCT*`, `Core_MulSpectrums`, `Core_DivSpectrums`) and `opencv_test_imgproc` (phaseCorrelate, matchTemplate, filter2D) pass; the x86-64 build (SSE3 baseline + SSE4.1/AVX2/AVX512_ICL dispatch) passes the DFT/DCT tests under Rosetta 2 (AVX2/AVX-512 paths compile-checked only on this machine). ## Performance ### 1D transforms (single row, one thread), microseconds `C2C` = complex-to-complex, `R2C` = real-to-CCS, `C2R` = CCS-to-real (inverse, scaled), `32`/`64` = float/double. | n | C2C32 | C2C64 | R2C32 | C2R32 | R2C64 | DCT32 | IDCT32 | DCT64 | |---|---|---|---|---|---|---|---|---| | 256 | 0.82 → 0.55 | 0.86 → 0.74 | 0.67 → 0.53 | 0.63 → 0.52 | 0.64 → 0.56 | 0.88 → 0.56 | 0.88 → 0.56 | 0.90 → 0.66 | | 1000 | 3.84 → 1.70 | 4.08 → 2.58 | 2.86 → 1.36 | 2.88 → 1.38 | 2.77 → 1.74 | 3.95 → 1.69 | 4.02 → 1.72 | 3.97 → 2.15 | | 1024 | 3.25 → 1.65 | 3.44 → 2.40 | 2.46 → 1.23 | 2.35 → 1.27 | 2.42 → 1.59 | 3.57 → 1.57 | 3.51 → 1.59 | 3.45 → 2.02 | | 4096 | 14.9 → 6.4 | 16.4 → 11.5 | 10.7 → 4.3 | 10.2 → 4.5 | 11.0 → 6.9 | 15.4 → 6.0 | 15.3 → 6.0 | 17.0 → 9.5 | | 4725 (3³·5²·7) | 27.5 → 17.2 | 29.4 → 24.1 | 28.2 → 16.4 | 29.8 → 18.3 | 30.3 → 24.7 | – | – | – | | 65536 | 350 → 273 | 411 → 494 | 223 → 136 | 274 → 139 | 251 → 249 | 318 → 167 | 299 → 159 | 372 → 320 | Each `cv::dft()` call builds its plan anew; at n = 4096 the plan takes ~1.9 µs of the 6.4 µs (the old code spent ~4 µs of 14.9 on its tables). For n = 65536 both versions are bound by the memory traffic of the out-of-cache data, and C2C64 gets slightly slower (the split layout needs one more pass over 1 MB of data; a plan cache or larger radices could recover this later). ### 2D transforms, single thread, microseconds | size | C2C32 | R2C32 | C2R32 | R2C64 | DCT32 | IDCT32 | R2C32 rows | |---|---|---|---|---|---|---|---| | 256×256 | 297 → 140 | 162 → 75 | 165 → 77 | 178 → 126 | 259 → 166 | 290 → 174 | 72 → 29 | | 512×512 | 1660 → 569 | 765 → 306 | 723 → 317 | 896 → 551 | 1381 → 946 | 1377 → 957 | 303 → 125 | | 480×640 | 1555 → 715 | 895 → 377 | 918 → 392 | 978 → 677 | 1248 → 707 | 1262 → 695 | 389 → 147 | | 1024×1024 | 7508 → 2625 | 3781 → 1387 | 3883 → 1398 | 4964 → 3201 | 6438 → 4556 | 6805 → 4583 | 1341 → 516 | | 1080×1920 | 13141 → 5543 | 7143 → 2880 | 7269 → 2970 | 7770 → 5348 | 9735 → 5190 | 9477 → 5381 | 3116 → 1192 | | 2048×2048 | 38151 → 16822 | 18381 → 6973 | 18784 → 7294 | 25146 → 17476 | 30291 → 21631 | 30540 → 22003 | 5809 → 2242 | ### 2D transforms, default thread count (16), microseconds | size | C2C32 | R2C32 | C2R32 | R2C64 | DCT32 | IDCT32 | R2C32 rows | |---|---|---|---|---|---|---|---| | 256×256 | 309 → 138 | 157 → 75 | 161 → 77 | 174 → 126 | 265 → 167 | 293 → 170 | 71 → 29 | | 512×512 | 1660 → 162 | 785 → 155 | 788 → 160 | 866 → 256 | 1410 → 235 | 1366 → 228 | 303 → 41 | | 480×640 | 1531 → 178 | 895 → 142 | 916 → 141 | 957 → 222 | 1241 → 172 | 1248 → 173 | 393 → 46 | | 1024×1024 | 7495 → 381 | 3755 → 274 | 3767 → 269 | 4875 → 478 | 6323 → 650 | 6583 → 630 | 1343 → 94 | | 1080×1920 | 12905 → 681 | 7131 → 403 | 7240 → 382 | 7760 → 657 | 9673 → 605 | 9513 → 607 | 3124 → 143 | | 2048×2048 | 38155 → 1481 | 18324 → 826 | 18559 → 857 | 24861 → 1776 | 30120 → 2592 | 30741 → 2734 | 5890 → 274 | (5.x is single-threaded for all of these; 256×256 stays single-threaded in the new code by design.) ### matchTemplate (`opencv_perf_imgproc`, `*matchTemplate*`), milliseconds Whole suite (156 cases): 921 → 284 ms. Selected cases (8-bit image, 16×16 template unless noted): | image, template | SQDIFF | SQDIFF_NORMED | CCORR | CCORR_NORMED | CCOEFF | CCOEFF_NORMED | |---|---|---|---|---|---|---| | 128×128 | 0.15 → 0.12 | 0.14 → 0.12 | 0.09 → 0.05 | 0.13 → 0.09 | 0.11 → 0.08 | 0.13 → 0.10 | | 320×240 | 0.99 → 0.52 | 1.09 → 0.58 | 0.79 → 0.23 | 0.96 → 0.42 | 0.93 → 0.38 | 1.02 → 0.53 | | 640×480 | 3.19 → 1.17 | 3.35 → 1.22 | 2.27 → 0.29 | 3.12 → 1.04 | 2.94 → 0.90 | 3.43 → 1.38 | | 800×600 | 5.86 → 1.64 | 5.61 → 1.77 | 4.11 → 0.34 | 5.48 → 1.53 | 5.19 → 1.28 | 5.82 → 2.04 | | 1024×768 | 9.73 → 2.72 | 9.59 → 2.90 | 6.88 → 0.48 | 9.11 → 2.45 | 8.44 → 2.05 | 9.84 → 3.44 | | 1280×1024 | 14.92 → 4.33 | 15.01 → 4.58 | 10.70 → 0.64 | 14.31 → 3.97 | 13.40 → 3.33 | 15.37 → 5.58 | | 1280×1024, 1260×1000 | 13.06 → 7.90 | 13.08 → 7.74 | 10.75 → 3.58 | 12.23 → 5.03 | 11.11 → 3.94 | 12.03 → 5.05 | `TM_CCORR` is now dominated by the (still single-threaded) `integral()` and normalization passes in the other methods; those are candidates for a follow-up. ## Notes for reviewers - `modules/core/src/dxt.hpp` documents the engine layout; the plan builder (`DftPlan::build`) and the driver (`runDft`) are in `dxt.cpp`, the kernels in `dxt.simd.hpp`. - Stages whose span is smaller than the vector width run scalar (on NEON this only affects lengths of the form 2·odd; on AVX2/AVX-512 also the first radix-4 stage of 4^k lengths); handling them with narrower fixed-width vectors is a possible follow-up. - A radix-8 middle stage was implemented and measured slower on NEON than two radix-4 stages (register pressure), so it is not included. ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [x] The feature is well documented and sample code can be built with the project CMake
1068 lines
40 KiB
C++
1068 lines
40 KiB
C++
/*M///////////////////////////////////////////////////////////////////////////////////////
|
|
//
|
|
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
|
|
//
|
|
// By downloading, copying, installing or using the software you agree to this license.
|
|
// If you do not agree to this license, do not download, install,
|
|
// copy or use the software.
|
|
//
|
|
//
|
|
// Intel License Agreement
|
|
// For Open Source Computer Vision Library
|
|
//
|
|
// Copyright (C) 2000, Intel Corporation, 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 Intel Corporation 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 "opencl_kernels_imgproc.hpp"
|
|
|
|
////////////////////////////////////////////////// matchTemplate //////////////////////////////////////////////////////////
|
|
|
|
namespace cv
|
|
{
|
|
|
|
static inline Size matchResultSize(Size imageSize, Size templSize)
|
|
{
|
|
return Size(imageSize.width - templSize.width + 1,
|
|
imageSize.height - templSize.height + 1);
|
|
}
|
|
|
|
#ifdef HAVE_OPENCL
|
|
|
|
/////////////////////////////////////////////////// CCORR //////////////////////////////////////////////////////////////
|
|
|
|
enum
|
|
{
|
|
SUM_1 = 0, SUM_2 = 1
|
|
};
|
|
|
|
static bool extractFirstChannel_32F(InputArray _image, OutputArray _result, int cn)
|
|
{
|
|
int depth = _image.depth();
|
|
|
|
ocl::Device dev = ocl::Device::getDefault();
|
|
int pxPerWIy = (dev.isIntel() && (dev.type() & ocl::Device::TYPE_GPU)) ? 4 : 1;
|
|
|
|
ocl::Kernel k("extractFirstChannel", ocl::imgproc::match_template_oclsrc, format("-D FIRST_CHANNEL -D T1=%s -D cn=%d -D PIX_PER_WI_Y=%d",
|
|
ocl::typeToStr(depth), cn, pxPerWIy));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat image = _image.getUMat();
|
|
UMat result = _result.getUMat();
|
|
|
|
|
|
size_t globalsize[2] = {(size_t)result.cols, ((size_t)result.rows+pxPerWIy-1)/pxPerWIy};
|
|
return k.args(ocl::KernelArg::ReadOnlyNoSize(image), ocl::KernelArg::WriteOnly(result)).run( 2, globalsize, NULL, false);
|
|
}
|
|
|
|
static bool sumTemplate(InputArray _src, UMat & result)
|
|
{
|
|
int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
int wdepth = CV_32F, wtype = CV_MAKE_TYPE(wdepth, cn);
|
|
size_t wgs = ocl::Device::getDefault().maxWorkGroupSize();
|
|
|
|
int wgs2_aligned = 1;
|
|
while (wgs2_aligned < (int)wgs)
|
|
wgs2_aligned <<= 1;
|
|
wgs2_aligned >>= 1;
|
|
|
|
char cvt[50];
|
|
ocl::Kernel k("calcSum", ocl::imgproc::match_template_oclsrc,
|
|
format("-D CALC_SUM -D T=%s -D T1=%s -D WT=%s -D cn=%d -D convertToWT=%s -D WGS=%d -D WGS2_ALIGNED=%d",
|
|
ocl::typeToStr(type), ocl::typeToStr(depth), ocl::typeToStr(wtype), cn,
|
|
ocl::convertTypeStr(depth, wdepth, cn, cvt, sizeof(cvt)),
|
|
(int)wgs, wgs2_aligned));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat src = _src.getUMat();
|
|
result.create(1, 1, CV_32FC1);
|
|
|
|
ocl::KernelArg srcarg = ocl::KernelArg::ReadOnlyNoSize(src),
|
|
resarg = ocl::KernelArg::PtrWriteOnly(result);
|
|
|
|
k.args(srcarg, src.cols, (int)src.total(), resarg);
|
|
|
|
size_t globalsize = wgs;
|
|
return k.run(1, &globalsize, &wgs, false);
|
|
}
|
|
|
|
static bool useNaive(Size size)
|
|
{
|
|
int dft_size = 18;
|
|
return size.height < dft_size && size.width < dft_size;
|
|
}
|
|
|
|
struct ConvolveBuf
|
|
{
|
|
Size result_size;
|
|
Size block_size;
|
|
Size user_block_size;
|
|
Size dft_size;
|
|
|
|
UMat image_spect, templ_spect, result_spect;
|
|
UMat image_block, templ_block, result_data;
|
|
|
|
void create(Size image_size, Size templ_size);
|
|
};
|
|
|
|
void ConvolveBuf::create(Size image_size, Size templ_size)
|
|
{
|
|
result_size = Size(image_size.width - templ_size.width + 1,
|
|
image_size.height - templ_size.height + 1);
|
|
|
|
const double blockScale = 4.5;
|
|
const int minBlockSize = 256;
|
|
|
|
block_size.width = cvRound(templ_size.width*blockScale);
|
|
block_size.width = std::max( block_size.width, minBlockSize - templ_size.width + 1 );
|
|
block_size.width = std::min( block_size.width, result_size.width );
|
|
block_size.height = cvRound(templ_size.height*blockScale);
|
|
block_size.height = std::max( block_size.height, minBlockSize - templ_size.height + 1 );
|
|
block_size.height = std::min( block_size.height, result_size.height );
|
|
|
|
dft_size.width = std::max(getOptimalDFTSize(block_size.width + templ_size.width - 1), 2);
|
|
dft_size.height = getOptimalDFTSize(block_size.height + templ_size.height - 1);
|
|
if( dft_size.width <= 0 || dft_size.height <= 0 )
|
|
CV_Error( cv::Error::StsOutOfRange, "the input arrays are too big" );
|
|
|
|
// recompute block size
|
|
block_size.width = dft_size.width - templ_size.width + 1;
|
|
block_size.width = std::min( block_size.width, result_size.width);
|
|
block_size.height = dft_size.height - templ_size.height + 1;
|
|
block_size.height = std::min( block_size.height, result_size.height );
|
|
|
|
image_block.create(dft_size, CV_32F);
|
|
templ_block.create(dft_size, CV_32F);
|
|
result_data.create(dft_size, CV_32F);
|
|
|
|
image_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
|
|
templ_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
|
|
result_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
|
|
|
|
// Use maximum result matrix block size for the estimated DFT block size
|
|
block_size.width = std::min(dft_size.width - templ_size.width + 1, result_size.width);
|
|
block_size.height = std::min(dft_size.height - templ_size.height + 1, result_size.height);
|
|
}
|
|
|
|
static bool convolve_dft(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
ConvolveBuf buf;
|
|
CV_Assert(_image.type() == CV_32F);
|
|
CV_Assert(_templ.type() == CV_32F);
|
|
|
|
buf.create(_image.size(), _templ.size());
|
|
_result.create(buf.result_size, CV_32F);
|
|
|
|
UMat image = _image.getUMat();
|
|
UMat templ = _templ.getUMat();
|
|
|
|
UMat result = _result.getUMat();
|
|
|
|
Size& block_size = buf.block_size;
|
|
Size& dft_size = buf.dft_size;
|
|
|
|
UMat& image_block = buf.image_block;
|
|
UMat& templ_block = buf.templ_block;
|
|
UMat& result_data = buf.result_data;
|
|
|
|
UMat& image_spect = buf.image_spect;
|
|
UMat& templ_spect = buf.templ_spect;
|
|
UMat& result_spect = buf.result_spect;
|
|
|
|
UMat templ_roi = templ;
|
|
copyMakeBorder(templ_roi, templ_block, 0, templ_block.rows - templ_roi.rows, 0,
|
|
templ_block.cols - templ_roi.cols, BORDER_ISOLATED);
|
|
|
|
dft(templ_block, templ_spect, 0, templ.rows);
|
|
|
|
// Process all blocks of the result matrix
|
|
for (int y = 0; y < result.rows; y += block_size.height)
|
|
{
|
|
for (int x = 0; x < result.cols; x += block_size.width)
|
|
{
|
|
Size image_roi_size(std::min(x + dft_size.width, image.cols) - x,
|
|
std::min(y + dft_size.height, image.rows) - y);
|
|
Rect roi0(x, y, image_roi_size.width, image_roi_size.height);
|
|
|
|
UMat image_roi(image, roi0);
|
|
|
|
copyMakeBorder(image_roi, image_block, 0, image_block.rows - image_roi.rows,
|
|
0, image_block.cols - image_roi.cols, BORDER_ISOLATED);
|
|
|
|
dft(image_block, image_spect, 0);
|
|
|
|
mulSpectrums(image_spect, templ_spect, result_spect, 0, true);
|
|
|
|
dft(result_spect, result_data, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
|
|
|
|
Size result_roi_size(std::min(x + block_size.width, result.cols) - x,
|
|
std::min(y + block_size.height, result.rows) - y);
|
|
|
|
Rect roi1(x, y, result_roi_size.width, result_roi_size.height);
|
|
Rect roi2(0, 0, result_roi_size.width, result_roi_size.height);
|
|
|
|
UMat result_roi(result, roi1);
|
|
UMat result_block(result_data, roi2);
|
|
|
|
result_block.copyTo(result_roi);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static bool convolve_32F(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
_result.create(matchResultSize(_image.size(), _templ.size()), CV_32F);
|
|
|
|
if (_image.channels() == 1)
|
|
return(convolve_dft(_image, _templ, _result));
|
|
else
|
|
{
|
|
UMat image = _image.getUMat();
|
|
UMat templ = _templ.getUMat();
|
|
UMat result_(image.rows-templ.rows+1,(image.cols-templ.cols+1)*image.channels(), CV_32F);
|
|
bool ok = convolve_dft(image.reshape(1), templ.reshape(1), result_);
|
|
if (ok==false)
|
|
return false;
|
|
UMat result = _result.getUMat();
|
|
return (extractFirstChannel_32F(result_, _result, _image.channels()));
|
|
}
|
|
}
|
|
|
|
static bool matchTemplateNaive_CCORR(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
int type = _image.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
int wdepth = CV_32F, wtype = CV_MAKE_TYPE(wdepth, cn);
|
|
|
|
ocl::Device dev = ocl::Device::getDefault();
|
|
int pxPerWIx = (cn==1 && dev.isIntel() && (dev.type() & ocl::Device::TYPE_GPU)) ? 4 : 1;
|
|
int rated_cn = cn;
|
|
int wtype1 = wtype;
|
|
|
|
if (pxPerWIx!=1)
|
|
{
|
|
rated_cn = pxPerWIx;
|
|
type = CV_MAKE_TYPE(depth, rated_cn);
|
|
wtype1 = CV_MAKE_TYPE(wdepth, rated_cn);
|
|
}
|
|
|
|
char cvt[50];
|
|
char cvt1[50];
|
|
const char* convertToWT1 = ocl::convertTypeStr(depth, wdepth, cn, cvt, sizeof(cvt));
|
|
const char* convertToWT = ocl::convertTypeStr(depth, wdepth, rated_cn, cvt1, sizeof(cvt1));
|
|
|
|
ocl::Kernel k("matchTemplate_Naive_CCORR", ocl::imgproc::match_template_oclsrc,
|
|
format("-D CCORR -D T=%s -D T1=%s -D WT=%s -D WT1=%s -D convertToWT=%s -D convertToWT1=%s -D cn=%d -D PIX_PER_WI_X=%d", ocl::typeToStr(type), ocl::typeToStr(depth), ocl::typeToStr(wtype1), ocl::typeToStr(wtype),
|
|
convertToWT, convertToWT1, cn, pxPerWIx));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat image = _image.getUMat(), templ = _templ.getUMat();
|
|
_result.create(matchResultSize(image.size(), templ.size()), CV_32FC1);
|
|
UMat result = _result.getUMat();
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image), ocl::KernelArg::ReadOnly(templ),
|
|
ocl::KernelArg::WriteOnly(result));
|
|
|
|
size_t globalsize[2] = { ((size_t)result.cols+pxPerWIx-1)/pxPerWIx, (size_t)result.rows};
|
|
return k.run(2, globalsize, NULL, false);
|
|
}
|
|
|
|
|
|
static bool matchTemplate_CCORR(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
if (useNaive(_templ.size()))
|
|
return( matchTemplateNaive_CCORR(_image, _templ, _result));
|
|
else
|
|
{
|
|
if(_image.depth() == CV_8U)
|
|
{
|
|
UMat imagef, templf;
|
|
UMat image = _image.getUMat();
|
|
UMat templ = _templ.getUMat();
|
|
image.convertTo(imagef, CV_32F);
|
|
templ.convertTo(templf, CV_32F);
|
|
return(convolve_32F(imagef, templf, _result));
|
|
}
|
|
else
|
|
{
|
|
return(convolve_32F(_image, _templ, _result));
|
|
}
|
|
}
|
|
}
|
|
|
|
static bool matchTemplatePrepared(InputArray _image, InputArray _templ, OutputArray _result,
|
|
const char* kernelName, const char* buildDef)
|
|
{
|
|
matchTemplate(_image, _templ, _result, cv::TM_CCORR);
|
|
|
|
int type = _image.type(), cn = CV_MAT_CN(type);
|
|
|
|
ocl::Kernel k(kernelName, ocl::imgproc::match_template_oclsrc,
|
|
format("-D %s -D T=%s -D cn=%d", buildDef, ocl::typeToStr(type), cn));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat image = _image.getUMat(), templ = _templ.getUMat();
|
|
_result.create(matchResultSize(image.size(), templ.size()), CV_32F);
|
|
UMat result = _result.getUMat();
|
|
|
|
UMat image_sums, image_sqsums;
|
|
integral(image.reshape(1), image_sums, image_sqsums, CV_32F, CV_32F);
|
|
|
|
UMat templ_sqsum;
|
|
if (!sumTemplate(_templ, templ_sqsum))
|
|
return false;
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result),
|
|
templ.rows, templ.cols, ocl::KernelArg::PtrReadOnly(templ_sqsum));
|
|
|
|
size_t globalsize[2] = { (size_t)result.cols, (size_t)result.rows };
|
|
return k.run(2, globalsize, NULL, false);
|
|
}
|
|
|
|
static bool matchTemplate_CCORR_NORMED(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
return matchTemplatePrepared(_image, _templ, _result, "matchTemplate_CCORR_NORMED", "CCORR_NORMED");
|
|
}
|
|
|
|
////////////////////////////////////// SQDIFF //////////////////////////////////////////////////////////////
|
|
|
|
static bool matchTemplateNaive_SQDIFF(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
int type = _image.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
int wdepth = CV_32F, wtype = CV_MAKE_TYPE(wdepth, cn);
|
|
|
|
char cvt[50];
|
|
ocl::Kernel k("matchTemplate_Naive_SQDIFF", ocl::imgproc::match_template_oclsrc,
|
|
format("-D SQDIFF -D T=%s -D T1=%s -D WT=%s -D convertToWT=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth),
|
|
ocl::typeToStr(wtype), ocl::convertTypeStr(depth, wdepth, cn, cvt, sizeof(cvt)), cn));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat image = _image.getUMat(), templ = _templ.getUMat();
|
|
_result.create(matchResultSize(image.size(), templ.size()), CV_32F);
|
|
UMat result = _result.getUMat();
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image), ocl::KernelArg::ReadOnly(templ),
|
|
ocl::KernelArg::WriteOnly(result));
|
|
|
|
size_t globalsize[2] = { (size_t)result.cols, (size_t)result.rows };
|
|
return k.run(2, globalsize, NULL, false);
|
|
}
|
|
|
|
static bool matchTemplate_SQDIFF(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
if (useNaive(_templ.size()))
|
|
return( matchTemplateNaive_SQDIFF(_image, _templ, _result));
|
|
else
|
|
return matchTemplatePrepared(_image, _templ, _result, "matchTemplate_Prepared_SQDIFF", "SQDIFF_PREPARED");
|
|
}
|
|
|
|
static bool matchTemplate_SQDIFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
return matchTemplatePrepared(_image, _templ, _result, "matchTemplate_SQDIFF_NORMED", "SQDIFF_NORMED");
|
|
}
|
|
|
|
///////////////////////////////////// CCOEFF /////////////////////////////////////////////////////////////////
|
|
|
|
static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
matchTemplate(_image, _templ, _result, cv::TM_CCORR);
|
|
|
|
UMat image_sums, temp;
|
|
integral(_image, image_sums, CV_32F);
|
|
|
|
int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
|
|
ocl::Kernel k("matchTemplate_Prepared_CCOEFF", ocl::imgproc::match_template_oclsrc,
|
|
format("-D CCOEFF -D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat templ = _templ.getUMat();
|
|
UMat result = _result.getUMat();
|
|
|
|
if (cn==1)
|
|
{
|
|
Scalar templMean = mean(templ);
|
|
float templ_sum = (float)templMean[0];
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum);
|
|
}
|
|
else
|
|
{
|
|
Vec4f templ_sum = Vec4f::all(0);
|
|
templ_sum = (Vec4f)mean(templ);
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum); }
|
|
|
|
size_t globalsize[2] = { (size_t)result.cols, (size_t)result.rows };
|
|
return k.run(2, globalsize, NULL, false);
|
|
}
|
|
|
|
static bool matchTemplate_CCOEFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result)
|
|
{
|
|
// Try to use double if supported to improve accuracy if integral images
|
|
bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0;
|
|
int sumDepth = doubleSupport ? CV_64F : CV_32F;
|
|
|
|
matchTemplate(_image, _templ, _result, cv::TM_CCORR);
|
|
|
|
UMat temp, image_sums, image_sqsums;
|
|
integral(_image, image_sums, image_sqsums, sumDepth, sumDepth);
|
|
|
|
int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
CV_Assert(cn >= 1 && cn <= 4);
|
|
|
|
ocl::Kernel k("matchTemplate_CCOEFF_NORMED", ocl::imgproc::match_template_oclsrc,
|
|
format("-D CCOEFF_NORMED -D T=%s -D T1=%s -D cn=%d%s", ocl::typeToStr(type), ocl::typeToStr(depth), cn,
|
|
doubleSupport ? " -D DOUBLE_SUPPORT" : ""));
|
|
if (k.empty())
|
|
return false;
|
|
|
|
UMat templ = _templ.getUMat();
|
|
Size size = _image.size(), tsize = templ.size();
|
|
_result.create(matchResultSize(size, tsize), CV_32F);
|
|
UMat result = _result.getUMat();
|
|
|
|
float scale = 1.f / tsize.area();
|
|
|
|
if (cn == 1)
|
|
{
|
|
float templ_sum = (float)sum(templ)[0];
|
|
|
|
multiply(templ, templ, temp, 1, CV_32F);
|
|
float templ_sqsum = (float)sum(temp)[0];
|
|
|
|
templ_sqsum -= scale * templ_sum * templ_sum;
|
|
templ_sum *= scale;
|
|
|
|
if (templ_sqsum < DBL_EPSILON)
|
|
{
|
|
result = Scalar::all(1);
|
|
return true;
|
|
}
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadOnlyNoSize(image_sqsums),
|
|
ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, scale, templ_sum, templ_sqsum);
|
|
}
|
|
else
|
|
{
|
|
Vec4f templ_sum = Vec4f::all(0), templ_sqsum = Vec4f::all(0);
|
|
templ_sum = sum(templ);
|
|
|
|
multiply(templ, templ, temp, 1, CV_32F);
|
|
templ_sqsum = sum(temp);
|
|
|
|
float templ_sqsum_sum = 0;
|
|
for (int i = 0; i < cn; i ++)
|
|
templ_sqsum_sum += templ_sqsum[i] - scale * templ_sum[i] * templ_sum[i];
|
|
|
|
templ_sum *= scale;
|
|
|
|
if (templ_sqsum_sum < DBL_EPSILON)
|
|
{
|
|
result = Scalar::all(1);
|
|
return true;
|
|
}
|
|
|
|
k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadOnlyNoSize(image_sqsums),
|
|
ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, scale,
|
|
templ_sum, templ_sqsum_sum); }
|
|
|
|
size_t globalsize[2] = { (size_t)result.cols, (size_t)result.rows };
|
|
return k.run(2, globalsize, NULL, false);
|
|
}
|
|
|
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
static bool ocl_matchTemplate( InputArray _img, InputArray _templ, OutputArray _result, int method)
|
|
{
|
|
int cn = _img.channels();
|
|
|
|
if (cn > 4)
|
|
return false;
|
|
|
|
typedef bool (*Caller)(InputArray _img, InputArray _templ, OutputArray _result);
|
|
|
|
static const Caller callers[] =
|
|
{
|
|
matchTemplate_SQDIFF, matchTemplate_SQDIFF_NORMED, matchTemplate_CCORR,
|
|
matchTemplate_CCORR_NORMED, matchTemplate_CCOEFF, matchTemplate_CCOEFF_NORMED
|
|
};
|
|
const Caller caller = callers[method];
|
|
|
|
return caller(_img, _templ, _result);
|
|
}
|
|
|
|
#endif
|
|
|
|
#include "opencv2/core/hal/hal.hpp"
|
|
|
|
void crossCorr( const Mat& img, const Mat& _templ, Mat& corr,
|
|
Point anchor, double delta, int borderType )
|
|
{
|
|
const double blockScale = 4.5;
|
|
const int minBlockSize = 256;
|
|
|
|
Mat templ = _templ;
|
|
int depth = img.depth(), cn = img.channels();
|
|
int tdepth = templ.depth(), tcn = templ.channels();
|
|
int cdepth = corr.depth(), ccn = corr.channels();
|
|
|
|
CV_Assert( img.dims <= 2 && templ.dims <= 2 && corr.dims <= 2 );
|
|
|
|
if( depth != tdepth && tdepth != std::max(CV_32F, depth) )
|
|
{
|
|
_templ.convertTo(templ, std::max(CV_32F, depth));
|
|
tdepth = templ.depth();
|
|
}
|
|
|
|
CV_Assert( depth == tdepth || tdepth == CV_32F);
|
|
CV_Assert( corr.rows <= img.rows + templ.rows - 1 &&
|
|
corr.cols <= img.cols + templ.cols - 1 );
|
|
|
|
CV_Assert( ccn == 1 || delta == 0 );
|
|
|
|
int maxDepth = depth > CV_8S ? CV_64F : std::max(std::max(CV_32F, tdepth), cdepth);
|
|
Size blocksize, dftsize;
|
|
|
|
blocksize.width = cvRound(templ.cols*blockScale);
|
|
blocksize.width = std::max( blocksize.width, minBlockSize - templ.cols + 1 );
|
|
blocksize.width = std::min( blocksize.width, corr.cols );
|
|
blocksize.height = cvRound(templ.rows*blockScale);
|
|
blocksize.height = std::max( blocksize.height, minBlockSize - templ.rows + 1 );
|
|
blocksize.height = std::min( blocksize.height, corr.rows );
|
|
|
|
dftsize.width = std::max(getOptimalDFTSize(blocksize.width + templ.cols - 1), 2);
|
|
dftsize.height = getOptimalDFTSize(blocksize.height + templ.rows - 1);
|
|
if( dftsize.width <= 0 || dftsize.height <= 0 )
|
|
CV_Error( cv::Error::StsOutOfRange, "the input arrays are too big" );
|
|
|
|
// recompute block size
|
|
blocksize.width = dftsize.width - templ.cols + 1;
|
|
blocksize.width = MIN( blocksize.width, corr.cols );
|
|
blocksize.height = dftsize.height - templ.rows + 1;
|
|
blocksize.height = MIN( blocksize.height, corr.rows );
|
|
|
|
Mat dftTempl( dftsize.height*tcn, dftsize.width, maxDepth );
|
|
|
|
int bufSize = 0;
|
|
if( tcn > 1 && tdepth != maxDepth )
|
|
bufSize = templ.cols*templ.rows*CV_ELEM_SIZE(tdepth);
|
|
|
|
if( cn > 1 && depth != maxDepth )
|
|
bufSize = std::max( bufSize, (blocksize.width + templ.cols - 1)*
|
|
(blocksize.height + templ.rows - 1)*CV_ELEM_SIZE(depth));
|
|
|
|
if( (ccn > 1 || cn > 1) && cdepth != maxDepth )
|
|
bufSize = std::max( bufSize, blocksize.width*blocksize.height*CV_ELEM_SIZE(cdepth));
|
|
|
|
{
|
|
AutoBuffer<uchar> buf(bufSize);
|
|
Ptr<hal::DFT2D> c = hal::DFT2D::create(dftsize.width, dftsize.height, dftTempl.depth(), 1, 1, CV_HAL_DFT_IS_INPLACE, templ.rows);
|
|
|
|
// compute DFT of each template plane
|
|
for( int k = 0; k < tcn; k++ )
|
|
{
|
|
int yofs = k*dftsize.height;
|
|
Mat src = templ;
|
|
Mat dst(dftTempl, Rect(0, yofs, dftsize.width, dftsize.height));
|
|
Mat dst1(dftTempl, Rect(0, yofs, templ.cols, templ.rows));
|
|
|
|
if( tcn > 1 )
|
|
{
|
|
src = tdepth == maxDepth ? dst1 : Mat(templ.size(), tdepth, &buf[0]);
|
|
int pairs[] = {k, 0};
|
|
mixChannels(&templ, 1, &src, 1, pairs, 1);
|
|
}
|
|
|
|
if( dst1.data != src.data )
|
|
src.convertTo(dst1, dst1.depth());
|
|
|
|
if( dst.cols > templ.cols )
|
|
{
|
|
Mat part(dst, Range(0, templ.rows), Range(templ.cols, dst.cols));
|
|
part = Scalar::all(0);
|
|
}
|
|
c->apply(dst.data, (int)dst.step, dst.data, (int)dst.step);
|
|
}
|
|
}
|
|
|
|
int tileCountX = (corr.cols + blocksize.width - 1)/blocksize.width;
|
|
int tileCountY = (corr.rows + blocksize.height - 1)/blocksize.height;
|
|
int tileCount = tileCountX * tileCountY;
|
|
|
|
Size wholeSize = img.size();
|
|
Point roiofs(0,0);
|
|
Mat img0 = img;
|
|
|
|
if( !(borderType & BORDER_ISOLATED) )
|
|
{
|
|
img.locateROI(wholeSize, roiofs);
|
|
img0.adjustROI(roiofs.y, wholeSize.height-img.rows-roiofs.y,
|
|
roiofs.x, wholeSize.width-img.cols-roiofs.x);
|
|
}
|
|
borderType |= BORDER_ISOLATED;
|
|
|
|
// calculate correlation by blocks; the tiles are independent, so they are processed in
|
|
// parallel. Every worker owns its DFT buffer, conversion buffer and DFT contexts (the
|
|
// contexts hold per-transform workspace and must not be shared between threads); they are
|
|
// created once per range, not per tile.
|
|
auto processTiles = [&](const Range& range)
|
|
{
|
|
Mat dftImg( dftsize, maxDepth );
|
|
AutoBuffer<uchar> buf(bufSize);
|
|
Ptr<hal::DFT2D> cF, cR;
|
|
int f = CV_HAL_DFT_IS_INPLACE;
|
|
int f_inv = f | CV_HAL_DFT_INVERSE | CV_HAL_DFT_SCALE;
|
|
cF = hal::DFT2D::create(dftsize.width, dftsize.height, maxDepth, 1, 1, f, blocksize.height + templ.rows - 1);
|
|
cR = hal::DFT2D::create(dftsize.width, dftsize.height, maxDepth, 1, 1, f_inv, blocksize.height);
|
|
|
|
for( int i = range.start; i < range.end; i++ )
|
|
{
|
|
int x = (i%tileCountX)*blocksize.width;
|
|
int y = (i/tileCountX)*blocksize.height;
|
|
|
|
Size bsz(std::min(blocksize.width, corr.cols - x),
|
|
std::min(blocksize.height, corr.rows - y));
|
|
Size dsz(bsz.width + templ.cols - 1, bsz.height + templ.rows - 1);
|
|
int x0 = x - anchor.x + roiofs.x, y0 = y - anchor.y + roiofs.y;
|
|
int x1 = std::max(0, x0), y1 = std::max(0, y0);
|
|
int x2 = std::min(img0.cols, x0 + dsz.width);
|
|
int y2 = std::min(img0.rows, y0 + dsz.height);
|
|
Mat src0(img0, Range(y1, y2), Range(x1, x2));
|
|
Mat dst(dftImg, Rect(0, 0, dsz.width, dsz.height));
|
|
Mat dst1(dftImg, Rect(x1-x0, y1-y0, x2-x1, y2-y1));
|
|
Mat cdst(corr, Rect(x, y, bsz.width, bsz.height));
|
|
|
|
for( int k = 0; k < cn; k++ )
|
|
{
|
|
Mat src = src0;
|
|
dftImg = Scalar::all(0);
|
|
|
|
if( cn > 1 )
|
|
{
|
|
src = depth == maxDepth ? dst1 : Mat(y2-y1, x2-x1, depth, &buf[0]);
|
|
int pairs[] = {k, 0};
|
|
mixChannels(&src0, 1, &src, 1, pairs, 1);
|
|
}
|
|
|
|
if( dst1.data != src.data )
|
|
src.convertTo(dst1, dst1.depth());
|
|
|
|
if( x2 - x1 < dsz.width || y2 - y1 < dsz.height )
|
|
copyMakeBorder(dst1, dst, y1-y0, dst.rows-dst1.rows-(y1-y0),
|
|
x1-x0, dst.cols-dst1.cols-(x1-x0), borderType);
|
|
|
|
if (bsz.height == blocksize.height)
|
|
cF->apply(dftImg.data, (int)dftImg.step, dftImg.data, (int)dftImg.step);
|
|
else
|
|
dft( dftImg, dftImg, 0, dsz.height );
|
|
|
|
Mat dftTempl1(dftTempl, Rect(0, tcn > 1 ? k*dftsize.height : 0,
|
|
dftsize.width, dftsize.height));
|
|
mulSpectrums(dftImg, dftTempl1, dftImg, 0, true);
|
|
|
|
if (bsz.height == blocksize.height)
|
|
cR->apply(dftImg.data, (int)dftImg.step, dftImg.data, (int)dftImg.step);
|
|
else
|
|
dft( dftImg, dftImg, DFT_INVERSE + DFT_SCALE, bsz.height );
|
|
|
|
src = dftImg(Rect(0, 0, bsz.width, bsz.height));
|
|
|
|
if( ccn > 1 )
|
|
{
|
|
if( cdepth != maxDepth )
|
|
{
|
|
Mat plane(bsz, cdepth, &buf[0]);
|
|
src.convertTo(plane, cdepth, 1, delta);
|
|
src = plane;
|
|
}
|
|
int pairs[] = {0, k};
|
|
mixChannels(&src, 1, &cdst, 1, pairs, 1);
|
|
}
|
|
else
|
|
{
|
|
if( k == 0 )
|
|
src.convertTo(cdst, cdepth, 1, delta);
|
|
else
|
|
{
|
|
if( maxDepth != cdepth )
|
|
{
|
|
Mat plane(bsz, cdepth, &buf[0]);
|
|
src.convertTo(plane, cdepth);
|
|
src = plane;
|
|
}
|
|
add(src, cdst, cdst);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// one stripe per tile: the work per tile is large (two 2D DFTs), the imbalance is negligible
|
|
parallel_for_(Range(0, tileCount), processTiles, tileCount);
|
|
}
|
|
|
|
static void crossCorrImgSq( const Mat& img, const Mat& mask2, Mat& dst )
|
|
{
|
|
crossCorr(img.mul(img), mask2, dst, Point(0, 0), 0, 0);
|
|
}
|
|
|
|
static Mat sumChannels( const Mat& e, int rows )
|
|
{
|
|
if (e.channels() == 1)
|
|
return e;
|
|
Mat r = e.reshape(1, e.rows * e.cols);
|
|
reduce(r, r, 1, REDUCE_SUM);
|
|
return r.reshape(1, rows);
|
|
}
|
|
|
|
static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _result, int method, InputArray _mask )
|
|
{
|
|
CV_Assert(_mask.depth() == CV_8U || _mask.depth() == CV_Bool || _mask.depth() == CV_32F);
|
|
CV_Assert(_mask.channels() == _templ.channels() || _mask.channels() == 1);
|
|
CV_Assert(_templ.size() == _mask.size());
|
|
CV_Assert(_img.size().height >= _templ.size().height &&
|
|
_img.size().width >= _templ.size().width);
|
|
|
|
Mat img = _img.getMat(), templ = _templ.getMat(), mask = _mask.getMat();
|
|
|
|
if (img.depth() == CV_8U)
|
|
{
|
|
img.convertTo(img, CV_32F);
|
|
}
|
|
if (templ.depth() == CV_8U)
|
|
{
|
|
templ.convertTo(templ, CV_32F);
|
|
}
|
|
if (mask.depth() == CV_Bool)
|
|
{
|
|
mask.convertTo(mask, CV_32F);
|
|
}
|
|
else if (mask.depth() == CV_8U)
|
|
{
|
|
Mat maskBin;
|
|
threshold(mask, maskBin, 0/*threshold*/, 1.0/*maxVal*/, THRESH_BINARY);
|
|
maskBin.convertTo(mask, CV_32F);
|
|
}
|
|
|
|
Size corrSize = matchResultSize(img.size(), templ.size());
|
|
_result.create(corrSize, CV_32F);
|
|
Mat result = _result.getMat();
|
|
|
|
// If mask has only one channel, we repeat it for every image/template channel
|
|
if (templ.type() != mask.type())
|
|
{
|
|
// Assertions above ensured, that depth is the same and only number of channel differ
|
|
std::vector<Mat> maskChannels(templ.channels(), mask);
|
|
merge(maskChannels.data(), templ.channels(), mask);
|
|
}
|
|
|
|
if (method == cv::TM_SQDIFF || method == cv::TM_SQDIFF_NORMED)
|
|
{
|
|
Mat temp_result(corrSize, CV_32F);
|
|
Mat mask2 = mask.mul(mask);
|
|
// If the mul() is ever unnested, declare MatExpr, *not* Mat, to be more efficient.
|
|
// NORM_L2SQR calculates sum of squares
|
|
double templ2_mask2_sum = norm(templ.mul(mask), NORM_L2SQR);
|
|
crossCorrImgSq(img, mask2, temp_result);
|
|
crossCorr(img, templ.mul(mask2), result, Point(0,0), 0, 0);
|
|
// result and temp_result should not be switched, because temp_result is potentially needed
|
|
// for normalization.
|
|
result = -2 * result + temp_result + templ2_mask2_sum;
|
|
|
|
if (method == cv::TM_SQDIFF_NORMED)
|
|
{
|
|
sqrt(templ2_mask2_sum * temp_result, temp_result);
|
|
result /= temp_result;
|
|
}
|
|
}
|
|
else if (method == cv::TM_CCORR || method == cv::TM_CCORR_NORMED)
|
|
{
|
|
// If the mul() is ever unnested, declare MatExpr, *not* Mat, to be more efficient.
|
|
Mat templ_mask2 = templ.mul(mask.mul(mask));
|
|
crossCorr(img, templ_mask2, result, Point(0,0), 0, 0);
|
|
|
|
if (method == cv::TM_CCORR_NORMED)
|
|
{
|
|
Mat temp_result(corrSize, CV_32F);
|
|
Mat mask2 = mask.mul(mask);
|
|
// NORM_L2SQR calculates sum of squares
|
|
double templ2_mask2_sum = norm(templ.mul(mask), NORM_L2SQR);
|
|
crossCorrImgSq(img, mask2, temp_result);
|
|
sqrt(templ2_mask2_sum * temp_result, temp_result);
|
|
result /= temp_result;
|
|
}
|
|
}
|
|
else if (method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED)
|
|
{
|
|
// Do mul() inline or declare MatExpr where possible, *not* Mat, to be more efficient.
|
|
|
|
Scalar mask_sum = sum(mask);
|
|
// T' * M where T' = M * (T - 1/sum(M)*sum(M*T))
|
|
Mat templx_mask = mask.mul(mask.mul(templ - sum(mask.mul(templ)).div(mask_sum)));
|
|
Mat img_mask_corr(corrSize, img.type()); // Needs separate channels
|
|
|
|
// CCorr(I, T'*M)
|
|
crossCorr(img, templx_mask, result, Point(0, 0), 0, 0);
|
|
// CCorr(I, M)
|
|
crossCorr(img, mask, img_mask_corr, Point(0, 0), 0, 0);
|
|
|
|
// CCorr(I', T') = CCorr(I, T'*M) - sum(T'*M)/sum(M)*CCorr(I, M)
|
|
// It does not matter what to use Mat/MatExpr, it should be evaluated to perform assign subtraction
|
|
Mat temp_res;
|
|
multiply(img_mask_corr, sum(templx_mask).div(mask_sum), temp_res);
|
|
result -= sumChannels(temp_res, result.rows);
|
|
if (method == cv::TM_CCOEFF_NORMED)
|
|
{
|
|
// norm(T')
|
|
double norm_templx = norm(mask.mul(templ - sum(mask.mul(templ)).div(mask_sum)),
|
|
NORM_L2);
|
|
// norm(I') = sqrt{ CCorr(I^2, M^2) - 2*CCorr(I, M^2)/sum(M)*CCorr(I, M)
|
|
// + sum(M^2)*CCorr(I, M)^2/sum(M)^2 }
|
|
// = sqrt{ CCorr(I^2, M^2)
|
|
// + CCorr(I, M)/sum(M)*{ sum(M^2) / sum(M) * CCorr(I,M)
|
|
// - 2 * CCorr(I, M^2) } }
|
|
Mat norm_imgx(corrSize, CV_32F);
|
|
Mat mask2 = mask.mul(mask);
|
|
Scalar mask2_sum = sum(mask2);
|
|
Mat img_mask2_corr(corrSize, img.type());
|
|
crossCorrImgSq(img, mask2, norm_imgx);
|
|
crossCorr(img, mask2, img_mask2_corr, Point(0,0), 0, 0);
|
|
Mat temp_res1;
|
|
multiply(img_mask_corr, Scalar(1.0, 1.0, 1.0, 1.0).div(mask_sum), temp_res1);
|
|
Mat temp_res2;
|
|
multiply(img_mask_corr, mask2_sum.div(mask_sum), temp_res2);
|
|
temp_res = temp_res1.mul(temp_res2 - 2 * img_mask2_corr);
|
|
norm_imgx += sumChannels(temp_res, result.rows);
|
|
sqrt(norm_imgx, norm_imgx);
|
|
result /= norm_imgx * norm_templx;
|
|
}
|
|
}
|
|
}
|
|
|
|
static void common_matchTemplate( Mat& img, Mat& templ, Mat& result, int method, int cn )
|
|
{
|
|
if( method == cv::TM_CCORR )
|
|
return;
|
|
|
|
int numType = method == cv::TM_CCORR || method == cv::TM_CCORR_NORMED ? 0 :
|
|
method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED ? 1 : 2;
|
|
bool isNormed = method == cv::TM_CCORR_NORMED ||
|
|
method == cv::TM_SQDIFF_NORMED ||
|
|
method == cv::TM_CCOEFF_NORMED;
|
|
|
|
double invArea = 1./((double)templ.rows * templ.cols);
|
|
|
|
Mat sum, sqsum;
|
|
Scalar templMean, templSdv;
|
|
double *q0 = 0, *q1 = 0, *q2 = 0, *q3 = 0;
|
|
double templNorm = 0, templSum2 = 0;
|
|
|
|
if( method == cv::TM_CCOEFF )
|
|
{
|
|
integral(img, sum, CV_64F);
|
|
templMean = mean(templ);
|
|
}
|
|
else
|
|
{
|
|
integral(img, sum, sqsum, CV_64F);
|
|
meanStdDev( templ, templMean, templSdv );
|
|
|
|
templNorm = templSdv[0]*templSdv[0] + templSdv[1]*templSdv[1] + templSdv[2]*templSdv[2] + templSdv[3]*templSdv[3];
|
|
|
|
if( templNorm < DBL_EPSILON && method == cv::TM_CCOEFF_NORMED )
|
|
{
|
|
result = Scalar::all(1);
|
|
return;
|
|
}
|
|
|
|
templSum2 = templNorm + templMean[0]*templMean[0] + templMean[1]*templMean[1] + templMean[2]*templMean[2] + templMean[3]*templMean[3];
|
|
|
|
if( numType != 1 )
|
|
{
|
|
templMean = Scalar::all(0);
|
|
templNorm = templSum2;
|
|
}
|
|
|
|
templSum2 /= invArea;
|
|
templNorm = std::sqrt(templNorm);
|
|
templNorm /= std::sqrt(invArea); // care of accuracy here
|
|
|
|
CV_Assert(sqsum.data != NULL);
|
|
q0 = (double*)sqsum.data;
|
|
q1 = q0 + templ.cols*cn;
|
|
q2 = (double*)(sqsum.data + templ.rows*sqsum.step);
|
|
q3 = q2 + templ.cols*cn;
|
|
}
|
|
|
|
CV_Assert(sum.data != NULL);
|
|
double* p0 = (double*)sum.data;
|
|
double* p1 = p0 + templ.cols*cn;
|
|
double* p2 = (double*)(sum.data + templ.rows*sum.step);
|
|
double* p3 = p2 + templ.cols*cn;
|
|
|
|
int sumstep = sum.data ? (int)(sum.step / sizeof(double)) : 0;
|
|
int sqstep = sqsum.data ? (int)(sqsum.step / sizeof(double)) : 0;
|
|
|
|
int i, j, k;
|
|
|
|
for( i = 0; i < result.rows; i++ )
|
|
{
|
|
float* rrow = result.depth() == CV_32F ? result.ptr<float>(i) : nullptr;
|
|
double* drow = result.depth() == CV_64F ? result.ptr<double>(i) : nullptr;
|
|
int idx = i * sumstep;
|
|
int idx2 = i * sqstep;
|
|
|
|
for( j = 0; j < result.cols; j++, idx += cn, idx2 += cn )
|
|
{
|
|
double num = rrow ? (double)rrow[j] : drow[j], t;
|
|
double wndMean2 = 0, wndSum2 = 0;
|
|
|
|
if( numType == 1 )
|
|
{
|
|
for( k = 0; k < cn; k++ )
|
|
{
|
|
t = p0[idx+k] - p1[idx+k] - p2[idx+k] + p3[idx+k];
|
|
wndMean2 += t*t;
|
|
num -= t*templMean[k];
|
|
}
|
|
|
|
wndMean2 *= invArea;
|
|
}
|
|
|
|
if( isNormed || numType == 2 )
|
|
{
|
|
for( k = 0; k < cn; k++ )
|
|
{
|
|
t = q0[idx2+k] - q1[idx2+k] - q2[idx2+k] + q3[idx2+k];
|
|
wndSum2 += t;
|
|
}
|
|
|
|
if( numType == 2 )
|
|
{
|
|
num = wndSum2 - 2*num + templSum2;
|
|
num = MAX(num, 0.);
|
|
}
|
|
}
|
|
|
|
if( isNormed )
|
|
{
|
|
double diff2 = MAX(wndSum2 - wndMean2, 0);
|
|
if (diff2 <= std::min(0.5, 10 * FLT_EPSILON * wndSum2))
|
|
t = 0; // avoid rounding errors
|
|
else
|
|
t = std::sqrt(diff2)*templNorm;
|
|
|
|
if( fabs(num) < t )
|
|
num /= t;
|
|
else if( fabs(num) < t*1.125 )
|
|
num = num > 0 ? 1 : -1;
|
|
else
|
|
num = method != cv::TM_SQDIFF_NORMED ? 0 : 1;
|
|
}
|
|
|
|
if (rrow) rrow[j] = (float)num;
|
|
else drow[j] = num;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
void cv::matchTemplate( InputArray _img, InputArray _templ, OutputArray _result, int method, InputArray _mask )
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
|
|
CV_Assert( cv::TM_SQDIFF <= method && method <= cv::TM_CCOEFF_NORMED );
|
|
CV_Assert( (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 );
|
|
|
|
if (!_mask.empty())
|
|
{
|
|
cv::matchTemplateMask(_img, _templ, _result, method, _mask);
|
|
return;
|
|
}
|
|
|
|
bool needswap = _img.size().height < _templ.size().height || _img.size().width < _templ.size().width;
|
|
if (needswap)
|
|
{
|
|
CV_Assert(_img.size().height <= _templ.size().height && _img.size().width <= _templ.size().width);
|
|
}
|
|
|
|
CV_OCL_RUN(_img.dims() <= 2 && _result.isUMat(),
|
|
(!needswap ? ocl_matchTemplate(_img, _templ, _result, method) : ocl_matchTemplate(_templ, _img, _result, method)))
|
|
|
|
Mat img = _img.getMat(), templ = _templ.getMat();
|
|
if (needswap)
|
|
std::swap(img, templ);
|
|
|
|
Size corrSize = matchResultSize(img.size(), templ.size());
|
|
_result.create(corrSize, CV_32F);
|
|
Mat result = _result.getMat();
|
|
|
|
{
|
|
int hal_res = cv_hal_matchTemplate(img.data, img.step, img.cols, img.rows,
|
|
templ.data, templ.step, templ.cols, templ.rows,
|
|
result.ptr<float>(), result.step, depth, cn, method);
|
|
if (hal_res == CV_HAL_ERROR_OK)
|
|
{
|
|
if (method == cv::TM_SQDIFF_NORMED || method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED)
|
|
common_matchTemplate(img, templ, result, method, 1);
|
|
return;
|
|
}
|
|
else if (hal_res != CV_HAL_ERROR_NOT_IMPLEMENTED)
|
|
{
|
|
CV_Error_(cv::Error::StsInternal,
|
|
("HAL implementation matchTemplate ==> cv_hal_matchTemplate returned %d (0x%08x)", hal_res, hal_res));
|
|
}
|
|
}
|
|
|
|
bool use64f = (depth == CV_8U) && (method == cv::TM_SQDIFF || method == cv::TM_SQDIFF_NORMED);
|
|
Mat result64f;
|
|
Mat& workResult = use64f ? result64f : result;
|
|
if (use64f)
|
|
result64f.create(corrSize, CV_64F);
|
|
|
|
crossCorr( img, templ, workResult, Point(0,0), 0, 0);
|
|
|
|
common_matchTemplate(img, templ, workResult, method, cn);
|
|
|
|
if (use64f)
|
|
result64f.convertTo(result, CV_32F);
|
|
}
|
|
|
|
/* End of file. */
|