Converting Numpy Array to OpenCV Array

后端 未结 3 1545
半阙折子戏
半阙折子戏 2020-12-08 04:01

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

3条回答
  •  无人及你
    2020-12-08 04:51

    Your code can be fixed as follows:

    import numpy as np, cv
    vis = np.zeros((384, 836), np.float32)
    h,w = vis.shape
    vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
    vis0 = cv.fromarray(vis)
    cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
    

    Short explanation:

    1. np.uint32 data type is not supported by OpenCV (it supports uint8, int8, uint16, int16, int32, float32, float64)
    2. cv.CvtColor can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray do this conversion.
    3. Both arguments of 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:

    import numpy as np, cv2
    vis = np.zeros((384, 836), np.float32)
    vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
    

提交回复
热议问题