Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have searched for similar questions, but haven't found anything helpful as most solutions use older versions of OpenCV.

I have a 3D numpy array, and I would like to display and/or save it as a BGR image using OpenCV (cv2).

As a short example, suppose I had:

import numpy, cv2 b = numpy.zeros([5,5,3])  b[:,:,0] = numpy.ones([5,5])*64 b[:,:,1] = numpy.ones([5,5])*128 b[:,:,2] = numpy.ones([5,5])*192 

What I would like to do is save and display b as a color image similar to:

cv2.imwrite('color_img.jpg', b) cv2.imshow('Color image', b) cv2.waitKey(0) cv2.destroyAllWindows() 

This doesn't work, presumably because the data type of b isn't correct, but after substantial searching, I can't figure out how to change it to the correct one. If you can offer any pointers, it would be greatly appreciated!

like image 746
Gillespie Avatar asked Oct 31 '14 19:10

Gillespie


People also ask

How do I convert an image to RGB in OpenCV?

OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.


2 Answers

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.0 img[:,:,1] = numpy.ones([5,5])*128/255.0 img[:,:,2] = numpy.ones([5,5])*192/255.0  cv2.imwrite('color_img.jpg', img) cv2.imshow("image", img) cv2.waitKey() 
like image 73
bikz05 Avatar answered Sep 26 '22 05:09

bikz05


You are looking for scipy.misc.toimage:

import scipy.misc rgb = 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

like image 30
Martin Thoma Avatar answered Sep 26 '22 05:09

Martin Thoma