python: drop the CV_16BF -> float32 mapping, share the empty / 0-D output path, run flag tests without ml_dtypes

Signed-off-by: Abhishek Gola <abhishek.gola@bigvisionllc.com>
This commit is contained in:
Abhishek Gola
2026-10-30 15:59:00 +05:30
parent 3f7c2f7077
commit 8751eb491e
9 changed files with 109 additions and 63 deletions

View File

@@ -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

View File

@@ -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<npy_intp> _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())
{

View File

@@ -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);

View File

@@ -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)