Commit Graph

26356 Commits

Author SHA1 Message Date
Abhishek Gola
ede3313ae7 Merge pull request #31041 from GeekQAQ/fix-yaml-dash-line
core: report an error for a '-' line after the first YAML document
2026-11-23 09:26:38 +05:30
Parchuri Poojith Kumar
01fcbe2b16 imgproc: stop approxPolyDP from looping forever on an open curve with an infinite coordinate
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.
2026-11-22 18:02:35 +05:30
Pu Cheng
29a31a187d core: report an error for a '-' line after the first YAML document
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.
2026-11-22 03:39:22 +08:00
Abhishek Gola
9ab3c8cd13 Merge pull request #30776 from tribhu05/fix-applycolormap-1x256-lut
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.
2026-11-21 14:37:09 +05:30
Abhishek Gola
3ab5a2c9c3 Merge pull request #31021 from sohailshk/fix/pyrup-empty-src
imgproc: do not crash in pyrUp on an empty source
2026-11-21 12:25:21 +05:30
Rahul Kumar
163e11b600 features2d: do not apply AKAZE max_points limit in compute() on provided keypoints 🤖🤖🤖 (#30912)
* 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.
2026-11-21 09:46:50 +05:30
Pu Cheng
0c948e3684 video: make clear() reset the MOG2 and KNN background models (#30992)
* 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.
2026-11-21 09:18:48 +05:30
Alexander Smorkalov
bc02403223 Merge pull request #30994 from lazerg/fix/issue-30991-filestorage-release-memory
core: free FileStorage session buffers in release()
2026-11-20 16:24:34 +03:00
Abhishek Gola
f0d9c67dc8 Merge pull request #30982 from abhishek-gola/tests/test-fixes-4x
tests: pass the mask in AccumulateWeighted.Mask
2026-11-20 17:08:07 +05:30
Abhishek Gola
38333d558f Merge pull request #30993 from GeekQAQ/fix-mjpeg-jflush-overflow
videoio: avoid signed overflow in BitStream::jflush
2026-11-20 14:33:02 +05:30
Pratham Kumar
6e772459fc Merge pull request #30472 from pratham-mcw/denoising_opt
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.
2026-11-20 13:26:56 +05:30
Abhishek Gola
6e0162fb08 photo: fix NORMCONV domain filter above 5.6 MP (#30863)
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.
2026-11-20 13:19:14 +05:30
Mohammad Sohail Shaikh
56d41f7166 core: return early for empty input in minMaxIdx (#30897)
* 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().
2026-11-20 12:54:42 +05:30
Abhishek Gola
294d550516 Merge pull request #30377 from kari-pikkarainen/fix/photo-debevec-gauge-row
photo: weight the CalibrateDebevec gauge equation like the data equations 🤖🤖🤖
2026-11-20 12:37:04 +05:30
Rahul Kumar
7158c479d8 imgproc: fix data races in the OpenCL separable filter and Laplacian kernels 🤖🤖🤖 (#30735)
* 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.
2026-11-20 09:16:35 +05:30
sohailshk
eab20f61de imgproc: do not crash in pyrUp on an empty source
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.
2026-11-20 09:13:32 +05:30
Abhishek Gola
93bb48ad50 Merge pull request #30961 from kazisufiyan-k2/python-typing-dnn-layerid
python: fix LayerId typing alias referencing missing cv2.dnn.DictValue
2026-11-20 08:30:15 +05:30
lazerg
e144a32646 core: free FileStorage session buffers in release() 2026-11-20 07:02:16 +05:00
Pu Cheng
9ef9d47714 videoio: avoid signed overflow in BitStream::jflush
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.
2026-11-20 05:58:03 +08:00
Abhishek Gola
a2506f124a Merge pull request #30948 from pctablet505/fix-dnn-cpu-norm-variance
dnn: fix CPU MVN, LayerNorm, InstanceNorm and GroupNorm outputs for inputs with a large mean 🤖🤖🤖
2026-11-19 21:39:55 +05:30
Abhishek Gola
b4806d3049 imgproc: prevent sub-threshold circles from overwriting valid circles in HoughCircles (#30845) 2026-11-19 19:17:44 +05:30
Rahul Kumar
9cef898938 dnn: repack the convolution after a reshape or a fusion change 🤖🤖🤖 (#30866)
* 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.
2026-11-19 19:16:03 +05:30
abhishek-gola
1cd88e4a2a tests: pass the mask in AccumulateWeighted.Mask and check the #24966 CRF fix directly
Signed-off-by: abhishek-gola <abhishek@opencv.org>
2026-11-19 18:58:17 +05:30
Kazi Sufiyan
2603b839cb python: fix LayerId typing alias referencing missing cv2.dnn.DictValue
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.
2026-11-19 08:58:07 +00:00
Muhammad Usman Mateen
19672eb03f Merge pull request #30842 from usmanmateen/fix/onnx-avgpool-count-include-pad
dnn: read count_include_pad in the ONNX AveragePool importer 🤖🤖🤖 - #30842

Fixes #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
2026-11-19 08:44:27 +03:00
Alexander Smorkalov
8c54b0252c Merge pull request #30902 from DinahK-2SO/4.x-remove-unused-dls
calib3d: remove the unused legacy DLS solver on 4.x
2026-11-19 08:41:36 +03:00
pctablet505
5fe3daad9c dnn: fix CPU normalization outputs for inputs with a large mean
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.
2026-11-18 20:54:52 +05:30
pctablet505
3e78b0731c photo: fix NORMCONV domain filter above 5.6 MP
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.
2026-11-18 20:11:19 +05:30
Tianyu Guo
3e1cb2371a Merge pull request #30798 from gty111:fix/python-video-stream-seek
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.
2026-11-18 14:28:37 +03:00
Alexander Smorkalov
3b11d40a26 Merge pull request #30604 from sshivensolanki:fix-pam-no-tupltype
imgcodecs: read 16-bit and 4-channel PAM files without TUPLTYPE
2026-11-18 11:44:27 +03:00
Alexander Smorkalov
3a96e82d17 Merge pull request #30496 from sshivensolanki:fix-pow-nonint-4x
core: fix out-of-bounds access in pow for integer depths with non-integer power
2026-11-18 10:57:48 +03:00
Dinah Gao (from Dev Box)
a9d20ae75a calib3d: remove the unused legacy DLS solver
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
2026-11-18 15:21:15 +08:00
melody419
9518d68f4d Merge pull request #30827 from melody419:fix-warppolar-inverse-border
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
2026-11-18 10:09:32 +03:00
Abhishek Gola
c47c93f0c5 Merge pull request #30875 from poojithparchuri-iiitk/affine-degenerate-4x
calib3d: reject degenerate minimal samples in estimateAffine2D and es…
2026-11-18 08:57:09 +05:30
pbkx
289c141a43 Merge pull request #30853 from pbkx/fix-masked-mean-performance-4x
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.
2026-11-18 08:54:00 +05:30
Shaanganesh
94957e4e64 imgproc: prevent sub-threshold circles from overwriting valid circles in HoughCircles 2026-11-17 21:30:19 +05:30
Alexander Smorkalov
f4fa6371cb Merge pull request #30889 from kazisufiyan-k2:docs-dft-convolve-example
core: fix output size in convolveDFT sample of dft() docs
2026-11-17 18:37:04 +03:00
Mohammad Sohail Shaikh
9713041d8f Merge pull request #30831 from sohailshk:fix/brisk-non-continuous
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
2026-11-17 16:56:10 +03:00
Rahul Kumar
5f335351c9 Merge pull request #30859 from pctablet505:fix-video-dis-collectgarbage-crash
video: fix DISOpticalFlow::calc() crash after collectGarbage() 🤖🤖🤖 - #30859

Fixes #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
2026-11-17 16:46:45 +03:00
Rahul Kumar
53d70cb630 Merge pull request #30860 from pctablet505:fix-video-dis-stale-initial-flow
video: clear stale initial flow in DISOpticalFlow::calc() 🤖🤖🤖 - #30860

Fixes #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
2026-11-17 12:53:30 +03:00
Shawn
0a4e150127 Merge pull request #30597 from ShawnNotFound:fix-20979-python-empty-umat
stitching: wrap default constructors of ImageFeatures, MatchesInfo and CameraParams - #30597

Fixes #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
2026-11-17 12:14:36 +03:00
Kazi Sufiyan
012c5c6da2 core: fix output size in convolveDFT sample of dft() docs
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
2026-11-17 07:45:37 +00:00
Rahul Kumar
0ced618c14 core: fix solveLP floating-point drift producing infeasible solutions 🤖🤖🤖 (#30823)
* 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.
2026-11-17 11:06:58 +05:30
Mohammad Sohail Shaikh
ecb072401a imgproc: do not read pixels outside a sub-matrix in LineSegmentDetector smoothing (#30811) 2026-11-17 11:06:04 +05:30
Parchuri Poojith Kumar
333974b268 calib3d: reject degenerate minimal samples in estimateAffine2D and estimateAffinePartial2D
Port of #30829 to 4.x.
2026-11-16 20:59:45 +05:30
A Aswanth Raj
6103e82e10 core: Accumulate Matx L1 and L2 norms in double (#30163)
* core: Accumulate Matx L2 norms in double

* core: Accumulate Matx L1 norms in double
2026-11-15 15:03:06 +05:30
SIDDARTHA REDDY
06e251ee79 fix(calib3d): read distCoeffs in standard order in initWideAngleProjMap (#30797)
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>
2026-11-15 12:49:10 +05:30
Abhishek Gola
59b6aad64b Merge pull request #30803 from ajbarryiii/python-loader-restore-syspath
python: restore sys.path when the native cv2 module fails to load 🤖🤖🤖
2026-11-14 09:25:16 +05:30
Abhishek Gola
f8b2d3394a Merge pull request #30791 from lazerg/fix/issue-30790-solvecubic-double-root
core: fix solveCubic missing double roots after coefficient normalization
2026-11-14 09:23:43 +05:30
Abhishek Gola
defca8b40e Merge pull request #30799 from sohailshk/fix/bayer-edgeaware-non-continuous
imgproc: fix edge-aware Bayer demosaicing of non-continuous source or destination
2026-11-14 09:22:16 +05:30