I'm trying to convert a 2D Numpy array, representing a black-and-white image, into a 3-channel OpenCV array (i.e. an RGB image).
Based on code samples and the docs I'm attempting to do this via Python like:
import numpy as np, cv
vis = np.zeros((384, 836), np.uint32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
cv.CvtColor(vis, vis2, cv.CV_GRAY2BGR)
However, the call to CvtColor() is throwing the following cpp-level Exception:
OpenCV Error: Image step is wrong () in cvSetData, file /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp, line 902
terminate called after throwing an instance of 'cv::Exception'
what(): /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp:902: error: (-13) in function cvSetData
Aborted
What am I doing wrong?
Best Answer
Your code can be fixed as follows:
Short explanation:
np.uint32
data type is not supported by OpenCV (it supportsuint8
,int8
,uint16
,int16
,int32
,float32
,float64
)cv.CvtColor
can't handle numpy arrays so both arguments has to be converted to OpenCV type.cv.fromarray
do this conversion.cv.CvtColor
must have the same depth. So I've changed source type to 32bit float to match the ddestination.Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type: