How to convert a python numpy array to an RGB image with Opencv 2.4? How to convert a python numpy array to an RGB image with Opencv 2.4? numpy numpy

How to convert a python numpy array to an RGB image with Opencv 2.4?


You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray.The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below.

img = numpy.zeros([5,5,3])img[:,:,0] = numpy.ones([5,5])*64/255.0img[:,:,1] = numpy.ones([5,5])*128/255.0img[:,:,2] = numpy.ones([5,5])*192/255.0cv2.imwrite('color_img.jpg', img)cv2.imshow("image", img)cv2.waitKey()


You are looking for scipy.misc.toimage:

import scipy.miscrgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray


The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>:

import numpy, cv2def show_pic(p):        ''' use esc to see the results'''        print(type(p))        cv2.imshow('Color image', p)        while True:            k = cv2.waitKey(0) & 0xFF            if k == 27: break         return        cv2.destroyAllWindows()b = numpy.zeros([200,200,3])b[:,:,0] = numpy.ones([200,200])*255b[:,:,1] = numpy.ones([200,200])*255b[:,:,2] = numpy.ones([200,200])*0cv2.imwrite('color_img.jpg', b)c = cv2.imread('color_img.jpg', 1)c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)d = cv2.imread('color_img.jpg', 1)d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)e = cv2.imread('color_img.jpg', -1)e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)f = cv2.imread('color_img.jpg', -1)f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)pictures = [d, c, f, e]for p in pictures:        show_pic(p)# show the matrixprint(c)print(c.shape)

See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

OR you could:

img = numpy.zeros([200,200,3])img[:,:,0] = numpy.ones([200,200])*255img[:,:,1] = numpy.ones([200,200])*255img[:,:,2] = numpy.ones([200,200])*0r,g,b = cv2.split(img)img_bgr = cv2.merge([b,g,r])