core: fix in-place cartToPolar when only the magnitude overwrites an input - #30646Fixes#30645
### Problem
`cv::cartToPolar` gives wrong results on `CV_32F` when only the magnitude output is the same `Mat` as `x` or `y`. The SIMD loop handles the leftover elements by repeating the last full block. In-place calls must skip this, but `cartToPolar32f_` only checked the angle, so the repeated block read magnitudes as inputs.
### Fix
Added `mag == X || mag == Y` to the check, so these calls handle the leftover elements with the scalar code. `polarToCart` and `magnitude` already check all their outputs.
### Tests
New `Core_CartToPolar_inplace_mag.accuracy` for `CV_32F` with lengths 1 to 39: the magnitude overwrites `x`, then `y`, and the results are compared with a call using separate outputs. The existing `Core_CartToPolar_inplace` test overwrites both inputs, so it never reached this case. `CV_64F` is not tested, because it works on separate float buffers and can't hit this bug.
On Apple M1 Pro, 28 of the 39 cases fail without the fix. All pass with the fix, along with the related `cartToPolar`, `polarToCart`, `magnitude` and `phase` tests, with OpenCL on and off.
### 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
core: throw an error instead of crashing in inRange on CV_16F #30668Fixes#30667
### Problem
`cv::inRange` crashed with a segmentation fault on `CV_16F` input. `inRangeTab` has `0` for `CV_16F`, and the code called the returned function without checking it.
### Fix
If no function is found, `cv::inRange` now raises `CV_Error` with `StsNotImplemented` and a message saying that `CV_16F` is not supported, like 5.x does for its unsupported depths.
### Tests
New `Core_InRange.unsupported_depth_throws` checks scalar and array bounds on `CV_16F`. Without the fix, the test program crashes. With the fix, it passes, and all `opencv_test_core` tests pass on Apple M1 Pro.
`inRange` supports `CV_16F` on 5.x, so this test does not throw there. It needs to be removed or changed when 4.x is merged into 5.x.
### 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
`u->mapcount` was incremented before `clEnqueueMapBuffer()`.
If mapping failed, the counter remained incremented even though no
mapping was established, leaving `UMatData` in an inconsistent state
and potentially triggering later assertions such as:
(-215:Assertion failed) u->mapcount == 0 in function 'deallocate'
Update the logic to increment `mapcount` only after a successful
`clEnqueueMapBuffer()` call.
The issue was observed while running:
OCL_PyrDownFixture_PyrDown.PyrDown/6 from opencv_perf_imgproc.
Assisted-by: LLM
Signed-off-by: jiajia Qian <jiajia.qian@nxp.com>
Each key block must have the form "{names | default | help}". The
constructor read the second and third fields without checking that they
exist, so a block such as "{help h}" or "{help h|}" read past the end
of a vector and crashed. Throw a parse error instead, as is already done
for other malformed key strings.
Laplacian picked the kernel type as max(CV_32F, ddepth, sdepth), which
is CV_16F for a CV_16F image because CV_16F > CV_64F. The 3x3 kernel
was then allocated as CV_16F (18 bytes) and filled with 9 doubles. Use
CV_64F when the source or destination is CV_64F and CV_32F otherwise,
so filter2D rejects the unsupported depth without the overflow.
Add an Imgproc_Laplacian regression test.
Validate the one-based Padding dimension before converting it to an
array index, and reject the minimum integer pad before negating it.
Add a serialized Torch7 regression test for valid and invalid bounds.
Signed-off-by: Nathan Keys <professor.moody@pm.me>
Same change as the 5.x port, to keep the two branches in sync.
The wrapper parses window_name, on_mouse and param, but the cv2.cpp help
text and the typing stub in api_refinement.py both say windowName and
onMouse, so the stub promises keywords the runtime rejects:
>>> cv2.setMouseCallback(windowName="w", onMouse=cb)
TypeError: function missing required argument 'window_name' (pos 1)
createTrackbar is left alone: it is registered METH_VARARGS, so its
arguments cannot be passed by keyword at all.
- Reading and writing 16-bit AVIF images requires libavif v1.4.0+
- Note that if the alpha plane contains only fully opaque pixels, the destination saves only color channels due to a libavif limitation.
Port from https://github.com/opencv/opencv/pull/30519
- Correct lossy test normalization from dividing by total samples (N) to root-mean-square (RMS) error divided by sqrt(N), and recalibrate thresholds with margin for 8/10/12/16-bit tests.
- Extend 16-bit AVIF tests to cover all supported channel counts (1, 3, and 4 channels) using testing::Combine.
Port from https://github.com/opencv/opencv/pull/30431
imgproc: don’t use ippiCopySubpixIntersect for windows crossing the image border - #30363Fixes#30301
### Problem
`ippiCopySubpixIntersect` (used by the IPP HAL for `getRectSubPix` with 8UC1→8U, 8UC1→32F and 32FC1→32F) gets two kinds of border windows wrong:
1. **The window crosses the top edge and reaches the last column** (reported in #30301): the top rows get `src(0, cols - 2)` instead of `src(0, cols - 1)`. For 1-column images this reads the element before the start of the image.
2. **8u→8u window entirely to the left of the image** (not in the original report): the fixed-point interpolation weights overflow and the result is wrong, e.g. a 1x1 image filled with 176 gives 112. This case doesn't read outside the image.
### Fix
Fall back to the generic implementation only for these two cases. The window position is computed the same way IPP does it (`(int)(x + w) - w`, which differs from `cvFloor()` for some inputs), as suggested by @andreyfe1. All other windows, including about 69% of the windows that cross the border, still go through IPP.
### Testing
- Added `Imgproc_GetRectSubPix.regression_30301`: 3 cases (top-right crossing, 1-column image, window left of the image) × 3 type combinations, with the images as ROIs of a 250-filled buffer. It fails on 7 of 9 checks without the patch.
- Compared IPP on vs off with IPPICV 2026.1.0: a grid sweep over 26M windows, plus on both the AVX2 and SSE4.2 paths random images up to 64x64 with windows up to 48x48 and far-away centers (16M), centers within a few ulps of every integer window position (35M), and images placed next to a PROT_NONE page so any out-of-image read crashes (31M). No differences and no crashes with the patch; without it the guard-page run crashes on case 1.
- `opencv_test_imgproc`: no new failures.
FileStorage::Impl::~Impl() calls release(), and release() can throw: for
example workaround() reports an empty key of a delayed Base64 sequence.
WriteStructContext::~WriteStructContext() calls endWriteStruct(), which
throws when the structure was already closed by hand or never opened. A
destructor is noexcept, so either exception ended the process.
Catch it in both destructors and log a warning instead, as other
destructors in OpenCV do. When release() throws in ~Impl(), call it a
second time, as FileStorage::open() does when opening fails: the first
call has already dropped the delayed structure that made it throw, so
the second one writes the rest of the file. ~Impl() then closes the
file in case both calls threw.
imgproc: avoid padding divisible dimensions in CLAHE - #30304
### 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
`CLAHE::apply` pads both dimensions whenever either dimension is not divisible by the tile grid. For an image with 80 rows and 81 columns and an 8x8 grid, the height already fits, but the implementation adds eight reflected rows anyway. The resulting 11-pixel tile height changes the histograms and interpolation across the image; only seven columns are needed to obtain tiles 11 pixels wide and 10 pixels high.
Compute the minimum reflected padding independently for each dimension in both the CPU and OpenCL paths. Images with both dimensions divisible, or neither dimension divisible, retain their existing tile geometry. No public interface changes.
Reproduction (applies to both `uint8` and `uint16`):
```python
import cv2
import numpy as np
src = np.random.default_rng(42).integers(0, 65536, (80, 81), dtype=np.uint16)
clahe = cv2.createCLAHE(2.0, (8, 8))
actual = clahe.apply(src)
padded = cv2.copyMakeBorder(src, 0, 0, 0, 7, cv2.BORDER_REFLECT_101)
expected = clahe.apply(padded)[:80, :81]
assert np.array_equal(actual, expected) # fails before this fix
```
Testing on `b254d3455a`, Linux x86-64, GCC 15.2, Release, IPP disabled, OpenCL enabled with PoCL 6 CPU device (`OPENCV_OPENCL_DEVICE=:CPU:`, `POCL_MAX_PTHREAD_COUNT=4`, `OPENCV_FOR_THREADS_NUM=2`):
- On base `9d80321677` with only the new tests: 88 failed, 64 passed. All 24 new OpenCL cases fail; the remaining failures are the CPU mixed-divisibility cases.
- With the fix, `opencv_test_imgproc --gtest_filter="*CLAHE_Padding*:*CLAHETest.ReflectedBorder*"`: 152 passed.
- `OPENCV_TEST_DATA_PATH=~/ocv-testdata opencv_test_imgproc --gtest_filter="*Hist*:*BackProject*:*CLAHE*"`: 232 passed, including the existing OpenCL CLAHE accuracy tests. The initial run lacked `cv/optflow/RubberWhale1.png`; rerunning with the official `opencv_extra` image passed.
- `opencv_perf_imgproc --gtest_filter="*CLAHE*" --perf_min_samples=10 --perf_force_samples=10`: 12 existing CLAHE performance cases passed, plus four framework checks.
- `git diff --check`: passed.
- CI revision `801fea96e3`: renamed the OpenCL test RNG to avoid shadowing its fixture member. Rebuilt `opencv_test_imgproc` with no compiler warnings and reran the selected accuracy suite: 232 passed.
The regression matrix covers 8-/16-bit inputs, square/rectangular/single-axis grids, all divisibility combinations, clipping, strided inputs, and in-place use. OpenCL cases cover both axes and UMat offsets. No additional test data is needed. Full imgproc suite and physical GPU execution were not run.
The reproduction above is the original report; no earlier issue or competing fix was found.
imgcodecs: honor PFM grayscale and color read modes 🤖🤖🤖 - #30371Fixes#30370.
Loading a grayscale PFM with the default color mode, or a color PFM in grayscale mode, fails through `imread()` and returns the wrong channel count through `imdecode()`. `PFMDecoder::readData()` relies on `Mat::convertTo()`, which changes depth while preserving source channels; this reallocates the output instead of honoring the requested type.
Convert between one and three channels in the floating-point buffer before the final depth conversion. Existing byte-order handling, scaling, unchanged-mode decoding, and RGB/BGR selection remain in place. No public API changes. This targets 4.x because the same bug exists there; 5.x contains the same affected implementation.
### Regression coverage
32 generated cases cover one/three-channel inputs, file/memory reads, grayscale/BGR/RGB requests, float depth preservation, unchanged/any-color controls, and reuse of a preallocated memory destination. No new external test data is required.
### Validation
Windows x64, GCC 16.2.0, Release, current 4.x base `9b6287ec500ef7b327ac74c4f6c9cd84a2cbc9cd`:
- New regression matrix before the fix: **12 failed, 20 passed**.
- After the fix: **32/32 passed**; existing PFM round-trip test also passed (**33/33 PFM tests**).
- Configured `opencv_test_imgcodecs` suite: **601 tests reported, zero failures**, with three skips reported by the OpenCV runner (memory/very-long/other conditions). JPEG/PNG and built-in codecs enabled; IPP/OpenCL disabled.
- `git diff --check` passed; independent read-only code review found no actionable defects.
- The issue reproducer also runs against the official OpenCV 5.0.0 Python wheel. Upstream CI results are separate from these local results.
AI assistance disclosure: investigation, implementation, tests, and this description were prepared with OpenAI Codex; the reproduction and source-build test results were executed in this workspace.
### Pull Request Readiness Checklist
See 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 code under GPL or another license 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 an accuracy test and test data, if applicable. Tests generate their own data; no opencv_extra change or performance test is needed for this correctness fix.
- [x] The existing documented read-mode behavior is preserved and the code builds with the project CMake configuration. No new API or sample is introduced.
5622958189 replaced pow() with std::pow() in three OpenCL C kernel
files. OpenCL C is a C99-derived language and has no std namespace, so
these kernels fail to compile at runtime on the GPU (e.g.
CL_BUILD_PROGRAM_FAILURE: use of undeclared identifier 'std') and dnn
silently falls back to CPU for the affected activations, LRN and fused
conv layers. Revert to the plain built-in pow() in the kernels.
In VideoCapture::open(), PR #22700 added checks to log warnings when a requested
backend cannot perform a capture mode (e.g. capturing by index with CAP_FFMPEG).
However, the condition only tested if (isBackendBuiltIn(apiPreference)), which
evaluates to true for all built-in backends regardless of whether they support the mode.
As a result, whenever a camera or file failed to open (e.g., camera not connected,
invalid camera index, missing or unreadable file), OpenCV emitted false-positive
warnings:
- VIDEOIO(V4L2): backend is generally available but can't be used to capture by index
- VIDEOIO(FFMPEG): backend is generally available but can't be used to capture by name
even though V4L2 and FFMPEG natively support those respective modes.
Track whether apiPreference matches an available backend for the requested mode in
getAvailableBackends_CaptureByIndex, getAvailableBackends_CaptureByFilename, and
getAvailableBackends_CaptureByStream. Only log the warning when the backend is
genuinely absent from the supported list for that mode while being available on the system.
Resolves#26519
Signed-off-by: paneendrakumar0 <paneendra100@gmail.com>
dnn: validate TFLite tensor buffer bounds 🤖🤖🤖 - #30261
OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1430
### What this changes
`TFLiteImporter::parseTensor` now checks the buffer index and required tensor bytes before constructing a `Mat` over model data. It rejects negative or overflowing shapes and unsupported sparse tensors. Absent or empty data remains a runtime tensor.
### Why
A TFLite model controls tensor shape, type, and buffer index. On 4.x at `802cf95aa3d42816995695bf68a86b3532f12760`, a tensor can claim more bytes than its selected buffer contains. The `tfliteShortBuffer` model included in this PR caused a stock Release SIGSEGV in three observed runs. The new check rejects it before the `Mat` wraps short data.
Associated upstream issue: none. Related DNN parser work includes #29371 and the closed, unmerged #29336; neither fixes this shape-to-buffer check.
### Tests and reproduction
This PR includes 15 small inline control and malformed TFLite models, importer tests, and `modules/dnn/test/generate_tflite_tensor_bounds_models.py`. The generator uses OpenCV's in-tree TFLite schema and `flatc` 25.12.19. The focused tests need no `opencv_extra` download.
To reproduce with the bytes in this PR, copy `modules/dnn/test/test_tflite_importer.cpp` and `modules/dnn/test/tflite_tensor_bounds_models.inc` from this PR into an otherwise unmodified 4.x checkout at the commit above. Build `opencv_test_dnn`, then run `./build/bin/opencv_test_dnn --gtest_filter=Test_TFLite_Importer.ShortInt32Buffer`. Apply the full PR and run `./build/bin/opencv_test_dnn --gtest_filter='Test_TFLite_Importer.*'`.
On Linux, an earlier tree that combined this patch with a separate ONNX importer fix passed all 15 focused TFLite tests and the 245-test `*Test_TFLite.*:*Test_ONNX_layers.*` filter in Release and GCC ASan builds. The compiled source and test files in this PR are byte-identical to that tree; only a generator comment changed afterwards, and rerunning the generator reproduced the include byte-for-byte. This branch has not been built on its own. Clang, MSVC, MinGW, and 5.x runtime tests have not run.
I used an AI coding tool to help prepare this change and will answer reviewer questions and address requested fixes within a day, following OpenCV's AI usage guideline. A separate reproducer archive is available on request; no files are attached to this PR.
### 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
The test models are inline in this PR; no opencv_extra change is proposed.
- [ ] The feature is well documented and sample code can be built with the project CMake
fix(python): handle non-native NumPy byte order 🤖🤖🤖 - #30369
Python bindings can read non-native-endian NumPy inputs as native bytes, producing incorrect values or NaN. Mark swapped arrays for the existing cast path before constructing `Mat`; this also rejects incompatible output/in-place destinations before writes.
Closes#30368. Targets 4.x so the common bridge fix can be merged into 5.x.
Validation on macOS ARM64, Python 3.11.11, NumPy 2.4.6:
- Built current 4.x and 5.x. Three regression tests cover 20 dtype/layout/output cases; 18 fail before and all pass after. Read-only inputs and rejected destinations remain unchanged.
- 21 native-input timing cells on 4.x, 101 alternating pairs: fixed/baseline median time 0.957–1.005×, identical results. The 5.x check also stayed within 0.971–1.004×.
- Draft: Linux/hosted CI validation remains pending.
### Pull Request Readiness Checklist
- [x] I agree to contribute to the project under Apache 2 License.
- [x] The patch is not based on GPL or other incompatible code.
- [x] The PR targets the appropriate branch.
- [x] The original bug report is linked.
- [x] Regression tests and native-input performance checks are included; no external test data is needed.
- [x] No public API, feature documentation or sample changes are needed.