1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-23 20:33:04 +04:00
Files
LHOOL1109 9dba8a7df0 Merge pull request #28747 from LHOOL1109:fix/python-zero-channel-crash
python: fix segfault on 0-channel numpy array input #28747

### 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
- [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
      N/A: a Python unit test is added in `modules/python/test/test_mat.py`. No external test data required.
- [x] The feature is well documented and sample code can be built with the project CMake
      N/A: this is a bug fix, not a new feature. No documentation update needed.

### Problem

Passing a numpy array with shape `(H, W, 0)` (0 channels) to any OpenCV function that accepts a `Mat` argument (e.g. `cv2.resize`, `cv2.warpAffine`, `cv2.blur`) causes a **segfault**.

**Reproducer:**
```python
import cv2
import numpy as np

arr = np.zeros((100, 100, 0), np.uint8)
cv2.resize(arr, (200, 200))  # segfault
```

### Root Cause

In `modules/python/src2/cv2_convert.cpp`, the numpy→Mat conversion checks channel validity only against `CV_CN_MAX` (upper bound):

```cpp
if (channels > CV_CN_MAX)   // channels=0 passes this check
```

With `channels=0`, `CV_MAKETYPE(0, 0)` produces `type=-8`, which corrupts the Mat's internal type field and causes undefined behavior downstream.

### Fix

Extend the check to also reject `channels < 1`:

```cpp
if (channels < 1 || channels > CV_CN_MAX)
```

**After fix:**
```
cv2.error: src unable to wrap channels, invalid count (0, must be in [1, 512])
```

### Notes

- This affects all functions that accept a `Mat` input, not just `cv2.resize`
- The same bug exists in the `5.x` branch
- A 0-channel array has no valid OpenCV Mat representation; rejecting it with a clear error is the correct behavior and poses no backward-compatibility risk (the previous behavior was a crash)
2026-04-03 14:26:18 +03:00

149 lines
6.0 KiB
Python

#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import cv2 as cv
import os
import sys
import unittest
from tests_common import NewOpenCVTests
try:
if sys.version_info[:2] < (3, 0):
raise unittest.SkipTest('Python 2.x is not supported')
class MatTest(NewOpenCVTests):
def test_mat_construct(self):
data = np.random.random([10, 10, 3])
#print(np.ndarray.__dictoffset__) # 0
#print(cv.Mat.__dictoffset__) # 88 (> 0)
#print(cv.Mat) # <class cv2.Mat>
#print(cv.Mat.__base__) # <class 'numpy.ndarray'>
mat_data0 = cv.Mat(data)
assert isinstance(mat_data0, cv.Mat)
assert isinstance(mat_data0, np.ndarray)
self.assertEqual(mat_data0.wrap_channels, False)
res0 = cv.utils.dumpInputArray(mat_data0)
self.assertEqual(res0, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=300 dims(-1)=3 size(-1)=[10 10 3] type(-1)=CV_64FC1")
mat_data1 = cv.Mat(data, wrap_channels=True)
assert isinstance(mat_data1, cv.Mat)
assert isinstance(mat_data1, np.ndarray)
self.assertEqual(mat_data1.wrap_channels, True)
res1 = cv.utils.dumpInputArray(mat_data1)
self.assertEqual(res1, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=100 dims(-1)=2 size(-1)=10x10 type(-1)=CV_64FC3")
mat_data2 = cv.Mat(mat_data1)
assert isinstance(mat_data2, cv.Mat)
assert isinstance(mat_data2, np.ndarray)
self.assertEqual(mat_data2.wrap_channels, True) # fail if __array_finalize__ doesn't work
res2 = cv.utils.dumpInputArray(mat_data2)
self.assertEqual(res2, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=100 dims(-1)=2 size(-1)=10x10 type(-1)=CV_64FC3")
def test_mat_construct_4d(self):
data = np.random.random([5, 10, 10, 3])
mat_data0 = cv.Mat(data)
assert isinstance(mat_data0, cv.Mat)
assert isinstance(mat_data0, np.ndarray)
self.assertEqual(mat_data0.wrap_channels, False)
res0 = cv.utils.dumpInputArray(mat_data0)
self.assertEqual(res0, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=1500 dims(-1)=4 size(-1)=[5 10 10 3] type(-1)=CV_64FC1")
mat_data1 = cv.Mat(data, wrap_channels=True)
assert isinstance(mat_data1, cv.Mat)
assert isinstance(mat_data1, np.ndarray)
self.assertEqual(mat_data1.wrap_channels, True)
res1 = cv.utils.dumpInputArray(mat_data1)
self.assertEqual(res1, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=500 dims(-1)=3 size(-1)=[5 10 10] type(-1)=CV_64FC3")
mat_data2 = cv.Mat(mat_data1)
assert isinstance(mat_data2, cv.Mat)
assert isinstance(mat_data2, np.ndarray)
self.assertEqual(mat_data2.wrap_channels, True) # __array_finalize__ doesn't work
res2 = cv.utils.dumpInputArray(mat_data2)
self.assertEqual(res2, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=500 dims(-1)=3 size(-1)=[5 10 10] type(-1)=CV_64FC3")
def test_mat_wrap_channels_fail(self):
data = np.random.random([2, 3, 4, 520])
mat_data0 = cv.Mat(data)
assert isinstance(mat_data0, cv.Mat)
assert isinstance(mat_data0, np.ndarray)
self.assertEqual(mat_data0.wrap_channels, False)
res0 = cv.utils.dumpInputArray(mat_data0)
self.assertEqual(res0, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=12480 dims(-1)=4 size(-1)=[2 3 4 520] type(-1)=CV_64FC1")
with self.assertRaises(cv.error):
mat_data1 = cv.Mat(data, wrap_channels=True) # argument unable to wrap channels, too high (520 > CV_CN_MAX=512)
res1 = cv.utils.dumpInputArray(mat_data1)
print(mat_data1.__dict__)
print(res1)
def test_mat_wrap_channels_zero(self):
# Passing a 0-channel array must raise cv.error, not segfault.
data = np.zeros((100, 100, 0), dtype=np.uint8)
with self.assertRaises(cv.error):
cv.resize(data, (200, 200)) # channels=0 -> invalid, must not segfault
with self.assertRaises(cv.error):
mat_data = cv.Mat(data, wrap_channels=True) # unable to wrap channels, invalid count (0)
cv.utils.dumpInputArray(mat_data)
# Verify that channels=1 (lower bound) still works correctly
data_1ch = np.zeros((100, 100, 1), dtype=np.uint8)
mat_1ch = cv.Mat(data_1ch, wrap_channels=True)
res = cv.utils.dumpInputArray(mat_1ch)
self.assertIn("CV_8UC1", res)
def test_ufuncs(self):
data = np.arange(10)
mat_data = cv.Mat(data)
mat_data2 = 2 * mat_data
self.assertEqual(type(mat_data2), cv.Mat)
np.testing.assert_equal(2 * data, 2 * mat_data)
def test_comparison(self):
# Undefined behavior, do NOT use that.
# Behavior may be changed in the future
data = np.ones((10, 10, 3))
mat_wrapped = cv.Mat(data, wrap_channels=True)
mat_simple = cv.Mat(data)
np.testing.assert_equal(mat_wrapped, mat_simple) # ???: wrap_channels is not checked for now
np.testing.assert_equal(data, mat_simple)
np.testing.assert_equal(data, mat_wrapped)
#self.assertEqual(mat_wrapped, mat_simple) # ???
#self.assertTrue(mat_wrapped == mat_simple) # ???
#self.assertTrue((mat_wrapped == mat_simple).all())
except unittest.SkipTest as e:
message = str(e)
class TestSkip(unittest.TestCase):
def setUp(self):
self.skipTest('Skip tests: ' + message)
def test_skip():
pass
pass
if __name__ == '__main__':
NewOpenCVTests.bootstrap()