For an open curve, a zero epsilon and an infinite segment, eps * segment_len_2 is NaN, so the test that stops splitting a slice was always false and the slices never got smaller. Write the test so that NaN counts as within the tolerance. Results for finite input are unchanged. Add tests.
After the first document, YAMLParser::parse() expects the next one to
start with '---'. A line that starts with an alphanumeric character is
rejected with "The YAML streams must start with '---', except the first
one", but a line that starts with '-' and is not '---' is neither
consumed nor rejected, so the loop that looks for the next document
never advances and FileStorage::open() does not return.
Report the same parse error for such a line.
imgproc: allow 1x256 custom lookup tables in applyColorMap 🤖🤖🤖
Updated the custom colormap dimension validation in applyColorMap to accept both Size(1, 256) (vertical 256x1) and Size(256, 1) (horizontal 1x256), while ensuring userColor.empty() and dims > 2 are rejected:
if (userColor.empty() || userColor.dims() > 2 ||
(userColor.size() != Size(1, 256) && userColor.size() != Size(256, 1)))
CV_Error(Error::StsAssert, "cv::LUT only supports tables of size 256.");
Because ColorMap::operator() checks _lut.isContinuous() and accesses the table sequentially via raw pointers (_lut.ptr<lut_pixel_t>(0)), continuous 1x256 and 256x1 matrices lay out identically in memory. Index lookup srcLUT[pixel_val] works identically without requiring buffer reallocation or reshaping.
* features2d: skip AKAZE max_points cut when keypoints are provided
Do not sort or truncate caller-supplied keypoints by max_points in AKAZE_Impl::detectAndCompute() when useProvidedKeypoints is true, preserving input count and order in compute() while keeping the limit for detection.
* features2d: document that AKAZE max_points applies only to detected keypoints
compute() and detectAndCompute() with provided keypoints keep the
keypoints they are given.
* video: make clear() reset the MOG2 and KNN background models
cv::Algorithm::clear() is documented to clear the algorithm state, but
BackgroundSubtractorMOG2 and BackgroundSubtractorKNN inherit the empty
base implementation. After clear(), apply() keeps updating the old model
and reports foreground against the previous scene.
Override clear() in both implementations to drop the model, so the next
apply() initializes a new one as it does on a newly created object.
* video: clear MOG2 and KNN models without going through initialize()
clear() called initialize(Size(), 0). With OpenCL active this builds the
apply and getBackgroundImage kernels for frame type 0 and runs create()
and setTo() on zero-size UMats; the setTo() call dereferences an empty
vector in ocl::checkOptimalVectorWidth() and crashes.
Release the model buffers (Mat and UMat) instead and reset the frame size,
frame type, frame counter and KNN's update counters to their constructor
values. The algorithm parameters are kept. The next apply() initializes
the model for the actual frame, as on a new object.
Add UMat variants of the clear() regression tests so the OpenCL path is
covered when OpenCL is available.
* video: do not assign theRNG() in the clear() tests
The clear_resets_model tests reseeded theRNG() before each of the two
apply() calls they compare. That is not needed: KNN takes its update
points from theRNG() only after a frame has been processed, so the
first apply() on an empty model gives the same mask and background
image whatever the RNG state is. Leave the global RNG as the test
system set it.
photo: vectorize fastNlMeansDenoising with universal intrinsics
Adds a universal-intrinsics path that processes four elements per iteration for single-channel uchar and ushort images.
Vectorizes the column distance update, the initial distance sums at the start of each row, and the weighted accumulation.
Uses the same integer arithmetic as the scalar code, so results are bit-exact.
The scalar loops are unchanged and handle the remaining elements at the end of each row.
Domain_Filter::compute_NCfilter encoded summed-area-table positions as float linear indices over 3 * h * (w + 1) elements and decoded them back into (row, col, channel). Above 2^24 (~5.59 MP for 3-channel images), float loses integer precision and reads neighbouring rows. Index box_filter directly by row i and integer column bounds from upper_idx and lower_idx.
* core: do not pass empty input to HAL minMaxIdx
cv::minMaxLoc and cv::minMaxIdx on an empty CV_8U Mat crashed with
SIGSEGV on ARM64 builds that use KleidiCV: the HAL min/max location
wrapper reads src_data[offset] when a min or max value is requested, and
src_data is NULL for an empty Mat. The generic code already returns zero
values and -1 indices for empty input, so skip the HAL calls then.
* core: fix comment on empty input in minMaxIdx
* core: return early for empty input in minMaxIdx
Check the input for emptiness at the top of cv::minMaxIdx and return zero
values and -1 indices, instead of skipping only the HAL calls. This also
covers a default constructed Mat (dims == 0) and empty UMat. Add a test
for cv::Mat().
* imgproc: fix a data race in the OpenCL single-pass separable filter
After each block of 8 output rows, filterSep_singlePass.cl moves the
last 2*RADIUSY rows of its local buffer to the top. For kernels of 11 to
21 vertical taps the rows it reads overlap the rows it writes, and
nothing orders the reads before the writes, so a work item can overwrite
a value before another work item has read it. Move the rows 8 at a time,
with a barrier after each step. Kernels of up to 9 taps take a single
step, which is the old loop.
The existing OpenCL tests use kernels of at most 9 taps. The new test
compares sepFilter2D on a UMat with the CPU result for larger kernels.
* imgproc: fix the same data race in the OpenCL Laplacian kernel
laplacian5.cl moves the last 2*RADIUS rows of its local buffer to the
top with the same loop as filterSep_singlePass.cl. Its block height
depends on the work-group and local memory sizes and can be smaller
than 2*RADIUS, for example 16 rows for a 19-tap, 4-channel Laplacian
with 48 KB of local memory. Move the rows BLK_Y at a time, with a
barrier after each step, as in the separable filter.
The existing OpenCL Laplacian tests use at most 5 taps. The new test
compares Laplacian on a 4-channel UMat with the CPU result for 23 and
31 taps; without the fix, 23 taps fails on an NVIDIA GPU.
* imgproc(test): run the large-kernel OpenCL filter tests through the existing fixtures
The 11, 15 and 21 tap sepFilter2D test now uses the SepFilter2D fixture, so
8-bit and 32-bit data, 1 to 4 channels, all borders and ROIs are covered.
The 23 and 31 tap Laplacian test uses BORDER_REPLICATE, which has no size gate,
so it cannot fall back to the CPU on devices with large work groups.
pyrUp on a source with zero columns and some rows (for example a 5x0
CV_8UC1 Mat) segfaults in the pyramid kernel. Return the empty
destination instead; a non-empty destination size for an empty source
is rejected.
The padding mask (1 << bitIdx) - 1 overflows int when bitIdx is 31,
which happens whenever the entropy-coded data of a frame leaves exactly
31 free bits in the last word. Compute the mask in a wider unsigned type.
* dnn: repack the convolution when SAME padding changes after a reshape
* dnn: rebuild the packed convolution in every finalize()
forward() packs fastConvImpl with the pads and the Winograd choice that
finalize() computes, and with weightsMat, into which fuseLayers() may
still fold BatchNorm. finalize() kept the pack whenever the Winograd
choice was unchanged, so a SAME convolution kept the old padding after a
reshape, and a convolution kept BatchNorm folded in after
enableFusion(false). Reset it in every finalize(), as convolutionOp is.
Also print the target as int in the test message (-Wsign-promo).
* dnn: drop the OpenCL case from the reshape test
The OpenCL path never uses fastConvImpl, so the case passed on 4.x too.
The generated cv2/typing/__init__.py defined LayerId as cv2.dnn.DictValue.
This line runs on every "import cv2", so if cv2.dnn.DictValue is not
available the whole import fails with AttributeError.
Net::Impl::getLayerId(DictValue&) accepts only an integer layer index or
a string layer name and asserts for anything else, so describe LayerId
as Union[int, str]. This also removes the runtime dependency on cv2.dnn
from the typing module.
Add a test that checks the generated cv2.typing.LayerId alias.
dnn: read count_include_pad in the ONNX AveragePool importer 🤖🤖🤖 - #30842Fixes#30834
`parseAveragePool` in the 4.x ONNX importer chose `ave_pool_padded_area` from the model's `producer_name` only (`framework_name == "pytorch"`) and ignored the node's `count_include_pad` attribute. PyTorch models with `nn.AvgPool2d(..., padding=p, count_include_pad=False)` (PoolFormer, timm Inception-v4 and Inception-ResNet-v2) therefore divided border windows by the full kernel area, and non-PyTorch models with `count_include_pad=1` left the padding out.
The importer now reads `count_include_pad` and falls back to the old producer-based default when the attribute is missing, the same way the 5.x importer does. Models without the attribute behave as before.
Tests: `test_averagepool_2d_pads_count_include_pad` and `test_averagepool_2d_precomputed_pads_count_include_pad` come off the `opencv_all` conformance denylist. Without the importer change they fail on OCV/CPU, OCV/OCL and OCV/OCL_FP16 (normInf 1.568 and 12.16), and with it they pass. Their test data is already in `opencv_extra`.
`Test_ONNX_layers.AveragePooling_exclude_pad` covers the reported case: a PyTorch-exported `nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)`, where the explicit `count_include_pad=0` has to override the PyTorch default. The model is in opencv/opencv_extra#1466. Without the importer change the test fails on OCV/CPU, OCV/OCL and OCV/OCL_FP16 (normInf 0.3855), and with it the test passes.
Tested on Ubuntu 24.04 (WSL2), x86-64, GCC 15.2.0, Release, `WITH_OPENCL=ON`, OpenCL through PoCL on the CPU. With and without the patch, I ran the `opencv_test_dnn` tests matching `*averagepool*:*AvePool*:*AveragePool*:*Pooling*:*pool*:Test_ONNX_conformance.*:Test_ONNX_layers.*`. Both runs passed the same 4137 tests, and the only difference is that the six re-enabled cases run (and pass) instead of being skipped. The repro from the issue prints all ones after the fix, matching PyTorch.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
MVN, LayerNormalization, InstanceNormalization and GroupNormalization took
the variance of each row as E[x^2] - E[x]^2 in float. When the mean is large
against the spread the two terms cancel: from about 1000 standard deviations
the variance comes out as 0 and the outputs are scaled by 1/sqrt(eps).
Keep the one-pass result for ordinary rows. When mean^2 > 64 * var, measure
the row again from d = x - mean, summed in double: mean += E[d],
var = E[d^2] - E[d]^2.
Domain_Filter::compute_NCfilter encoded summed-area-table positions as float linear indices over 3 * h * (w + 1) elements and decoded them back into (row, col, channel). Above 2^24 (~5.59 MP for 3-channel images), float loses integer precision and reads neighbouring rows. Index box_filter directly by row i and integer column bounds from upper_idx and lower_idx.
videoio: fix large Python stream seeks and callback failures 🤖🤖🤖 - #30798
Opening an MP4 from a Python stream can segfault when its `moov` box requires an absolute seek beyond 2 GiB. `PythonStreamReader::seek()` narrows the 64-bit offset to `int`; a resulting Python exception is followed by operations on a null callback result. This was reproduced independently of a model runtime and through the unmodified video decoder class from vLLM main.
This patch preserves 64-bit read/seek arguments using the Python C API's `L` format, checks callback and conversion results before using them, and uses `PyEnsureGIL`/`PySafeObject` for cleanup. It also holds the GIL when releasing the stream's last Python reference. FFmpeg read callbacks now return `AVERROR(EIO)` on exceptions: returning zero caused an endless retry loop once callback exceptions were handled safely.
Regression tests cover a virtual MP4 larger than 2 GiB, exceptions and invalid results from read/seek callbacks, oversized reads, overflowing seek results, and releasing the last stream reference. The large-stream test reuses the existing 6.6 KB `highgui/video/sample_23976fps.mp4` fixture and moves its metadata into virtual free space; it does not allocate or add a multi-gigabyte asset.
Related reports: https://github.com/vllm-project/vllm/issues/46589 and https://github.com/vllm-project/vllm/issues/35285. The affected stream interface was introduced in https://github.com/opencv/opencv/pull/25584. Searches for open PythonStreamReader / Python seek fixes did not find another PR addressing this issue.
### Validation
Built unmodified and patched OpenCV from `4.x` at `38af4e35d7e6e001fa89c26b74a24232375afc1e`, using CMake/Ninja with `BUILD_LIST=core,imgproc,imgcodecs,videoio,python3` and FFmpeg enabled.
Environment: Linux aarch64, GCC 13.3, CPython 3.12.3, NumPy 2.2.6, system FFmpeg 6.1.1.
- Added standalone C++ regression `Videoio.stream_capture_ffmpeg_read_exception` next to `stream_capture_ffmpeg`: an `IStreamReader` whose `read()` throws is exercised, and `open()` returns false with `isOpened() == false`. It reuses the neighbouring backend/plugin ABI/API skips and needs neither Python bindings nor video fixtures.
- Built `opencv_test_videoio` with `BUILD_TESTS=ON` and `BUILD_LIST=core,imgproc,imgcodecs,videoio,highgui,ts,python3`. The C++ regression passed with both test-data environment variables unset. With the same test binary loading unpatched `38af4e3` libraries, opening the stream hung until an external 5-second timeout terminated it (exit 124); patched libraries completed immediately. Disabling FFmpeg verified the backend skip.
- Patched `modules/videoio/misc/python/test/test_videoio.py -v`: **8 tests passed**, including all eight invalid-callback subcases.
- Each of the four new test methods, run in a separate process against the unmodified source build, terminated with **SIGSEGV (-11)**. The four existing methods passed against that build.
- vLLM main `c07d58dc82d75f7d1a947b3264b460384ec3e18d`: the unmodified `OpenCVVideoBackendMixin` class was extracted and executed on a generated, valid 2,147,549,184-byte MP4. Unmodified OpenCV segfaulted during open; patched OpenCV opened/decoded a frame, released the capture, and retrieved correct metadata (4 frames, 2 fps, 2 seconds).
- `git diff --check`: passed.
Example test command after configuring/building the Python module:
```sh
PYTHONPATH="$PWD/build/lib/python3:$PWD/modules/python/test" \
OPENCV_TEST_DATA_PATH=/path/to/opencv_extra/testdata \
python3 modules/videoio/misc/python/test/test_videoio.py -v
```
This is decoder-level validation; a full Qwen model server was not started. Windows, macOS and MSMF have not been validated locally.
Prepared with AI assistance (Codex); native builds and the reported tests were run locally.
### Pull Request Readiness Checklist
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`4.x`).
- [x] There is a reference to the original bug report and related work.
- [x] Regression tests reuse existing opencv_extra data; no companion data PR is needed.
- [x] The patch builds with CMake. No public API is added.
SOLVEPNP_DLS and SOLVEPNP_UPNP already use EPnP on 4.x. Remove the unused private solver and its include without changing those flags or the independent USAC implementation.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 67ff71b3-42e9-4b46-89ea-1b8873bc8c51
imgproc: fix warpPolar inverse mapping at the angular seam and for sub-matrix input - #30827
### Summary
`cv::warpPolar()` with `WARP_INVERSE_MAP` pads the polar image with one wrapped row above and below before calling `remap()`:
```cpp
const int ANGLE_BORDER = 1;
cv::copyMakeBorder(_src, _dst, ANGLE_BORDER, ANGLE_BORDER, 0, 0, BORDER_WRAP);
```
This has two problems:
1. One row covers the 2-tap linear kernel only. With `INTER_CUBIC` (4 taps) and `INTER_LANCZOS4` (8 taps) the kernel reads rows beyond the padding, so pixels along the ray at angle 0 are computed from the remap border instead of the wrapped image.
2. There is no `BORDER_ISOLATED`, so for a sub-matrix the padding rows come from the parent image instead of being wrapped.
The patch picks the number of wrapped rows from the interpolation kernel (1 / 2 / 4) and adds `BORDER_ISOLATED`.
### Reproducer
A constant polar image should give a constant result inside the circle:
```python
import cv2, numpy as np
polar = np.full((360, 100), 200, np.uint8) # rows = angle, cols = radius
center, radius = (100.0, 100.0), 100.0
yy, xx = np.mgrid[0:201, 0:201]
r = np.hypot(xx - center[0], yy - center[1])
ring = (r >= 4) & (r <= 90) # inside the source, away from the centre
for name in ("INTER_NEAREST", "INTER_LINEAR", "INTER_CUBIC", "INTER_LANCZOS4"):
flags = getattr(cv2, name) | cv2.WARP_INVERSE_MAP | cv2.WARP_FILL_OUTLIERS
dst = cv2.warpPolar(polar, (201, 201), center, radius, flags)
bad = ring & (dst != 200)
print("%-15s wrong pixels: %3d" % (name, bad.sum()))
```
Output with opencv-python 4.12.0:
```
INTER_NEAREST wrong pixels: 0
INTER_LINEAR wrong pixels: 0
INTER_CUBIC wrong pixels: 29
INTER_LANCZOS4 wrong pixels: 232
```
The wrong values are 201..212 for cubic and 190..218 for Lanczos. The same happens on 5.x.
### Testing
Two new parameterized tests in `test_imgwarp.cpp`, each run for nearest, linear, cubic and Lanczos:
- `Imgproc_warpPolar_Inverse.angular_seam`: the check above, with and without `WARP_FILL_OUTLIERS`.
- `Imgproc_warpPolar_Inverse.submatrix`: a sub-matrix and its copy must give identical results.
Without the fix 6 of the 8 cases fail (cubic and Lanczos in `angular_seam`, all four in `submatrix`); with the fix all pass. `opencv_test_imgproc --gtest_filter=*olar*:*Warp*:*warp*:*Remap*:*remap*` passes (503 tests). Built with MSVC 19.29 on Windows 11.
### Not changed
- The legacy `cvLinearPolar()` / `cvLogPolar()` in the same file use the same one-row padding. I left them as they are; I can update them here if you prefer.
- With `INTER_LANCZOS4` the pixels within about 4 px of the centre still read past the radial border of the source. That is a separate problem and is not addressed here.
### AI assistance
This change, the tests and this description were prepared with Claude Code. I reviewed the code, and the tests above were run locally on my machine.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
core: vectorize masked mean for 8-bit inputs.
The cv::mean() function is currently implemented with scalar loops for 8-bit masked inputs on the CPU fallback path.
This PR provides a Universal Intrinsics reduction-based implementation for 1-4 channel inputs.
features2d: fix BRISK on sub-matrix images - #30831
`BRISK_Impl::smoothedIntensity()` indexes the image with its width as the row stride in the direct-pixel paths. For an image that is a region of a larger one (`img(roi)`) the row step differs from the width, so those samples were read from the wrong rows. `detect()`/`compute()` on such an image returned wrong keypoint angles (the orientation uses these samples) and wrong descriptor bytes (maximum byte difference 255), and both depended on the pixels around the region. The function now uses `image.step`; the integral image is a fresh continuous matrix and is unchanged. Proposed to 4.x because BRISK is no longer in the main repository on 5.x (it moved to opencv_contrib).
`Features2d_BRISK.descriptors_of_sub_matrix` computes keypoints, angles and descriptors on a continuous image and on a region of a larger image with unrelated pixels around it and requires identical output. On 4.x it fails (1 descriptor mismatch, 68 angle mismatches) and passes with the change. Continuous images are unchanged. Checks run on macOS arm64 (Release); the BRISK tests that read opencv_extra images were not run. The open PR #28194 also edits `brisk.cpp` (keypoint orientation in `compute()`) at different lines.
Thank you for taking a look.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
video: fix DISOpticalFlow::calc() crash after collectGarbage() 🤖🤖🤖 - #30859Fixes#30858
`DISOpticalFlow::calc()` crashed after `collectGarbage()`, which cleared the vector of `VariationalRefinement` objects that only the constructor creates.
### Change
- Keep the objects and call `collectGarbage()` on each of them instead.
- Also release the buffers that `collectGarbage()` missed: `I0x_buf`, `I0y_buf` and their `_aux` copies, the initial-flow pyramids, and their OpenCL counterparts.
### Tests
`DenseOpticalFlow_DIS.calc_after_collectGarbage` calls `collectGarbage()` between `calc()` calls, after a call with an initial flow, before the first call and after parameter changes, on `Mat` and `UMat`. Each result must equal that of a fresh object.
| Check (Linux x86-64, GCC 15.2, with opencv_extra) | 4.x | This PR |
|---|---|---|
| new test | segfault | passes, 3 seeds |
| `calc()` after `collectGarbage()` under AddressSanitizer | heap-use-after-free in `prepareBuffers()` | no report |
| `opencv_test_video`, 178 existing tests | 8 failures (GOTURN model, data) | same 8 |
The `UMat` part also passed with OpenCL on an NVIDIA RTX PRO 6000. 5.x has the same code; the test sits before `regression_20185_patch_larger_than_border` so that the regular 4.x to 5.x merge is clean. Not run on Windows.
Prepared with an AI assistant; every result was reproduced by running the code.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
video: clear stale initial flow in DISOpticalFlow::calc() 🤖🤖🤖 - #30860Fixes#30857
`DISOpticalFlow::calc()` kept the initial-flow pyramid of an earlier call, so a later call without an initial flow still used it, or read past it when the frame grew.
### Change
- Clear `initial_Ux` and `initial_Uy` in `prepareBuffers()` when no initial flow is given.
- The OpenCL path is unchanged: it never reads an initial flow.
### Tests
`DenseOpticalFlow_DIS.StaleInitialFlow` gives one object an initial flow, then calls it without one, on the same frame and on a larger one, and compares with a fresh object (`NORM_INF == 0`).
| Check (Linux x86-64, GCC 15.2, with opencv_extra) | 4.x | This PR |
|---|---|---|
| new test | fails, then segfaults on the larger frame | passes, 4 seeds |
| clear removed | | fails, then segfaults |
| larger frame under AddressSanitizer | heap-buffer-overflow | no report |
| `opencv_test_video`, 178 existing tests | 8 failures (GOTURN model, data) | same 8 |
5.x has the same code; the change merges cleanly. Not run on Windows or macOS.
Prepared with an AI assistant; every result was reproduced by running the code.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
stitching: wrap default constructors of ImageFeatures, MatchesInfo and CameraParams - #30597Fixes#20979
`cv2.detail_ImageFeatures()`, `cv2.detail_MatchesInfo()` and `cv2.detail_CameraParams()` have no wrapped constructor, so the Python bindings create the object without running the C++ constructor and the fields are left zero-filled:
- reading `ImageFeatures().descriptors` copies a zeroed `UMat` and segfaults
- `MatchesInfo()` returns `src_img_idx`/`dst_img_idx` 0 instead of -1
- `CameraParams()` returns `focal` 0.0 and `R` None instead of 1 and the identity
This marks the existing default constructors of `MatchesInfo` and `CameraParams` as `CV_WRAP` and adds one for `ImageFeatures` (`img_idx(0)`), so the generator emits a constructor for all three. Stitching is only wrapped for Python, so other bindings are not affected.
### Testing
Added `stitching_detail_default_construct_test` to `modules/stitching/misc/python/test/test_stitching.py`. Without the fix the `ImageFeatures` test segfaults and the other two fail on the default values. With the fix, `test_stitching.py` (10 tests) and `opencv_test_stitching` (22 tests) pass locally (Linux x86-64, GCC 13, Python 3.13).
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
The sample allocated C as (|A.rows - B.rows| + 1) x (|A.cols - B.cols| + 1) and copied the top-left corner of the inverse DFT into it. That is neither the full nor the valid convolution. Allocate C with the full convolution size (A.rows + B.rows - 1) x (A.cols + B.cols - 1), which matches the DFT size used below.
Fixes#4558
* core: fix solveLP floating-point drift producing infeasible solutions
* core(lpsolver): tighten pivot-eps comment per review (drop issue ref, note cost)
* core(lpsolver): snap cancellation noise relative to the operands
Replace the fixed 1e-12 cutoff on the whole tableau with a relative test on
the subtraction that updates it. A fixed cutoff turns legitimate small data
into zeros (right-hand sides around 1e-14 were returned as z = 0), while the
relative test removes only results that are within rounding noise of the
values being subtracted.
Add small_magnitude_data, which fails with the fixed cutoff.
* core(lpsolver): snap cancellation noise when restoring objective after Phase I
When any constraint has a negative right-hand side, initialize_simplex() runs Phase I and then rebuilds the original objective from old_c and the Phase I tableau before entering Phase II inner_simplex(). Snap cancellation noise in those updates consistently with pivot() so that exact-zero checks in Phase II are not distorted by residual rounding error.
Add negative_rhs_restore_cancellation regression test.
* core(lpsolver): compare the regression tests with their exact optima
issue_12343 has the unique optimum z = (16, 15, 0, 24)/37, objective
189/37. Compare z with it through cvtest::norm, as regression_basic does.
Checking only the status and the constraints passes for any feasible
point reported as SOLVELP_SINGLE.
Compare small_magnitude_data with its exact solution as well, and check
that the point returned by negative_rhs_restore_cancellation lies on its
optimal segment. Assert the status first in all three tests.
Inline add_snap_zero, which had one caller, and drop an example noise
magnitude from the sub_snap_zero comment that does not hold in general.
* core(lpsolver): pivot the Phase I auxiliary variable out on a nonzero entry
When Phase I ends with the auxiliary variable x0 basic at value 0,
initialize_simplex() makes it nonbasic by one degenerate pivot. It always
pivoted on the first column of x0's row, but that entry can be 0. With
cancellation noise snapped to exact zeros this happens often: the pivot
divides by 0 and solveLP returns SOLVELP_UNBOUNDED for bounded problems.
Pivot on the entry of largest magnitude instead.
Add phase1_auxiliary_basic_at_zero, which returned SOLVELP_UNBOUNDED.
* core(lpsolver): guard zero Phase I pivot row and snap v updates
* core(lpsolver): snap each restored objective coefficient once
After Phase I, each coefficient of the original objective is rebuilt as a
sum of terms. Add up each column and the absolute values of its terms, and
set the coefficient to 0 once, when it is at most 1e-12 times that
absolute sum, instead of snapping after every term.
The objective value v is never compared or returned, so its updates go
back to plain additions. The doc comment of initialize_simplex() now
lists SOLVELP_LOST.
initWideAngleProjMap unpacked the distortion coefficients as
(k1, k2, k3, p1, p2, ...) while the documented order, and the one used by
initUndistortRectifyMap, is (k1, k2, p1, p2, k3, ...). With a nonzero p1
the map came out wrong (e.g. dist=[0,0,0.1,0,0] gave u=212.139, v=197.349
instead of u=227.979, v=228.751). Reorder the unpacking to match the
standard model.
Also fix two further issues in the same function: the radial factor used
kr = 1 + (num-1)/(den) instead of the rational model
kr = (1 + k1*r2 + k2*r4 + k3*r6)/(1 + k4*r2 + k5*r4 + k6*r6), which is off
by about 14 px with 8 coefficients, and the principal point was read
from scenter before the camera matrix was converted, so cx/cy were
always 0 and the map was shifted by about 400 px for a real camera
matrix. Read cx/cy from the converted camera matrix and drop scenter.
Add a regression test next to regression_14467: with a real principal
point and 8 coefficients it round-trips the map through undistortPoints
and checks the result against the spherical projection.
Fixes#30744
Signed-off-by: SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com>
Signed-off-by: Siddartha Reddy Chinthala <siddarthareddychinthala@gmail.com>