Compare commits

..

28 Commits

Author SHA1 Message Date
Ishita Singh
6adbf18e1b dnn: compute Mean output in LayerNorm2 when 2 outputs are requested (#31306)
Problem
LayerNorm2LayerImpl::getMemoryShapes supports 1 to 3 outputs matching the ONNX LayerNormalization spec (Y, optional Mean, optional InvStdDev), and allocates outputs[1] when 2 outputs are requested. However, LayerNorm2LayerImpl::forward checked if (outputs.size() >= 3), so requesting 2 outputs (Y, Mean) left outputs[1] unwritten.

Fix
Check if (outputs.size() >= 2) in LayerNorm2LayerImpl::forward, bind mean to outputs[1] by reference, and pass outputs[2] or a scratch Mat(mean.shape(), mean.type()) for InvStdDev to fastNormMeanInvStdDev. Added regression test Layer_Test_LayerNorm2.OptionalMeanAndInvStdDevOutputs covering 1, 2, and 3 outputs for both CV_32F and CV_64F with and without bias.
2026-12-02 23:31:48 +05:30
Abhishek Gola
7ab720c3d1 Merge pull request #31324 from kari-pikkarainen/fix/python-lone-surrogate-5.x
5.x port of #31296 (merged to 4.x), requested there. It is a clean cherry-pick of the same change.

A Python str containing a lone surrogate, such as 'a\udcff', crashes the interpreter when it is passed to bindings that take a string, for example cv.putText, cv.imread or cv.imwrite. Python produces such strings for non-UTF-8 filenames on POSIX.

getUnicodeString() in modules/python/src2/pycompat.hpp passed the NULL that PyUnicode_AsUTF8String() returns on failure to PyBytes_Check(). This PR adds the NULL check, so the pending UnicodeEncodeError is reported instead.

Difference from 4.x: cv.getTextSize raises cv.error here, because 5.x has another overload; 4.x raises UnicodeEncodeError.
2026-12-02 22:40:18 +05:30
Abhishek Gola
ad46af53d3 Merge pull request #31328 from vrabaud/ci2
ci: fix Ubuntu2004-x64-CUDA label condition in PR-5.x.yaml
2026-12-02 22:38:33 +05:30
Vincent Rabaud
dc619942a2 ci: fix Ubuntu2004-x64-CUDA label condition in PR-5.x.yaml
Combine the split ${{ ... }} || ${{ ... }} expression into a single
boolean expression so it no longer evaluates to the always-truthy string
"false || false" and runs CUDA on every PR.

Also include 'category: gpu/cuda (contrib)' to match the CUDA workflow
guard.
2026-12-02 17:03:51 +01:00
Abhishek Gola
ffd7b6d9d4 Merge pull request #31312 from saanvimundra/fix/commandlineparser-key-validation-5x
core: report malformed CommandLineParser key descriptions
2026-12-02 20:44:04 +05:30
Kari Pikkarainen
ec2101a1a1 python: raise instead of crashing on strings that can't be encoded as UTF-8
getUnicodeString passed the result of PyUnicode_AsUTF8String to
PyBytes_Check without a NULL check. For a str with a lone surrogate
(for example '\udcff') the encoder fails and returns NULL, so passing such
a string to any std::string argument (putText, getTextSize, ...) crashed
the interpreter. It now returns false with the UnicodeEncodeError set,
which the converters already report.

Prepared with AI assistance (Claude Code); I reviewed the change and the verification results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 06:59:07 -08:00
sanjayk9
395a67b1b7 dnn: fix Pow with an integer base and a float exponent (#31280)
* dnn: fix Pow with an integer base and a float exponent

The output keeps the base type, and the exponent was converted to it before
the power was computed, so x^0.5 became x^0. Compute in double and truncate
toward zero, as onnxruntime does.

Florence-2's vision encoder computes sqrt(num_patches) this way to build a
Reshape shape, which made the Reshape fail.

* dnn: call std::pow for Pow with an integer base and a float exponent

A single exponent went through cv::pow, whose exp(y*log(x)) can land one
ulp below an exact integer (4^1.5 = 7.99..), and truncation then gave
7 instead of 8. Compute each element with std::pow, as onnxruntime does.
The new test uses a constant scalar exponent, as Florence-2 does.
2026-12-02 19:36:00 +05:30
Abhishek Gola
fcd8b96e64 Merge pull request #31314 from blank-0007/fix-dnn-cpu-target-warning-30806
dnn: accept DNN_TARGET_CPU on mainGraph when HAVE_CUDA is disabled
2026-12-02 19:25:17 +05:30
Abhishek Gola
a282408291 Merge pull request #31307 from ish1416/fix-gather2-int64-bounds-5x
Problem
In gather2_layer.cpp, CPU gather() casts CV_64S indices to 32-bit int before bounds checking (int k = ind32 ? (int)ind32[j] : (int)ind64[j]), so out-of-range 64-bit indices such as 1LL << 32 or (1LL << 32) - 1 silently truncate to 0 or -1 and gather valid slices instead of raising Error::StsOutOfRange (unlike CUDA GatherOp, which already validates in int64_t). Related to the Gather2 note in #30575.

The error flag volatile bool globOutOfRangeIdx is also shared across parallel_for_ threads without atomicity, and the index bounds check ran inside the nslices loop.

Fix
Keep k and shape_a in int64_t, hoist negative-index normalization and bounds validation out of the nslices loop, guard memcpy on sliceSize > 0, and use std::atomic<bool> for globOutOfRangeIdx. Added regression test Layer_Test_Gather2.Int64IndexBoundsCheck.
2026-12-02 18:15:55 +05:30
Abhishek Gola
2e0a8aa90b Merge pull request #31315 from Prasadayus/agent_contrib_rules_5x
Document branch policy and PR checklist rules
2026-12-02 17:29:54 +05:30
Prasadayus
83b4f1da21 Document branch policy and PR checklist rules 2026-12-02 16:59:10 +05:30
Karnajeet Gosavi
659b7829c6 core: Prevent overflow in wide sums of 8-bit inputs (#31255)
On the CPU, reducing a row of 8,421,505 unsigned bytes set to 255 into CV_64F returns -2,147,483,521. The integer accumulator overflows before the result is stored. The correct sum is 2,147,483,775.

This patch uses a double accumulator for signed and unsigned 8-bit input with CV_64F output. For CV_32F, it keeps the existing fast path for lengths that are safe to sum in an int and uses double for longer reductions.

The regression test covers positive overflow and negative underflow on both axes and with both floating-point outputs. All 48 selected CPU reduction tests passed on Windows with MSVC. A separate strided, three-channel check failed before the fix and passed afterward.

The unsigned SUM case overlaps with #31079. This draft also exercises the signed 8-bit paths on 5.x. The 4.x PR covers additional SUM2 and default-output AVG cases. This draft can be reassessed when that change is ported.
2026-12-02 16:35:43 +05:30
Abhishek Gola
6519977a19 Merge pull request #31103 from wzy712/fix-file_storage_overload
Problem
cv2.FileStorage.write() stores any Python integer outside the int32 range as a
boolean instead of a 64-bit integer: YAML gets true, XML/JSON get 1, and
reading the node back yields 1.0. The write(const String&, int64_t)
overload is exposed to Python but is unreachable.

The C++ API is not affected — FileStorage::write(name, (int64_t)value) stores
the exact value, as already covered by FileStorage_exact_type.long_int in
modules/core/test/test_io.cpp.

Root cause
The Python binding resolves FileStorage::write() overloads in declaration
order (modules/core/include/opencv2/core/persistence.hpp):

CV_WRAP void write(const String& name, int val);
CV_WRAP void write(const String& name, bool val);
CV_WRAP void write(const String& name, int64_t val);
For a Python integer outside int32, pyopencv_to(int&) fails the range check
and pyopencv_to(bool&) (modules/python/src2/cv2_convert.cpp, accepts any
integer scalar) consumes the value before the int64_t overload is tried.

Fix
Declare the int64_t overload before bool.
2026-12-02 16:32:53 +05:30
Kaushal Dhaked
7cd2e794c2 dnn: accept DNN_TARGET_CPU on mainGraph when HAVE_CUDA is disabled 2026-12-02 16:24:59 +05:30
Andrei Fedorov
aaaaf213a5 [IPP] Reworked IPP-based pyramids and moved it to HAL (#30417)
* enabling pyrup and prparing pyrdown

* move pyramids to hal

* updated build pyramid

* aligning with 5.x

* removed ipp_buildpyramid
2026-12-02 16:03:34 +05:30
uwezkhan
ca53fa88bd photo: check polyfit coefficients in ccm Polyfit::read 🤖🤖🤖 (#30878)
ASan, ColorCorrectionModel::read + correctImage on a model whose polyfit linearization has deg: 3 and a 1x1 coefficient Mat:

ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 8 in cv::ccm::Polyfit::fromEW(double) linearize.cpp:64
0x609000000a48 is located 0 bytes after 8-byte region
Polyfit::read takes deg and the coefficient Mat p from the file without checking them against each other, and fromEW then reads p.at<double>(d, 0) for every d <= deg. This affects all four polyfit linearizations (LogPolyfit stores a Polyfit). A CV_32F coefficient Mat of the right length overruns the buffer the same way.

The fix checks deg >= 0, a CV_64FC1 coefficient Mat and deg + 1 coefficients in Polyfit::read. This matches what the fitting constructor produces (cv::solve on an n x (deg+1) CV_64F system), so models saved by ColorCorrectionModel::write load as before. The regression test fails on the unpatched tree and passes with the fix. All Photo_ColorCorrection tests pass under ASan with opencv_extra data.
2026-12-02 15:45:13 +05:30
Vladimir Iglovikov
5608a3b4ae core: accelerate interleaved mixChannels permutations 🤖🤖🤖 (#30883)
cv::mixChannels copies each channel pair separately. This patch processes full permutations of a single interleaved matrix into a disjoint output in one pass over pixel blocks.

Use universal SIMD for 2–4 channels with 1-, 2-, or 4-byte elements.
Use dispatched byte shuffles for 5–16 channels on x86 and for 5–8 and 13–16 on AArch64. Start at 1,024 pixels and require at least 16 pixels per iterator plane. The NEON byte-shuffle code requires a 64-bit Arm target. ARMv7 uses the pairwise fallback for these wide byte maps. Preparing a shuffle costs more than it saves on smaller inputs. The AArch64 route for 9–12 channels regressed in the 512 × 512 tests.
Traverse pixels directly for CV_32F, CV_32S, and CV_32U with at least 32 channels and 65,536 pixels. This keeps reads local to each pixel and copies the 32-bit values without conversion. The size threshold avoids the slowdown seen on smaller wide matrices.
Overlap checks use the actual byte ranges of contiguous views and parent bounds for strided views. Partial maps and views that may overlap use the existing pairwise copy order. Identity mappings copy each iterator plane with a size_t byte count.
2026-12-02 15:28:29 +05:30
Ishita Singh
4abaaa33e2 dnn: avoid int64 index truncation in Gather2 bounds check 2026-12-02 15:15:31 +05:30
Nakamura
471c4bc46b dnn: honor pre-13 ONNX Hardmax flattening 🤖🤖🤖 (#31256)
Before opset 13, Hardmax groups every trailing dimension from the selected axis into one reduction. The importer currently applies the modern single-axis rule. Share the existing opset and default-axis handling with Softmax and pass the flattened-tail mode through to the Hardmax layer.

A rank-three input with shape [2,2,3] and axis 1 should produce two ones, one per flattened row. Added a DNN accuracy regression and checked legacy and modern ONNX graphs on the CPU backend.
2026-12-02 14:53:31 +05:30
saanvimundra
4f9fa9d199 core: report malformed CommandLineParser key descriptions
A key without all three parts (names | default | help) read past the end of the split result. Throw StsParseError instead.
2026-12-02 07:16:09 +00:00
SWETANK KUMAR
8b5e51541d dnn: add the ONNX DeformConv operator (#31214)
* dnn: add the ONNX DeformConv operator

Adds a CPU DeformConv layer for the new engine (2D, opsets 19-22). Each
kernel tap samples the input bilinearly at its offset position (corners
outside the image count as zero, like the ONNX reference), the optional
mask scales the samples, and each group is then one fastGemm. group,
offset_group, strides, dilations, pads and the optional B and mask
inputs are supported.

Enables the 4 DeformConv conformance tests and adds two tests for groups,
strides, dilations, asymmetric pads, batch 2, and a mask without a bias.

* dnn: DeformConv review fixes

- compute the 4 corner indices and weights once per (offset group, k, i, j)
  and reuse them for all channels of the offset group (branch-free inner loop)
- read kernel_size/stride/dilation/pad with params.getVector<int>()
- take the output size from convInferShape()

* dnn: DeformConv: keep the im2col buffer in the engine scratch pool, use cvFloor, parallel bias
2026-12-02 11:50:49 +05:30
Abhishek Gola
c03416a9e9 Merge pull request #31290 from aryany3101/fix-charuco-empty-5x
Ports the fix from #31174 to 5.x, as requested in the maintainer’s comment.

The calibration sample now skips frames with fewer than four ChArUco corners and continues with the remaining views. If no view has enough corners, it prints No calibration patterns found and exits cleanly.

On OpenCV 5.1, the detector returns corners in an (N, 2) array. The sample reshapes them to (N, 1, 2) for the debug drawing call so that even detections with only one to three corners remain visible.
2026-12-02 11:47:54 +05:30
Abhishek Gola
3b1d678343 Merge pull request #31297 from ChandraguptSharma07/docs-mcc-migration
updated the color checker tutorial for 5.x
2026-12-02 11:34:05 +05:30
Abhishek Gola
24d37ecc01 Merge pull request #31291 from poojithparchuri-iiitk/mat-negative-size
Why
In 4.x, setSize has CV_Assert( s >= 0 ) for every dimension. On 5.x, setSize copies the sizes into a MatShape and the check is gone. Mat::create then leaves a matrix without memory and the caller writes into it. I did not find an issue or PR about this.

What I changed
The same check in setSize, with a guard for a null pointer, as 4.x did (5 lines). A size of 0 is still allowed. I added two tests: Core_Mat.create_negative_size (Mat::create and the Mat constructor) and Imgproc_Hist_Calc.regression_negative_hist_size (calcHist with negative bins in 1D, 2D and with a mask, and a normal call afterwards).
2026-12-02 11:33:39 +05:30
ChandraguptSharma07
178c3c73e7 updated the color checker tutorial for 5.x 2026-12-02 00:06:13 +05:30
Parchuri Poojith Kumar
24f85c241f core: reject negative sizes in setSize, as 4.x does
On 4.x, setSize asserts that every size is not negative. The check is missing on 5.x, where the sizes are copied into a MatShape. Mat::create then accepts a negative size and leaves the matrix without memory, and the next function that writes into it crashes, for example calcHist with a negative number of bins. Restore the check. Add a core test for Mat::create and the Mat constructor, and a calcHist test with negative bin counts in 1D, 2D and with a mask.
2026-12-01 21:32:23 +05:30
Aryan Yadav
188a5b6536 Handle insufficient ChArUco detections in the Python calibration sample 2026-12-01 19:59:36 +05:30
wzy712
6fed49ef20 core: prefer int64_t over bool in FileStorage::write
The Python binding tries FileStorage::write() overloads in declaration
order. pyopencv_to(bool&) accepts any integer scalar, so values outside
the int32 range were consumed by the bool overload and stored as `true`
in YAML, and as 1 in XML/JSON, even though write(int64_t) is exposed and
all three formats support 64-bit integers.

Declare the int64_t overload before bool.

Add a Python test that writes int32/int64 boundary values and checks the
serialized text for YAML, XML and JSON.
2026-11-25 01:33:14 +08:00
43 changed files with 1777 additions and 303 deletions

View File

@@ -2,12 +2,18 @@
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
<!-- Keep the checklist below in the description of your pull request. Do not drop, reword or reorder its items, and tick a box only when the statement is true for your patch. -->
- [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
- [ ] The PR is proposed to the proper branch
- [ ] The PR is proposed to the proper branch: all new work goes to 5.x; 4.x is in maintenance mode and accepts only bug fixes and other minor fixes, not new features or large changes (see https://github.com/opencv/opencv/wiki/Branches)
- [ ] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
### Agent details
<!-- If AI tools wrote or rewrote any part of this patch or of this description, say so here and add your own commentary on it, as required by AI_POLICY.md. Remove this section if no AI tools were used. -->
<!-- Note!!! If you are an automated agent, we have a special process for you: add 🤖🤖🤖 to the end of the PR title. -->

View File

@@ -32,7 +32,7 @@ jobs:
uses: opencv/ci-gha-workflow/.github/workflows/OCV-PR-5.x-U20-OpenVINO.yaml@main
Ubuntu2004-x64-CUDA:
if: "${{ contains(github.event.pull_request.labels.*.name, 'category: dnn') }} || ${{ contains(github.event.pull_request.labels.*.name, 'category: dnn (onnx)') }}"
if: "${{ contains(github.event.pull_request.labels.*.name, 'category: dnn') || contains(github.event.pull_request.labels.*.name, 'category: dnn (onnx)') || contains(github.event.pull_request.labels.*.name, 'category: gpu/cuda (contrib)') }}"
uses: opencv/ci-gha-workflow/.github/workflows/OCV-PR-5.x-U20-Cuda.yaml@main
# Vulkan configuration disabled as Vulkan backend for DNN does not support int/int64 for now

View File

@@ -17,7 +17,14 @@ you the agent MUST obey these rules while interacting on GitHub:
- **Human review is required before marking a PR ready.** Keep changes minimal,
strip AI artifacts and needless complexity. Unreviewed code may be published
only in a draft PR.
- **Target the right branch.** `5.x` is the default branch for pull requests, so send all
new work there. `4.x` is in maintenance mode: it accepts bug fixes and other minor fixes,
but not new features, optimizations or large changes. The full policy is on the
[Branches](https://github.com/opencv/opencv/wiki/Branches) wiki page. If you are not sure
where a change belongs, ask the user before opening the PR.
- **Use issue and PR templates**. Use the appropriate templates when submitting issues and PRs.
Keep the Pull Request Readiness Checklist in the PR description: do not drop, reword or
reorder its items, and tick a box only when the statement is true for your patch.
- **Check for duplicates.** Before opening an issue, search for existing open ones
(e.g., `gh search issues --repo opencv/opencv --state open "<keywords>"`).
Do the same with `gh search prs` before opening a PR, unless the user is a regular

View File

@@ -1,3 +1,7 @@
## Contributing guidelines
All guidelines for contributing to the OpenCV repository can be found at [`How to contribute guideline`](https://github.com/opencv/opencv/wiki/How_to_contribute).
Target your pull request to the right branch. `5.x` is the default and takes all new work. `4.x` is in maintenance mode: it accepts bug fixes and other minor fixes, but not new features, optimizations or large changes. See the [`Branches`](https://github.com/opencv/opencv/wiki/Branches) page for the full policy.
If you use AI tools to prepare a contribution, read [`AI_POLICY.md`](AI_POLICY.md) first. Agents working in this repository must follow [`AGENTS.md`](AGENTS.md).

View File

@@ -20,7 +20,7 @@ Please read the [contribution guidelines](https://github.com/opencv/opencv/wiki/
#### Summary of the guidelines:
* One pull request per issue;
* Choose the right base branch;
* Choose the right base branch: all new work goes to `5.x`, while `4.x` accepts only bug fixes and other minor fixes;
* Include tests and documentation;
* Clean up "oops" commits before submitting;
* Follow the [coding style guide](https://github.com/opencv/opencv/wiki/Coding_Style_Guide).

View File

@@ -50,7 +50,7 @@ Explanation
-# **Set header and namespaces**
@code{.cpp}
#include <opencv2/mcc.hpp>
#include <opencv2/objdetect/mcc_checker_detector.hpp>
using namespace std;
using namespace cv;
using namespace mcc;
@@ -69,14 +69,14 @@ Explanation
This is just to create the object.
-# **Run the detector**
@code{.cpp}
detector->process(image, chartType);
detector->setColorChartType(chartType);
detector->process(image, nc);
@endcode
If the detector successfully detects atleast one chart, it return true otherwise it returns false. In the above given code we print a failure message if no chart were detected. Otherwise if it were successful, the list of colorcharts is stored inside the detector itself, we will see in the next step on how to extract it. By default it will detect atmost one chart, but you can tune the third parameter, nc(maximum number of charts), for detecting more charts.
`process()` returns `true` when it detects at least one chart. The `nc` argument sets the maximum number of charts to detect and defaults to 1.
-# **Get List of ColorCheckers**
@code{.cpp}
std::vector<cv::Ptr<mcc::CChecker>> checkers;
detector->getListColorChecker(checkers);
std::vector<cv::Ptr<mcc::CChecker>> checkers = detector->getListColorChecker();
@endcode
All the colorcheckers that were detected are now stored in the 'checkers' vector.
@@ -86,3 +86,29 @@ Explanation
detector->draw(checkers, image);
@endcode
Migrating Python code from OpenCV 4.x
-----------
Both examples use a BGR image named `image`.
In OpenCV 4.x, `mcc` is part of `opencv_contrib`. Pass the chart type to `process()` and use `CCheckerDraw` to draw the detection.
```python
import cv2 as cv
detector = cv.mcc.CCheckerDetector.create()
if detector.process(image, cv.mcc.MCC24, 1):
cv.mcc.CCheckerDraw.create(detector.getBestColorChecker()).draw(image)
```
In OpenCV 5.x, `mcc` is part of `objdetect` and keeps the `cv.mcc` namespace in Python. Set the chart type on the detector before calling `process()`, then draw with the detector itself.
```python
import cv2 as cv
detector = cv.mcc.CCheckerDetector.create()
detector.setColorChartType(cv.mcc.MCC24)
if detector.process(image, nc=1):
detector.draw(detector.getListColorChecker(), image)
```

View File

@@ -1,63 +0,0 @@
{
"$schema": "https://fundingjson.org/schema/v1.1.0.json",
"version": "v1.1.0",
"entity": {
"type": "organisation",
"role": "steward",
"name": "Open Source Vision Foundation",
"email": "grants@opencv.org",
"description": "Open Source Vision Foundation is the U.S. 501(c)(3) nonprofit that operates OpenCV. We support the development and maintenance of freely available computer vision software. Support helps the people who maintain the library, test changes, review community contributions, and keep useful computer vision tools available to everyone.",
"webpageUrl": {
"url": "https://github.com/opencv"
}
},
"projects": [
{
"guid": "opencv",
"name": "OpenCV 5.x",
"description": "This request supports the OpenCV 5.x release line and its 5.x source branch: https://github.com/opencv/opencv/tree/5.x. OpenCV is an open source computer vision and machine learning library released under the Apache License 2.0. It provides reusable algorithms for working with images and video, with C++, Python and Java interfaces across major desktop and mobile platforms. Students, researchers and developers use OpenCV as a shared foundation for their applications.",
"webpageUrl": {
"url": "https://github.com/opencv/opencv"
},
"repositoryUrl": {
"url": "https://github.com/opencv/opencv"
},
"licenses": [
"spdx:Apache-2.0"
],
"tags": [
"computer-vision",
"machine-learning",
"image-processing",
"video",
"library",
"cpp",
"python"
]
}
],
"funding": {
"channels": [
{
"guid": "github-sponsors",
"type": "payment-provider",
"address": "https://github.com/sponsors/opencv",
"description": "OpenCV's official GitHub Sponsors page. For grant payment arrangements and required nonprofit documentation, contact grants@opencv.org."
}
],
"plans": [
{
"guid": "opencv-maintenance",
"status": "active",
"name": "OpenCV 5.x maintenance and sustainability",
"description": "We are seeking $100,000 for one year to help sustain maintenance and development of OpenCV 5.x. Support will contribute to core developer work on the 5.x branch, including bug fixes, testing, documentation, and review of community contributions. These are continuing needs of this existing release line. The request is for general support of OpenCV 5.x rather than a new product or a fixed staffing commitment.",
"amount": 100000,
"currency": "USD",
"frequency": "yearly",
"channels": [
"github-sponsors"
]
}
]
}
}

View File

@@ -28,6 +28,7 @@ add_library(ipphal STATIC
"${CMAKE_CURRENT_SOURCE_DIR}/src/threshold_ipp.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/distancetransform_ipp.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bilateral_filter_ipp.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/pyramids_ipp.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/samplers_ipp.cpp"
)

View File

@@ -42,6 +42,21 @@ int ipp_hal_warpPerspective(int src_type, const uchar *src_data, size_t src_step
#undef cv_hal_warpPerspective
#define cv_hal_warpPerspective ipp_hal_warpPerspective
#if IPP_VERSION_X100 >= 202610
int ipp_hal_pyrdown(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,
int depth, int cn, int border_type);
#undef cv_hal_pyrdown
#define cv_hal_pyrdown ipp_hal_pyrdown
int ipp_hal_pyrup(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,
int depth, int cn, int border_type);
#undef cv_hal_pyrup
#define cv_hal_pyrup ipp_hal_pyrup
#endif // IPP_VERSION_X100 >= 202610
#endif // IPP_VERSION_X100 >= 202600
#if defined(HAVE_IPP_IW)

View File

@@ -0,0 +1,212 @@
// 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, Intel Corporation, all rights reserved.
#include "ipp_hal_imgproc.hpp"
#include <opencv2/core.hpp>
#include "precomp_ipp.hpp"
#include <climits>
#if IPP_VERSION_X100 >= 202610
static bool ipp_pyr_checkArgs(int depth, int cn, size_t src_step, size_t dst_step, int border_type)
{
return (border_type & ~cv::BORDER_ISOLATED) == cv::BORDER_DEFAULT &&
depth >= 0 && depth < CV_DEPTH_MAX && cn >= 1 && cn <= 4 &&
src_step <= (size_t)INT_MAX && dst_step <= (size_t)INT_MAX;
}
int ipp_hal_pyrdown(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,
int depth, int cn, int border_type)
{
CV_HAL_CHECK_USE_IPP();
if (!ipp_pyr_checkArgs(depth, cn, src_step, dst_step, border_type))
return CV_HAL_ERROR_NOT_IMPLEMENTED;
if (dst_width != (src_width + 1)/2 || dst_height != (src_height + 1)/2)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
// It is slower than OpenCV's fused, multi-threaded implementation for all types,
// so it is used only with IPP_CALLS_ENFORCED.
/* C1 C2 C3 C4 */
#if defined(IPP_CALLS_ENFORCED)
const char impl[CV_DEPTH_MAX][4] = {{1, 0, 1, 0}, //8U
{0, 0, 0, 0}, //8S
{1, 0, 1, 0}, //16U
{0, 0, 0, 0}, //16S
{0, 0, 0, 0}, //32S
{1, 0, 1, 0}, //32F
{0, 0, 0, 0}}; //64F
#else
const char impl[CV_DEPTH_MAX][4] = {{0, 0, 0, 0}, //8U
{0, 0, 0, 0}, //8S
{0, 0, 0, 0}, //16U
{0, 0, 0, 0}, //16S
{0, 0, 0, 0}, //32S
{0, 0, 0, 0}, //32F
{0, 0, 0, 0}}; //64F
#endif // IPP_CALLS_ENFORCED
if (impl[depth][cn-1] == 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
typedef IppStatus (CV_STDCALL * ippiPyrDownGetSize)(IppiSize srcRoi, Ipp32f rate, int kernelSize, int* pStateSize, int* pBufSize);
typedef IppStatus (CV_STDCALL * ippiPyrDownInit)(void** state, IppiSize srcRoi, Ipp32f rate, void* pKernel, int kernelSize, int mode, Ipp8u* stateBuf, Ipp8u* buffer);
typedef IppStatus (CV_STDCALL * ippiPyrDown)(const void* pSrc, int srcStep, IppiSize srcRoiSize, void* pDst, int dstStep, IppiSize dstRoiSize, void* pState);
int type = CV_MAKETYPE(depth, cn);
ippiPyrDownGetSize pyrDownGetSizeFunc = type == CV_8UC1 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_8u_C1R :
type == CV_8UC3 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_8u_C3R :
type == CV_16UC1 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_16u_C1R :
type == CV_16UC3 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_16u_C3R :
type == CV_32FC1 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_32f_C1R :
type == CV_32FC3 ? (ippiPyrDownGetSize) ippiPyramidLayerDownGetSize_32f_C3R : 0;
ippiPyrDownInit pyrDownInitFunc = type == CV_8UC1 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_8u_C1R :
type == CV_8UC3 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_8u_C3R :
type == CV_16UC1 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_16u_C1R :
type == CV_16UC3 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_16u_C3R :
type == CV_32FC1 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_32f_C1R :
type == CV_32FC3 ? (ippiPyrDownInit) ippiPyramidLayerDownInit_32f_C3R : 0;
ippiPyrDown pyrDownFunc = type == CV_8UC1 ? (ippiPyrDown) ippiPyramidLayerDown_8u_C1R :
type == CV_8UC3 ? (ippiPyrDown) ippiPyramidLayerDown_8u_C3R :
type == CV_16UC1 ? (ippiPyrDown) ippiPyramidLayerDown_16u_C1R :
type == CV_16UC3 ? (ippiPyrDown) ippiPyramidLayerDown_16u_C3R :
type == CV_32FC1 ? (ippiPyrDown) ippiPyramidLayerDown_32f_C1R :
type == CV_32FC3 ? (ippiPyrDown) ippiPyramidLayerDown_32f_C3R : 0;
if (!pyrDownGetSizeFunc || !pyrDownInitFunc || !pyrDownFunc)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
int stateSize = 0, bufSize = 0;
IppiSize srcRoi = { src_width, src_height };
IppiSize dstRoi = { dst_width, dst_height };
const Ipp32f rate = 2.0f;
const int kernelSize = 5;
Ipp32f kernel32f[kernelSize] = { 1.f/16.f, 4.f/16.f, 6.f/16.f, 4.f/16.f, 1.f/16.f }; // normalized kernel improves performance for small sizes
Ipp16s kernel16s[kernelSize] = { 1, 4, 6, 4, 1 }; // with rate 2 enables the dedicated single-pass 8u C1 kernel
void* kernel = (depth == CV_32F) ? (void*)kernel32f : (void*)kernel16s;
IppStatus ok = pyrDownGetSizeFunc(srcRoi, rate, kernelSize, &stateSize, &bufSize);
if (ok < 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
Ipp8u* pStateBuf = stateSize > 0 ? (Ipp8u*)ippMalloc_L(stateSize) : NULL;
Ipp8u* pBuffer = bufSize > 0 ? (Ipp8u*)ippMalloc_L(bufSize) : NULL;
if ((stateSize > 0 && !pStateBuf) || (bufSize > 0 && !pBuffer))
{
if (pStateBuf) ippFree(pStateBuf);
if (pBuffer) ippFree(pBuffer);
return CV_HAL_ERROR_NOT_IMPLEMENTED;
}
void* state = NULL;
ok = pyrDownInitFunc(&state, srcRoi, rate, kernel, kernelSize, IPPI_INTER_LINEAR | IPPI_OCV_ALIGNMENT, pStateBuf, pBuffer);
if (ok >= 0)
ok = CV_INSTRUMENT_FUN_IPP(pyrDownFunc, src_data, (int)src_step, srcRoi, dst_data, (int)dst_step, dstRoi, state);
if (pStateBuf) ippFree(pStateBuf);
if (pBuffer) ippFree(pBuffer);
if (ok < 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
return CV_HAL_ERROR_OK;
}
int ipp_hal_pyrup(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,
int depth, int cn, int border_type)
{
CV_HAL_CHECK_USE_IPP();
if (!ipp_pyr_checkArgs(depth, cn, src_step, dst_step, border_type))
return CV_HAL_ERROR_NOT_IMPLEMENTED;
if (dst_width != src_width*2 || dst_height != src_height*2)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
// 16U is used only with IPP_CALLS_ENFORCED.
/* C1 C2 C3 C4 */
#if defined(IPP_CALLS_ENFORCED)
const char impl[CV_DEPTH_MAX][4] = {{1, 0, 1, 0}, //8U
{0, 0, 0, 0}, //8S
{1, 0, 1, 0}, //16U
{0, 0, 0, 0}, //16S
{0, 0, 0, 0}, //32S
{1, 0, 1, 0}, //32F
{0, 0, 0, 0}}; //64F
#else
const char impl[CV_DEPTH_MAX][4] = {{1, 0, 1, 0}, //8U
{0, 0, 0, 0}, //8S
{0, 0, 0, 0}, //16U
{0, 0, 0, 0}, //16S
{0, 0, 0, 0}, //32S
{1, 0, 1, 0}, //32F
{0, 0, 0, 0}}; //64F
#endif // IPP_CALLS_ENFORCED
if (impl[depth][cn-1] == 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
typedef IppStatus (CV_STDCALL * ippiPyrUpGetSize)(IppiSize dstRoi, Ipp32f rate, int kernelSize, int* pStateSize);
typedef IppStatus (CV_STDCALL * ippiPyrUpInit)(void** state, IppiSize dstRoi, Ipp32f rate, void* pKernel, int kernelSize, int mode, Ipp8u* stateBuf);
typedef IppStatus (CV_STDCALL * ippiPyrUp)(const void* pSrc, int srcStep, IppiSize srcRoiSize, void* pDst, int dstStep, IppiSize dstRoiSize, void* pState);
int type = CV_MAKETYPE(depth, cn);
ippiPyrUpGetSize pyrUpGetSizeFunc = type == CV_8UC1 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_8u_C1R :
type == CV_8UC3 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_8u_C3R :
type == CV_16UC1 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_16u_C1R :
type == CV_16UC3 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_16u_C3R :
type == CV_32FC1 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_32f_C1R :
type == CV_32FC3 ? (ippiPyrUpGetSize) ippiPyramidLayerUpGetSize_32f_C3R : 0;
ippiPyrUpInit pyrUpInitFunc = type == CV_8UC1 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_8u_C1R :
type == CV_8UC3 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_8u_C3R :
type == CV_16UC1 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_16u_C1R :
type == CV_16UC3 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_16u_C3R :
type == CV_32FC1 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_32f_C1R :
type == CV_32FC3 ? (ippiPyrUpInit) ippiPyramidLayerUpInit_32f_C3R : 0;
ippiPyrUp pyrUpFunc = type == CV_8UC1 ? (ippiPyrUp) ippiPyramidLayerUp_8u_C1R :
type == CV_8UC3 ? (ippiPyrUp) ippiPyramidLayerUp_8u_C3R :
type == CV_16UC1 ? (ippiPyrUp) ippiPyramidLayerUp_16u_C1R :
type == CV_16UC3 ? (ippiPyrUp) ippiPyramidLayerUp_16u_C3R :
type == CV_32FC1 ? (ippiPyrUp) ippiPyramidLayerUp_32f_C1R :
type == CV_32FC3 ? (ippiPyrUp) ippiPyramidLayerUp_32f_C3R : 0;
if (!pyrUpGetSizeFunc || !pyrUpInitFunc || !pyrUpFunc)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
int stateSize = 0;
const Ipp32f rate = 2.0f;
const int kernelSize = 5;
Ipp32f kernel32f[kernelSize] = { 1.f, 4.f, 6.f, 4.f, 1.f };
Ipp16s kernel16s[kernelSize] = { 1, 4, 6, 4, 1 };
void* kernel = (depth == CV_32F) ? (void*)kernel32f : (void*)kernel16s;
IppiSize srcRoi = { src_width, src_height };
IppiSize dstRoi = { dst_width, dst_height };
const int pyrUpMode = IPPI_INTER_LINEAR | IPPI_OCV_ALIGNMENT;
IppStatus ok = pyrUpGetSizeFunc(dstRoi, rate, kernelSize, &stateSize);
if (ok < 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
Ipp8u* pStateBuf = stateSize > 0 ? (Ipp8u*)ippMalloc_L(stateSize) : NULL;
if (stateSize > 0 && !pStateBuf)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
void* state = NULL;
ok = pyrUpInitFunc(&state, dstRoi, rate, kernel, kernelSize, pyrUpMode, pStateBuf);
if (ok >= 0)
ok = CV_INSTRUMENT_FUN_IPP(pyrUpFunc, src_data, (int)src_step, srcRoi, dst_data, (int)dst_step, dstRoi, state);
if (pStateBuf) ippFree(pStateBuf);
if (ok < 0)
return CV_HAL_ERROR_NOT_IMPLEMENTED;
return CV_HAL_ERROR_OK;
}
#endif // IPP_VERSION_X100 >= 202610

View File

@@ -11,6 +11,7 @@ ocv_add_dispatched_file(has_non_zero SSE2 AVX2 LASX )
ocv_add_dispatched_file(matmul SSE2 SSE4_1 AVX2 AVX512_SKX NEON_DOTPROD LASX)
ocv_add_dispatched_file(mean SSE2 AVX2 AVX512_SKX AVX512_ICL LASX)
ocv_add_dispatched_file(merge SSE2 AVX2 LASX)
ocv_add_dispatched_file(channel_permutation SSE4_1 AVX2 LASX)
ocv_add_dispatched_file(minmax SSE2 SSE4_1 AVX2 AVX512_SKX AVX512_ICL VSX3 LASX)
ocv_add_dispatched_file(nan_mask SSE2 AVX2 LASX)
ocv_add_dispatched_file(split SSE2 AVX2 LASX)

View File

@@ -370,12 +370,12 @@ public:
*/
CV_WRAP void write(const String& name, int val);
/// @overload
CV_WRAP void write(const String& name, bool val);
CV_WRAP void write(const String& name, int64_t val);
/// @overload
CV_WRAP void write(const String& name, double val);
/// @overload
CV_WRAP void write(const String& name, bool val);
/// @overload
CV_WRAP void write(const String& name, const String& val);
/// @overload
CV_WRAP void write(const String& name, const Mat& val);

View File

@@ -189,9 +189,6 @@ T* allocSingletonNew() { return new(allocSingletonNewBuffer(sizeof(T))) T(); }
#define OPENCV_IPP_REDUCE_SIZE 1
// Temporary disabled named IPP region. Accuracy
#define IPP_DISABLE_PYRAMIDS_UP 1 // Different results
#define IPP_DISABLE_PYRAMIDS_DOWN 1 // Different results
#define IPP_DISABLE_PYRAMIDS_BUILD 1 // Different results
#define IPP_DISABLE_REMAP 1 // Different results
#define IPP_DISABLE_HOUGH 1 // improper integration/results
#define IPP_DISABLE_FILTER2D_BIG_MASK 1 // different results on masks > 7x7

View File

@@ -0,0 +1,65 @@
// 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
#include "perf_precomp.hpp"
namespace opencv_test
{
using namespace perf;
typedef TestBaseWithParam<tuple<Size, MatType, bool, bool>> MixChannelsPermutation;
PERF_TEST_P(MixChannelsPermutation, interleaved,
testing::Combine(testing::Values(Size(256, 256), Size(512, 512), Size(1024, 1024)),
testing::Values(CV_8UC2, CV_8UC3, CV_8UC4, CV_16UC2, CV_16UC3, CV_16UC4,
CV_32FC2, CV_32FC3, CV_32FC4),
testing::Bool(), testing::Bool()))
{
const Size size = get<0>(GetParam());
const int type = get<1>(GetParam());
const bool roi = get<2>(GetParam());
const bool swapOuter = get<3>(GetParam());
const Rect region(roi ? 1 : 0, roi ? 1 : 0, size.width, size.height);
const Size storage(region.x + size.width, region.y + size.height);
Mat source(storage, type);
Mat destination(storage, type);
const Mat src = source(region);
Mat dst = destination(region);
declare.in(source, WARMUP_RNG).out(destination);
const int rgb[] = {2, 0, swapOuter ? 1 : 0, 1, swapOuter ? 0 : 1, 2, 3, 3};
const int twoChannels[] = {swapOuter ? 1 : 0, 0, swapOuter ? 0 : 1, 1};
const int* fromTo = src.channels() == 2 ? twoChannels : rgb;
TEST_CYCLE() mixChannels(&src, 1, &dst, 1, fromTo, src.channels());
SANITY_CHECK_NOTHING();
}
typedef TestBaseWithParam<tuple<MatType, bool>> MixChannelsWidePermutation;
PERF_TEST_P(MixChannelsWidePermutation, interleaved,
testing::Combine(testing::Values(CV_8UC(5), CV_8UC(8), CV_8UC(12), CV_8UC(16),
CV_32FC(32), CV_32FC(64), CV_32FC(CV_CN_MAX),
CV_32SC(64), CV_32UC(64)),
testing::Bool()))
{
const int type = get<0>(GetParam());
const bool roi = get<1>(GetParam());
const Rect region(roi ? 1 : 0, 0, 512, 512);
Mat source(region.height, region.x + region.width, type);
Mat destination(source.size(), type);
const Mat src = source(region);
Mat dst = destination(region);
declare.in(source, WARMUP_RNG).out(destination);
std::vector<int> fromTo;
for (int channel = 0; channel < src.channels(); ++channel)
{
fromTo.push_back(src.channels() - 1 - channel);
fromTo.push_back(channel);
}
TEST_CYCLE() mixChannels(&src, 1, &dst, 1, fromTo.data(), src.channels());
SANITY_CHECK_NOTHING();
}
} // namespace opencv_test

View File

@@ -0,0 +1,268 @@
// 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
#include "precomp.hpp"
#include <numeric>
namespace cv {
CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN
bool permuteByteChannels(NAryMatIterator& it, const int* order, int channels);
bool permuteSmallChannels(NAryMatIterator& it, const int* order, int channels, size_t elemSize);
bool permuteWideChannels(NAryMatIterator& it, const int* order, int channels);
#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY
#if CV_NEON && (defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC))
#define CV_CHANNEL_PERMUTATION_NEON_AARCH64 1
#else
#define CV_CHANNEL_PERMUTATION_NEON_AARCH64 0
#endif
#if CV_SSSE3 || CV_CHANNEL_PERMUTATION_NEON_AARCH64
namespace {
constexpr int vectorBytes = 16;
struct ByteShuffle
{
int offset;
#if CV_SSSE3
v_uint8x16 masks[4];
#else
v_uint8x16 mask;
#endif
};
template<int vectors>
inline v_uint8x16 shuffleBytes(const uchar* src, const ByteShuffle& shuffle)
{
#if CV_SSSE3
__m128i result = _mm_shuffle_epi8(v_load(src).val, shuffle.masks[0].val);
for (int index = 1; index < vectors; ++index)
result = _mm_or_si128(result, _mm_shuffle_epi8(v_load(src + index * vectorBytes).val,
shuffle.masks[index].val));
return v_uint8x16(result);
#elif CV_CHANNEL_PERMUTATION_NEON_AARCH64
if constexpr (vectors == 1)
return v_uint8x16(vqtbl1q_u8(vld1q_u8(src), shuffle.mask.val));
else if constexpr (vectors == 2)
{
const uint8x16x2_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes)}};
return v_uint8x16(vqtbl2q_u8(table, shuffle.mask.val));
}
else if constexpr (vectors == 3)
{
const uint8x16x3_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes),
vld1q_u8(src + 2 * vectorBytes)}};
return v_uint8x16(vqtbl3q_u8(table, shuffle.mask.val));
}
else
{
const uint8x16x4_t table = {{vld1q_u8(src), vld1q_u8(src + vectorBytes),
vld1q_u8(src + 2 * vectorBytes), vld1q_u8(src + 3 * vectorBytes)}};
return v_uint8x16(vqtbl4q_u8(table, shuffle.mask.val));
}
#endif
}
template<int vectors>
void shufflePlanes(NAryMatIterator& it, const int* order, int channels,
const ByteShuffle* shuffles, int blockBytes)
{
const size_t rowBytes = it.size * channels;
const size_t bulk = rowBytes / blockBytes * blockBytes;
for (size_t plane = 0; plane < it.nplanes; ++plane, ++it)
{
const uchar* src = it.ptrs[0];
uchar* dst = it.ptrs[1];
if (vectors == 1 && blockBytes == vectorBytes)
{
for (size_t out = 0; out < bulk; out += vectorBytes)
v_store(dst + out, shuffleBytes<1>(src + out, shuffles[0]));
}
else
{
for (size_t out = 0; out < bulk; out += blockBytes)
for (int step = 0; step < blockBytes / vectorBytes; ++step)
v_store(dst + out + step * vectorBytes,
shuffleBytes<vectors>(src + out + shuffles[step].offset, shuffles[step]));
}
for (size_t out = bulk; out < rowBytes; out += channels)
for (int channel = 0; channel < channels; ++channel)
dst[out + channel] = src[out + order[channel]];
}
}
} // namespace
#endif
template<typename T>
void copyPermutedPixels(const T* src, T* dst, int pixels, const int* order, int channels)
{
for (int pixel = 0; pixel < pixels; ++pixel, src += channels, dst += channels)
for (int channel = 0; channel < channels; ++channel)
dst[channel] = src[order[channel]];
}
#if CV_SIMD || CV_SIMD_SCALABLE
template<typename T, typename VecT, int channels, bool swapRB = false>
void permuteChannels(NAryMatIterator& it, const int* order)
{
const int lanes = VTraits<VecT>::vlanes();
const int pixels = static_cast<int>(it.size);
VecT a, b, c, d;
const VecT* vectors[] = {&a, &b, &c, &d};
const VecT& first = swapRB ? c : *vectors[order[0]];
const VecT& second = swapRB ? b : *vectors[order[1]];
const VecT& third = swapRB ? a : *vectors[channels == 2 ? 0 : order[2]];
const VecT& fourth = swapRB ? d : *vectors[channels == 4 ? order[3] : 0];
for (size_t plane = 0; plane < it.nplanes; ++plane, ++it)
{
const T* src = reinterpret_cast<const T*>(it.ptrs[0]);
T* dst = reinterpret_cast<T*>(it.ptrs[1]);
int pixel = 0;
for (; pixel <= pixels - lanes; pixel += lanes, src += lanes * channels, dst += lanes * channels)
{
if constexpr (channels == 2)
{
v_load_deinterleave(src, a, b);
v_store_interleave(dst, b, a);
}
else if constexpr (channels == 3)
{
v_load_deinterleave(src, a, b, c);
v_store_interleave(dst, first, second, third);
}
else
{
v_load_deinterleave(src, a, b, c, d);
v_store_interleave(dst, first, second, third, fourth);
}
}
copyPermutedPixels(src, dst, pixels - pixel, order, channels);
}
vx_cleanup();
}
template<typename T, typename VecT>
void permuteChannels(NAryMatIterator& it, const int* order, int channels)
{
const bool swapRB = order[0] == 2 && order[1] == 1;
if (channels == 2)
permuteChannels<T, VecT, 2>(it, order);
else if (channels == 3)
{
if (swapRB)
permuteChannels<T, VecT, 3, true>(it, order);
else
permuteChannels<T, VecT, 3>(it, order);
}
else if (swapRB && order[3] == 3)
permuteChannels<T, VecT, 4, true>(it, order);
else
permuteChannels<T, VecT, 4>(it, order);
}
#endif
bool permuteSmallChannels(NAryMatIterator& it, const int* order, int channels, size_t elemSize)
{
#if CV_SIMD || CV_SIMD_SCALABLE
switch (elemSize)
{
case 1: permuteChannels<uchar, v_uint8>(it, order, channels); return true;
case 2: permuteChannels<ushort, v_uint16>(it, order, channels); return true;
case 4: permuteChannels<unsigned, v_uint32>(it, order, channels); return true;
default: return false;
}
#else
CV_UNUSED(it);
CV_UNUSED(order);
CV_UNUSED(channels);
CV_UNUSED(elemSize);
return false;
#endif
}
bool permuteWideChannels(NAryMatIterator& it, const int* order, int channels)
{
for (size_t plane = 0; plane < it.nplanes; ++plane, ++it)
copyPermutedPixels(reinterpret_cast<const unsigned*>(it.ptrs[0]), reinterpret_cast<unsigned*>(it.ptrs[1]),
static_cast<int>(it.size), order, channels);
return true;
}
bool permuteByteChannels(NAryMatIterator& it, const int* order, int channels)
{
#if CV_SSSE3 || CV_CHANNEL_PERMUTATION_NEON_AARCH64
#if CV_CHANNEL_PERMUTATION_NEON_AARCH64
if (channels >= 9 && channels <= 12)
return false;
#endif
// Align each block to both a pixel boundary and a vector boundary.
const int blockBytes = std::lcm(channels, vectorBytes);
const int steps = blockBytes / vectorBytes;
int indices[vectorBytes][vectorBytes];
int bases[vectorBytes];
int vectors = 1;
for (int step = 0; step < steps; ++step)
{
for (int lane = 0; lane < vectorBytes; ++lane)
{
const int out = step * vectorBytes + lane;
indices[step][lane] = out / channels * channels + order[out % channels];
}
const auto range = std::minmax_element(indices[step], indices[step] + vectorBytes);
bases[step] = *range.first / vectorBytes * vectorBytes;
vectors = std::max(vectors, (*range.second - bases[step]) / vectorBytes + 1);
}
CV_DbgAssert(vectors <= 4);
ByteShuffle shuffles[vectorBytes];
for (int step = 0; step < steps; ++step)
{
ByteShuffle& shuffle = shuffles[step];
shuffle.offset = std::min(bases[step], blockBytes - vectors * vectorBytes);
#if CV_SSSE3
for (int index = 0; index < vectors; ++index)
{
uchar mask[vectorBytes];
for (int lane = 0; lane < vectorBytes; ++lane)
{
const int local = indices[step][lane] - shuffle.offset - index * vectorBytes;
mask[lane] = static_cast<uchar>(local >= 0 && local < vectorBytes ? local : 255);
}
shuffle.masks[index] = v_load(mask);
}
#else
uchar mask[vectorBytes];
for (int lane = 0; lane < vectorBytes; ++lane)
mask[lane] = static_cast<uchar>(indices[step][lane] - shuffle.offset);
shuffle.mask = v_load(mask);
#endif
}
switch (vectors)
{
case 1: shufflePlanes<1>(it, order, channels, shuffles, blockBytes); return true;
case 2: shufflePlanes<2>(it, order, channels, shuffles, blockBytes); return true;
case 3: shufflePlanes<3>(it, order, channels, shuffles, blockBytes); return true;
case 4: shufflePlanes<4>(it, order, channels, shuffles, blockBytes); return true;
default: return false;
}
#else
CV_UNUSED(it);
CV_UNUSED(order);
CV_UNUSED(channels);
return false;
#endif
}
#undef CV_CHANNEL_PERMUTATION_NEON_AARCH64
#endif
CV_CPU_OPTIMIZATION_NAMESPACE_END
} // namespace cv

View File

@@ -6,6 +6,11 @@
#include "precomp.hpp"
#include "opencl_kernels_core.hpp"
#include "convert.hpp"
#include "channel_permutation.simd.hpp"
#include "channel_permutation.simd_declarations.hpp"
#include <bitset>
#include <functional>
/****************************************************************************************\
* Generalized split/merge: mixing channels *
@@ -91,6 +96,64 @@ static MixChannelsFunc getMixchFunc(int depth)
return mixchTab[depth];
}
static bool tryPermuteChannels(const Mat& src, const Mat& dst, const int* fromTo, size_t npairs,
NAryMatIterator& it)
{
const int channels = src.channels();
if (npairs != static_cast<size_t>(channels) || src.type() != dst.type() || src.empty() || dst.empty())
return false;
const size_t elemSize = src.elemSize1();
const size_t pixels = it.size * it.nplanes;
const bool bytes = channels >= 5 && channels <= 16 && elemSize == 1 && it.size >= 16 && pixels >= 1024;
const bool wide32 = channels >= 32 && elemSize == 4 && pixels >= 65536;
const bool small = channels >= 2 && channels <= 4 && elemSize <= 4;
if (!(small || bytes || wide32))
return false;
// Preserve the existing write order for overlapping matrices.
const size_t planeBytes = it.size * src.elemSize();
const size_t totalBytes = it.nplanes * planeBytes;
const uchar* srcStart = src.isContinuous() ? src.data : src.datastart;
const uchar* srcEnd = src.isContinuous() ? src.data + totalBytes : src.dataend;
const uchar* dstStart = dst.isContinuous() ? dst.data : dst.datastart;
const uchar* dstEnd = dst.isContinuous() ? dst.data + totalBytes : dst.dataend;
std::less<const uchar*> less;
if (less(srcStart, dstEnd) && less(dstStart, srcEnd))
return false;
int order[CV_CN_MAX];
std::fill_n(order, channels, -1);
std::bitset<CV_CN_MAX> used;
bool identity = true;
for (size_t pair = 0; pair < npairs; ++pair)
{
const int from = fromTo[2 * pair];
const int to = fromTo[2 * pair + 1];
if (from < 0 || order[to] >= 0 || used[from])
return false;
order[to] = from;
used[from] = true;
identity &= from == to;
}
if (identity)
{
for (size_t plane = 0; plane < it.nplanes; ++plane, ++it)
std::memcpy(it.ptrs[1], it.ptrs[0], planeBytes);
return true;
}
if (bytes)
{
CV_CPU_DISPATCH(permuteByteChannels, (it, order, channels), CV_CPU_DISPATCH_MODES_ALL);
}
if (wide32)
{
CV_CPU_DISPATCH(permuteWideChannels, (it, order, channels), CV_CPU_DISPATCH_MODES_ALL);
}
CV_CPU_DISPATCH(permuteSmallChannels, (it, order, channels, elemSize), CV_CPU_DISPATCH_MODES_ALL);
}
} // cv::
@@ -156,6 +219,9 @@ void cv::mixChannels( const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, cons
MixChannelsFunc func = getMixchFunc(depth);
CV_Assert(func);
if (nsrcs == 1 && ndsts == 1 && tryPermuteChannels(src[0], dst[0], fromTo, npairs, it))
return;
for( i = 0; i < it.nplanes; i++, ++it )
{
for( k = 0; k < npairs; k++ )

View File

@@ -230,6 +230,9 @@ CommandLineParser::CommandLineParser(int argc, const char* const argv[], const S
for (size_t i = 0; i < k.size(); i++)
{
std::vector<String> l = impl->split_string(k[i], '|', true);
if (l.size() < 3)
CV_Error_(Error::StsParseError,
("invalid key description '{%s}': expected 'names | default | help'", k[i].c_str()));
CommandLineParserParams p;
p.keys = impl->split_string(l[0]);
p.def_value = l[1];

View File

@@ -779,6 +779,11 @@ MatAllocator* Mat::getStdAllocator()
void setSize( Mat& m, int _dims, const int* _sz, const size_t* _steps, bool autoSteps)
{
CV_Assert( 0 <= _dims && _dims <= CV_MAX_DIM && _dims <= MatShape::MAX_DIMS);
if (_sz)
{
for (int i = 0; i < _dims; i++)
CV_Assert( _sz[i] >= 0 );
}
m.dims = _dims;
m.size = MatShape(_dims, _sz);

View File

@@ -844,18 +844,38 @@ void cv::reduce(InputArray _src, OutputArray _dst, int dim, int op, int dtype)
_dst.create(dim == 0 ? 1 : src.rows, dim == 0 ? src.cols : 1, dtype);
Mat dst = _dst.getMat(), temp = dst;
const bool wideSum = (op == REDUCE_SUM || op == REDUCE_AVG) &&
(ddepth == CV_32F || ddepth == CV_64F) && (sdepth == CV_8U || sdepth == CV_8S) &&
(dim == 0 ? src.rows : src.cols) > (sdepth == CV_8U ? INT_MAX / 255 : INT_MIN / -128);
if( op == REDUCE_AVG )
{
op = REDUCE_SUM;
if( sdepth < CV_32S && ddepth < CV_32S )
{
temp.create(dst.rows, dst.cols, CV_32SC(cn));
ddepth = CV_32S;
}
else if( wideSum )
ddepth = CV_64F; // Scale the sum before rounding to the output depth.
if( ddepth != dst.depth() )
temp.create(dst.size(), CV_MAKETYPE(ddepth, cn));
}
ReduceFunc func = 0;
if( dim == 0 )
// Keep the int kernels unless the reduction length permits overflow.
if (wideSum)
{
if (ddepth == CV_32F)
{
if (sdepth == CV_8U)
func = dim == 0 ? reduceR_<uchar, float, OpAdd<double> > : reduceC_<uchar, float, OpAdd<double> >;
else
func = dim == 0 ? reduceR_<schar, float, OpAdd<double> > : reduceC_<schar, float, OpAdd<double> >;
}
else if (sdepth == CV_8U)
func = dim == 0 ? reduceR_<uchar, double, OpAdd<double> > : reduceC_<uchar, double, OpAdd<double> >;
else
func = dim == 0 ? reduceR_<schar, double, OpAdd<double> > : reduceC_<schar, double, OpAdd<double> >;
}
else if( dim == 0 )
{
if( op == REDUCE_SUM )
{

View File

@@ -1255,7 +1255,35 @@ TEST(Core_Reduce, int32_accumulator_does_not_overflow)
}
}
// CV_8S reduces through an int accumulator, like CV_8U; check the signed extremes survive it.
TEST(Core_Reduce, wide_sum_of_8bit_input)
{
for (int value : {255, -128})
{
const int depth = value > 0 ? CV_8U : CV_8S;
const int limit = value > 0 ? INT_MAX / value : INT_MIN / value;
const cv::Mat row(1, limit + 1, depth, cv::Scalar(value));
for (int n : {limit, limit + 1})
{
const double expected = static_cast<double>(n) * value;
for (int dim : {0, 1})
{
SCOPED_TRACE(cv::format("value=%d n=%d dim=%d", value, n, dim));
const cv::Mat src = row.colRange(0, n).reshape(1, dim == 0 ? n : 1);
cv::Mat dst;
cv::reduce(src, dst, dim, cv::REDUCE_SUM, CV_64F);
EXPECT_EQ(expected, dst.at<double>(0, 0));
cv::reduce(src, dst, dim, cv::REDUCE_SUM, CV_32F);
EXPECT_EQ(static_cast<float>(expected), dst.at<float>(0, 0));
if (n > limit)
{
cv::reduce(src, dst, dim, cv::REDUCE_AVG, CV_32F);
EXPECT_EQ(static_cast<float>(value), dst.at<float>(0, 0));
}
}
}
}
}
TEST(Core_Reduce, int8_signed_extremes)
{
for (int dim = 0; dim <= 1; dim++)
@@ -3549,4 +3577,32 @@ TEST(Mat, ScalarMul) {
ASSERT_EQ(cv_mat_mul.at<cv::Vec3f>(0, 0), cv::Vec3f(2, 6, 12));
}
// A negative size used to be accepted by Mat::create and by the Mat constructor that takes an array of sizes.
// The matrix then had no memory behind it, and the first function that wrote into it crashed.
TEST(Core_Mat, create_negative_size)
{
const int sizes[][2] = { {-1, 4}, {4, -1}, {-3, -3} };
for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++)
{
SCOPED_TRACE(cv::format("sizes %d x %d", sizes[i][0], sizes[i][1]));
Mat m;
EXPECT_THROW(m.create(2, sizes[i], CV_8UC1), cv::Exception);
EXPECT_THROW(Mat tmp(2, sizes[i], CV_8UC1), cv::Exception);
const int size1d[] = { std::min(sizes[i][0], sizes[i][1]) }; // the negative one
EXPECT_THROW(m.create(1, size1d, CV_32FC1), cv::Exception);
}
// valid sizes still work, also after a failed call
Mat m;
const int sizeOk[] = { 3, 4 };
EXPECT_NO_THROW(m.create(2, sizeOk, CV_8UC1));
EXPECT_EQ(3, m.rows);
EXPECT_EQ(4, m.cols);
// a size of zero is still allowed
const int sizeZero[] = { 0, 4 };
EXPECT_NO_THROW(m.create(2, sizeZero, CV_8UC1));
EXPECT_TRUE(m.empty());
}
}} // namespace

View File

@@ -47,6 +47,128 @@
namespace opencv_test {
namespace {
typedef testing::TestWithParam<tuple<int, int, bool> > Core_MixChannelsInterleaved;
TEST_P(Core_MixChannelsInterleaved, interleaved_permutations)
{
const int channels = get<0>(GetParam());
const int depth = get<1>(GetParam());
const bool roi = get<2>(GetParam());
const int type = CV_MAKETYPE(depth, channels);
const Rect region(roi ? 1 : 0, roi ? 2 : 0, 39, 19);
Mat input(region.y + region.height, region.x + region.width + (roi ? 3 : 0), type);
Mat output(input.size(), type);
Mat expected = Mat::zeros(input.size(), type);
Mat bytes(input.rows, static_cast<int>(input.cols * input.elemSize()), CV_8U, input.data, input.step);
theRNG().fill(bytes, RNG::UNIFORM, 0, 256);
const Mat src = input(region);
Mat dst = output(region);
std::vector<Mat> planes;
split(src, planes);
std::vector<int> order = {0, 1, 2, 3};
order.resize(channels);
do
{
output.setTo(Scalar::all(0));
std::vector<int> fromTo;
std::vector<Mat> expectedPlanes(channels);
for (int to = channels - 1; to >= 0; --to)
{
fromTo.push_back(order[to]);
fromTo.push_back(to);
expectedPlanes[to] = planes[order[to]];
}
Mat expectedRoi = expected(region);
merge(expectedPlanes, expectedRoi);
cv::mixChannels(&src, 1, &dst, 1, fromTo.data(), order.size());
ASSERT_EQ(0, std::memcmp(expected.data, output.data, output.total() * output.elemSize()))
<< testing::PrintToString(order);
}
while (std::next_permutation(order.begin(), order.end()));
}
INSTANTIATE_TEST_CASE_P(Core, Core_MixChannelsInterleaved, testing::Combine(
testing::Values(2, 3, 4),
testing::Values(CV_8U, CV_16F, CV_32F),
testing::Bool()));
TEST(Core_MixChannels, overlapping_interleaved_arrays)
{
std::vector<Vec3b> pixels(39, Vec3b(11, 22, 33));
Mat src(1, static_cast<int>(pixels.size()) - 1, CV_8UC3, pixels.data());
Mat dst(src.rows, src.cols, src.type(), pixels.data() + 1);
const int fromTo[] = {0, 1, 1, 2, 2, 0};
cv::mixChannels(&src, 1, &dst, 1, fromTo, 3);
EXPECT_EQ(Vec3b(11, 22, 33), pixels.front());
EXPECT_EQ(Vec3b(33, 11, 22), pixels[1]);
EXPECT_EQ(Vec3b(11, 11, 11), pixels.back());
}
TEST(Core_MixChannels, identity_mapping_wide_row)
{
applyTestTag(CV_TEST_TAG_MEMORY_6GB);
const int cols = INT_MAX / 8 + 1;
Mat src(1, cols, CV_8UC(8)), dst(src.size(), src.type());
const size_t bytes = src.total() * src.elemSize();
std::memset(src.data, 0, bytes);
src.data[0] = 11;
src.data[bytes - 1] = 22;
const int fromTo[] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7};
cv::mixChannels(&src, 1, &dst, 1, fromTo, 8);
EXPECT_EQ(0, std::memcmp(src.data, dst.data, bytes));
}
TEST(Core_MixChannels, partial_mapping_with_full_pair_count)
{
const Mat src(7, 39, CV_8UC4, Scalar(11, 22, 33, 44));
Mat dst(src.size(), src.type(), Scalar::all(77));
const Mat expected(src.size(), src.type(), Scalar(44, 0, 77, 77));
const int fromTo[] = {0, 0, 2, 0, -1, 1, 3, 0};
cv::mixChannels(&src, 1, &dst, 1, fromTo, 4);
EXPECT_EQ(0, cvtest::norm(dst, expected, NORM_INF));
}
typedef testing::TestWithParam<tuple<perf::MatType, bool> > Core_MixChannelsWideInterleaved;
TEST_P(Core_MixChannelsWideInterleaved, wide_interleaved_permutations)
{
const int type = get<0>(GetParam());
const int channels = CV_MAT_CN(type);
const bool roi = get<1>(GetParam());
const Rect region(roi ? 1 : 0, 0, channels <= 16 ? 39 : 257, channels <= 16 ? 37 : 256);
Mat source(region.height, region.x + region.width + (roi ? 1 : 0), type);
Mat destination = Mat::zeros(source.size(), type);
Mat expected = Mat::zeros(source.size(), type);
Mat bytes(source.rows, static_cast<int>(source.cols * source.elemSize()), CV_8U, source.data, source.step);
theRNG().fill(bytes, RNG::UNIFORM, 0, 256);
const Mat src = source(region);
Mat dst = destination(region);
Mat expectedROI = expected(region);
std::vector<Mat> planes;
split(src, planes);
std::vector<int> fromTo;
for (int channel = 0; channel < channels; ++channel)
{
fromTo.push_back(channels - 1 - channel);
fromTo.push_back(channel);
}
std::reverse(planes.begin(), planes.end());
merge(planes, expectedROI);
cv::mixChannels(&src, 1, &dst, 1, fromTo.data(), channels);
ASSERT_EQ(0, std::memcmp(expected.data, destination.data, destination.total() * destination.elemSize()));
}
INSTANTIATE_TEST_CASE_P(Core, Core_MixChannelsWideInterleaved, testing::Combine(
testing::Values(CV_8UC(5), CV_8UC(6), CV_8UC(7), CV_8UC(8), CV_8UC(9), CV_8UC(10),
CV_8UC(11), CV_8UC(12), CV_8UC(13), CV_8UC(14), CV_8UC(15), CV_8UC(16),
CV_32FC(32), CV_32FC(64), CV_32FC(CV_CN_MAX), CV_32SC(32), CV_32UC(32)),
testing::Bool()));
class CV_OperationsTest : public cvtest::BaseTest
{
public:

View File

@@ -36,6 +36,14 @@ TEST(CommandLineParser, testFailure)
EXPECT_FALSE(parser.check());
}
TEST(CommandLineParser, testMalformedKeyDescription)
{
const char* argv[] = {"<bin>"};
const int argc = 1;
EXPECT_THROW(cv::CommandLineParser(argc, argv, "{ a }"), cv::Exception);
EXPECT_THROW(cv::CommandLineParser(argc, argv, "{ a | 1 }"), cv::Exception);
}
TEST(CommandLineParser, testHas_noValues)
{
const char* argv[] = {"<bin>", "-h", "--info"};

View File

@@ -759,6 +759,12 @@ CV__DNN_INLINE_NS_BEGIN
static Ptr<GridSampleLayer> create(const LayerParams& params);
};
class CV_EXPORTS DeformConvLayer : public Layer
{
public:
static Ptr<DeformConvLayer> create(const LayerParams& params);
};
class CV_EXPORTS OneHotLayer : public Layer
{
public:

View File

@@ -149,6 +149,7 @@ void initializeLayerFactory()
CV_DNN_REGISTER_LAYER_CLASS(BitShift, BitShiftLayer);
CV_DNN_REGISTER_LAYER_CLASS(TensorScatter, TensorScatterLayer);
CV_DNN_REGISTER_LAYER_CLASS(GridSample, GridSampleLayer);
CV_DNN_REGISTER_LAYER_CLASS(DeformConv, DeformConvLayer);
CV_DNN_REGISTER_LAYER_CLASS(Reduce2, Reduce2Layer);
CV_DNN_REGISTER_LAYER_CLASS(NegativeLogLikelihoodLoss, NegativeLogLikelihoodLossLayer);
CV_DNN_REGISTER_LAYER_CLASS(SoftmaxCrossEntropyLoss, SoftmaxCrossEntropyLossLayer);

View File

@@ -0,0 +1,285 @@
// 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.
#include "../precomp.hpp"
#include "layers_common.hpp"
#include "conv2_common.hpp"
#include "cpu_kernels/fast_gemm.hpp"
#include <opencv2/dnn/shape_utils.hpp>
// ONNX operator: DeformConv
// Spec: https://onnx.ai/onnx/operators/onnx__DeformConv.html
// Supported opsets: 19-22 (2D input only)
namespace cv {
namespace dnn {
class DeformConvLayerImpl CV_FINAL : public DeformConvLayer
{
public:
int group = 1;
int offset_group = 1;
std::vector<int> kernel_shape; // empty: take it from W
std::vector<int> strides, dilations, pads;
FastGemmOpt gemmOpt;
DeformConvLayerImpl(const LayerParams& params)
{
setParamsFrom(params);
gemmOpt.init();
group = params.get<int>("group", 1);
offset_group = params.get<int>("offset_group", 1);
kernel_shape = params.getVector<int>("kernel_size");
strides = params.getVector<int>("stride");
dilations = params.getVector<int>("dilation");
pads = params.getVector<int>("pad");
CV_CheckGT(group, 0, "DeformConv: group must be positive");
CV_CheckGT(offset_group, 0, "DeformConv: offset_group must be positive");
if (strides.empty()) strides.assign(2, 1);
if (dilations.empty()) dilations.assign(2, 1);
if (pads.empty()) pads.assign(4, 0);
CV_CheckEQ((int)strides.size(), 2, "DeformConv: only 2D input is supported");
CV_CheckEQ((int)dilations.size(), 2, "DeformConv: only 2D input is supported");
CV_CheckEQ((int)pads.size(), 4, "DeformConv: only 2D input is supported");
if (!kernel_shape.empty())
CV_CheckEQ((int)kernel_shape.size(), 2, "DeformConv: only 2D input is supported");
}
bool supportBackend(int backendId) CV_OVERRIDE
{
return backendId == DNN_BACKEND_OPENCV;
}
static bool hasInput(const std::vector<MatShape>& inputs, size_t i)
{
return inputs.size() > i && !inputs[i].empty();
}
// Validates the inputs and returns the output shape.
MatShape checkShapes(const MatShape& x, const MatShape& w, const MatShape& off,
const MatShape* b, const MatShape* mask, int& kh, int& kw) const
{
CV_CheckEQ(x.dims, 4, "DeformConv: only 2D input (N x C x H x W) is supported");
CV_CheckEQ(w.dims, 4, "DeformConv: W must be oC x C/group x kH x kW");
CV_CheckEQ(off.dims, 4, "DeformConv: offset must be N x (offset_group*kH*kW*2) x oH x oW");
kh = kernel_shape.empty() ? w[2] : kernel_shape[0];
kw = kernel_shape.empty() ? w[3] : kernel_shape[1];
CV_CheckEQ(kh, w[2], "DeformConv: kernel_shape does not match W");
CV_CheckEQ(kw, w[3], "DeformConv: kernel_shape does not match W");
int C = x[1], oC = w[0];
CV_CheckEQ(C, w[1] * group, "DeformConv: input channels must be W.shape[1] * group");
CV_CheckEQ(oC % group, 0, "DeformConv: output channels must be divisible by group");
CV_CheckEQ(C % offset_group, 0, "DeformConv: input channels must be divisible by offset_group");
CV_CheckEQ(off[0], x[0], "DeformConv: offset batch size does not match X");
CV_CheckEQ(off[1], offset_group * kh * kw * 2, "DeformConv: offset channels must be offset_group*kH*kW*2");
MatShape outshape = convInferShape(x, w, kernel_shape, group, strides, dilations, pads,
AUTO_PAD_NONE, false);
int oh = outshape[2], ow = outshape[3];
CV_CheckEQ(off[2], oh, "DeformConv: offset height does not match the output height");
CV_CheckEQ(off[3], ow, "DeformConv: offset width does not match the output width");
if (b)
CV_CheckEQ((int)b->total(), oC, "DeformConv: B must have oC elements");
if (mask)
{
CV_CheckEQ(mask->dims, 4, "DeformConv: mask must be N x (offset_group*kH*kW) x oH x oW");
CV_Assert((*mask)[0] == x[0] && (*mask)[1] == offset_group * kh * kw &&
(*mask)[2] == oh && (*mask)[3] == ow &&
"DeformConv: mask must be N x (offset_group*kH*kW) x oH x oW");
}
return outshape;
}
bool getMemoryShapes(const std::vector<MatShape>& inputs,
const int requiredOutputs,
std::vector<MatShape>& outputs,
std::vector<MatShape>& internals) const CV_OVERRIDE
{
CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required");
int kh, kw;
MatShape b, mask;
if (hasInput(inputs, 3)) b = inputs[3];
if (hasInput(inputs, 4)) mask = inputs[4];
MatShape outshape = checkShapes(inputs[0], inputs[1], inputs[2],
b.empty() ? nullptr : &b, mask.empty() ? nullptr : &mask, kh, kw);
outputs.assign(requiredOutputs, outshape);
// the im2col matrix of one image, C*kH*kW x oH*oW; the engine reuses it between layers
internals.clear();
int rows = inputs[0][1] * kh * kw, L = outshape[2] * outshape[3];
if (rows > 0 && L > 0)
internals.assign(1, MatShape({rows, L}));
return false;
}
void getTypes(const std::vector<MatType>& inputs,
const int requiredOutputs,
const int requiredInternals,
std::vector<MatType>& outputs,
std::vector<MatType>& internals) const CV_OVERRIDE
{
CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required");
CV_CheckType(inputs[0], inputs[0] == CV_32F, "DeformConv: only float32 is supported");
CV_CheckTypeEQ(inputs[1], inputs[0], "DeformConv: W must have the same type as X");
CV_CheckTypeEQ(inputs[2], inputs[0], "DeformConv: offset must have the same type as X");
outputs.assign(requiredOutputs, inputs[0]);
internals.assign(requiredInternals, CV_32F);
}
void forward(InputArrayOfArrays inputs_arr,
OutputArrayOfArrays outputs_arr,
OutputArrayOfArrays internals_arr) CV_OVERRIDE
{
std::vector<Mat> inputs, outputs, internals;
inputs_arr.getMatVector(inputs);
outputs_arr.getMatVector(outputs);
internals_arr.getMatVector(internals);
CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required");
Mat X = inputs[0], Wt = inputs[1], Off = inputs[2];
Mat B = inputs.size() > 3 ? inputs[3] : Mat();
Mat Mask = inputs.size() > 4 ? inputs[4] : Mat();
if (!B.empty()) CV_CheckTypeEQ(B.type(), X.type(), "DeformConv: B must have the same type as X");
if (!Mask.empty()) CV_CheckTypeEQ(Mask.type(), X.type(), "DeformConv: mask must have the same type as X");
int kh, kw;
MatShape bshape = B.shape(), mshape = Mask.shape();
checkShapes(X.shape(), Wt.shape(), Off.shape(),
B.empty() ? nullptr : &bshape, Mask.empty() ? nullptr : &mshape, kh, kw);
X = X.isContinuous() ? X : X.clone();
Wt = Wt.isContinuous() ? Wt : Wt.clone();
Off = Off.isContinuous() ? Off : Off.clone();
if (!B.empty() && !B.isContinuous()) B = B.clone();
if (!Mask.empty() && !Mask.isContinuous()) Mask = Mask.clone();
Mat& Y = outputs[0];
CV_Assert(Y.isContinuous() && Y.type() == CV_32F);
const int N = X.size[0], C = X.size[1], H = X.size[2], W = X.size[3];
const int oC = Wt.size[0], oH = Off.size[2], oW = Off.size[3];
const int K = kh * kw, L = oH * oW;
const int Cg = C / group, oCg = oC / group, Cog = C / offset_group;
const int sh = strides[0], sw = strides[1], dh = dilations[0], dw = dilations[1];
const int padT = pads[0], padL = pads[1];
const float* xdata = X.ptr<float>();
const float* wdata = Wt.ptr<float>();
const float* offdata = Off.ptr<float>();
const float* bdata = B.empty() ? nullptr : B.ptr<float>();
const float* mdata = Mask.empty() ? nullptr : Mask.ptr<float>();
float* ydata = Y.ptr<float>();
if (Y.total() == 0)
return;
// im2col with deformed sampling positions: row c*K + k holds input channel c sampled at
// kernel tap k for every output position; then each group is one GEMM.
// The sampling position depends only on the offset group, so for every
// (offset group, k, i) the 4 corner indices and weights of each j are computed once
// (bilinear with zero padding, like GridSample with align_corners=1; corners outside
// the image get weight 0 and index 0, the mask is folded into the weights) and then
// reused for all channels of the offset group.
Mat cols;
if (!internals.empty() && internals[0].type() == CV_32F && internals[0].isContinuous() &&
internals[0].total() >= (size_t)C * K * L)
cols = internals[0];
else
cols.create(C * K, L, CV_32F);
float* cdata = cols.ptr<float>();
const int HW = H * W;
for (int n = 0; n < N; n++)
{
const float* xn = xdata + (size_t)n * C * HW;
const float* offn = offdata + (size_t)n * offset_group * K * 2 * L;
const float* mn = mdata ? mdata + (size_t)n * offset_group * K * L : nullptr;
parallel_for_(Range(0, offset_group * K * oH), [&](const Range& r) {
AutoBuffer<int> idxbuf(oW * 4);
AutoBuffer<float> wbuf(oW * 4);
int* cidx = idxbuf.data();
float* cw = wbuf.data();
for (int t = r.start; t < r.end; t++)
{
int og = t / (K * oH), k = (t / oH) % K, i = t % oH;
int ki = k / kw, kj = k % kw;
const float* offY = offn + ((size_t)og * K * 2 + (size_t)k * 2) * L + (size_t)i * oW;
const float* offX = offY + L;
const float* mrow = mn ? mn + ((size_t)og * K + k) * L + (size_t)i * oW : nullptr;
float ybase = (float)(i * sh - padT + ki * dh);
for (int j = 0; j < oW; j++)
{
float y = ybase + offY[j];
float x = (float)(j * sw - padL + kj * dw) + offX[j];
float m = mrow ? mrow[j] : 1.f;
int* ci = cidx + j * 4;
float* wj = cw + j * 4;
if (!(y > -1.f && y < (float)H && x > -1.f && x < (float)W))
m = 0.f, y = x = 0.f; // also guards against NaN offsets
int y0 = cvFloor(y), x0 = cvFloor(x);
float ly = y - (float)y0, lx = x - (float)x0;
float hy = 1.f - ly, hx = 1.f - lx;
bool y0in = y0 >= 0, y1in = y0 + 1 < H, x0in = x0 >= 0, x1in = x0 + 1 < W;
ci[0] = (y0in && x0in) ? y0 * W + x0 : 0;
ci[1] = (y0in && x1in) ? y0 * W + x0 + 1 : 0;
ci[2] = (y1in && x0in) ? (y0 + 1) * W + x0 : 0;
ci[3] = (y1in && x1in) ? (y0 + 1) * W + x0 + 1 : 0;
wj[0] = (y0in && x0in) ? hy * hx * m : 0.f;
wj[1] = (y0in && x1in) ? hy * lx * m : 0.f;
wj[2] = (y1in && x0in) ? ly * hx * m : 0.f;
wj[3] = (y1in && x1in) ? ly * lx * m : 0.f;
}
for (int c = og * Cog; c < (og + 1) * Cog; c++)
{
const float* plane = xn + (size_t)c * HW;
float* crow = cdata + ((size_t)c * K + k) * L + (size_t)i * oW;
for (int j = 0; j < oW; j++)
{
const int* ci = cidx + j * 4;
const float* wj = cw + j * 4;
crow[j] = wj[0] * plane[ci[0]] + wj[1] * plane[ci[1]] +
wj[2] * plane[ci[2]] + wj[3] * plane[ci[3]];
}
}
}
});
// Y_g [oCg x L] = W_g [oCg x Cg*K] * cols_g [Cg*K x L]
const int Kg = Cg * K;
for (int g = 0; g < group; g++)
{
const float* wg = wdata + (size_t)g * oCg * Kg;
const float* cg = cdata + (size_t)g * Kg * L;
float* yg = ydata + ((size_t)n * oC + (size_t)g * oCg) * L;
fastGemm(false, false, oCg, Kg, Kg, L, 1.f, wg, Kg, 1, cg, L, 1, 0.f, yg, L, gemmOpt);
}
if (bdata)
{
parallel_for_(Range(0, oC), [&](const Range& r) {
for (int oc = r.start; oc < r.end; oc++)
{
float* yrow = ydata + ((size_t)n * oC + oc) * L;
float bv = bdata[oc];
for (int l = 0; l < L; l++)
yrow[l] += bv;
}
});
}
}
}
};
Ptr<DeformConvLayer> DeformConvLayer::create(const LayerParams& params)
{
return Ptr<DeformConvLayer>(new DeformConvLayerImpl(params));
}
}} // namespace cv::dnn

View File

@@ -6,6 +6,7 @@
#include "layers_common.hpp"
#include "../net_impl.hpp"
#include "../op_cuda.hpp"
#include <atomic>
#ifdef HAVE_CUDA
#include "../cuda4dnn/primitives/gather.hpp"
#endif
@@ -57,33 +58,36 @@ static void gather(const Mat& data, const Mat& ind, Mat& out, int axis)
}
size_t dataStep = sliceSize * dataShape[axis];
size_t outStep = sliceSize * indTotal;
volatile bool globOutOfRangeIdx = false;
std::atomic<bool> globOutOfRangeIdx(false);
parallel_for_(Range(0, (int)indTotal), [&](const Range& r) {
int shape_a = dataShape[axis];
int64_t shape_a = dataShape[axis];
const uchar* dataptr0 = data.data;
uchar* outptr0 = out.data;
const int32_t* ind32 = indType == CV_32S ? ind.ptr<int32_t>() : nullptr;
const int64_t* ind64 = indType == CV_64S ? ind.ptr<int64_t>() : nullptr;
bool outOfRangeIdx = globOutOfRangeIdx;
bool outOfRangeIdx = globOutOfRangeIdx.load(std::memory_order_relaxed);
for (int j = r.start; j < r.end && !outOfRangeIdx; j++) {
int k = ind32 ? (int)ind32[j] : (int)ind64[j];
uchar* outptr = outptr0 + j*sliceSize;
const uchar* dataptr = dataptr0;
for (size_t i = 0; i < nslices; i++, dataptr += dataStep, outptr += outStep) {
k += k < 0 ? shape_a : 0;
if (k < 0 || k >= shape_a) {
outOfRangeIdx = true;
break;
int64_t k = ind32 ? (int64_t)ind32[j] : ind64[j];
if (k < 0)
k += shape_a;
if (k < 0 || k >= shape_a) {
outOfRangeIdx = true;
break;
}
if (sliceSize > 0) {
uchar* outptr = outptr0 + (size_t)j * sliceSize;
const uchar* dataptr = dataptr0 + (size_t)k * sliceSize;
for (size_t i = 0; i < nslices; i++, dataptr += dataStep, outptr += outStep) {
memcpy(outptr, dataptr, sliceSize);
}
memcpy(outptr, dataptr + k*sliceSize, sliceSize);
}
}
if (outOfRangeIdx)
globOutOfRangeIdx = true;
globOutOfRangeIdx.store(true, std::memory_order_relaxed);
}, std::min((double)indTotal, (double)sliceSize*nslices*indTotal/1e6));
if (globOutOfRangeIdx) {
if (globOutOfRangeIdx.load(std::memory_order_relaxed)) {
CV_Error(Error::StsOutOfRange, "some of indices are outside of range");
}
}

View File

@@ -8,13 +8,17 @@ namespace cv
namespace dnn
{
// ONNX Hardmax: https://onnx.ai/onnx/operators/onnx__Hardmax.html
// Opset 13 and later find the maximum along the selected axis alone.
class LayerHardmaxImpl CV_FINAL : public HardmaxLayer
{
public:
int axis;
bool coerced2d; // Before opset 13, reduce the flattened tail starting at axis.
LayerHardmaxImpl(const LayerParams& params)
{
axis = params.get<int>("axis", -1);
coerced2d = params.get<bool>("coerced_2d", false);
}
virtual bool supportBackend(int backendId) CV_OVERRIDE
@@ -97,8 +101,8 @@ public:
auto *dst_ptr = dst.ptr<T>();
const size_t outer_size = src.total(0, axis);
const auto mid_size = static_cast<size_t>(src.size[axis]);
const size_t inner_size = src.total(axis + 1);
const size_t mid_size = coerced2d ? src.total(axis) : static_cast<size_t>(src.size[axis]);
const size_t inner_size = coerced2d ? 1 : src.total(axis + 1);
const size_t outer_step = src.total(axis);
double nstripes = (double) outer_size * inner_size / 1024.0;

View File

@@ -135,10 +135,11 @@ public:
int axis_ = normalize_axis(axis0, input.dims);
if (outputs.size() >= 3)
if (outputs.size() >= 2)
{
Mat& mean = outputs[1];
Mat& invStdDev = outputs[2];
Mat scratch = outputs.size() >= 3 ? Mat() : Mat(mean.shape(), mean.type());
Mat& invStdDev = outputs.size() >= 3 ? outputs[2] : scratch;
fastNormMeanInvStdDev(input, mean, invStdDev, epsilon, (size_t)axis_);
}

View File

@@ -1262,6 +1262,26 @@ public:
if (op == OPERATION::POW) {
CV_Assert(used_inputs.size() == 2);
const int out_type = outputs[0].type();
// A float exponent cast to an integer base type would lose its fraction (x^0.5 -> x^0),
// so compute in double and truncate toward zero, as onnxruntime does. Call std::pow
// directly: a single exponent would otherwise go to cv::pow, whose exp(y*log(x)) can
// land one ulp below an exact integer (4^1.5 = 7.99..), and truncation would then
// give 7 instead of 8.
if (CV_IS_INT_TYPE(out_type) && CV_IS_FLOAT_TYPE(used_inputs[1].type())) {
std::vector<Mat> in64(2), out64(1);
used_inputs[0].convertTo(in64[0], CV_64F);
used_inputs[1].convertTo(in64[1], CV_64F);
out64[0].create(outputs[0].shape(), CV_64F);
helper.init(in64, out64);
CV_CheckTrue(helper.prepare_for_broadcast_op(), "NaryEltwiseLayer: Preparation for broadcasting failed");
auto truncPow = [](const double& a, const double& b) { return std::trunc(std::pow(a, b)); };
binary_forward_impl<double, double>(truncPow, helper.max_ndims, helper.shapes[0],
in64[0].ptr<char>(), helper.steps[1],
in64[1].ptr<char>(), helper.steps[2],
out64[0].ptr<char>(), helper.steps[0], 1e5);
out64[0].convertTo(outputs[0], out_type);
return;
}
if (used_inputs[0].type() != out_type || used_inputs[1].type() != out_type) {
Mat a_conv, b_conv;
used_inputs[0].convertTo(a_conv, out_type);

View File

@@ -375,8 +375,11 @@ void Net::Impl::setPreferableTarget(int targetId)
if (mainGraph)
{
if (targetId == DNN_TARGET_CPU
#ifdef HAVE_CUDA
if (targetId == DNN_TARGET_CPU || IS_DNN_CUDA_TARGET(targetId))
|| IS_DNN_CUDA_TARGET(targetId)
#endif
)
{
if (preferableTarget != targetId) {
preferableTarget = targetId;
@@ -384,7 +387,6 @@ void Net::Impl::setPreferableTarget(int targetId)
}
return;
}
#endif
CV_LOG_WARNING(NULL, "Targets are not supported by the new graph engine for now");
return;
}

View File

@@ -275,6 +275,7 @@ protected:
void parseHammingWindow (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseCenterCropPad (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseGridSample (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseDeformConv (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseNegativeLogLikelihoodLoss(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseSoftmaxCrossEntropyLoss (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
void parseAffineGrid (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
@@ -2471,6 +2472,15 @@ void ONNXImporter2::parseGridSample(LayerParams& layerParams, const opencv_onnx:
addLayer(layerParams, node_proto);
}
void ONNXImporter2::parseDeformConv(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
{
int n_inputs = node_proto.input_size();
CV_CheckGE(n_inputs, 3, "DeformConv: X, W and offset are required");
CV_CheckLE(n_inputs, 5, "DeformConv: at most 5 inputs (X, W, offset, B, mask)");
layerParams.type = "DeformConv";
addLayer(layerParams, node_proto);
}
void ONNXImporter2::parseAffineGrid(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
{
layerParams.type = "AffineGrid";
@@ -2583,11 +2593,11 @@ void ONNXImporter2::parseSoftMax(LayerParams& layerParams, const opencv_onnx::No
const std::string& layer_type = node_proto.op_type();
int axis;
if (onnx_opset_map.find(str_domain_ai_onnx) == onnx_opset_map.end()) {
CV_Error(Error::StsParseError , "ONNX/Softmax: opset for ai.onnx domain is not found");
CV_Error(Error::StsParseError, "ONNX/" + layer_type + ": opset for ai.onnx domain is not found");
}
const int opset_onnx_ai = onnx_opset_map[str_domain_ai_onnx];
// Softmax-13 is the first version that reduces along "axis" alone; up to opset 12 the
// Softmax, LogSoftmax and Hardmax reduce along axis alone from opset 13. In earlier opsets the
// spec coerces the input to 2D and reduces over the flattened dims [axis, rank), and
// the default axis is 1 rather than -1. A node fused from an Exp/ReduceSum/Div
// subgraph states its own meaning through the attribute added by the simplifier.
@@ -2601,8 +2611,12 @@ void ONNXImporter2::parseSoftMax(LayerParams& layerParams, const opencv_onnx::No
}
layerParams.set<int>("axis", axis);
layerParams.set("coerced_2d", coerced);
layerParams.type = "Softmax";
layerParams.set("log_softmax", layer_type == "LogSoftmax");
if (layer_type == "Hardmax")
layerParams.type = "Hardmax";
else {
layerParams.type = "Softmax";
layerParams.set("log_softmax", layer_type == "LogSoftmax");
}
addLayer(layerParams, node_proto);
}
@@ -3798,6 +3812,7 @@ void ONNXImporter2::buildDispatchMap_ONNX_AI()
dispatch["HannWindow"] = &ONNXImporter2::parseHannWindow;
dispatch["HammingWindow"] = &ONNXImporter2::parseHammingWindow;
dispatch["GridSample"] = &ONNXImporter2::parseGridSample;
dispatch["DeformConv"] = &ONNXImporter2::parseDeformConv;
dispatch["AffineGrid"] = &ONNXImporter2::parseAffineGrid;
dispatch["RoiAlign"] = &ONNXImporter2::parseRoiAlign;
dispatch["Upsample"] = &ONNXImporter2::parseUpsample;
@@ -3808,6 +3823,7 @@ void ONNXImporter2::buildDispatchMap_ONNX_AI()
dispatch["BitwiseXor"] = &ONNXImporter2::parseBitwise;
dispatch["BitwiseNot"] = &ONNXImporter2::parseBitwiseNot;
dispatch["NonMaxSuppression"] = &ONNXImporter2::parseNonMaxSuppression;
dispatch["Hardmax"] = &ONNXImporter2::parseSoftMax;
dispatch["SoftMax"] = dispatch["Softmax"] = dispatch["LogSoftmax"] = &ONNXImporter2::parseSoftMax;
dispatch["DetectionOutput"] = &ONNXImporter2::parseDetectionOutput;
dispatch["PriorBox"] = &ONNXImporter2::parsePriorBox;

View File

@@ -6633,6 +6633,22 @@ TEST(Test_TensorScatter, InplaceNewEngineGraph)
EXPECT_EQ(pastBuf, outBuf);
}
TEST(Layer_Test_Hardmax_Axis, coercedTail)
{
LayerParams lp;
lp.set("axis", 1);
lp.set("coerced_2d", true);
Ptr<Layer> layer = LayerFactory::createLayerInstance("Hardmax", lp);
ASSERT_TRUE(layer);
int dims[] = {2, 2, 3};
float data[] = {0, 9, 1, 2, 3, 4, 5, 0, 1, 2, 8, 3};
float expected[] = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0};
std::vector<Mat> inputs{Mat(3, dims, CV_32F, data)}, outputs;
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)1);
EXPECT_EQ(0, cvtest::norm(outputs[0], Mat(3, dims, CV_32F, expected), NORM_INF));
}
TEST(Layer_Test_Hardmax_Axis, keepsNegativeAxisAcrossRanks)
{
LayerParams lp;
@@ -6663,4 +6679,206 @@ TEST(Layer_Test_Hardmax_Axis, keepsNegativeAxisAcrossRanks)
EXPECT_EQ(0, cvtest::norm(outputs[0], Mat(3, sz, CV_32F, expected), NORM_INF));
}
TEST(Layer_Test_Gather2, Int64IndexBoundsCheck)
{
LayerParams lp;
lp.type = "Gather2";
lp.name = "test_gather2";
lp.set("axis", 0);
Ptr<Layer> layer = LayerFactory::createLayerInstance(lp.type, lp);
ASSERT_TRUE(layer);
float dataVals[] = {10.f, 20.f, 30.f, 40.f, 50.f, 60.f};
Mat data(3, 2, CV_32F, dataVals);
// Valid positive and negative indices for both CV_32S and CV_64S
{
int32_t idx32Vals[] = {-3, 0, -1, 1};
int64_t idx64Vals[] = {-3, 0, -1, 1};
float expectedVals[] = {10.f, 20.f, 10.f, 20.f, 50.f, 60.f, 30.f, 40.f};
Mat expected(4, 2, CV_32F, expectedVals);
for (int idxType : {CV_32S, CV_64S})
{
SCOPED_TRACE(cv::format("valid idxType=%d", idxType));
Mat idx = (idxType == CV_32S) ? Mat(1, 4, CV_32S, idx32Vals)
: Mat(1, 4, CV_64S, idx64Vals);
int idxShape[] = {4};
idx = idx.reshape(1, 1, idxShape);
std::vector<Mat> inputs = {data, idx}, outputs;
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)1);
EXPECT_EQ(0, cvtest::norm(outputs[0], expected, NORM_INF));
}
}
// Out-of-range int64 indices, including values that wrap to 0 or -1 when truncated to int32
const int64_t oob64[] = {
3,
-4,
(int64_t)1 << 32,
((int64_t)1 << 32) - 1,
-((int64_t)1 << 32),
std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::min()
};
for (int64_t badIdx : oob64)
{
SCOPED_TRACE(cv::format("oob64=%lld", (long long)badIdx));
int idxShape[] = {1};
Mat idx(1, idxShape, CV_64S);
idx.at<int64_t>(0) = badIdx;
std::vector<Mat> inputs = {data, idx}, outputs;
try
{
runLayer(layer, inputs, outputs);
FAIL() << "Expected StsOutOfRange for int64 index " << badIdx;
}
catch (const cv::Exception& e)
{
EXPECT_EQ(e.code, Error::StsOutOfRange);
}
}
// Out-of-range int32 indices
for (int32_t badIdx : {3, -4, std::numeric_limits<int32_t>::min()})
{
SCOPED_TRACE(cv::format("oob32=%d", badIdx));
int idxShape[] = {1};
Mat idx(1, idxShape, CV_32S);
idx.at<int32_t>(0) = badIdx;
std::vector<Mat> inputs = {data, idx}, outputs;
try
{
runLayer(layer, inputs, outputs);
FAIL() << "Expected StsOutOfRange for int32 index " << badIdx;
}
catch (const cv::Exception& e)
{
EXPECT_EQ(e.code, Error::StsOutOfRange);
}
}
// Multi-slice gather along axis=1 (verifies outer slices and negative indices)
{
LayerParams lp1;
lp1.type = "Gather2";
lp1.name = "test_gather2_axis1";
lp1.set("axis", 1);
Ptr<Layer> layer1 = LayerFactory::createLayerInstance(lp1.type, lp1);
ASSERT_TRUE(layer1);
int idxShape[] = {2};
int64_t idxVals[] = {-1, 0};
Mat idx(1, idxShape, CV_64S, idxVals);
float expectedVals[] = {20.f, 10.f, 40.f, 30.f, 60.f, 50.f};
std::vector<Mat> inputs = {data, idx}, outputs;
runLayer(layer1, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)1);
EXPECT_EQ(0, cvtest::norm(outputs[0], Mat(3, 2, CV_32F, expectedVals), NORM_INF));
}
}
TEST(Layer_Test_LayerNorm2, OptionalMeanAndInvStdDevOutputs)
{
// Input [2, 2, 4] with power-of-two normalization size (exact in float32 and float64):
// slice (0,0): [1, 2, 3, 4] -> mean = 2.5, var = 1.25
// slice (0,1): [2, 4, 6, 8] -> mean = 5.0, var = 5.0
// slice (1,0): [-3, -1, 1, 3] -> mean = 0.0, var = 5.0
// slice (1,1): [4, 4, 4, 4] -> mean = 4.0, var = 0.0
const int xDims[] = {2, 2, 4};
const int meanDims[] = {2, 2, 1};
const double xVals[] = {
1, 2, 3, 4,
2, 4, 6, 8,
-3, -1, 1, 3,
4, 4, 4, 4
};
const double scaleVals[] = {2.0, 0.5, 1.0, 1.5};
const double biasVals[] = {0.5, -1.0, 2.0, -0.25};
const float eps = 1e-5f;
const double refMean[] = {2.5, 5.0, 0.0, 4.0};
const double refVar[] = {1.25, 5.0, 5.0, 0.0};
double refInvStd[4];
double refYWithBias[16], refYNoBias[16];
for (int i = 0; i < 4; ++i)
{
refInvStd[i] = 1.0 / std::sqrt(refVar[i] + (double)eps);
for (int j = 0; j < 4; ++j)
{
double normVal = (xVals[i * 4 + j] - refMean[i]) * refInvStd[i] * scaleVals[j];
refYNoBias[i * 4 + j] = normVal;
refYWithBias[i * 4 + j] = normVal + biasVals[j];
}
}
auto makeMat = [](int dims, const int* sz, const double* vals, int type) {
Mat m64(dims, sz, CV_64F);
std::memcpy(m64.ptr<double>(), vals, m64.total() * sizeof(double));
if (type == CV_64F)
return m64;
Mat m32;
m64.convertTo(m32, CV_32F);
return m32;
};
for (int type : {CV_32F, CV_64F})
{
const double tol = (type == CV_64F) ? 1e-10 : 1e-5;
Mat x = makeMat(3, xDims, xVals, type);
Mat scale = makeMat(1, &xDims[2], scaleVals, type);
Mat bias = makeMat(1, &xDims[2], biasVals, type);
Mat expectedMean = makeMat(3, meanDims, refMean, type);
Mat expectedInvStd = makeMat(3, meanDims, refInvStd, type);
for (bool withBias : {false, true})
{
Mat expectedY = makeMat(3, xDims, withBias ? refYWithBias : refYNoBias, type);
for (int noutputs : {1, 2, 3})
{
SCOPED_TRACE(cv::format("type=%d withBias=%d noutputs=%d", type, (int)withBias, noutputs));
LayerParams lp;
lp.type = "LayerNormalization2";
lp.name = "test_layernorm2";
lp.set("axis", -1);
lp.set("epsilon", eps);
lp.blobs.push_back(scale);
if (withBias)
lp.blobs.push_back(bias);
Ptr<Layer> layer = LayerFactory::createLayerInstance(lp.type, lp);
ASSERT_TRUE(layer);
std::vector<Mat> inputs = {x};
std::vector<MatShape> inpShapes = {shape(x)}, outShapes, intShapes;
std::vector<cv::dnn::MatType> inpTypes = {cv::dnn::MatType(type)}, outTypes, intTypes;
layer->getMemoryShapes(inpShapes, noutputs, outShapes, intShapes);
ASSERT_EQ(outShapes.size(), (size_t)noutputs);
layer->getTypes(inpTypes, noutputs, (int)intShapes.size(), outTypes, intTypes);
std::vector<Mat> outputs(noutputs), internals(intShapes.size());
for (int i = 0; i < noutputs; ++i)
{
outputs[i].create(outShapes[i], outTypes[i]);
outputs[i].setTo(Scalar(-999.0));
}
layer->finalize(inputs, outputs);
layer->forward(inputs, outputs, internals);
EXPECT_LE(cvtest::norm(outputs[0], expectedY, NORM_INF), tol);
if (noutputs >= 2)
{
EXPECT_LE(cvtest::norm(outputs[1], expectedMean, NORM_INF), tol);
}
if (noutputs >= 3)
{
EXPECT_LE(cvtest::norm(outputs[2], expectedInvStd, NORM_INF), tol);
}
}
}
}
}
}} // namespace

View File

@@ -282,6 +282,10 @@ CASE(test_basic_conv_without_padding)
#endif
CASE(test_basic_convinteger)
SKIP;
CASE(test_basic_deform_conv_with_padding)
SKIP;
CASE(test_basic_deform_conv_without_padding)
SKIP;
CASE(test_batchnorm_epsilon)
SKIP;
CASE(test_batchnorm_epsilon_training_mode)
@@ -868,6 +872,10 @@ CASE(test_cumsum_2d_int32)
SKIP;
CASE(test_cumsum_2d_negative_axis)
// no filter
CASE(test_deform_conv_with_mask_bias)
SKIP;
CASE(test_deform_conv_with_multiple_offset_groups)
SKIP;
CASE(test_depthtospace_crd_mode)
// no filter
if (target == DNN_TARGET_OPENCL)

View File

@@ -14,8 +14,6 @@
"test_ai_onnx_ml_tree_ensemble_single_tree",
"test_attention_4d_diff_heads_mask4d_padded_kv", // needs the nonpad_kv_seqlen input (padded-KV variant) which is not supported yet
"test_averagepool_2d_ceil_last_window_starts_on_pad",
"test_basic_deform_conv_with_padding",
"test_basic_deform_conv_without_padding",
"test_batchnorm_epsilon_training_mode", // ---- same as above ---
"test_batchnorm_example_training_mode", // ---- same as above ---
"test_bernoulli", // Issues::Layer::Can't create layer "onnx_node_output_0!y" of type "Bernoulli" in function 'getLayerInstance'
@@ -26,8 +24,6 @@
"test_bernoulli_seed_expanded", // ---- same as above ---
"test_castlike_FLOAT_to_STRING",
"test_castlike_STRING_to_FLOAT", // Issues::Layer::Can't create layer "onnx_node_output_0!output" of type "CastLike" in function 'getLayerInstance'
"test_deform_conv_with_mask_bias",
"test_deform_conv_with_multiple_offset_groups",
"test_equal_string",
"test_equal_string_broadcast",
"test_identity_opt", // 23221 illegal hardware instruction

View File

@@ -341,6 +341,22 @@ TEST_P(Test_ONNX_layers, MaxUnpool_pads)
testONNXModels("maxunpool_pads", npy, 0, 0, false, false, 2);
}
// DeformConv cases the conformance tests don't cover: groups, offset groups, batch 2, strides,
// dilations, asymmetric pads, and a mask without a bias.
TEST_P(Test_ONNX_layers, DeformConv_groups_stride_dilation)
{
if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU)
throw SkipTestException("Only CPU is supported");
testONNXModels("deform_conv_groups_stride_dilation", npy, 0, 0, false, false, 4);
}
TEST_P(Test_ONNX_layers, DeformConv_mask_no_bias)
{
if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU)
throw SkipTestException("Only CPU is supported");
testONNXModels("deform_conv_mask_no_bias", npy, 0, 0, false, false, 4);
}
// Opset 20 removed DFT's axis attribute; with no axis input, the axis defaults to -2.
TEST_P(Test_ONNX_layers, DFT_opset20_default_axis)
{
@@ -807,6 +823,18 @@ TEST_P(Test_ONNX_layers, Power)
testONNXModels("pow2", npy, 0, 0, false, false);
}
// An int64 base keeps its type, so x^0.5 must truncate sqrt(x), not round the exponent to 0.
TEST_P(Test_ONNX_layers, PowIntBaseFloatExponent)
{
testONNXModels("pow_int_base_float_exp", npy, 0, 0, false, true, 2);
}
// A single constant exponent (as in Florence-2): (r^2)^1.5 must give r^3 exactly, not r^3 - 1.
TEST_P(Test_ONNX_layers, PowIntBaseScalarExponent)
{
testONNXModels("pow_int_base_scalar_exp", npy, 0, 0, false, true, 1);
}
TEST_P(Test_ONNX_layers, Exp)
{
if (backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
@@ -1635,6 +1663,14 @@ TEST_P(Test_ONNX_layers, Softmax)
}
}
TEST_P(Test_ONNX_layers, Hardmax_opset11)
{
if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU)
throw SkipTestException("Only the OpenCV CPU backend is supported");
testONNXModels("hardmax_11_axis0");
testONNXModels("hardmax_11_default");
}
TEST_P(Test_ONNX_layers, Split_EltwiseMax)
{
#if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LT(2023000000)

View File

@@ -1554,67 +1554,6 @@ void cv::pyrDown( InputArray _src, OutputArray _dst, const Size& _dsz, int borde
}
#if defined(HAVE_IPP)
namespace cv
{
static bool ipp_pyrup( InputArray _src, OutputArray _dst, const Size& _dsz, int borderType )
{
CV_INSTRUMENT_REGION_IPP();
#if IPP_VERSION_X100 >= 810 && !IPP_DISABLE_PYRAMIDS_UP
Size sz = _src.dims() <= 2 ? _src.size() : Size();
Size dsz = _dsz.empty() ? Size(_src.cols()*2, _src.rows()*2) : _dsz;
Mat src = _src.getMat();
_dst.create( dsz, src.type() );
Mat dst = _dst.getMat();
int depth = src.depth();
{
bool isolated = (borderType & BORDER_ISOLATED) != 0;
int borderTypeNI = borderType & ~BORDER_ISOLATED;
if (borderTypeNI == BORDER_DEFAULT && (!src.isSubmatrix() || isolated) && dsz == Size(src.cols*2, src.rows*2))
{
typedef IppStatus (CV_STDCALL * ippiPyrUp)(const void* pSrc, int srcStep, void* pDst, int dstStep, IppiSize srcRoi, Ipp8u* buffer);
int type = src.type();
CV_SUPPRESS_DEPRECATED_START
ippiPyrUp pyrUpFunc = type == CV_8UC1 ? (ippiPyrUp) ippiPyrUp_Gauss5x5_8u_C1R :
type == CV_8UC3 ? (ippiPyrUp) ippiPyrUp_Gauss5x5_8u_C3R :
type == CV_32FC1 ? (ippiPyrUp) ippiPyrUp_Gauss5x5_32f_C1R :
type == CV_32FC3 ? (ippiPyrUp) ippiPyrUp_Gauss5x5_32f_C3R : 0;
CV_SUPPRESS_DEPRECATED_END
if (pyrUpFunc)
{
int bufferSize;
IppiSize srcRoi = { src.cols, src.rows };
IppDataType dataType = depth == CV_8U ? ipp8u : ipp32f;
CV_SUPPRESS_DEPRECATED_START
IppStatus ok = ippiPyrUpGetBufSize_Gauss5x5(srcRoi.width, dataType, src.channels(), &bufferSize);
CV_SUPPRESS_DEPRECATED_END
if (ok >= 0)
{
Ipp8u* buffer = ippsMalloc_8u_L(bufferSize);
ok = pyrUpFunc(src.data, (int) src.step, dst.data, (int) dst.step, srcRoi, buffer);
ippsFree(buffer);
if (ok >= 0)
{
CV_IMPL_ADD(CV_IMPL_IPP);
return true;
}
}
}
}
}
#else
CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(_dsz); CV_UNUSED(borderType);
#endif
return false;
}
}
#endif
void cv::pyrUp( InputArray _src, OutputArray _dst, const Size& _dsz, int borderType )
{
CV_INSTRUMENT_REGION();
@@ -1633,14 +1572,6 @@ void cv::pyrUp( InputArray _src, OutputArray _dst, const Size& _dsz, int borderT
CALL_HAL(pyrUp, cv_hal_pyrup, src.data, src.step, src.cols, src.rows, dst.data, dst.step, dst.cols, dst.rows, depth, src.channels(), borderType);
#ifdef HAVE_IPP
bool isolated = (borderType & BORDER_ISOLATED) != 0;
int borderTypeNI = borderType & ~BORDER_ISOLATED;
#endif
CV_IPP_RUN(borderTypeNI == BORDER_DEFAULT && (!_src.isSubmatrix() || isolated) && dsz == Size(_src.cols()*2, _src.rows()*2),
ipp_pyrup( _src, _dst, _dsz, borderType));
PyrFunc func = 0;
if( depth == CV_8U )
func = pyrUp_< FixPtCast<uchar, 6> >;
@@ -1659,121 +1590,6 @@ void cv::pyrUp( InputArray _src, OutputArray _dst, const Size& _dsz, int borderT
}
#ifdef HAVE_IPP
namespace cv
{
static bool ipp_buildpyramid( InputArray _src, OutputArrayOfArrays _dst, int maxlevel, int borderType )
{
CV_INSTRUMENT_REGION_IPP();
#if IPP_VERSION_X100 >= 810 && !IPP_DISABLE_PYRAMIDS_BUILD
Mat src = _src.getMat();
_dst.create( maxlevel + 1, 1, 0 );
_dst.getMatRef(0) = src;
int i=1;
{
bool isolated = (borderType & BORDER_ISOLATED) != 0;
int borderTypeNI = borderType & ~BORDER_ISOLATED;
if (borderTypeNI == BORDER_DEFAULT && (!src.isSubmatrix() || isolated))
{
typedef IppStatus (CV_STDCALL * ippiPyramidLayerDownInitAlloc)(void** ppState, IppiSize srcRoi, Ipp32f rate, void* pKernel, int kerSize, int mode);
typedef IppStatus (CV_STDCALL * ippiPyramidLayerDown)(void* pSrc, int srcStep, IppiSize srcRoiSize, void* pDst, int dstStep, IppiSize dstRoiSize, void* pState);
typedef IppStatus (CV_STDCALL * ippiPyramidLayerDownFree)(void* pState);
int type = src.type();
int depth = src.depth();
ippiPyramidLayerDownInitAlloc pyrInitAllocFunc = 0;
ippiPyramidLayerDown pyrDownFunc = 0;
ippiPyramidLayerDownFree pyrFreeFunc = 0;
if (type == CV_8UC1)
{
pyrInitAllocFunc = (ippiPyramidLayerDownInitAlloc) ippiPyramidLayerDownInitAlloc_8u_C1R;
pyrDownFunc = (ippiPyramidLayerDown) ippiPyramidLayerDown_8u_C1R;
pyrFreeFunc = (ippiPyramidLayerDownFree) ippiPyramidLayerDownFree_8u_C1R;
}
else if (type == CV_8UC3)
{
pyrInitAllocFunc = (ippiPyramidLayerDownInitAlloc) ippiPyramidLayerDownInitAlloc_8u_C3R;
pyrDownFunc = (ippiPyramidLayerDown) ippiPyramidLayerDown_8u_C3R;
pyrFreeFunc = (ippiPyramidLayerDownFree) ippiPyramidLayerDownFree_8u_C3R;
}
else if (type == CV_32FC1)
{
pyrInitAllocFunc = (ippiPyramidLayerDownInitAlloc) ippiPyramidLayerDownInitAlloc_32f_C1R;
pyrDownFunc = (ippiPyramidLayerDown) ippiPyramidLayerDown_32f_C1R;
pyrFreeFunc = (ippiPyramidLayerDownFree) ippiPyramidLayerDownFree_32f_C1R;
}
else if (type == CV_32FC3)
{
pyrInitAllocFunc = (ippiPyramidLayerDownInitAlloc) ippiPyramidLayerDownInitAlloc_32f_C3R;
pyrDownFunc = (ippiPyramidLayerDown) ippiPyramidLayerDown_32f_C3R;
pyrFreeFunc = (ippiPyramidLayerDownFree) ippiPyramidLayerDownFree_32f_C3R;
}
if (pyrInitAllocFunc && pyrDownFunc && pyrFreeFunc)
{
float rate = 2.f;
IppiSize srcRoi = { src.cols, src.rows };
IppiPyramid *gPyr;
IppStatus ok = ippiPyramidInitAlloc(&gPyr, maxlevel + 1, srcRoi, rate);
Ipp16s iKernel[5] = { 1, 4, 6, 4, 1 };
Ipp32f fKernel[5] = { 1.f, 4.f, 6.f, 4.f, 1.f };
void* kernel = depth >= CV_32F ? (void*) fKernel : (void*) iKernel;
if (ok >= 0) ok = pyrInitAllocFunc((void**) &(gPyr->pState), srcRoi, rate, kernel, 5, IPPI_INTER_LINEAR);
if (ok >= 0)
{
gPyr->pImage[0] = src.data;
gPyr->pStep[0] = (int) src.step;
gPyr->pRoi[0] = srcRoi;
for( ; i <= maxlevel; i++ )
{
IppiSize dstRoi;
ok = ippiGetPyramidDownROI(gPyr->pRoi[i-1], &dstRoi, rate);
Mat& dst = _dst.getMatRef(i);
dst.create(Size(dstRoi.width, dstRoi.height), type);
gPyr->pImage[i] = dst.data;
gPyr->pStep[i] = (int) dst.step;
gPyr->pRoi[i] = dstRoi;
if (ok >= 0) ok = pyrDownFunc(gPyr->pImage[i-1], gPyr->pStep[i-1], gPyr->pRoi[i-1],
gPyr->pImage[i], gPyr->pStep[i], gPyr->pRoi[i], gPyr->pState);
if (ok < 0)
{
pyrFreeFunc(gPyr->pState);
return false;
}
else
{
CV_IMPL_ADD(CV_IMPL_IPP);
}
}
pyrFreeFunc(gPyr->pState);
}
else
{
ippiPyramidFree(gPyr);
return false;
}
ippiPyramidFree(gPyr);
}
return true;
}
return false;
}
#else
CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(maxlevel); CV_UNUSED(borderType);
#endif
return false;
}
}
#endif
void cv::buildPyramid( InputArray _src, OutputArrayOfArrays _dst, int maxlevel, int borderType )
{
CV_INSTRUMENT_REGION();
@@ -1794,11 +1610,6 @@ void cv::buildPyramid( InputArray _src, OutputArrayOfArrays _dst, int maxlevel,
_dst.create( maxlevel + 1, 1, 0 );
_dst.getMatRef(0) = src;
int i=1;
CV_IPP_RUN(((IPP_VERSION_X100 >= 810) && ((borderType & ~BORDER_ISOLATED) == BORDER_DEFAULT && (!_src.isSubmatrix() || ((borderType & BORDER_ISOLATED) != 0)))),
ipp_buildpyramid( _src, _dst, maxlevel, borderType));
for( ; i <= maxlevel; i++ )
for( int i = 1; i <= maxlevel; i++ )
pyrDown( _dst.getMatRef(i-1), _dst.getMatRef(i), Size(), borderType );
}

View File

@@ -109,6 +109,44 @@ TEST(Imgproc_Hist_Calc, badarg)
EXPECT_NO_THROW(cv::calcBackProject(&img, 1, channels, hist, backProj, NULL, 1, true));
}
// A negative number of bins used to crash on 5.x: Mat::create did not reject a negative size, so the histogram
// had no memory behind it and calcHist then wrote into it.
TEST(Imgproc_Hist_Calc, regression_negative_hist_size)
{
const int channels[] = {0, 1};
float range[] = {0, 256};
const float* ranges[] = {range, range};
Mat img = cv::Mat::zeros(16, 16, CV_8UC1);
const Mat images[] = {img, img};
Mat mask(16, 16, CV_8UC1, Scalar(255));
Mat hist;
const int bad1d[][1] = { {-1}, {-2}, {-5} };
for (size_t i = 0; i < sizeof(bad1d) / sizeof(bad1d[0]); i++)
{
SCOPED_TRACE(cv::format("1D, %d bins", bad1d[i][0]));
EXPECT_THROW(cv::calcHist(images, 1, channels, noArray(), hist, 1, bad1d[i], ranges, true), cv::Exception);
EXPECT_THROW(cv::calcHist(images, 1, channels, mask, hist, 1, bad1d[i], ranges, true), cv::Exception);
}
const int bad2d[][2] = { {-1, 8}, {8, -1}, {-3, -3} };
for (size_t i = 0; i < sizeof(bad2d) / sizeof(bad2d[0]); i++)
{
SCOPED_TRACE(cv::format("2D, %d x %d bins", bad2d[i][0], bad2d[i][1]));
EXPECT_THROW(cv::calcHist(images, 2, channels, noArray(), hist, 2, bad2d[i], ranges, true), cv::Exception);
}
// normal calls still work afterwards
const int good1d[] = {8};
const int good2d[] = {8, 8};
EXPECT_NO_THROW(cv::calcHist(images, 1, channels, noArray(), hist, 1, good1d, ranges, true));
EXPECT_EQ(8, (int)hist.total());
EXPECT_EQ(256, cvRound(cv::sum(hist)[0]));
EXPECT_NO_THROW(cv::calcHist(images, 2, channels, noArray(), hist, 2, good2d, ranges, true));
EXPECT_EQ(2, hist.dims);
EXPECT_EQ(64, (int)hist.total());
EXPECT_EQ(256, cvRound(cv::sum(hist)[0]));
}
TEST(Imgproc_Hist_Calc, IPP_ranges_with_equal_exponent_21595)
{
const int channels[] = { 0 };

View File

@@ -20,6 +20,10 @@ void Polyfit::write(cv::FileStorage& fs) const {
void Polyfit::read(const cv::FileNode& node) {
node["deg"] >> deg;
node["p"] >> p;
CV_CheckGE(deg, 0, "Polyfit: degree must be non-negative");
CV_CheckTypeEQ(p.type(), CV_64FC1, "Polyfit: coefficients must be CV_64FC1");
CV_CheckEQ(p.rows - 1, deg, "Polyfit: coefficients must be a (deg + 1) x 1 column vector");
CV_CheckEQ(p.cols, 1, "Polyfit: coefficients must be a (deg + 1) x 1 column vector");
}
// Global functions to support FileStorage for Polyfit
@@ -53,6 +57,8 @@ Polyfit::Polyfit(Mat x, Mat y, int deg_)
Mat Polyfit::operator()(const Mat& inp)
{
// A missing polyfit node leaves the default (deg 0, empty p) in place without going through read().
CV_Assert(p.type() == CV_64FC1 && p.rows - 1 == deg && p.cols == 1);
return elementWise(inp, [this](double x) -> double { return fromEW(x); });
};

View File

@@ -309,5 +309,94 @@ TEST(Photo_ColorCorrection, serialization)
EXPECT_EQ(yaml1, yaml2);
}
static void writePolyfit(FileStorage& fs, const char* name, bool isLog, int deg, const Mat& p)
{
fs << name << "{" << "deg" << deg;
if (isLog)
writePolyfit(fs, "p", false, deg, p);
else
fs << "p" << p;
fs << "}";
}
static std::string makeModelWithPolyfit(int linearType, int deg, const Mat& p, bool omitPolyfit = false)
{
const bool isLog = linearType == cv::ccm::LINEARIZATION_GRAYLOGPOLYFIT ||
linearType == cv::ccm::LINEARIZATION_COLORLOGPOLYFIT;
const bool isColor = linearType == cv::ccm::LINEARIZATION_COLORPOLYFIT ||
linearType == cv::ccm::LINEARIZATION_COLORLOGPOLYFIT;
FileStorage fs("", FileStorage::WRITE | FileStorage::MEMORY);
fs << "ColorCorrectionModel" << "{"
<< "ccm" << Mat::eye(3, 3, CV_64F)
<< "loss" << 0.
<< "csEnum" << (int)cv::ccm::COLOR_SPACE_SRGB
<< "ccm_type" << (int)cv::ccm::CCM_LINEAR
<< "shape" << 9
<< "linear" << "{" << "deg" << deg;
if (!omitPolyfit)
{
for (const char* name : isColor ? std::vector<const char*>{"pr", "pg", "pb"} : std::vector<const char*>{"p"})
writePolyfit(fs, name, isLog, deg, p);
}
fs << "}"
<< "distance" << (int)cv::ccm::DISTANCE_CIE2000
<< "linear_type" << linearType
<< "gamma" << 2.2
<< "deg" << deg
<< "saturated_threshold" << std::vector<double>{0, 0.98}
<< "}";
return fs.releaseAndGetString();
}
CV_ENUM(PolyfitLinearization, ccm::LINEARIZATION_GRAYPOLYFIT, ccm::LINEARIZATION_COLORPOLYFIT,
ccm::LINEARIZATION_GRAYLOGPOLYFIT, ccm::LINEARIZATION_COLORLOGPOLYFIT)
typedef testing::TestWithParam<PolyfitLinearization> Photo_ColorCorrection_Polyfit;
TEST_P(Photo_ColorCorrection_Polyfit, read_rejects_inconsistent_polyfit)
{
const int type = GetParam();
const Mat img(4, 4, CV_8UC3, Scalar(10, 100, 200));
const Mat good = Mat_<double>({4, 1}, {0., 1., 0., 0.});
{
cv::ccm::ColorCorrectionModel model;
FileStorage fs(makeModelWithPolyfit(type, 3, good), FileStorage::READ | FileStorage::MEMORY);
ASSERT_NO_THROW(model.read(fs["ColorCorrectionModel"]));
Mat out;
ASSERT_NO_THROW(model.correctImage(img, out));
EXPECT_EQ(img.size(), out.size());
}
const Mat bad[] = {
Mat(1, 1, CV_64F, Scalar(0.5)), // fewer coefficients than deg + 1
Mat(4, 1, CV_32F, Scalar(0.5)), // coefficients are not double
Mat(1, 4, CV_64F, Scalar(0.5)), // row vector, fromEW indexes (d, 0)
Mat(4, 2, CV_64F, Scalar(0.5)), // deg + 1 rows but more than one column
Mat(std::vector<int>{1, 1, 4}, CV_64F, Scalar(0.5)), // N-D layout with the right total
Mat() // empty coefficient Mat
};
for (const Mat& p : bad)
{
cv::ccm::ColorCorrectionModel model;
FileStorage fs(makeModelWithPolyfit(type, 3, p), FileStorage::READ | FileStorage::MEMORY);
EXPECT_THROW(model.read(fs["ColorCorrectionModel"]), cv::Exception) << "dims=" << p.dims << " rows=" << p.rows << " cols=" << p.cols << " type=" << p.type();
}
{
cv::ccm::ColorCorrectionModel model;
FileStorage fs(makeModelWithPolyfit(type, -1, good), FileStorage::READ | FileStorage::MEMORY);
EXPECT_THROW(model.read(fs["ColorCorrectionModel"]), cv::Exception);
}
{
// missing polyfit node: read() falls back to the default Polyfit, correctImage must throw instead of crashing
cv::ccm::ColorCorrectionModel model;
FileStorage fs(makeModelWithPolyfit(type, 3, good, true), FileStorage::READ | FileStorage::MEMORY);
Mat out;
EXPECT_THROW({ model.read(fs["ColorCorrectionModel"]); model.correctImage(img, out); }, cv::Exception);
}
}
INSTANTIATE_TEST_CASE_P(/**/, Photo_ColorCorrection_Polyfit, PolyfitLinearization::all());
} // namespace
} // namespace opencv_test

View File

@@ -72,8 +72,9 @@ static inline bool getUnicodeString(PyObject * obj, std::string &str)
bool res = false;
if (PyUnicode_Check(obj))
{
// NULL with UnicodeEncodeError set, e.g. for a lone surrogate
PyObject * bytes = PyUnicode_AsUTF8String(obj);
if (PyBytes_Check(bytes))
if (bytes && PyBytes_Check(bytes))
{
const char * raw = PyBytes_AsString(bytes);
if (raw)

View File

@@ -111,6 +111,100 @@ class filestorage_io_test(NewOpenCVTests):
def test_json(self):
self.run_fs_test(".json")
def test_write_int64_out_of_int32_range(self):
int32_max = 2**31 - 1
below_int32_min = -2**31 - 1
int64_max = 2**63 - 1
int64_min = -2**63
too_big = 2**64 # does not fit int64: written through the double overload
too_small = -2**63 - 1 # does not fit int64; double-rounds to -2**63
np_int64_value = np.int64(2**40)
np_uint64_value = np.uint64(2**40 + 7)
values = {
'int32_max': int32_max,
'int64_max': int64_max,
'int64_min': int64_min,
'below_int32_min': below_int32_min,
'np_int64': np_int64_value,
'np_uint64': np_uint64_value,
'too_big': too_big,
'too_small': too_small,
'bool_value': True,
}
expected = {
'int32_max': str(int32_max),
'int64_max': str(int64_max),
'int64_min': str(int64_min),
'below_int32_min': str(below_int32_min),
'np_int64': str(int(np_int64_value)),
'np_uint64': str(int(np_uint64_value)),
'too_big': '%.17g' % float(too_big),
'too_small': '%.17g' % float(too_small),
}
for ext in ('.yml', '.xml', '.json'):
fd, fname = tempfile.mkstemp(prefix='opencv_python_int64_filestorage', suffix=ext)
os.close(fd)
try:
fs = cv.FileStorage(fname, cv.FileStorage_WRITE)
for name, value in values.items():
fs.write(name, value)
fs.release()
with open(fname) as f:
text = f.read()
for name, want in expected.items():
if ext == '.yml':
entry = '{}: {}'.format(name, want)
elif ext == '.xml':
entry = '<{0}>{1}</{0}>'.format(name, want)
else:
entry = '"{}": {}'.format(name, want)
self.assertIn(entry, text, '{} in {}'.format(name, ext))
if ext == '.yml':
self.assertIn('bool_value: true', text)
elif ext == '.xml':
self.assertIn('<bool_value>1</bool_value>', text)
else:
self.assertIn('"bool_value": 1\n', text)
finally:
os.remove(fname)
def test_write_numpy_bool(self):
values = {
'bool_value': True,
'np_bool_true': np.bool_(True),
'np_bool_false': np.bool_(False),
}
for ext in ('.yml', '.xml', '.json'):
fd, fname = tempfile.mkstemp(prefix='opencv_python_numpy_bool_filestorage', suffix=ext)
os.close(fd)
try:
fs = cv.FileStorage(fname, cv.FileStorage_WRITE)
for name, value in values.items():
fs.write(name, value)
fs.release()
with open(fname) as f:
text = f.read()
if ext == '.yml':
self.assertIn('bool_value: true', text)
self.assertIn('np_bool_true: true', text)
self.assertIn('np_bool_false: false', text)
elif ext == '.xml':
self.assertIn('<bool_value>1</bool_value>', text)
self.assertIn('<np_bool_true>1</np_bool_true>', text)
self.assertIn('<np_bool_false>0</np_bool_false>', text)
else:
self.assertRegex(text, r'"bool_value": 1[,}\s]')
self.assertRegex(text, r'"np_bool_true": 1[,}\s]')
self.assertRegex(text, r'"np_bool_false": 0[,}\s]')
finally:
os.remove(fname)
def test_base64(self):
fd, fname = tempfile.mkstemp(prefix="opencv_python_sample_filestorage_base64", suffix=".json")
os.close(fd)

View File

@@ -585,6 +585,21 @@ class Arguments(NewOpenCVTests):
with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
_ = cv.utils.dumpString(not_convertible)
@unittest.skipIf(sys.version_info[0] < 3, 'lone surrogates need Python 3 str')
def test_parse_to_string_not_encodable(self):
# A lone surrogate can't be encoded as UTF-8; this used to crash the interpreter
not_encodable = 'a\udcff'
for func in (cv.utils.dumpString, cv.utils.dumpCString):
with self.assertRaises(UnicodeEncodeError, msg=get_no_exception_msg(not_encodable)):
_ = func(not_encodable)
# Functions with several overloads report the encoding error through cv.error
for call in (lambda: cv.putText(np.zeros((8, 8), np.uint8), not_encodable, (0, 7),
cv.FONT_HERSHEY_SIMPLEX, 0.3, 255),
lambda: cv.imread(not_encodable),
lambda: cv.imwrite(not_encodable, np.zeros((2, 2), np.uint8))):
with self.assertRaises((cv.error, UnicodeEncodeError), msg=get_no_exception_msg(not_encodable)):
call()
def test_parse_to_rect_convertible(self):
Rect = namedtuple('Rect', ('x', 'y', 'w', 'h'))
try_to_convert = partial(self._try_to_convert, cv.utils.dumpRect)

View File

@@ -130,7 +130,7 @@ def main():
frame_obj_points = pattern_points
elif pattern_type == 'charucoboard':
corners, charucoIds, _, _ = charuco_detector.detectBoard(img)
if (len(corners) > 0):
if corners is not None and len(corners) >= 4:
frame_obj_points, frame_img_points = board.matchImagePoints(corners, charucoIds)
found = True
else:
@@ -143,8 +143,8 @@ def main():
vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
if pattern_type == 'chessboard':
cv.drawChessboardCorners(vis, pattern_size, corners, found)
elif pattern_type == 'charucoboard':
cv.aruco.drawDetectedCornersCharuco(vis, corners, charucoIds=charucoIds)
elif pattern_type == 'charucoboard' and charucoIds is not None:
cv.aruco.drawDetectedCornersCharuco(vis, corners.reshape(-1, 1, 2), charucoIds=charucoIds)
_path, name, _ext = splitfn(fn)
outfile = os.path.join(debug_dir, name + '_board.png')
cv.imwrite(outfile, vis)
@@ -170,6 +170,10 @@ def main():
img_points.append(corners)
obj_points.append(pattern_points)
if not img_points:
print("No calibration patterns found")
return
# calculate camera distortion
rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None)