Converting Numpy Array to OpenCV Array Converting Numpy Array to OpenCV Array numpy numpy

Converting Numpy Array to OpenCV Array


Your code can be fixed as follows:

import numpy as np, cvvis = np.zeros((384, 836), np.float32)h,w = vis.shapevis2 = 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, cv2vis = np.zeros((384, 836), np.float32)vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)


This is what worked for me...

import cv2import numpy as np#Created an image (really an ndarray) with three channels new_image = np.ndarray((3, num_rows, num_cols), dtype=int)#Did manipulations for my project where my array values went way over 255#Eventually returned numbers to between 0 and 255#Converted the datatype to np.uint8new_image = new_image.astype(np.uint8)#Separated the channels in my new imagenew_image_red, new_image_green, new_image_blue = new_image#Stacked the channelsnew_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])#Displayed the imagecv2.imshow("WindowNameHere", new_rgbrgb)cv2.waitKey(0)


The simplest solution would be to use Pillow lib:

from PIL import Imageimage = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.