diff --git a/doc/py_tutorials/py_bindings/py_bindings_basics/py_bindings_basics.markdown b/doc/py_tutorials/py_bindings/py_bindings_basics/py_bindings_basics.markdown index 3e80213080..275093b9e1 100644 --- a/doc/py_tutorials/py_bindings/py_bindings_basics/py_bindings_basics.markdown +++ b/doc/py_tutorials/py_bindings/py_bindings_basics/py_bindings_basics.markdown @@ -220,3 +220,7 @@ out = net.forward() # bfloat16 / float8 outputs keep their type default. An array passed as an output argument, such as `dst`, is filled in place and returned as is, whatever the setting. If the setting is on but `ml_dtypes` has not been imported, outputs are still converted to `float32` and a warning is printed once. + +The setting is global, so it changes the outputs of every piece of code in the process that +calls OpenCV. Turn it on in your application. A library should not change it, because the +application that imports the library may expect `float32` outputs. diff --git a/modules/core/include/opencv2/core/hal/interface.h b/modules/core/include/opencv2/core/hal/interface.h index 10c72c132b..721dd8b94f 100644 --- a/modules/core/include/opencv2/core/hal/interface.h +++ b/modules/core/include/opencv2/core/hal/interface.h @@ -157,8 +157,15 @@ typedef int16_t cv_hal_bf16; #define CV_16BFC(n) CV_MAKETYPE(CV_16BF,(n)) #define CV_8F_E4M3FNC1 CV_MAKETYPE(CV_8F_E4M3FN,1) +#define CV_8F_E4M3FNC2 CV_MAKETYPE(CV_8F_E4M3FN,2) +#define CV_8F_E4M3FNC3 CV_MAKETYPE(CV_8F_E4M3FN,3) +#define CV_8F_E4M3FNC4 CV_MAKETYPE(CV_8F_E4M3FN,4) #define CV_8F_E4M3FNC(n) CV_MAKETYPE(CV_8F_E4M3FN,(n)) + #define CV_8F_E4M3FNUZC1 CV_MAKETYPE(CV_8F_E4M3FNUZ,1) +#define CV_8F_E4M3FNUZC2 CV_MAKETYPE(CV_8F_E4M3FNUZ,2) +#define CV_8F_E4M3FNUZC3 CV_MAKETYPE(CV_8F_E4M3FNUZ,3) +#define CV_8F_E4M3FNUZC4 CV_MAKETYPE(CV_8F_E4M3FNUZ,4) #define CV_8F_E4M3FNUZC(n) CV_MAKETYPE(CV_8F_E4M3FNUZ,(n)) #define CV_8FC1 CV_MAKETYPE(CV_8F,1) diff --git a/modules/dnn/include/opencv2/dnn/dnn.hpp b/modules/dnn/include/opencv2/dnn/dnn.hpp index 67c6f8a97c..b64a4a3fa8 100644 --- a/modules/dnn/include/opencv2/dnn/dnn.hpp +++ b/modules/dnn/include/opencv2/dnn/dnn.hpp @@ -726,7 +726,8 @@ CV__DNN_INLINE_NS_BEGIN * import the optional ml_dtypes package and call * `cv.setAllowNonConventionalDataTypes(True)` before forward(). This process-wide * setting affects outputs only; registered bfloat16 / float8 input arrays are - * accepted regardless of it. See @ref tutorial_py_bindings_basics for details. + * accepted regardless of it. It belongs to the application: libraries should not + * change it. See @ref tutorial_py_bindings_basics for details. */ CV_WRAP Mat forward(const String& outputName = String()); diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 78b756bdd0..156b404cb6 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -137,7 +137,8 @@ static PyMethodDef special_methods[] = { {"redirectError", CV_PY_FN_WITH_KW(pycvRedirectError), "redirectError(onError) -> None"}, {"setAllowNonConventionalDataTypes", (PyCFunction)(pycvSetAllowNonConventionalDataTypes), METH_O, "setAllowNonConventionalDataTypes(allow) -> None\n. Keep output bfloat16 / float8 arrays at their exact dtype " - "(registered by the ml_dtypes package, which must be imported) instead of widening them to float32. Off by default. Input arrays are accepted regardless of this flag."}, + "(registered by the ml_dtypes package, which must be imported) instead of widening them to float32. Off by default. Input arrays are accepted regardless of this flag. " + "The flag is process-wide: set it in the application, libraries should not change it."}, {"getAllowNonConventionalDataTypes", (PyCFunction)(pycvGetAllowNonConventionalDataTypes), METH_NOARGS, "getAllowNonConventionalDataTypes() -> retval"}, #ifdef HAVE_OPENCV_HIGHGUI @@ -620,14 +621,14 @@ static bool init_body(PyObject * m) PUBLISH(CV_16BFC4); PUBLISH(CV_8F_E4M3FN); PUBLISH(CV_8F_E4M3FNC1); - PUBLISH_(CV_8F_E4M3FNC(2), "CV_8F_E4M3FNC2", CV_8F_E4M3FNC2_obj); - PUBLISH_(CV_8F_E4M3FNC(3), "CV_8F_E4M3FNC3", CV_8F_E4M3FNC3_obj); - PUBLISH_(CV_8F_E4M3FNC(4), "CV_8F_E4M3FNC4", CV_8F_E4M3FNC4_obj); + PUBLISH(CV_8F_E4M3FNC2); + PUBLISH(CV_8F_E4M3FNC3); + PUBLISH(CV_8F_E4M3FNC4); PUBLISH(CV_8F_E4M3FNUZ); PUBLISH(CV_8F_E4M3FNUZC1); - PUBLISH_(CV_8F_E4M3FNUZC(2), "CV_8F_E4M3FNUZC2", CV_8F_E4M3FNUZC2_obj); - PUBLISH_(CV_8F_E4M3FNUZC(3), "CV_8F_E4M3FNUZC3", CV_8F_E4M3FNUZC3_obj); - PUBLISH_(CV_8F_E4M3FNUZC(4), "CV_8F_E4M3FNUZC4", CV_8F_E4M3FNUZC4_obj); + PUBLISH(CV_8F_E4M3FNUZC2); + PUBLISH(CV_8F_E4M3FNUZC3); + PUBLISH(CV_8F_E4M3FNUZC4); #undef PUBLISH_ #undef PUBLISH diff --git a/modules/python/src2/cv2_convert.cpp b/modules/python/src2/cv2_convert.cpp index 901be2aee8..dc251bca86 100644 --- a/modules/python/src2/cv2_convert.cpp +++ b/modules/python/src2/cv2_convert.cpp @@ -334,8 +334,9 @@ bool pyopencv_to(PyObject* o, Mat& m, const ArgInfo& info) return true; } -// Builds an empty or 0-D array of dtype `descr`; the caller guarantees it matches m.depth(). -static PyObject* pyopencv_from_nonconventional(const cv::Mat& m, PyArray_Descr* descr) +// Copies an empty or 0-D Mat into a new array of dtype `descr`, which must match m.depth(). +// Steals the reference to `descr`. Channels become the last axis, so a 0-D Mat has shape (cn,). +static PyObject* pyopencv_from_new_array(const cv::Mat& m, PyArray_Descr* descr) { const int cn = m.channels(); int dims = m.dims; @@ -345,7 +346,6 @@ static PyObject* pyopencv_from_nonconventional(const cv::Mat& m, PyArray_Descr* if( cn > 1 ) _sizes[dims++] = cn; - Py_INCREF(descr); // PyArray_NewFromDescr steals the reference PyObject* o = PyArray_NewFromDescr(&PyArray_Type, descr, dims, _sizes.data(), nullptr, nullptr, 0, nullptr); if( o && !m.empty() ) @@ -356,12 +356,14 @@ static PyObject* pyopencv_from_nonconventional(const cv::Mat& m, PyArray_Descr* template<> PyObject* pyopencv_from(const cv::Mat& m) { + PyArray_Descr* exotic = nullptr; if( isNonConventionalDepth(m.depth()) ) { - PyArray_Descr* descr = nonConventionalDescrForCvDepth(m.depth()); - if( !descr ) + exotic = nonConventionalDescrForCvDepth(m.depth()); + if( !exotic ) { // The caller's own array (e.g. dst=) already has the exact dtype: return it as is. + // Like the shared path below, this assumes m spans the whole array, not a ROI of it. if( m.u && m.allocator == &GetNumpyAllocator() ) { PyObject* o = (PyObject*)m.u->userdata; @@ -377,36 +379,21 @@ PyObject* pyopencv_from(const cv::Mat& m) ERRWRAP2(m.convertTo(m32f, CV_32F)); return pyopencv_from(m32f); } - if( m.empty() || m.dims == 0 ) - return pyopencv_from_nonconventional(m, descr); - // Otherwise share the path below: NumpyAllocator allocates with `descr`. } - if( m.empty() ) - { - // empty() also catches a live buffer with a zero-length dim: return an empty array, not None. - if( m.dims >= 1 ) - { - int cn = m.channels(); - int typenum = cvDepthToNumpyType(m.depth()); - int dims = m.dims; - cv::AutoBuffer _sizes(dims + 1); - for( int i = 0; i < dims; i++ ) - _sizes[i] = (npy_intp)m.size[i]; - if( cn > 1 ) - _sizes[dims++] = cn; - return PyArray_SimpleNew(dims, _sizes.data(), typenum); - } + if( m.empty() && m.dims == 0 ) Py_RETURN_NONE; - } - // 0D (scalar) Mat: return a true 0D numpy array. - if( m.dims == 0 ) + // empty() also catches a live buffer with a zero-length dim: return an empty array, not None. + // A 0D (scalar) Mat becomes a true 0D numpy array. + if( m.empty() || m.dims == 0 ) { - int typenum = cvDepthToNumpyType(CV_MAT_DEPTH(m.type())); - PyObject* o = PyArray_SimpleNew(0, nullptr, typenum); - if( o ) - memcpy(PyArray_DATA((PyArrayObject*)o), m.data, CV_ELEM_SIZE(m.type())); - return o; + PyArray_Descr* descr = exotic; + if( descr ) + Py_INCREF(descr); + else + descr = PyArray_DescrFromType(cvDepthToNumpyType(m.depth())); + return pyopencv_from_new_array(m, descr); } + // NumpyAllocator gives bfloat16 / float8 arrays their exact dtype here too. cv::Mat temp, *p = (cv::Mat*)&m; if(!p->u || p->allocator != &GetNumpyAllocator()) { diff --git a/modules/python/src2/cv2_numpy.cpp b/modules/python/src2/cv2_numpy.cpp index a1066a74fb..7a2e803c17 100644 --- a/modules/python/src2/cv2_numpy.cpp +++ b/modules/python/src2/cv2_numpy.cpp @@ -53,10 +53,12 @@ UMatData* NumpyAllocator::allocate(int dims0, const int* sizes, int type, void* CV_Error_(Error::StsError, ("The numpy array of depth=%d, ndims=%d can not be created", depth, dims)); return allocate(eo, dims0, sizes, type, step); } + // Mat::create() falls back to the default allocator on this error; pyopencv_from() then widens to float32. if( isNonConventionalDepth(depth) ) - CV_Error(Error::StsNotImplemented, - "bfloat16 / float8 arrays cannot be allocated through the NumPy allocator: " - "call cv.setAllowNonConventionalDataTypes(True) and import ml_dtypes first"); + CV_Error(Error::StsNotImplemented, getAllowNonConventionalDataTypes() + ? "bfloat16 / float8 arrays cannot be allocated through the NumPy allocator: import ml_dtypes first" + : "bfloat16 / float8 arrays cannot be allocated through the NumPy allocator: " + "call cv.setAllowNonConventionalDataTypes(True) first"); int typenum = cvDepthToNumpyType(depth); PyObject* o = PyArray_SimpleNew(dims, _sizes.data(), typenum); diff --git a/modules/python/src2/cv2_util.cpp b/modules/python/src2/cv2_util.cpp index 4acc441d28..790a237d37 100644 --- a/modules/python/src2/cv2_util.cpp +++ b/modules/python/src2/cv2_util.cpp @@ -30,8 +30,6 @@ int cvDepthToNumpyType(int depth) case CV_32F: return NPY_FLOAT; case CV_64F: return NPY_DOUBLE; case CV_16F: return NPY_HALF; - // NumPy has no native bfloat16; pyopencv_from() widens it to float32 unless allowed. - case CV_16BF: return NPY_FLOAT; case CV_Bool: return NPY_BOOL; default: CV_Error(cv::Error::StsNotImplemented, @@ -85,6 +83,14 @@ PyArray_Descr* nonConventionalDescr(int idx) return g_nonConventionalDescrs[idx]; } +int nonConventionalIndex(int depth) +{ + for (int i = 0; i < kNumNonConventionalDtypes; i++) + if (kNonConventionalDtypes[i].depth == depth) + return i; + return -1; +} + } // namespace void setAllowNonConventionalDataTypes(bool allow) @@ -99,17 +105,15 @@ bool getAllowNonConventionalDataTypes() bool isNonConventionalDepth(int depth) { - return depth == CV_16BF || depth == CV_8F_E4M3FN || depth == CV_8F_E4M3FNUZ; + return nonConventionalIndex(depth) >= 0; } PyArray_Descr* nonConventionalDescrForCvDepth(int depth) { - if (!g_allowNonConventionalDataTypes) + const int idx = nonConventionalIndex(depth); + if (!g_allowNonConventionalDataTypes || idx < 0) return nullptr; - for (int i = 0; i < kNumNonConventionalDtypes; i++) - if (kNonConventionalDtypes[i].depth == depth) - return nonConventionalDescr(i); - return nullptr; + return nonConventionalDescr(idx); } int nonConventionalTypeToCvDepth(int typenum) diff --git a/modules/python/test/test_misc.py b/modules/python/test/test_misc.py index c3079fa57c..984bd8ef47 100644 --- a/modules/python/test/test_misc.py +++ b/modules/python/test/test_misc.py @@ -235,14 +235,23 @@ class Bindings(NewOpenCVTests): cv.CV_32SC1: [cv.CV_32S, 1, cv.CV_32SC], cv.CV_16FC3: [cv.CV_16F, 3, cv.CV_16FC], cv.CV_BoolC1: [cv.CV_Bool, 1, cv.CV_BoolC], - cv.CV_16BFC2: [cv.CV_16BF, 2, cv.CV_16BFC], - cv.CV_8F_E4M3FNC3: [cv.CV_8F_E4M3FN, 3, cv.CV_8F_E4M3FNC], - cv.CV_8F_E4M3FNUZC4: [cv.CV_8F_E4M3FNUZ, 4, cv.CV_8F_E4M3FNUZC], } for ref, (depth, channels, func) in data.items(): self.assertEqual(ref, cv.CV_MAKETYPE(depth, channels)) self.assertEqual(ref, func(channels)) + def test_type_constants_for_all_depths(self): + # Same depth list as export_matrix_type_constants() in api_refinement.py. + depths = ("CV_8U", "CV_8S", "CV_16U", "CV_16S", "CV_32S", "CV_32F", "CV_64F", "CV_16F", + "CV_16BF", "CV_Bool", "CV_64U", "CV_64S", "CV_32U", "CV_8F_E4M3FN", "CV_8F_E4M3FNUZ") + for name in depths: + depth = getattr(cv, name) + make_type = getattr(cv, name + "C") + for channels in range(1, 5): + ref = cv.CV_MAKETYPE(depth, channels) + self.assertEqual(getattr(cv, "%sC%d" % (name, channels)), ref, name) + self.assertEqual(make_type(channels), ref, name) + class Arguments(NewOpenCVTests): diff --git a/modules/python/test/test_ml_dtypes.py b/modules/python/test/test_ml_dtypes.py index 556f47a797..56ff180793 100644 --- a/modules/python/test/test_ml_dtypes.py +++ b/modules/python/test/test_ml_dtypes.py @@ -10,17 +10,51 @@ except ImportError: from tests_common import NewOpenCVTests +NON_CONVENTIONAL_DEPTHS = (cv.CV_16BF, cv.CV_8F_E4M3FN, cv.CV_8F_E4M3FNUZ) + + +class non_conventional_dtypes_test(NewOpenCVTests): + # Runs with or without ml_dtypes. + + def setUp(self): + super(non_conventional_dtypes_test, self).setUp() + self.addCleanup(cv.setAllowNonConventionalDataTypes, cv.getAllowNonConventionalDataTypes()) + cv.setAllowNonConventionalDataTypes(False) + + def test_flag_roundtrip(self): + cv.setAllowNonConventionalDataTypes(True) + self.assertTrue(cv.getAllowNonConventionalDataTypes()) + cv.setAllowNonConventionalDataTypes(False) + self.assertFalse(cv.getAllowNonConventionalDataTypes()) + + def test_disallowed_widens_to_float32(self): + for depth in NON_CONVENTIONAL_DEPTHS: + for m in cv.utils.generateVectorOfMat(1, 3, 4, depth): + self.assertEqual(m.dtype, np.float32) + + def test_allowed_without_ml_dtypes_widens_to_float32(self): + if ml_dtypes is not None: + self.skipTest("ml_dtypes is installed") + cv.setAllowNonConventionalDataTypes(True) + for depth in NON_CONVENTIONAL_DEPTHS: + for m in cv.utils.generateVectorOfMat(1, 3, 4, depth): + self.assertEqual(m.dtype, np.float32) + + def test_short_bool_array_scalar_operands(self): + for channels in range(1, 5): + src = np.zeros((2, 3, channels), dtype=np.float32) + operand = np.array([True, False, True, True][:channels]) + np.testing.assert_array_equal(cv.add(src, operand), + cv.add(src, tuple(float(v) for v in operand))) + class ml_dtypes_test(NewOpenCVTests): def setUp(self): super(ml_dtypes_test, self).setUp() - self.addCleanup(cv.setAllowNonConventionalDataTypes, cv.getAllowNonConventionalDataTypes()) - cv.setAllowNonConventionalDataTypes(False) - if self._testMethodName == "test_disallowed_widens_to_float32": - return if ml_dtypes is None: self.skipTest("ml_dtypes is not installed") + self.addCleanup(cv.setAllowNonConventionalDataTypes, cv.getAllowNonConventionalDataTypes()) cv.setAllowNonConventionalDataTypes(True) # (numpy dtype, OpenCV depth, typeToString prefix, relative half-ULP) self.cases = [ @@ -29,11 +63,6 @@ class ml_dtypes_test(NewOpenCVTests): (ml_dtypes.float8_e4m3fnuz, cv.CV_8F_E4M3FNUZ, "CV_8FNUZ", 2.0 ** -4), ] - def test_disallowed_widens_to_float32(self): - for depth in (cv.CV_16BF, cv.CV_8F_E4M3FN, cv.CV_8F_E4M3FNUZ): - for m in cv.utils.generateVectorOfMat(1, 3, 4, depth): - self.assertEqual(m.dtype, np.float32) - def assertSameBits(self, actual, expected): self.assertEqual(actual.dtype, expected.dtype) self.assertEqual(actual.shape, expected.shape) @@ -78,9 +107,11 @@ class ml_dtypes_test(NewOpenCVTests): self.assertSameBits(cv.add(img, operand), img + operand) def test_roundtrip_through_numpy_allocator(self): - src = np.array([[0.5, -1.25, 3.0, 7.0], [448.0, -448.0, 0.0, -0.5]], dtype=np.float32) + # 240 is the largest finite float8_e4m3fnuz value, so every case keeps these values exactly. + src = np.array([[0.5, -1.25, 3.0, 7.0], [240.0, -240.0, 0.0, -0.5]], dtype=np.float32) for dt, _, _, _ in self.cases: a = src.astype(dt) + np.testing.assert_array_equal(a.astype(np.float32), src) self.assertSameBits(cv.flip(a, 1), a[:, ::-1]) self.assertSameBits(cv.transpose(a), a.T) strided = a[:, ::2]